diff --git a/.gitignore b/.gitignore
index e6d44a02467ae5f02a2f443de9b0acdd66b6a9ca..9fc713587a21b9d9b587ceda3611c8c6f0902f89 100644
--- a/.gitignore
+++ b/.gitignore
@@ -60,6 +60,7 @@ checksum
 /doc/dynare.info
 /doc/dynare.info-1
 /doc/dynare.info-2
+/doc/dynare.info-3
 /doc/dynare.cp
 /doc/dynare.fn
 /doc/dynare.fns
@@ -212,3 +213,6 @@ tests/julia/rbc/rbc*.jl
 
 # Octave variables saved when Octave crashes
 octave-workspace
+
+# VERSION generated file
+VERSION
\ No newline at end of file
diff --git a/NEWS b/NEWS
index 500f3e325db118e06b94d3540b9953e475ddff89..71e9b45d4e07515eb4c7d42e53ead781e81abbf1 100644
--- a/NEWS
+++ b/NEWS
@@ -1,3 +1,800 @@
+Announcement for Dynare 4.5.0 (on 2013-12-16)
+=============================================
+
+We are pleased to announce the release of Dynare 4.5.0.
+
+This major release adds new features and fixes various bugs.
+
+The Windows packages are already available for download at:
+
+ http://www.dynare.org/download/dynare-stable
+
+The Mac and Debian/Ubuntu packages should follow soon.
+
+All users are strongly encouraged to upgrade.
+
+This release is compatible with MATLAB versions ranging from 7.3 (R2006b) to
+9.2 (R2017a) and with GNU Octave version 4.2.
+
+Here is the list of major user-visible changes:
+
+
+
+Dynare 4.5
+==========
+
+
+ - Ramsey policy
+
+   + Added command `ramsey_model` that builds the expanded model with
+     FOC conditions for the planner's problem but doesn't perform any
+     computation. Usefull to compute Ramsey policy in a perfect
+     foresight model,
+
+   + `ramsey_policy` accepts multipliers in its variable list and
+     displays results for them.
+
+
+ - Perfect foresight models
+
+   + New commands `perfect_foresight_setup` (for preparing the
+     simulation) and `perfect_foresight_solver` (for computing it). The
+     old `simul` command still exist and is now an alias for
+     `perfect_foresight_setup` + `perfect_foresight_solver`. It is no
+     longer possible to manipulate by hand the contents of
+     `oo_.exo_simul` when using `simul`. People who want to do
+     it must first call `perfect_foresight_setup`, then do the
+     manipulations, then call `perfect_foresight_solver`,
+
+   + By default, the perfect foresight solver will try a homotopy
+     method if it fails to converge at the first try. The old behavior
+     can be restored with the `no_homotopy` option,
+
+   + New option `stack_solve_algo=7` that allows specifying a
+     `solve_algo` solver for solving the model,
+
+   + New option `solve_algo` that allows specifying a solver for
+     solving the model when using `stack_solve_algo=7`,
+
+   + New option `lmmcp` that solves the model via a Levenberg-Marquardt
+     mixed complementarity problem (LMMCP) solver,
+
+   + New option `robust_lin_solve` that triggers the use of a robust
+     linear solver for the default `solve_algo=4`,
+
+   + New options `tolf` and `tolx` to control termination criteria of
+     solvers,
+
+   + New option `endogenous_terminal_period` to `simul`,
+
+   + Added the possibility to set the initial condition of the
+     (stochastic) extended path simulations with the histval block.
+
+
+ - Optimal simple rules
+
+   + Saves the optimal value of parameters to `oo_.osr.optim_params`,
+
+   + New block `osr_params_bounds` allows specifying bounds for the
+     estimated parameters,
+
+   + New option `opt_algo` allows selecting different optimizers while
+     the new option `optim` allows specifying the optimizer options,
+
+   + The `osr` command now saves the names, bounds, and indices for the
+     estimated parameters as well as the indices and weights of the
+     variables entering the objective function into `M_.osr`.
+
+
+ - Forecasts and Smoothing
+
+   + The smoother and forecasts take uncertainty about trends and means
+     into account,
+
+   + Forecasts accounting for measurement error are now saved in fields
+     of the form `HPDinf_ME` and `HPDsup_ME`,
+
+   + New fields `oo_.Smoother.Trend` and `oo_.Smoother.Constant` that
+     save the trend and constant parts of the smoothed variables,
+
+   + new field `oo_.Smoother.TrendCoeffs` that stores the trend
+     coefficients.
+
+   + Rolling window forecasts allowed in `estimation` command by
+     passing a vector to `first_obs`,
+
+   + The `calib_smoother` command now accepts the `loglinear`,
+     `prefilter`, `first_obs` and `filter_decomposition` options.
+
+
+ - Estimation
+
+   + New options: `logdata`, `consider_all_endogenous`,
+     `consider_only_observed`, `posterior_max_subsample_draws`,
+     `mh_conf_sig`, `diffuse_kalman_tol`, `dirname`, `nodecomposition`
+
+   + `load_mh_file` and `mh_recover` now try to load chain's proposal density,
+
+   + New option `load_results_after_load_mh` that allows loading some
+     posterior results from a previous run if no new MCMC draws are
+     added,
+
+   + New option `posterior_nograph` that suppresses the generation of
+     graphs associated with Bayesian IRFs, posterior smoothed objects,
+     and posterior forecasts,
+
+   + Saves the posterior density at the mode in
+     `oo_.posterior.optimization.log_density`,
+
+   + The `filter_covariance` option now also works with posterior
+     sampling like Metropolis-Hastings,
+
+   + New option `no_posterior_kernel_density` to suppress computation
+     of kernel density of posterior objects,
+
+   + Recursive estimation and forecasting now provides the individual
+     `oo_` structures for each sample in `oo_recursive_`,
+
+   + The `trace_plot` command can now plot the posterior density,
+
+   + New command `generate_trace_plots` allows generating all trace
+     plots for one chain,
+
+   + New commands `prior_function` and `posterior_function` that
+     execute a user-defined function on parameter draws from the
+     prior/posterior distribution,
+
+   + New option `huge_number` for replacement of infinite bounds with
+     large number during `mode_compute`,
+
+   + New option `posterior_sampling_method` allows selecting the new
+     posterior sampling options:
+     `tailored_random_block_metropolis_hastings` (Tailored randomized
+     block (TaRB) Metropolis-Hastings), `slice` (Slice sampler),
+     `independent_metropolis_hastings` (Independent
+     Metropolis-Hastings),
+
+   + New option `posterior_sampler_options` that allow controlling the
+     options of the `posterior_sampling_method`, its `scale_file`-option
+     pair allows loading the `_mh_scale.mat`-file storing the tuned
+     scale factor from a previous run of `mode_compute=6`,
+
+   + New option `raftery_lewis_diagnostics` that computes Raftery/Lewis
+     (1992) convergence diagnostics,
+
+   + New option `fast_kalman_filter` that provides fast Kalman filter
+     using Chandrasekhar recursions as described in Ed Herbst (2015),
+
+   + The `dsge_var` option now saves results at the posterior mode into
+     `oo_.dsge_var`,
+
+   + New option `smoothed_state_uncertainty` to provide the uncertainty
+     estimate for the smoothed state estimate from the Kalman smoother,
+
+   + New prior density: generalized Weibull distribution,
+
+   + Option `mh_recover` now allows continuing a crashed chain at the
+     last save mh-file,
+
+   + New option `nonlinear_filter_initialization` for the
+     `estimation` command. Controls the initial covariance matrix
+     of the state variables in nonlinear filters.
+
+   + The `conditional_variance_decomposition` option now displays
+     output and stores it as a LaTeX-table when the `TeX` option is
+     invoked,
+
+   + The `use_calibration` to `estimated_params_init` now also works
+     with ML,
+
+   + Improved initial estimation checks.
+
+
+ - Steady state
+
+   + The default solver for finding the steady state is now a
+     trust-region solver (can be triggered explicitly with option
+     `solve_algo=4`),
+
+   + New options `tolf` and `tolx` to control termination criteria of
+     solver,
+
+   + The debugging mode now provides the termination values in steady
+     state finding.
+
+
+ - Stochastic simulations
+
+   + New options `nodecomposition`,
+
+   + New option `bandpass_filter` to compute bandpass-filtered
+     theoretical and simulated moments,
+
+   + New option `one_sided_hp_filter` to compute one-sided HP-filtered
+     simulated moments,
+
+   + `stoch_simul` displays a simulated variance decomposition when
+     simulated moments are requested,
+
+   + `stoch_simul` saves skewness and kurtosis into respective fields
+     of `oo_` when simulated moments have been requested,
+
+   + `stoch_simul` saves the unconditional variance decomposition in
+     `oo_.variance_decomposition`,
+
+   + New option `dr_display_tol` that governs omission of small terms
+     in display of decision rules,
+
+   + The `stoch_simul` command now prints the displayed tables as LaTeX
+     code when the new `TeX` option is enabled,
+
+   + The `loglinear` option now works with lagged and leaded exogenous
+     variables like news shocks,
+
+   + New option `spectral_density` that allows displaying the spectral
+     density of (filtered) endogenous variables,
+
+   + New option `contemporaneous_correlation` that allows saving
+     contemporaneous correlations in addition to the covariances.
+
+
+ - Identification
+
+   + New options `diffuse_filter` and `prior_trunc`,
+
+   + The `identification` command now supports correlations via
+     simulated moments,
+
+
+ - Sensitivity analysis
+
+   + New blocks `irf_calibration` and `moment_calibration`,
+
+   + Outputs LaTeX tables if the new `TeX` option is used,
+
+   + New option `relative_irf` to `irf_calibration` block.
+
+
+ - Conditional forecast
+
+   + Command `conditional_forecast` now takes into account `histval`
+     block if present.
+
+
+ - Shock decomposition
+
+   + New option `colormap` to `shocks_decomposition` for controlling
+     the color map used in the shocks decomposition graphs,
+
+   + `shocks_decomposition` now accepts the `nograph` option,
+
+   + New command `realtime_shock_decomposition` that for each period `T= [presample,...,nobs]`
+     allows computing the:
+
+     * realtime historical shock decomposition `Y(t|T)`, i.e. without observing data in `[T+1,...,nobs]`
+
+     * forecast shock decomposition `Y(T+k|T)`
+
+     * realtime conditional shock decomposition `Y(T+k|T+k)-Y(T+k|T)`
+
+   + New block `shock_groups` that allows grouping shocks for the
+     `shock_decomposition` and `realtime_shock_decomposition` commands,
+
+   + New command `plot_shock_decomposition` that allows plotting the
+     results from `shock_decomposition` and
+     `realtime_shock_decomposition` for different vintages and shock
+     groupings.
+
+
+ - Macroprocessor
+
+   + Can now pass a macro-variable to the `@#include` macro directive,
+
+   + New preprocessor flag `-I`, macro directive `@#includepath`, and
+     dynare config file block `[paths]` to pass a search path to the
+     macroprocessor to be used for file inclusion via `@#include`.
+
+
+ - Command line
+
+   + New option `onlyclearglobals` (do not clear JIT compiled functions
+     with recent versions of Matlab),
+
+   + New option `minimal_workspace` to use fewer variables in the
+     current workspace,
+
+   + New option `params_derivs_order` allows limiting the order of the
+     derivatives with respect to the parameters that are calculated by
+     the preprocessor,
+
+   + New command line option `mingw` to support the MinGW-w64 C/C++
+     Compiler from TDM-GCC for `use_dll`.
+
+
+ - dates/dseries/reporting classes
+
+   + New methods `abs`, `cumprod` and `chain`,
+
+   + New option `tableRowIndent` to `addTable`,
+
+   + Reporting system revamped and made more efficient, dependency on
+     matlab2tikz has been dropped.
+
+
+ - Optimization algorithms
+
+   + `mode_compute=2` Uses the simulated annealing as described by
+     Corana et al. (1987),
+
+   + `mode_compute=101` Uses SOLVEOPT as described by Kuntsevich and
+     Kappel (1997),
+
+   + `mode_compute=102` Uses `simulannealbnd` from Matlab's Global
+     Optimization Toolbox (if available),
+
+   + New option `silent_optimizer` to shut off output from mode
+     computing/optimization,
+
+   + New options `verbosity` and `SaveFiles` to control output and
+     saving of files during mode computing/optimization.
+
+
+ - LaTeX output
+
+   + New command `write_latex_original_model`,
+
+   + New option `write_equation_tags` to `write_latex_dynamic_model`
+     that allows printing the specified equation tags to the generate
+     LaTeX code,
+
+   + New command `write_latex_parameter_table` that writes the names and
+     values of model parameters to a LaTeX table,
+
+   + New command `write_latex_prior_table` that writes the descriptive
+     statistics about the prior distribution to a LaTeX table,
+
+   + New command `collect_latex_files` that creates one compilable LaTeX
+     file containing all TeX-output.
+
+
+ - Misc.
+
+   + Provides 64bit preprocessor,
+
+   + Introduces new path management to avoid conflicts with other
+     toolboxes,
+
+   + Full compatibility with Matlab 2014b's new graphic interface,
+
+   + When using `model(linear)`, Dynare automatically checks
+     whether the model is truly linear,
+
+   + `usedll`, the `msvc` option now supports `normcdf`, `acosh`,
+     `asinh`, and `atanh`,
+
+   + New parallel option `NumberOfThreadsPerJob` for Windows nodes that
+     sets the number of threads assigned to each remote MATLAB/Octave
+     run,
+
+   + Improved numerical performance of
+     `schur_statespace_transformation` for very large models,
+
+   + The `all_values_required` option now also works with `histval`,
+
+   + Add missing `horizon` option to `ms_forecast`,
+
+   + BVAR now saves the marginal data density in
+     `oo_.bvar.log_marginal_data_density` and stores prior and
+     posterior information in `oo_.bvar.prior` and
+     `oo_.bvar.posterior`.
+
+
+
+* Bugs and problems identified in version 4.4.3 and that have been fixed in version 4.5.0:
+
+
+ - BVAR models
+
+   + `bvar_irf` could display IRFs in an unreadable way when they moved from
+     negative to positive values,
+
+   + In contrast to what is stated in the documentation, the confidence interval
+     size `conf_sig` was 0.6 by default instead of 0.9.
+
+
+ - Conditional forecasts
+
+   + The `conditional_forecast` command produced wrong results in calibrated
+     models when used at initial values outside of the steady state (given with
+     `initval`),
+
+   + The `plot_conditional_forecast` option could produce unreadable figures if
+     the areas overlap,
+
+   + The `conditional_forecast` command after MLE crashed,
+
+   + In contrast to what is stated in the manual, the confidence interval size
+     `conf_sig` was 0.6 by default instead of 0.8.
+
+   + Conditional forecasts were wrong when the declaration of endogenous
+     variables was not preceeding the declaration of the exogenous
+     variables and parameters.
+
+
+ - Discretionary policy
+
+   + Dynare allowed running models where the number of instruments did not match
+     the number of omitted equations,
+
+   + Dynare could crash in some cases when trying to display the solution,
+
+   + Parameter dependence embedded via a `steady_state` was not taken into
+     account, typically resulting in crashes.
+
+ - dseries class
+
+   + When subtracting a dseries object from a number, the number was instead
+     subtracted from the dseries object.
+
+
+ - DSGE-VAR models
+
+   + Dynare crashed when estimation encountered non-finite values in the Jacobian
+     at the steady state,
+
+   + The presence of a constant was not considered for degrees of freedom
+     computation of the Gamma function used during the posterior computation; due
+     to only affecting the constant term, results should be be unaffected, except
+     for model_comparison when comparing models with and without.
+
+
+ - Estimation command
+
+   + In contrast to what was stated in the manual, the confidence interval size
+     `conf_sig` for `forecast` without MCMC was 0.6 by default instead of 0.9,
+
+   + Calling estimation after identification could lead to crashes,
+
+   + When using recursive estimation/forecasting and setting some elements of
+     `nobs` to be larger than the number of observations T in the data,
+     `oo_recursive_` contained additional cell entries that simply repeated the
+     results obtained for `oo_recursive_T`,
+
+   + Computation of Bayesian smoother could crash for larger models when
+     requesting `forecast` or `filtered_variables`,
+
+   + Geweke convergence diagnostics were not computed on the full MCMC chain when
+     the `load_mh_file` option was used,
+
+   + The Geweke convergence diagnostics always used the default `taper_steps` and
+   `geweke_interval`,
+
+   + Bayesian IRFs (`bayesian_irfs` option) could be displayed in an unreadable
+     way when they move from negative to positive values,
+
+   + If `bayesian_irfs` was requested when `mh_replic` was too low to compute
+     HPDIs, plotting was crashing,
+
+   + The x-axis value in `oo_.prior_density` for the standard deviation and
+     correlation of measurement errors was written into a field
+     `mearsurement_errors_*` instead of `measurement_errors_*`,
+
+   + Using a user-defined `mode_compute` crashed estimation,
+
+   + Option `mode_compute=10` did not work with infinite prior bounds,
+
+   + The posterior variances and covariances computed by `moments_varendo` were
+     wrong for very large models due to a matrix erroneously being filled up with
+     zeros,
+
+   + Using the `forecast` option with `loglinear` erroneously added the unlogged
+     steady state,
+
+   + When using the `loglinear` option the check for the presence of a constant
+     was erroneously based on the unlogged steady state,
+
+   + Estimation of `observation_trends` was broken as the trends specified as a
+     function of deep parameters were not correctly updated during estimation,
+
+   + When using `analytic_derivation`, the parameter values were not set before
+     testing whether the steady state file changes parameter values, leading to
+     subsequent crashes,
+
+   + If the steady state of an initial parameterization did not solve, the
+     observation equation could erroneously feature no constant when the
+     `use_calibration` option was used,
+
+   + When computing posterior moments, Dynare falsely displayed that moment
+     computations are skipped, although the computation was performed correctly,
+
+   + If `conditional_variance_decomposition` was requested, although all
+     variables contain unit roots, Dynare crashed instead of providing an error
+     message,
+
+   + Computation of the posterior parameter distribution was erroneously based
+     on more draws than specified (there was one additional draw for every Markov
+     chain),
+
+   + The estimation option `lyapunov=fixed_point` was broken,
+
+   + Computation of `filtered_vars` with only one requested step crashed Dynare,
+
+   + Option `kalman_algo=3` was broken with non-diagonal measurement error,
+
+   + When using the diffuse Kalman filter with missing observations, an additive
+     factor log(2*pi) was missing in the last iteration step,
+
+   + Passing of the `MaxFunEvals` and `InitialSimplexSize` options to
+     `mode_compute=8` was broken,
+
+   + Bayesian forecasts contained initial conditions and had the wrong length in
+     both plots and stored variables,
+
+   + Filtered variables obtained with `mh_replic=0`, ML, or
+     `calibrated_smoother` were padded with zeros at the beginning and end and
+     had the wrong length in stored variables,
+
+   + Computation of smoothed measurement errors in Bayesian estimation was broken,
+
+   + The `selected_variables_only` option (`mh_replic=0`, ML, or
+     `calibrated_smoother`) returned wrong results for smoothed, updated, and
+     filtered variables,
+
+   + Combining the `selected_variables_only` option with forecasts obtained
+     using `mh_replic=0`, ML, or `calibrated_smoother` leaded to crashes,
+
+   + `oo_.UpdatedVariables` was only filled when the `filtered_vars` option was specified,
+
+   + When using Bayesian estimation with `filtered_vars`, but without
+     `smoother`, then `oo_.FilteredVariables` erroneously also contained filtered
+     variables at the posterior mean as with `mh_replic=0`,
+
+   + Running an MCMC a second time in the same folder with a different number of
+     iterations could result in crashes due to the loading of stale files,
+
+   + Results displayed after Bayesian estimation when not specifying
+     the `smoother` option were based on the parameters at the mode
+     from mode finding instead of the mean parameters from the
+     posterior draws. This affected the smoother results displayed, but
+     also calls to subsequent command relying on the parameters stored
+     in `M_.params` like `stoch_simul`,
+
+   + The content of `oo_.posterior_std` after Bayesian estimation was based on
+     the standard deviation at the posterior mode, not the one from the MCMC, this
+     was not consistent with the reference manual,
+
+   + When the initialization of an MCMC run failed, the metropolis.log file was
+     locked, requiring a restart of Matlab to restart estimation,
+
+   + If the posterior mode was right at the corner of the prior bounds, the
+     initialization of the MCMC erroneously crashed,
+
+   + If the number of dropped draws via `mh_drop` coincided with the number of
+     draws in a `_mh'-file`, `oo_.posterior.metropolis.mean` and
+     `oo_.posterior.metropolis.Variance` were NaN.
+
+
+ - Estimation and calibrated smoother
+
+   + When using `observation_trends` with the `prefilter` option, the mean shift
+     due to the trend was not accounted for,
+
+   + When using `first_obs`>1, the higher trend starting point of
+     `observation_trends` was not taken into account, leading, among other things,
+     to problems in recursive forecasting,
+
+   + The diffuse Kalman smoother was crashing if the forecast error variance
+     matrix becomes singular,
+
+   + The multivariate Kalman smoother provided incorrect state estimates when
+     all data for one observation are missing,
+
+   + The multivariate diffuse Kalman smoother provided incorrect state estimates
+     when the `Finf` matrix becomes singular,
+
+   + The univariate diffuse Kalman filter was crashing if the initial covariance
+     matrix of the nonstationary state vector is singular,
+
+
+ - Forecats
+
+   + In contrast to what is stated in the manual, the confidence interval size
+     `conf_sig` was 0.6 by default instead of 0.9.
+
+   + Forecasting with exogenous deterministic variables provided wrong decision
+     rules, yielding wrong forecasts.
+
+   + Forecasting with exogenous deterministic variables crashed when the
+     `periods` option was not explicitly specified,
+
+   + Option `forecast` when used with `initval` was using the initial values in
+     the `initval` block and not the steady state computed from these initial
+     values as the starting point of forecasts.
+
+
+ - Global Sensitivity Analysis
+
+   + Sensitivity with ML estimation could result in crashes,
+
+   + Option `mc` must be forced if `neighborhood_width` is used,
+
+   + Fixed dimension of `stock_logpo` and `stock_ys`,
+
+   + Incomplete variable initialization could lead to crashes with `prior_range=1`.
+
+
+ - Indentification
+
+   + Identification did not correctly pass the `lik_init` option,
+     requiring the manual setting of `options_.diffuse_filter=1` in
+     case of unit roots,
+
+   + Testing identification of standard deviations as the only
+     parameters to be estimated with ML leaded to crashes,
+
+   + Automatic increase of the lag number for autocovariances when the
+     number of parameters is bigger than the number of non-zero moments
+     was broken,
+
+   + When using ML, the asymptotic Hessian was not computed,
+
+   + Checking for singular values when the eigenvectors contained only
+     one column did not work correctly,
+
+
+ - Model comparison
+
+   + Selection of the `modifiedharmonicmean` estimator was broken,
+
+
+ - Optimal Simple Rules
+
+   + When covariances were specified, variables that only entered with
+     their variance and no covariance term obtained a wrong weight,
+     resulting in wrong results,
+
+   + Results reported for stochastic simulations after `osr` were based
+     on the last parameter vector encountered during optimization,
+     which does not necessarily coincide with the optimal parameter
+     vector,
+
+   + Using only one (co)variance in the objective function resulted in crashes,
+
+   + For models with non-stationary variables the objective function was computed wrongly.
+
+
+ - Ramsey policy
+
+   + If a Lagrange multiplier appeared in the model with a lead or a lag
+     of more than one period, the steady state could be wrong.
+
+   + When using an external steady state file, incorrect steady states
+     could be accepted,
+
+   + When using an external steady state file with more than one
+     instrument, Dynare crashed,
+
+   + When using an external steady state file and running `stoch_simul`
+     after `ramsey_planner`, an incorrect steady state was used,
+
+   + When the number of instruments was not equal to the number of
+     omitted equations, Dynare crashed with a cryptic message,
+
+   + The `planner_objective` accepted `varexo`, but ignored them for computations,
+
+
+ - Shock decomposition
+
+   + Did not work with the `parameter_set=calibration` option if an
+     `estimated_params` block is present,
+
+   + Crashed after MLE.
+
+
+ - Perfect foresight models
+
+   + The perfect foresight solver could accept a complex solution
+     instead of continuing to look for a real-valued one,
+
+   + The `initval_file` command only accepted column and not row vectors,
+
+   + The `initval_file` command did not work with Excel files,
+
+   + Deterministic simulations with one boundary condition crashed in
+     `solve_one_boundary` due to a missing underscore when passing
+     `options_.simul.maxit`,
+
+   + Deterministic simulation with exogenous variables lagged by more
+     than one period crashed,
+
+   + Termination criterion `maxit` was hard-coded for `solve_algo=0`
+     and could no be changed,
+
+   + When using `block`/`bytecode`, relational operators could not be enforced,
+
+   + When using `block` some exceptions were not properly handled,
+     leading to code crashes,
+
+   + Using `periods=1` crashed the solver (bug only partially fixed).
+
+
+ - Smoothing
+
+   + The univariate Kalman smoother returned wrong results when used
+     with correlated measurement error,
+
+   + The diffuse smoother sometimes returned linear combinations of the
+     smoothed stochastic trend estimates instead of the original trend
+     estimates.
+
+ - Perturbation reduced form
+
+   + In contrast to what is stated in the manual, the results of the
+     unconditional variance decomposition were only stored in
+     `oo_.gamma_y(nar+2)`, not in `oo_.variance_decomposition`,
+
+   + Dynare could crash when the steady state could not be computed
+     when using the `loglinear` option,
+
+   + Using `bytcode` when declared exogenous variables were not
+     used in the model leaded to crashes in stochastic simulations,
+
+   + Displaying decision rules involving lags of auxiliary variables of
+     type 0 (leads>1) crashed.
+
+   + The `relative_irf` option resulted in wrong output at `order>1` as
+     it implicitly relies on linearity.
+
+
+ - Displaying of the MH-history with the `internals` command crashed
+   if parameter names did not have same length.
+
+ - Dynare crashed when the user-defined steady state file returned an
+   error code, but not an conformable-sized steady state vector.
+
+ - Due to a bug in `mjdgges.mex` unstable parameter draws with
+   eigenvalues up to 1+1e-6 could be accepted as stable for the
+   purpose of the Blanchard-Kahn conditions, even if `qz_criterium<1`.
+
+ - The `use_dll` option on Octave for Windows required to pass a
+   compiler flag at the command line, despite the manual stating this
+   was not necessary.
+
+ - Dynare crashed for models with `block` option if the Blanchard-Kahn
+   conditions were not satisfied instead of generating an error
+   message.
+
+ - The `verbose` option did not work with `model(block)`.
+
+ - When falsely specifying the `model(linear)` for nonlinear models,
+   incorrect steady states were accepted instead of aborting.
+
+ - The `STEADY_STATE` operator called on model local variables
+   (so-called pound variables) did not work as expected.
+
+ - The substring operator in macro-processor was broken. The
+   characters of the substring could be mixed with random characters
+   from the memory space.
+
+ - Block decomposition could sometimes cause the preprocessor to crash.
+
+ - A bug when external functions were used in model local variables
+   that were contained in equations that required auxiliary
+   variable/equations led to crashes of Matlab.
+
+ - Sampling from the prior distribution for an inverse gamma II
+   distribution when `prior_trunc>0` could result in incorrect
+   sampling.
+
+ - Sampling from the prior distribution for a uniform distribution
+   when `prior_trunc>0` was ignoring the prior truncation.
+
+ - Conditional forecasts were wrong when the declaration of endogenous
+   variables was not preceeding the declaration of the exogenous
+   variables and parameters.
+
+
+
 Announcement for Dynare 4.4.3 (on 2014-07-31)
 =============================================
 
@@ -988,7 +1785,7 @@ Here is a list of the main bugfixes since version 4.2.0:
 
  * Option `conditional_variance_decomposition' of `stoch_simul' and
    `estimation' has been fixed
- 
+
  * Automatic detrending now works in conjunction with the `EXPECTATION'
    operator
 
@@ -1029,7 +1826,7 @@ This release is compatible with MATLAB versions ranging from 6.5 (R13) to 7.11
 
 Here is the list of major user-visible changes:
 
-* New solution algorithms: 
+* New solution algorithms:
 
   - Pruning for second order simulations has been added, as described in Kim,
     Kim, Schaumburg and Sims (2008) [1,2]
@@ -1066,7 +1863,7 @@ Here is the list of major user-visible changes:
 
   - Syntax of deterministic shocks has changed: after the values keyword,
     arbitrary expressions must be enclosed within parentheses (but numeric
-    constants are still accepted as is) 
+    constants are still accepted as is)
 
 * Various improvements:
 
@@ -1095,7 +1892,7 @@ Here is the list of major user-visible changes:
     from the console, it will replace graphical waitbars by text waitbars for
     long computations
 
-  - Steady option "solve_algo=0" (uses fsolve()) now works under Octave 
+  - Steady option "solve_algo=0" (uses fsolve()) now works under Octave
 
 * For Emacs users:
 
diff --git a/README.md b/README.md
index 202ed7d5b1c08c24823a9fb2d6396612919b135b..0a19dc9975bcddb05445974582def8167e8c5a1c 100644
--- a/README.md
+++ b/README.md
@@ -91,7 +91,7 @@ If you have downloaded the sources from an official source archive or the source
 
 If you want to use Git, do the following from a terminal:
 
-    git clone --recursive http://github.com/DynareTeam/dynare.git
+    git clone --recursive https://github.com/DynareTeam/dynare.git
     cd dynare
     autoreconf -si
 
@@ -303,7 +303,7 @@ After this, prepare the source and configure the build tree as described for Lin
 - **NB**: If not compiling Dynare mex files for Octave, add ```--without-octave``` to the installation command
 - **NB**: To compile the latest stable version of dynare, follow the same instructions as above, omitting the ```--HEAD``` argument
 - **NB**: To update a ```--HEAD``` install of dynare you need to uninstall it then install it again: ```brew uninstall dynare; brew install dynare --HEAD```.
-- **NB**: If you want to maintain a separate git directory of dynare, you can do a ```--HEAD``` install of dynare, then uninstall it. This will have the effect of bringing in all the dependencies you will need to then compile dynare from your git directory. Then, change to the git directory and type:
+- **NB**: If you want to maintain a separate git directory of dynare, you can do a ```--HEAD``` install of dynare, then uninstall it. This will have the effect of bringing in all the dependencies you will need to then compile dynare from your git directory. (For `flex` and `bison` it may be necessary to symlink them via `brew link bison --force` and `brew link flex --force` as they are keg-only). Then, change to the git directory and type:
     - ```autoreconf -si; ./configure --with-matlab=/Applications/MATLAB_R2015a.app MATLAB_VERSION=R2015a```, adjusting the Matlab path and version to accord with your version
 - Once compilation is done, open Matlab and type the last line shown when you type ```brew info dynare``` in the Terminal window. With the typical Homebrew setup, this is:
     - ```addpath /usr/local/opt/dynare/lib/dynare/matlab```
diff --git a/VERSION.in b/VERSION.in
new file mode 100644
index 0000000000000000000000000000000000000000..7b4f3f3a02cc308fc5cdf8dba56ceddf2a8fa80f
--- /dev/null
+++ b/VERSION.in
@@ -0,0 +1 @@
+@PACKAGE_VERSION@
\ No newline at end of file
diff --git a/configure.ac b/configure.ac
index a29888519ddb471564857f2f9980f0b44104e858..4ddf926825486fb27fc50158a3d2afd1510ac219 100755
--- a/configure.ac
+++ b/configure.ac
@@ -18,7 +18,7 @@ dnl You should have received a copy of the GNU General Public License
 dnl along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 AC_PREREQ([2.62])
-AC_INIT([dynare], [4.5-unstable])
+AC_INIT([dynare], [4.6-unstable])
 AC_CONFIG_SRCDIR([preprocessor/DynareMain.cc])
 AM_INIT_AUTOMAKE([1.11 -Wall -Wno-portability foreign no-dist-gzip dist-xz tar-pax])
 
@@ -172,6 +172,7 @@ esac
 AX_PTHREAD
 
 AC_CONFIG_FILES([Makefile
+                 VERSION
                  preprocessor/macro/Makefile
                  preprocessor/Makefile
                  doc/Makefile
diff --git a/doc/bvar-a-la-sims.tex b/doc/bvar-a-la-sims.tex
index 07af9fb77cec737cad4e4b41f24273c98f3a0e1c..b58b83b75e431e7ee71832b94a1d97074db406e6 100644
--- a/doc/bvar-a-la-sims.tex
+++ b/doc/bvar-a-la-sims.tex
@@ -12,7 +12,7 @@
 \begin{document}
 
 \title{BVAR models ``\`a la Sims'' in Dynare\thanks{Copyright \copyright~2007--2015 S\'ebastien
-    Villemot; \copyright~2016 S\'ebastien
+    Villemot; \copyright~2016--2017 S\'ebastien
     Villemot and Johannes Pfeifer. Permission is granted to copy, distribute and/or modify
     this document under the terms of the GNU Free Documentation
     License, Version 1.3 or any later version published by the Free
@@ -26,8 +26,8 @@
   }}
 
 \author{S\'ebastien Villemot\thanks{Paris School of Economics and
-    CEPREMAP.} \and Johannes Pfeifer\thanks{University of Mannheim. E-mail: \href{mailto:pfeifer@uni-mannheim.de}{\texttt{pfeifer@uni-mannheim.de}}.}}
-\date{First version: September 2007 \hspace{1cm} This version: October 2016}
+    CEPREMAP.} \and Johannes Pfeifer\thanks{University of Cologne. E-mail: \href{mailto:jpfeifer@uni-koeln.de}{\texttt{jpfeifer@uni-koeln.de}}.}}
+\date{First version: September 2007 \hspace{1cm} This version: May 2017}
 
 \maketitle
 
@@ -545,7 +545,7 @@ Most results are stored for future use:
 The syntax for computing impulse response functions is:
 
 \medskip
-\texttt{bvar\_irf(}\textit{number\_of\_periods},\textit{identification\_scheme}\texttt{);}
+\texttt{bvar\_irf(}\textit{number\_of\_lags},\textit{identification\_scheme}\texttt{);}
 \medskip
 
 The \textit{identification\_scheme} option has two potential values
@@ -556,7 +556,25 @@ The \textit{identification\_scheme} option has two potential values
 
 Keep in mind that the first factorization of the covariance matrix is sensible to the ordering of the variables (as declared in the mod file with \verb+var+). This is not the case of the second factorization, but its structural interpretation is, at best, unclear (the Matrix square root of a covariance matrix, $\Sigma$, is the unique symmetric matrix $A$ such that $\Sigma = AA$).\newline
 
-The mean, median, variance and confidence intervals for IRFs are saved in \texttt{oo\_.bvar.irf}
+If you want to change the length of the IRFs plotted by the command, you can put\\
+
+\medskip
+\texttt{options\_.irf=40;}\\
+\medskip
+
+before the \texttt{bvar\_irf}-command. Similarly, to change the coverage of the highest posterior density intervals to e.g. 60\% you can put the command\\
+
+\medskip
+\texttt{options\_.bvar.conf\_sig=0.6;}\\
+\medskip
+
+there.\newline
+
+
+The mean, median, variance, and confidence intervals for IRFs are saved in \texttt{oo\_.bvar.irf}
+
+
+
 
 \section{Examples}
 
diff --git a/doc/dynare.texi b/doc/dynare.texi
index 0dc42dacf707f90093a70845819b3d36fffe2de7..e244eafb289c5983bb430c0b5f3fa68ae8e7fdef 100644
--- a/doc/dynare.texi
+++ b/doc/dynare.texi
@@ -2,6 +2,8 @@
 @c %**start of header
 @setfilename dynare.info
 @documentencoding UTF-8
+@set txicodequoteundirected
+
 @settitle Dynare Reference Manual
 @afourwide
 @dircategory Math
@@ -112,8 +114,8 @@ A copy of the license can be found at @uref{http://www.gnu.org/licenses/fdl.txt}
 @subtitle Reference Manual, version @value{VERSION}
 @author Stéphane Adjemian
 @author Houtan Bastani
-@author Frédéric Karamé
 @author Michel Juillard
+@author Frédéric Karamé
 @author Junior Maih
 @author Ferhat Mihoubi
 @author George Perendia
@@ -169,14 +171,14 @@ Installation of Dynare
 
 * On Windows::
 * On Debian GNU/Linux and Ubuntu::
-* On Mac OS X::
+* On macOS::
 * For other systems::
 
 Compiler installation
 
 * Prerequisites on Windows::
 * Prerequisites on Debian GNU/Linux and Ubuntu::
-* Prerequisites on Mac OS X::
+* Prerequisites on macOS::
 
 Configuration
 
@@ -206,6 +208,9 @@ The Model file
 * Deterministic simulation::
 * Stochastic solution and simulation::
 * Estimation::
+* Model Comparison::
+* Shock Decomposition::
+* Calibrated Smoother::
 * Forecasting::
 * Optimal policy::
 * Sensitivity and identification analysis::
@@ -345,23 +350,21 @@ as a support tool for forecasting exercises. In the academic world,
 Dynare is used for research and teaching purposes in postgraduate
 macroeconomics courses.
 
-Dynare is a free software, which means that it can be downloaded free
-of charge, that its source code is freely available, and that it can
-be used for both non-profit and for-profit purposes. Most of the
-source files are covered by the GNU General Public Licence (GPL)
-version 3 or later (there are some exceptions to this, see the file
-@file{license.txt} in Dynare distribution). It is available for the
-Windows, Mac and Linux platforms and is fully documented through a
-user guide and a reference manual. Part of Dynare is programmed in
-C++, while the rest is written using the
-@uref{http://www.mathworks.com/products/matlab/, MATLAB} programming
-language.  The latter implies that commercially-available MATLAB
-software is required in order to run Dynare. However, as an
-alternative to MATLAB, Dynare is also able to run on top of
-@uref{http://www.octave.org, GNU Octave} (basically a free clone of
-MATLAB): this possibility is particularly interesting for students or
-institutions who cannot afford, or do not want to pay for, MATLAB and
-are willing to bear the concomitant performance loss.
+Dynare is a free software, which means that it can be downloaded free of
+charge, that its source code is freely available, and that it can be used for
+both non-profit and for-profit purposes. Most of the source files are covered
+by the GNU General Public Licence (GPL) version 3 or later (there are some
+exceptions to this, see the file @file{license.txt} in Dynare distribution). It
+is available for the Windows, macOS, and Linux platforms and is fully
+documented through a user guide and a reference manual. Part of Dynare is
+programmed in C++, while the rest is written using the
+@uref{http://www.mathworks.com/products/matlab/, MATLAB} programming language.
+The latter implies that commercially-available MATLAB software is required in
+order to run Dynare. However, as an alternative to MATLAB, Dynare is also able
+to run on top of @uref{http://www.octave.org, GNU Octave} (basically a free
+clone of MATLAB): this possibility is particularly interesting for students or
+institutions who cannot afford, or do not want to pay for, MATLAB and are
+willing to bear the concomitant performance loss.
 
 The development of Dynare is mainly done at
 @uref{http://www.cepremap.fr, Cepremap} by a core team of
@@ -371,7 +374,7 @@ Adjemian (Université du Maine, Gains and Cepremap), Houtan Bastani
 (Cepremap), Michel Juillard (Banque de France), Frédéric Karamé
 (Université du Maine, Gains and Cepremap), Junior Maih (Norges Bank),
 Ferhat Mihoubi (Université Paris-Est Créteil, Epee and Cepremap), George
-Perendia, Johannes Pfeifer (University of Mannheim), Marco Ratto (European Commission, Joint Research Centre - JRC)
+Perendia, Johannes Pfeifer (University of Cologne), Marco Ratto (European Commission, Joint Research Centre - JRC)
 and Sébastien Villemot (OFCE – Sciences Po).
 Increasingly, the developer base is expanding, as tools developed by
 researchers outside of Cepremap are integrated into Dynare. Financial
@@ -439,7 +442,7 @@ If you want to give a URL, use the address of the Dynare website:
 
 Packaged versions of Dynare are available for Windows XP/Vista/7/8,
 @uref{http://www.debian.org,Debian GNU/Linux},
-@uref{http://www.ubuntu.com/,Ubuntu} and Mac OS X 10.8 or later.  Dynare should
+@uref{http://www.ubuntu.com/,Ubuntu} and macOS 10.8 or later.  Dynare should
 work on other systems, but some compilation steps are necessary in that case.
 
 In order to run Dynare, you need one of the following:
@@ -447,7 +450,7 @@ In order to run Dynare, you need one of the following:
 @itemize
 
 @item
-MATLAB version 7.5 (R2007b) or above (MATLAB R2009b 64-bit for Mac OS X);
+MATLAB version 7.5 (R2007b) or above (MATLAB R2009b 64-bit for macOS);
 
 @item
 GNU Octave version 3.6 or above.
@@ -470,10 +473,6 @@ If under GNU Octave, the following
 @uref{http://octave.sourceforge.net/,Octave-Forge} packages: optim,
 io, statistics, control.
 
-@item 
-Mac OS X Octave users will also need to install
-gnuplot if they want graphing capabilities.
-
 @end itemize
 
 
@@ -490,7 +489,7 @@ about your own files.
 @menu
 * On Windows::
 * On Debian GNU/Linux and Ubuntu::
-* On Mac OS X::
+* On macOS::
 * For other systems::
 @end menu
 
@@ -521,25 +520,29 @@ Wiki} for detailed instructions.
 Dynare will be installed under @file{/usr/lib/dynare}. Documentation will be
 under @file{/usr/share/doc/dynare-doc}.
 
-@node On Mac OS X
-@subsection On Mac OS X
-
-Execute the automated installer called
-@file{dynare-4.@var{x}.@var{y}.pkg} (where
-4.@var{x}.@var{y} is the version number), and follow the
-instructions. The default installation directory is
-@file{/Applications/Dynare/4.@var{x}.@var{y}}.
+@node On macOS
+@subsection On macOS
 
-Please refer to the
+To install Dynare for use with Matlab, execute the automated installer called
+@file{dynare-4.@var{x}.@var{y}.pkg} (where 4.@var{x}.@var{y} is the version
+number), and follow the instructions. The default installation directory is
+@file{/Applications/Dynare/4.@var{x}.@var{y}} (please refer to the
 @uref{http://www.dynare.org/DynareWiki/InstallOnMacOSX,Dynare Wiki} for
-detailed instructions.
+detailed instructions).
 
 After installation, this directory will contain several sub-directories,
 among which are @file{matlab}, @file{mex} and @file{doc}.
 
-Note that you can have several versions of Dynare coexisting (for
-example in @file{/Applications/Dynare}), as long as you correctly
-adjust your path settings (@pxref{Some words of warning}).
+Note that several versions of Dynare can coexist (by default in
+@file{/Applications/Dynare}), as long as you correctly adjust your path
+settings (@pxref{Some words of warning}).
+
+To install Dynare for Octave, first install Homebrew following the instructions
+on their site: @uref{https://brew.sh/}. Then install Octave, issuing the
+command @code{brew install octave} at the Terminal prompt. You can then install
+the latest stable version of Dynare by typing @code{brew install dynare} at the
+Terminal prompt. You can also pass options to the installation command. These
+options can be viewed by typing @code{brew info dynare} at the Terminal prompt.
 
 @node For other systems
 @subsection For other systems
@@ -568,7 +571,7 @@ Octave comes with built-in functionality for compiling mex-files.
 @menu
 * Prerequisites on Windows::
 * Prerequisites on Debian GNU/Linux and Ubuntu::
-* Prerequisites on Mac OS X::
+* Prerequisites on macOS::
 @end menu
 
 @node Prerequisites on Windows
@@ -596,9 +599,9 @@ it can be installed via @code{apt-get install build-essential}.
 Users of Octave under Linux should install the package for MEX file compilation 
 (under Debian or Ubuntu, it is called @file{liboctave-dev}).
 
-@node Prerequisites on Mac OS X
-@subsection Prerequisites on Mac OS X
-If you are using MATLAB under Mac OS X, you should install the latest
+@node Prerequisites on macOS
+@subsection Prerequisites on macOS
+If you are using MATLAB under macOS, you should install the latest
 version of XCode: see
 @uref{http://www.dynare.org/DynareWiki/InstallOnMacOSX,instructions on
 the Dynare wiki}.
@@ -638,7 +641,7 @@ Under Debian GNU/Linux or Ubuntu, type:
 addpath /usr/lib/dynare/matlab
 @end example
 
-Under Mac OS X, assuming that you have installed Dynare in the standard
+Under macOS, assuming that you have installed Dynare in the standard
 location, and replacing @code{4.@var{x}.@var{y}} with the correct version
 number, type:
 
@@ -653,7 +656,7 @@ will have to do it again.
 Via the menu entries:
 
 Select the ``Set Path'' entry in the ``File'' menu, then click on
-``Add Folder@dots{}'', and select the @file{matlab} subdirectory of your
+``Add Folder@dots{}'', and select the @file{matlab} subdirectory of `your
 Dynare installation. Note that you @emph{should not} use ``Add with
 Subfolders@dots{}''. Apply the settings by clicking on ``Save''. Note that
 MATLAB will remember this setting next time you run it.
@@ -677,18 +680,16 @@ addpath c:\dynare\4.@var{x}.@var{y}\matlab
 Under Debian GNU/Linux or Ubuntu, there is no need to use the
 @code{addpath} command; the packaging does it for you.
 
-Under Mac OS X, assuming that you have installed Dynare in the
-standard location, and replacing ``4.@var{x}.@var{y}'' with the correct
-version number, type:
+Under macOS, assuming that you have installed Dynare and Octave via Homebrew, type:
 
 @example
-addpath /Applications/Dynare/4.@var{x}.@var{y}/matlab
+addpath /usr/local/opt/dynare/lib/dynare/matlab
 @end example
 
 If you don't want to type this command every time you run Octave, you
 can put it in a file called @file{.octaverc} in your home directory
 (under Windows this will generally be @file{c:\Documents and
-Settings\USERNAME\} while under Mac OS X it is @file{/Users/USERNAME/}).
+Settings\USERNAME\} while under macOS it is @file{/Users/USERNAME/}).
 This file is run by Octave at every startup.
 
 @node Some words of warning
@@ -1065,6 +1066,9 @@ end of line one and the parser would continue processing.
 * Deterministic simulation::
 * Stochastic solution and simulation::
 * Estimation::
+* Model Comparison::
+* Shock Decomposition::
+* Calibrated Smoother::
 * Forecasting::
 * Optimal policy::
 * Sensitivity and identification analysis::
@@ -1104,6 +1108,10 @@ mutually exclusive arguments are separated by vertical bars: @samp{|};
 @item
 @var{INTEGER} indicates an integer number;
 
+@item
+@var{INTEGER_VECTOR} indicates a vector of integer numbers separated by spaces,
+enclosed by square brackets;
+
 @item
 @var{DOUBLE} indicates a double precision number. The following syntaxes
 are valid: @code{1.1e3}, @code{1.1E3}, @code{1.1d3}, @code{1.1D3}. In
@@ -2085,6 +2093,7 @@ Compiling the @TeX{} file requires the following @LaTeX{} packages:
 @anchor{write_latex_dynamic_model}
 
 @deffn Command write_latex_dynamic_model ;
+@deffnx Command write_latex_dynamic_model (@var{OPTIONS}) ;
 
 @descriptionhead
 
@@ -2131,6 +2140,16 @@ also have been replaced by new auxiliary variables and equations.
 
 For the required @LaTeX{} packages, @pxref{write_latex_original_model}.
 
+@optionshead
+
+@table @code
+
+@item write_equation_tags
+Write the equation tags in the @LaTeX{} output. NB: the equation tags will be
+interpreted with @LaTeX{} markups.
+
+@end table
+
 @end deffn
 
 @deffn Command write_latex_static_model ;
@@ -2303,7 +2322,7 @@ necessary for lagged/leaded variables, while feasible starting values are requir
 It is important to be aware that if some variables, endogenous or exogenous, are not mentioned in the
 @code{initval} block, a zero value is assumed. It is particularly important to keep 
 this in mind when specifying exogenous variables using @code{varexo} that are not allowed 
-to take on the value of zero, like e.g. TFP. 
+to take on the value of zero, like @i{e.g.} TFP.
 
 Note that if the @code{initval} block is immediately followed by a
 @code{steady} command, its semantics are slightly changed. 
@@ -2549,7 +2568,7 @@ equilibrium values.
 The fact that @code{c} at @math{t=0} and @code{k} at @math{t=201} specified in
 @code{initval} and @code{endval} are taken as given has an important
 implication for plotting the simulated vector for the endogenous
-variables, i.e. the rows of @code{oo_.endo_simul}: this vector will 
+variables, @i{i.e.} the rows of @code{oo_.endo_simul}: this vector will
 also contain the initial and terminal
 conditions and thus is 202 periods long in the example. When you specify
 arbitrary values for the initial and terminal conditions for forward- and
@@ -2626,13 +2645,18 @@ Moreover, as only states enter the recursive policy functions, all values specif
 @itemize
 
 @item
-in @ref{stoch_simul}, if the @code{periods} option is specified. Note that this only affects the starting point for the simulation, but not for the impulse response functions.
+in @ref{stoch_simul}, if the @code{periods} option is specified. Note that this
+only affects the starting point for the simulation, but not for the impulse
+response functions. When using the @ref{loglinear} option, the
+@code{histval}-block nevertheless takes the unlogged starting values.
 
 @item
-in @ref{forecast} as the initial point at which the forecasts are computed
+in @ref{forecast} as the initial point at which the forecasts are computed. When using the @ref{loglinear} option, 
+the @code{histval}-block nevertheless takes the unlogged starting values.
 
 @item
-in @ref{conditional_forecast} for a calibrated model as the initial point at which the conditional forecasts are computed
+in @ref{conditional_forecast} for a calibrated model as the initial point at which the conditional forecasts are computed.
+When using the @ref{loglinear} option, the @code{histval}-block nevertheless takes the unlogged starting values.
 
 @item 
 in @ref{Ramsey} policy, where it also specifies the values of the endogenous states at 
@@ -3463,6 +3487,7 @@ end;
 
 @deffn Command check ;
 @deffnx Command check (solve_algo = @var{INTEGER}) ;
+@anchor{check}
 
 @descriptionhead
 
@@ -3983,6 +4008,12 @@ moments. If theoretical moments are requested, the spectrum of the model solutio
 following the approach outlined in @cite{Uhlig (2001)}.
 Default: no filter.
 
+@item one_sided_hp_filter = @var{DOUBLE}
+Uses the one-sided HP filter with @math{\lambda} = @var{DOUBLE} described in @cite{Stock and Watson (1999)}
+before computing moments. This option is only available with simulated moments.
+Default: no filter.
+
+
 @item hp_ngrid = @var{INTEGER}
 Number of points in the grid for the discrete Inverse Fast Fourier
 Transform used in the HP filter computation. It may be necessary to
@@ -3997,7 +4028,7 @@ Default: no filter.
 
 @item bandpass_filter = @var{[HIGHEST_PERIODICITY LOWEST_PERIODICITY]}
 Uses a bandpass filter before computing moments. The passband is set to a periodicity of @code{HIGHEST_PERIODICITY} 
-to @code{LOWEST_PERIODICITY}, e.g. 6 to 32 quarters if the model frequency is quarterly.
+to @code{LOWEST_PERIODICITY}, @i{e.g.} @math{6} to @math{32} quarters if the model frequency is quarterly.
 Default: @code{[6,32]}.
 
 @item irf = @var{INTEGER}
@@ -4139,7 +4170,7 @@ period(s). The periods must be strictly positive. Conditional variances are give
 decomposition provides the decomposition of the effects of shocks upon
 impact. The results are stored in
 @code{oo_.conditional_variance_decomposition}
-(@pxref{oo_.conditional_variance_decomposition}). The variance decomposition is only conducted, if theoretical moments are requested, i.e. using the @code{periods=0}-option. In case of @code{order=2}, Dynare provides a second-order accurate approximation to the true second moments based on the linear terms of the second-order solution (see @cite{Kim, Kim, Schaumburg and Sims (2008)}). Note that the unconditional variance decomposition (i.e. at horizon infinity) is automatically conducted if theoretical moments are requested and if @code{nodecomposition} is not set (@pxref{oo_.variance_decomposition})
+(@pxref{oo_.conditional_variance_decomposition}). The variance decomposition is only conducted, if theoretical moments are requested, @i{i.e.} using the @code{periods=0}-option. In case of @code{order=2}, Dynare provides a second-order accurate approximation to the true second moments based on the linear terms of the second-order solution (see @cite{Kim, Kim, Schaumburg and Sims (2008)}). Note that the unconditional variance decomposition (@i{i.e.} at horizon infinity) is automatically conducted if theoretical moments are requested and if @code{nodecomposition} is not set (@pxref{oo_.variance_decomposition})
 
 @item pruning
 Discard higher order terms when iteratively computing simulations of
@@ -4367,7 +4398,7 @@ accurate approximation of the true second moments, see @code{conditional_varianc
 @anchor{oo_.variance_decomposition}
 @defvr {MATLAB/Octave variable} oo_.variance_decomposition
 After a run of @code{stoch_simul} when requesting theoretical moments (@code{periods=0}), 
-contains a matrix with the result of the unconditional variance decomposition (i.e. at horizon infinity). 
+contains a matrix with the result of the unconditional variance decomposition (@i{i.e.} at horizon infinity).
 The first dimension corresponds to the endogenous variables (in the order of declaration) and 
 the second dimension corresponds to exogenous variables (in the order of declaration). 
 Numbers are in percent and sum up to 100 across columns.
@@ -4755,7 +4786,7 @@ varobs
 
 This block specifies @emph{linear} trends for observed variables as
 functions of model parameters. In case the @code{loglinear}-option is used,
-this corresponds to a linear trend in the logged observables, i.e. an exponential
+this corresponds to a linear trend in the logged observables, @i{i.e.} an exponential
 trend in the level of the observables.
 
 Each line inside of the block should be of the form:
@@ -5091,7 +5122,7 @@ convergence is  then checked using  the @cite{Brooks and  Gelman (1998)}
 univariate convergence diagnostic.
 
 The inefficiency factors are computed as in @cite{Giordano et al. (2011)} based on 
-Parzen windows as in e.g. @cite{Andrews (1991)}.
+Parzen windows as in @i{e.g.} @cite{Andrews (1991)}.
 
 @optionshead
 
@@ -5154,9 +5185,10 @@ first observation of the rolling window.
 
 
 @item prefilter = @var{INTEGER}
-@anchor{prefilter}
-A value of @code{1} means that the estimation procedure will demean
-each data series by its empirical mean. If the (@ref{loglinear}) option without the (@ref{logdata}) option is requested, the data will first be logged and then demeaned. Default: @code{0}, @i{i.e.} no prefiltering
+@anchor{prefilter} A value of @code{1} means that the estimation procedure will
+demean each data series by its empirical mean. If the @ref{loglinear} option
+without the @ref{logdata} option is requested, the data will first be logged
+and then demeaned. Default: @code{0}, @i{i.e.} no prefiltering
 
 @item presample = @var{INTEGER}
 @anchor{presample}
@@ -5265,8 +5297,8 @@ smoothed shocks,  forecast, moments,  IRF).  The  draws used  to compute
 these posterior moments are sampled uniformly in the estimated empirical
 posterior  distribution (@i{ie}  draws of  the MCMC).   @code{sub_draws}
 should  be  smaller than  the  total  number  of MCMC  draws  available.
-Default:  @code{min(posterior_max_subsample_draws,0.25*Total  number  of
-draws)}
+Default:  @code{min(posterior_max_subsample_draws,(Total  number  of
+draws)*(number of chains))}
 
 @item posterior_max_subsample_draws = @var{INTEGER}
 @anchor{posterior_max_subsample_draws} maximum number  of draws from the
@@ -5305,11 +5337,11 @@ The scale to be used for drawing the initial value of the
 Metropolis-Hastings chain. Generally, the starting points should be overdispersed
 for the @cite{Brooks and Gelman (1998)}-convergence diagnostics to be meaningful. Default: 2*@code{mh_jscale}. 
 It is important to keep in mind that @code{mh_init_scale} is set at the beginning of 
-Dynare execution, i.e. the default will not take into account potential changes in
+Dynare execution, @i{i.e.} the default will not take into account potential changes in
 @ref{mh_jscale} introduced by either @code{mode_compute=6} or the 
 @code{posterior_sampler_options}-option @ref{scale_file}. 
 If @code{mh_init_scale} is too wide during initalization of the posterior sampler so that 100 tested draws 
-are inadmissible (e.g. Blanchard-Kahn conditions are always violated), Dynare will request user input 
+are inadmissible (@i{e.g.} Blanchard-Kahn conditions are always violated), Dynare will request user input 
 of a new @code{mh_init_scale} value with which the next 100 draws will be drawn and tested. 
 If the @ref{nointeractive}-option has been invoked, the program will instead automatically decrease 
 @code{mh_init_scale} by 10 percent after 100 futile draws and try another 100 draws. This iterative 
@@ -5507,7 +5539,7 @@ generator state of the already present draws is currently not supported.
 
 @item load_results_after_load_mh
 @anchor{load_results_after_load_mh} This option is available when loading a previous MCMC run without
-adding additional draws, i.e. when @code{load_mh_file} is specified with @code{mh_replic=0}. It tells Dynare 
+adding additional draws, @i{i.e.} when @code{load_mh_file} is specified with @code{mh_replic=0}. It tells Dynare 
 to load the previously computed convergence diagnostics, marginal data density, and posterior statistics from an
 existing @code{_results}-file instead of recomputing them.
 
@@ -5834,7 +5866,7 @@ Note that @code{'slice'} is incompatible with
 @anchor{posterior_sampler_options}
 A list of @var{NAME} and @var{VALUE} pairs. Can be used to set options for the posterior sampling methods.
 The set of available options depends on the selected posterior sampling routine 
-(i.e. on the value of option @ref{posterior_sampling_method}):
+(@i{i.e.} on the value of option @ref{posterior_sampling_method}):
 
 @table @code
 
@@ -5904,7 +5936,7 @@ mode to perform rotated slice iterations. Default: 0
 
 @item 'initial_step_size'
 Sets the initial size of the interval in the stepping-out procedure as fraction of the prior support
-i.e. the size will be initial_step_size*(UB-LB). @code{initial_step_size} must be a real number in the interval [0, 1]. 
+@i{i.e.} the size will be initial_step_size*(UB-LB). @code{initial_step_size} must be a real number in the interval [0, 1]. 
 Default: 0.8
 
 @item 'use_mh_covariance_matrix'
@@ -5976,13 +6008,13 @@ option @code{moments_varendo} to be specified.
 
 @item filtered_vars
 @anchor{filtered_vars} Triggers the computation of the posterior
-distribution of filtered endogenous variables/one-step ahead forecasts, i.e. @math{E_{t}{y_{t+1}}}. Results are
+distribution of filtered endogenous variables/one-step ahead forecasts, @i{i.e.} @math{E_{t}{y_{t+1}}}. Results are
 stored in @code{oo_.FilteredVariables} (see below for a description of
 this variable)
 
 @item smoother
 @anchor{smoother} Triggers the computation of the posterior distribution
-of smoothed endogenous variables and shocks, i.e. the expected value of variables and shocks given the information available in all observations up to the @emph{final} date (@math{E_{T}{y_t}}). Results are stored in
+of smoothed endogenous variables and shocks, @i{i.e.} the expected value of variables and shocks given the information available in all observations up to the @emph{final} date (@math{E_{T}{y_t}}). Results are stored in
 @code{oo_.SmoothedVariables}, @code{oo_.SmoothedShocks} and
 @code{oo_.SmoothedMeasurementErrors}.  Also triggers the computation of
 @code{oo_.UpdatedVariables}, which contains the estimation of the expected value of variables given the information available at the @emph{current} date (@math{E_{t}{y_t}}).  See below for a description of all these
@@ -6024,9 +6056,9 @@ Use the Univariate Diffuse Kalman Filter
 
 @end table
 @noindent
-Default value is @code{0}. In case of missing observations of single or all series, Dynare treats those missing values as unobserved states and uses the Kalman filter to infer their value (see e.g. @cite{Durbin and Koopman (2012), Ch. 4.10})
+Default value is @code{0}. In case of missing observations of single or all series, Dynare treats those missing values as unobserved states and uses the Kalman filter to infer their value (see @i{e.g.} @cite{Durbin and Koopman (2012), Ch. 4.10})
 This procedure has the advantage of being capable of dealing with observations where the forecast error variance matrix becomes singular for some variable(s).
-If this happens, the respective observation enters with a weight of zero in the log-likelihood, i.e. this observation for the respective variable(s) is dropped
+If this happens, the respective observation enters with a weight of zero in the log-likelihood, @i{i.e.} this observation for the respective variable(s) is dropped
 from the likelihood computations (for details see @cite{Durbin and Koopman (2012), Ch. 6.4 and 7.2.5} and @cite{Koopman and Durbin (2000)}). If the use of a multivariate Kalman filter is specified and a
 singularity is encountered, Dynare by default automatically switches to the univariate Kalman filter for this parameter draw. This behavior can be changed via the
 @ref{use_univariate_filters_if_singularity_is_detected} option.
@@ -6036,7 +6068,7 @@ singularity is encountered, Dynare by default automatically switches to the univ
 recursions as described by @cite{Herbst, 2015}. This setting is only used with
 @code{kalman_algo=1} or @code{kalman_algo=3}. In case of using the diffuse Kalman 
 filter (@code{kalman_algo=3/lik_init=3}), the observables must be stationary. This option 
-is not yet compatible with @code{analytical_derivation}.
+is not yet compatible with @ref{analytic_derivation}.
 
 @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}
@@ -6047,23 +6079,25 @@ is not yet compatible with @code{analytical_derivation}.
 @item filter_covariance
 @anchor{filter_covariance} Saves the series of one step ahead error of
 forecast covariance matrices. With Metropolis, they are saved in @ref{oo_.FilterCovariance},
-otherwise in @ref{oo_.Smoother.Variance}.
+otherwise in @ref{oo_.Smoother.Variance}. Saves also k-step ahead error of
+forecast covariance matrices if @code{filter_step_ahead} is set.
 
 @item filter_step_ahead = [@var{INTEGER1}:@var{INTEGER2}]
 See below.
 
 @item filter_step_ahead = [@var{INTEGER1} @var{INTEGER2}  @dots{}]
 @anchor{filter_step_ahead}
-Triggers the computation k-step ahead filtered values, i.e. @math{E_{t}{y_{t+k}}}. Stores results in
-@code{oo_.FilteredVariablesKStepAhead} and
-@code{oo_.FilteredVariablesKStepAheadVariances}.
+Triggers the computation k-step ahead filtered values, @i{i.e.} @math{E_{t}{y_{t+k}}}. Stores results in
+@code{oo_.FilteredVariablesKStepAhead}. Also stores 1-step ahead values in @code{oo_.FilteredVariables}. 
+@code{oo_.FilteredVariablesKStepAheadVariances} is stored if @code{filter_covariance}.
+ 
 
 @item filter_decomposition
 @anchor{filter_decomposition} Triggers the computation of the shock
 decomposition of the above k-step ahead filtered values. Stores results in @code{oo_.FilteredVariablesShockDecomposition}.
 
 @item smoothed_state_uncertainty
-@anchor{smoothed_state_uncertainty} Triggers the computation of the variance of smoothed estimates, i.e.
+@anchor{smoothed_state_uncertainty} Triggers the computation of the variance of smoothed estimates, @i{i.e.}
 @code{Var_T(y_t)}. Stores results in @code{oo_.Smoother.State_uncertainty}.
 
 @item diffuse_filter
@@ -6180,9 +6214,10 @@ where the model is ill-behaved. By default the original objective function is
 used.
 
 @item analytic_derivation
+@anchor{analytic_derivation}
 Triggers estimation with analytic gradient. The final hessian is also
 computed analytically. Only works for stationary models without
-missing observations.
+missing observations, i.e. for @code{kalman_algo<3}.
 
 @item ar = @var{INTEGER}
 @xref{ar}. Only useful in conjunction with option @code{moments_varendo}.
@@ -6213,10 +6248,14 @@ such a singularity is encountered. Default: @code{1}.
 With the default @ref{use_univariate_filters_if_singularity_is_detected}=1, Dynare will switch 
 to the univariate Kalman filter when it encounters a singular forecast error variance
 matrix during Kalman filtering. Upon encountering such a singularity for the first time, all subsequent
-parameter draws and computations will automatically rely on univariate filter, i.e. Dynare will never try 
+parameter draws and computations will automatically rely on univariate filter, @i{i.e.} Dynare will never try 
 the multivariate filter again. Use the @code{keep_kalman_algo_if_singularity_is_detected} option to have the 
 @code{use_univariate_filters_if_singularity_is_detected} only affect the behavior for the current draw/computation.
 
+@item rescale_prediction_error_covariance
+@anchor{rescale_prediction_error_covariance}
+Rescales the prediction error covariance in the Kalman filter to avoid badly scaled matrix and reduce the probability of a switch to univariate Kalman filters (which are slower). By default no rescaling is done.
+
 @item qz_zero_threshold = @var{DOUBLE}
 @xref{qz_zero_threshold}.
 
@@ -6325,6 +6364,22 @@ Sets the method for approximating the particle distribution. Possible values for
 @item cpf_weights = @var{OPTION}
 @anchor{cpf_weights} Controls the method used to update the weights in conditional particle filter, possible values are @code{amisanotristani} (@cite{Amisano et al (2010)}) or @code{murrayjonesparslow} (@cite{Murray et al. (2013)}). Default value is @code{amisanotristani}.
 
+@item nonlinear_filter_initialization = @var{INTEGER}
+@anchor{nonlinear_filter_initialization} Sets the initial condition of the
+nonlinear filters. By default the nonlinear filters are initialized with the
+unconditional covariance matrix of the state variables, computed with the
+reduced form solution of the first order approximation of the model. If
+@code{nonlinear_filter_initialization=2}, the nonlinear filter is instead
+initialized with a covariance matrix estimated with a stochastic simulation of
+the reduced form solution of the second order approximation of the model. Both
+these initializations assume that the model is stationary, and cannot be used
+if the model has unit roots (which can be seen with the @ref{check} command
+prior to estimation). If the model has stochastic trends, user must use
+@code{nonlinear_filter_initialization=3}, the filters are then initialized with
+an identity matrix for the covariance matrix of the state variables. Default
+value is @code{nonlinear_filter_initialization=1} (initialization based on the
+first order approximation of the model).
+
 @end table
 
 
@@ -6343,7 +6398,7 @@ It is also possible to impose implicit ``endogenous'' priors about IRFs and mome
 estimation. For example, one can specify that all valid parameter draws for the model must generate fiscal multipliers that are
 bigger than 1 by specifying how the IRF to a government spending shock must look like. The prior restrictions can be imposed
 via @code{irf_calibration} and @code{moment_calibration} blocks (@pxref{IRF/Moment calibration}). The way it works internally is that 
-any parameter draw that is inconsistent with the ``calibration'' provided in these blocks is discarded, i.e. assigned a prior density of 0. 
+any parameter draw that is inconsistent with the ``calibration'' provided in these blocks is discarded, @i{i.e.} assigned a prior density of 0. 
 When specifying these blocks, it is important to keep in mind that one won't be able to easily do @code{model_comparison} in this case, 
 because the prior density will not integrate to 1.
 
@@ -6387,7 +6442,7 @@ Upper bound of a 90% HPD interval
 @item HPDinf_ME
 Lower bound of a 90% HPD interval@footnote{See option @ref{conf_sig}
 to change the size of the HPD interval} for observables when taking 
-measurement error into account (see e.g. @cite{Christoffel et al. (2010), p.17}).
+measurement error into account (see @i{e.g.} @cite{Christoffel et al. (2010), p.17}).
 
 @item HPDsup_ME
 Upper bound of a 90% HPD interval for observables when taking 
@@ -6520,7 +6575,7 @@ indicate the respective variables. The third dimension of the array provides the
 observation for which the forecast has been made. For example, if @code{filter_step_ahead=[1 2 4]} 
 and @code{nobs=200}, the element (3,5,204) stores the four period ahead filtered 
 value of variable 5 computed at time t=200 for time t=204. The periods at the beginning 
-and end of the sample for which no forecasts can be made, e.g. entries (1,5,1) and 
+and end of the sample for which no forecasts can be made, @i{e.g.} entries (1,5,1) and 
 (1,5,204) in the example, are set to zero. Note that in case of Bayesian estimation 
 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 
@@ -6556,7 +6611,7 @@ The fourth dimension of the array provides the
 observation for which the forecast has been made. For example, if @code{filter_step_ahead=[1 2 4]} 
 and @code{nobs=200}, the element (3,5,2,204) stores the contribution of the second shock to the 
 four period ahead filtered value of variable 5 (in deviations from the mean) computed at time t=200 for time t=204. The periods at the beginning 
-and end of the sample for which no forecasts can be made, e.g. entries (1,5,1) and 
+and end of the sample for which no forecasts can be made, @i{e.g.} entries (1,5,1) and 
 (1,5,204) in the example, are set to zero. Padding with zeros and variable ordering is analogous to 
 @code{oo_.FilteredVariablesKStepAhead}. 
 @end defvr
@@ -6706,7 +6761,7 @@ Fields are of the form:
 Variable set by the @code{estimation} command (if used with the
 @code{smoother} option), or by the @code{calib_smoother} command.
 Contains the constant part of the endogenous variables used in the
-smoother, accounting e.g. for the data mean when using the @code{prefilter}
+smoother, accounting @i{e.g.} for the data mean when using the @code{prefilter}
 option.
 
 Fields are of the form:
@@ -6715,6 +6770,11 @@ Fields are of the form:
 @end example
 @end defvr
 
+@defvr {MATLAB/Octave variable} oo_.Smoother.loglinear
+Indicator keeping track of whether the smoother was run with the @ref{loglinear} option 
+and thus whether stored smoothed objects are in logs.
+@end defvr
+
 @defvr {MATLAB/Octave variable} oo_.PosteriorTheoreticalMoments
 @anchor{oo_.PosteriorTheoreticalMoments}
 Variable set by the @code{estimation} command, if it is used with the
@@ -6737,7 +6797,7 @@ Auto- and cross-correlation of endogenous variables. Fields are vectors with cor
 
 
 @item VarianceDecomposition
-Decomposition of variance (unconditional variance, i.e. at horizon infinity)@footnote{When the shocks are correlated, it
+Decomposition of variance (unconditional variance, @i{i.e.} at horizon infinity)@footnote{When the shocks are correlated, it
 is the decomposition of orthogonalized shocks via Cholesky
 decomposition according to the order of declaration of shocks
 (@pxref{Variable declarations})}
@@ -6903,7 +6963,7 @@ Upper/lower bound of the 90% HPD interval taking into account both parameter and
 
 @end table
 
-@var{VARIABLE_NAME} contains a matrix of the following size: number of time periods for which forecasts are requested using the nobs = [@var{INTEGER1}:@var{INTEGER2}] option times the number of forecast horizons requested by the @code{forecast} option. I.e., the row indicates the period at which the forecast is performed and the column the respective k-step ahead forecast. The starting periods are sorted in ascending order, not in declaration order.
+@var{VARIABLE_NAME} contains a matrix of the following size: number of time periods for which forecasts are requested using the nobs = [@var{INTEGER1}:@var{INTEGER2}] option times the number of forecast horizons requested by the @code{forecast} option. @i{i.e.}, the row indicates the period at which the forecast is performed and the column the respective k-step ahead forecast. The starting periods are sorted in ascending order, not in declaration order.
 
 @end defvr
 
@@ -6957,13 +7017,31 @@ estimates using a higher tapering are usually more reliable.
 @end table
 @end defvr
 
+@deffn Command unit_root_vars @var{VARIABLE_NAME}@dots{};
+
+This command is deprecated. Use @code{estimation} option @code{diffuse_filter} instead for estimating a model with non-stationary observed variables or @code{steady} option @code{nocheck} to prevent @code{steady} to check the steady state returned by your steady state file.
+@end deffn
+
+Dynare also has the ability to estimate Bayesian VARs:
+
+@deffn Command bvar_density ;
+Computes the marginal density of an estimated BVAR model, using
+Minnesota priors.
+
+See @file{bvar-a-la-sims.pdf}, which comes with Dynare distribution,
+for more information on this command.
+@end deffn
+
+@node Model Comparison
+@section Model Comparison
+
 @deffn Command model_comparison @var{FILENAME}[(@var{DOUBLE})]@dots{};
 @deffnx Command model_comparison (marginal_density = laplace | modifiedharmonicmean) @var{FILENAME}[(@var{DOUBLE})]@dots{};
 @anchor{model_comparison}
 @descriptionhead
 
 This command computes odds ratios and estimate a posterior density over a
-collection of models (see e.g. @cite{Koop (2003), Ch. 1}). The priors over
+collection of models (see @i{e.g.} @cite{Koop (2003), Ch. 1}). The priors over
 models can be specified as the @var{DOUBLE} values, otherwise a uniform prior
 over all models is assumed.  In contrast to frequentist econometrics, the
 models to be compared do not need to be nested.  However, as the computation of
@@ -7032,14 +7110,17 @@ Posterior probability of the respective model
 
 @end defvr
 
+@node Shock Decomposition
+@section Shock Decomposition
 
 @deffn Command shock_decomposition [@var{VARIABLE_NAME}]@dots{};
 @deffnx Command shock_decomposition (@var{OPTIONS}@dots{}) [@var{VARIABLE_NAME}]@dots{};
+@anchor{shock_decomposition}
 
 @descriptionhead
 
 This command computes the historical shock decomposition for a given sample based on 
-the Kalman smoother, i.e. it decomposes the historical deviations of the endogenous 
+the Kalman smoother, @i{i.e.} it decomposes the historical deviations of the endogenous 
 variables from their respective steady state values into the contribution coming 
 from the various shocks. The @code{variable_names} provided govern for which 
 variables the decomposition is plotted.
@@ -7052,16 +7133,14 @@ model).
 
 @table @code
 
-@item parameter_set = @var{PARAMETER_SET}
-Specify the parameter set to use for running the smoother. The
-@var{PARAMETER_SET} can take one of the following seven values:
-@code{calibration}, @code{prior_mode}, @code{prior_mean},
-@code{posterior_mode}, @code{posterior_mean},
-@code{posterior_median}, @code{mle_mode}. Default value: @code{posterior_mean} if
+@item parameter_set = @code{calibration} | @code{prior_mode} | @code{prior_mean} | @code{posterior_mode} | @code{posterior_mean} | @code{posterior_median} | @code{mle_mode}
+@anchor{parameter_set} Specify the parameter set to use for running the smoother. Note that the
+parameter set used in subsequent commands like @code{stoch_simul} will be set
+to the specified @code{parameter_set}. Default value: @code{posterior_mean} if
 Metropolis has been run, @code{mle_mode} if MLE has been run.
 
 @item datafile = @var{FILENAME}
-@xref{datafile}. Useful when computing the shock decomposition on a
+@anchor{datafile_shock_decomp} @xref{datafile}. Useful when computing the shock decomposition on a
 calibrated model.
 
 @item first_obs = @var{INTEGER}
@@ -7070,31 +7149,43 @@ calibrated model.
 @item nobs = @var{INTEGER}
 @xref{nobs}.
 
-@item use_shock_groups [= @var{SHOCK_GROUPS_NAME}]
-@anchor{use_shock_groups}. Uses groups of shocks instead of individual shocks in
-the decomposition. Groups of shocks are defined in @xref{shock_groups} block.
+@item use_shock_groups [= @var{STRING}]
+@anchor{use_shock_groups} Uses shock grouping defined by the string instead of individual shocks in
+the decomposition. The groups of shocks are defined in the @ref{shock_groups} block.
 
-@item colormap = @var{COLORMAP_NAME}
-@anchor{colormap}. Controls the colormap used for the shocks decomposition
-graphs. See @code{colormap} in Matlab/Octave manual.
+@item colormap = @var{STRING}
+@anchor{colormap} Controls the colormap used for the shocks decomposition
+graphs. See @code{colormap} in Matlab/Octave manual for valid arguments.
 
 @item nograph
-@xref{nograph}. Suppresses the display and creation only within the @code{shock_decomposition}-command
-but does not affect other commands.
+@xref{nograph}. Suppresses the display and creation only within the
+@code{shock_decomposition}-command, but does not affect other commands.
+@xref{plot_shock_decomposition} for plotting graphs.
 
+@item init_state = @var{BOOLEAN}
+@anchor{init_state} If equal to @math{0}, the shock decomposition is computed conditional on the smoothed state
+variables in period @math{0}, @i{i.e.} the smoothed shocks starting in period
+@math{1} are used.  If equal to @math{1}, the shock decomposition is computed
+conditional on the smoothed state variables in period @math{1}. Default:
+@math{0}
 @end table
 
+@outputhead
+
+@defvr {MATLAB/Octave variable} oo_.shock_decomposition
 @vindex oo_.shock_decomposition
+@anchor{oo_.shock_decomposition}
 The results are stored in the field @code{oo_.shock_decomposition}, which is a three
 dimensional array. The first dimension contains the @code{M_.endo_nbr} endogenous variables. 
-The second dimension stores
+The second dimension stores 
 in the first @code{M_.exo_nbr} columns the contribution of the respective shocks.
 Column @code{M_.exo_nbr+1} stores the contribution of the initial conditions,
 while column @code{M_.exo_nbr+2} stores the smoothed value of the respective
-endogenous variable in deviations from their steady state, i.e. the mean and trends are
+endogenous variable in deviations from their steady state, @i{i.e.} the mean and trends are
 subtracted. The third dimension stores the time periods. Both the variables 
-and shocks are stored in the order of declaration, i.e. @code{M_.endo_names} and 
+and shocks are stored in the order of declaration, @i{i.e.} @code{M_.endo_names} and 
 @code{M_.exo_names}, respectively.
+@end defvr
 
 @end deffn
 
@@ -7105,11 +7196,11 @@ and shocks are stored in the order of declaration, i.e. @code{M_.endo_names} and
 of the shock groups is written in a block delimited by @code{shock_groups} and
 @code{end}.
 
-Each line defines a group of shock as a list of exogenous variables:
+Each line defines a group of shocks as a list of exogenous variables:
 
 @example
 SHOCK_GROUP_NAME   = VARIABLE_1 [[,] VARIABLE_2 [,]@dots{}];
-`SHOCK GROUP NAME' = VARIABLE_1 [[,] VARIABLE_2 [,]@dots{}];
+'SHOCK GROUP NAME' = VARIABLE_1 [[,] VARIABLE_2 [,]@dots{}];
 @end example
 
 @optionshead
@@ -7120,7 +7211,7 @@ SHOCK_GROUP_NAME   = VARIABLE_1 [[,] VARIABLE_2 [,]@dots{}];
 Specifies a name for the following definition of shock groups. It is possible
 to use several @code{shock_groups} blocks in a model file, each grouping being
 identified by a different name. This name must in turn be used in the
-@code{shocks_decomposition} command.
+@code{shock_decomposition} command.
 
 @end table
 
@@ -7133,29 +7224,276 @@ varexo e_a, e_b, e_c, e_d;
 
 shock_groups(name=group1);
 supply = e_a, e_b;
-`aggregate demand' = e_c, e_d;
+'aggregate demand' = e_c, e_d;
 end;
 
-shocks_decomposition(use_shock_groups=group1);
+shock_decomposition(use_shock_groups=group1);
 @end example
-
+This example defines a shock grouping with the name @code{group1}, containing a set of supply and demand shocks 
+and conducts the shock decomposition for these two groups.
 @end deffn
 
-@deffn Command unit_root_vars @var{VARIABLE_NAME}@dots{};
+@deffn Command realtime_shock_decomposition [@var{VARIABLE_NAME}]@dots{};
+@deffnx Command realtime_shock_decomposition (@var{OPTIONS}@dots{}) [@var{VARIABLE_NAME}]@dots{};
+@anchor{realtime_shock_decomposition}
+
+@descriptionhead
+
+This command computes the realtime historical shock decomposition for a given
+sample based on the Kalman smoother. For each period
+@math{T=[@code{presample},@dots{},@code{nobs}]}, it recursively computes three objects:
+@itemize @bullet
+@item
+realtime historical shock decomposition @math{Y(t|T)} for @math{t=[1,@dots{},T]},
+@i{i.e.} without observing data in @math{[T+1,@dots{},@code{nobs}]}. This results in a standard 
+shock decomposition being computed for each additional datapoint becoming available after @code{presample}.
+@item
+forecast shock decomposition @math{Y(T+k|T)} for @math{k=[1,@dots{},forecast]}, @i{i.e.} the @math{k}-step 
+ahead forecast made for every @math{T} is decomposed in its shock contributions.
+@item
+realtime conditional shock decomposition of the difference between the realtime historical shock decomposition and the 
+forecast shock decomposition. If @ref{vintage} is equal to @math{0}, it computes the effect of shocks realizing in period 
+@math{T}, @i{i.e.} decomposes @math{Y(T|T)-Y(T|T-1)}. Put differently it conducts a @math{1}-period ahead shock decomposition from 
+@math{T-1} to @math{T}, by decomposing the update step of the Kalman filter. If @code{vintage>0} and smaller than @code{nobs},
+the decomposition is conducted of the forecast revision @math{Y(T+k|T+k)-Y(T+k|T)}.
+
+@end itemize
+
+Like @ref{shock_decomposition} it decomposes the historical deviations of the endogenous 
+variables from their respective steady state values into the contribution coming 
+from the various shocks. The @code{variable_names} provided govern for which 
+variables the decomposition is plotted.
+
+Note that this command must come after either @code{estimation} (in case
+of an estimated model) or @code{stoch_simul} (in case of a calibrated
+model).
+
+@optionshead
+
+@table @code
+
+@item parameter_set = @code{calibration} | @code{prior_mode} | @code{prior_mean} | @code{posterior_mode} | @code{posterior_mean} | @code{posterior_median} | @code{mle_mode}
+@xref{parameter_set}.
+
+@item datafile = @var{FILENAME}
+@xref{datafile_shock_decomp}.
+
+@item first_obs = @var{INTEGER}
+@xref{first_obs}.
+
+@item nobs = @var{INTEGER}
+@xref{nobs}.
+
+@item use_shock_groups [= @var{STRING}]
+@xref{use_shock_groups}.
+
+@item colormap = @var{STRING}
+@xref{colormap}.
+
+@item nograph
+@xref{nograph}. Only shock decompositions are computed and stored in @code{oo_.realtime_shock_decomposition},
+@code{oo_.conditional_shock_decomposition} and @code{oo_.realtime_forecast_shock_decomposition} but no plot is made 
+(@xref{plot_shock_decomposition}).
+
+@item presample = @var{INTEGER}
+@anchor{presample_shock_decomposition} First data point from which recursive
+realtime shock decompositions are computed, @i{i.e.} for
+@math{T=[@code{presample}@dots{}@code{nobs}]}.
+
+@item forecast = @var{INTEGER}
+@anchor{forecast_shock_decomposition} Compute shock decompositions up to
+@math{T+k} periods, @i{i.e.} get shock contributions to k-step ahead forecasts.
+
+@item save_realtime = @var{INTEGER_VECTOR}
+@anchor{save_realtime} Choose for which vintages to save the full realtime
+shock decomposition. Default: @math{0}.
+@end table
+
+@outputhead
+
+@defvr {MATLAB/Octave variable} oo_.realtime_shock_decomposition
+@vindex oo_.realtime_shock_decomposition
+Structure storing the results of realtime historical decompositions. Fields are three-dimensional arrays with 
+the first two dimension equal to the ones of @ref{oo_.shock_decomposition}. The third dimension stores the time 
+periods and is therefore of size @code{T+forecast}. Fields are of the form:
+@example
+@code{oo_.realtime_shock_decomposition.@var{OBJECT}}
+@end example
+where @var{OBJECT} is one of the following:
+
+@table @code
+
+@item pool
+Stores the pooled decomposition, @i{i.e.} for every realtime shock decomposition terminal period
+@math{T=[@code{presample},@dots{},@code{nobs}]} it collects the last period's decomposition @math{Y(T|T)}
+(see also @ref{plot_shock_decomposition}). The third dimension of the array will have size 
+@code{nobs+forecast}.
+
+@item time_*
+Stores the vintages of realtime historical shock decompositions if @code{save_realtime} is used. For example, if
+@code{save_realtime=[5]} and @code{forecast=8}, the third dimension will be of size 13.
+
+@end table
+@end defvr
+
+@defvr {MATLAB/Octave variable} oo_.realtime_conditional_shock_decomposition
+@vindex oo_.realtime_conditional_shock_decomposition
+Structure storing the results of realtime conditional decompositions. Fields are of the form:
+@example
+@code{oo_.realtime_conditional_shock_decomposition.@var{OBJECT}}
+@end example
+where @var{OBJECT} is one of the following:
+
+@table @code
+
+@item pool
+Stores the pooled realtime conditional shock decomposition, @i{i.e.} collects the decompositions of 
+@math{Y(T|T)-Y(T|T-1)} for the terminal periods @math{T=[@code{presample},@dots{},@code{nobs}]}. 
+The third dimension is of size @code{nobs}.
+
+@item time_*
+Store the vintages of @math{k}-step conditional forecast shock decompositions @math{Y(t|T+k)}, for
+@math{t=[T@dots{}T+k]}. @xref{vintage}. The third dimension is of size @code{1+forecast}.
+
+@end table
+@end defvr
+
+@defvr {MATLAB/Octave variable} oo_.realtime_forecast_shock_decomposition
+@vindex oo_.realtime_forecast_shock_decomposition
+Structure storing the results of realtime forecast decompositions. Fields are of the form:
+@example
+@code{oo_.realtime_forecast_shock_decomposition.@var{OBJECT}}
+@end example
+where @var{OBJECT} is one of the following:
+
+@table @code
+
+@item pool
+Stores the pooled realtime forecast decomposition of the @math{1}-step ahead effect of shocks
+on the @math{1}-step ahead prediction, @i{i.e.} @math{Y(T|T-1)}. 
+
+@item time_*
+Stores the vintages of @math{k}-step out-of-sample forecast shock
+decompositions, @i{i.e.} @math{Y(t|T)}, for @math{t=[T@dots{}T+k]}. @xref{vintage}.
+@end table
+@end defvr
 
-This command is deprecated. Use @code{estimation} option @code{diffuse_filter} instead for estimating a model with non-stationary observed variables or @code{steady} option @code{nocheck} to prevent @code{steady} to check the steady state returned by your steady state file.
 @end deffn
 
-Dynare also has the ability to estimate Bayesian VARs:
+@deffn Command plot_shock_decomposition [@var{VARIABLE_NAME}]@dots{};
+@deffnx Command plot_shock_decomposition (@var{OPTIONS}@dots{}) [@var{VARIABLE_NAME}]@dots{};
+@anchor{plot_shock_decomposition}
 
-@deffn Command bvar_density ;
-Computes the marginal density of an estimated BVAR model, using
-Minnesota priors.
+@descriptionhead
+
+This command plots the historical shock decomposition already computed by
+@code{shock_decomposition} or @code{realtime_shock_decomposition}. For that reason,
+it must come after one of these commands. The @code{variable_names} provided govern which
+variables the decomposition is plotted for.
+
+Further note that, unlike the majority of Dynare commands, the options
+specified below are overwritten with their defaults before every call to
+@code{plot_shock_decomposition}. Hence, if you want to reuse an option in a
+subsequent call to @code{plot_shock_decomposition}, you must pass it to the
+command again.
+
+@optionshead
+
+@table @code
+
+@item use_shock_groups [= @var{STRING}]
+@xref{use_shock_groups}.
+
+@item colormap = @var{STRING}
+@xref{colormap}.
+
+@item nodisplay
+@xref{nodisplay}.
+
+@item graph_format = @var{FORMAT}
+@itemx graph_format = ( @var{FORMAT}, @var{FORMAT}@dots{} )
+@xref{graph_format}.
+
+@item detail_plot
+Plots shock contributions using subplots, one per shock (or group of
+shocks). Default: not activated
+
+@item interactive
+Under MATLAB, add uimenus for detailed group plots. Default: not activated
+
+@item screen_shocks
+@anchor{screen_shcoks} For large models (@i{i.e.} for models with more than @math{16}
+shocks), plots only the shocks that have the largest historical contribution
+for chosen selected @code{variable_names}.  Historical contribution is ranked
+by the mean absolute value of all historical contributions.
+
+@item steadystate
+@anchor{steadystate} If passed, the the @math{y}-axis value of the zero line in
+the shock decomposition plot is translated to the steady state level. Default:
+not activated
+
+@item type = @code{qoq} | @code{yoy} | @code{aoa}
+@anchor{type} For quarterly data, valid arguments are: @code{qoq} for
+quarter-on-quarter plots, @code{yoy} for year-on-year plots of growth rates,
+@code{aoa} for annualized variables, @i{i.e.} the value in the last quarter for
+each year is plotted.  Default value: @code{empty}, @i{i.e.} standard
+period-on-period plots (@code{qoq} for quarterly data).
+
+@item fig_name = @var{STRING}
+@anchor{fig_name} Specifies a user-defined keyword to be appended to the
+default figure name set by @code{plot_shock_decomposition}.  This can avoid to
+overwrite plots in case of sequential calls to @code{plot_shock_decomposition}.
+
+@item write_xls 
+@anchor{write_xls} Saves shock decompositions to Excel-file in the main directory, named 
+@code{FILENAME_shock_decomposition_TYPE_FIG_NAME.xls}. This option requires your system to be
+configured to be able to write Excel files.@footnote{In case of Excel not being installed, 
+@url{https://mathworks.com/matlabcentral/fileexchange/38591-xlwrite--generate-xls-x--files-without-excel-on-mac-linux-win} may be helpful.}
+
+@item realtime = @var{INTEGER}
+@anchor{realtime} Which kind of shock decomposition to plot. @var{INTEGER} can take following values:
+@itemize @bullet
+@item
+@code{0}: standard historical shock decomposition. @xref{shock_decomposition}.
+@item
+@code{1}: realtime historical shock decomposition. @xref{realtime_shock_decomposition}.
+@item
+@code{2}: conditional realtime shock decomposition. @xref{realtime_shock_decomposition}.
+@item
+@code{3}: realtime forecast shock decomposition. @xref{realtime_shock_decomposition}.
+@end itemize
+If no @ref{vintage} is requested, @i{i.e.} @code{vintage=0} then the pooled objects from @ref{realtime_shock_decomposition}
+will be plotted and the respective vintage otherwise.
+Default: @math{0}
+
+@item vintage = @var{INTEGER}
+@anchor{vintage} Selects a particular data vintage in @math{[presample,@dots{},nobs]} for which to plot the results from
+@ref{realtime_shock_decomposition} selected via the @ref{realtime} option. If the standard 
+historical shock decomposition is selected (@code{realtime=0}), @code{vintage} will have no effect. If @code{vintage=0}
+the pooled objects from @ref{realtime_shock_decomposition} will be plotted. If @code{vintage>0}, it plots the shock
+decompositions for vintage @math{T=@code{vintage}} under the following scenarios:
+@itemize @bullet
+@item
+@code{realtime=1}: the full vintage shock decomposition @math{Y(t|T)} for
+@math{t=[1,@dots{},T]}
+@item
+@code{realtime=2}: the conditional forecast shock decomposition from @math{T},
+@i{i.e.} plots @math{Y(T+j|T+j)} and the shock contributions needed to get to
+the data @math{Y(T+j)} conditional on @math{T=}@code{vintage}, with
+@math{j=[0,@dots{},@code{forecast}]}.
+@item
+@code{realtime=3}: plots unconditional forecast shock decomposition from
+@math{T}, @i{i.e.} @math{Y(T+j|T)}, where @math{T=@code{vintage}} and
+@math{j=[0,@dots{},@code{forecast}]}.
+@end itemize
+Default: @math{0}
+@end table
 
-See @file{bvar-a-la-sims.pdf}, which comes with Dynare distribution,
-for more information on this command.
 @end deffn
 
+@node Calibrated Smoother
+@section Calibrated Smoother
+
 Dynare can also run the smoother on a calibrated model:
 
 @deffn Command calib_smoother [@var{VARIABLE_NAME}]@dots{};
@@ -7552,8 +7890,8 @@ is not specified, a value of 0 is assumed. That is, if you specify only
 values for periods 1 and 3, the values for period 2 will be 0. Currently, it is not 
 possible to have uncontrolled intermediate periods.
 In case of the presence of @code{observation_trends}, the specified controlled path for 
-these variables needs to include the trend component.
-
+these variables needs to include the trend component. When using the @ref{loglinear} option, 
+it is necessary to specify the logarithm of the controlled variables.
 
 @end deffn
 
@@ -7753,7 +8091,7 @@ where:
 
 @item
 @math{\gamma} are parameters to be optimized. They must be elements
-of the matrices @math{A_1}, @math{A_2}, @math{A_3}, i.e. be specified as
+of the matrices @math{A_1}, @math{A_2}, @math{A_3}, @i{i.e.} be specified as
 parameters in the @code{params}-command and be entered in the
 @code{model}-block;
 
@@ -7775,7 +8113,7 @@ parameters to minimize the weighted (co)-variance of a specified subset
 of endogenous variables, subject to a linear law of motion implied by the
 first order conditions of the model. A few things are worth mentioning.
 First, @math{y} denotes the selected endogenous variables' deviations
-from their steady state, i.e. in case they are not already mean 0 the
+from their steady state, @i{i.e.} in case they are not already mean 0 the
 variables entering the loss function are automatically demeaned so that
 the centered second moments are minimized. Second, @code{osr} only solves
 linear quadratic problems of the type resulting from combining the
@@ -7812,7 +8150,7 @@ by listing them after the command, as @code{stoch_simul}
 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 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}.
+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{i.e.} on the value of option @ref{opt_algo}). @xref{optim}.
 
 @item maxit = @var{INTEGER} 
 Determines the maximum number of iterations used in @code{opt_algo=4}.  This option is now deprecated and will be 
@@ -7924,7 +8262,7 @@ Each line has the following syntax:
 PARAMETER_NAME, LOWER_BOUND, UPPER_BOUND;
 @end example
 
-Note that the use of this block requires the use of a constrained optimizer, i.e. setting @ref{opt_algo} to 
+Note that the use of this block requires the use of a constrained optimizer, @i{i.e.} setting @ref{opt_algo} to 
 1,2,5, or 9.
 
 @examplehead
@@ -8069,7 +8407,7 @@ 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. The Ramsey policy is computed
 by approximating the equilibrium system around the perturbation point where the 
-Lagrange multipliers are at their steady state, i.e. where the Ramsey planner acts 
+Lagrange multipliers are at their steady state, @i{i.e.} where the Ramsey planner 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 
@@ -8132,7 +8470,7 @@ 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 
+initial Lagrange multipliers of the planner's problem set to 0, @i{i.e.} it is assumed 
 that the planner exploits its ability to surprise private agents in the first
 period of implementing Ramsey policy. This is the value of implementating
 optimal policy for the first time and committing not to re-optimize in the future.
@@ -8251,7 +8589,7 @@ This command triggers sensitivity analysis on a DSGE model.
 @anchor{Sampling Options}
 @table @code
 
-@item nsam = @var{INTEGER}
+@item Nsam = @var{INTEGER}
 Size of the Monte-Carlo sample. Default: @code{2048}
 
 @item ilptau = @var{INTEGER}
@@ -8308,11 +8646,7 @@ 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}
+Default: @code{0}
 
 @item pvalue_ks = @var{DOUBLE}
 The threshold @math{pvalue} for significant Kolmogorov-Smirnov test (@i{i.e.} plot parameters with
@@ -8345,7 +8679,7 @@ An empty vector indicates that these entries will not be filtered. Default: @cod
 
 @item ksstat_redform = @var{DOUBLE}
 Critical value for Smirnov statistics @math{d} when reduced form entries
-are filtered. Default: @code{0.1}
+are filtered. Default: @code{0.001}
 
 @item alpha2_redform = @var{DOUBLE}
 Critical value for correlations @math{\rho}  when reduced form entries
@@ -8392,7 +8726,7 @@ error). Default: @code{presample+1}
 
 @item alpha_rmse = @var{DOUBLE}
 Critical value for Smirnov statistics @math{d}: plot parameters with
-@math{d>} @code{alpha_rmse}. Default: @code{0.002}
+@math{d>} @code{alpha_rmse}. Default: @code{0.001}
 
 @item alpha2_rmse = @var{DOUBLE}
 Critical value for correlation @math{\rho}: plot couples of parmaters with
@@ -8475,7 +8809,7 @@ Maximum number of lags for moments in identification analysis. Default: @code{1}
 
 The @code{irf_calibration} and @code{moment_calibration} blocks allow imposing implicit ``endogenous'' priors 
 about IRFs and moments on the model. The way it works internally is that 
-any parameter draw that is inconsistent with the ``calibration'' provided in these blocks is discarded, i.e. assigned a prior density of 0. 
+any parameter draw that is inconsistent with the ``calibration'' provided in these blocks is discarded, @i{i.e.} assigned a prior density of @math{0}. 
 In the context of @code{dynare_sensitivity}, these restrictions allow tracing out which parameters are driving the model to
 satisfy or violate the given restrictions.
 
@@ -10586,7 +10920,7 @@ related to the model (and hence not placed in the model file). At the
 moment, it is only used when using Dynare to run parallel
 computations.
 
-On Linux and Mac OS X, the default location of the configuration file
+On Linux and macOS, the default location of the configuration file
 is @file{$HOME/.dynare}, while on Windows it is
 @file{%APPDATA%\dynare.ini} (typically @file{C:\Documents and
 Settings\@var{USERNAME}\Application Data\dynare.ini} under Windows XP,
@@ -10847,7 +11181,7 @@ If just one integer is passed, the number of processors to use. If a
 range of integers is passed, the specific processors to use (processor
 counting is defined to begin at one as opposed to zero). Note that
 using specific processors is only possible under Windows; under Linux
-and Mac OS X, if a range is passed the same number of processors will
+and macOS, if a range is passed the same number of processors will
 be used but the range will be adjusted to begin at one.
 
 @item ComputerName = @var{COMPUTER_NAME}
@@ -10934,7 +11268,7 @@ This section outlines the steps necessary on most Windows systems to set up Dyna
 
 @enumerate
 @item Write a configuration file containing the options you want. A mimimum working 
-    example setting up a cluster consisting of two local CPU cores that allows for e.g. running
+    example setting up a cluster consisting of two local CPU cores that allows for @i{e.g.} running
     two Monte Carlo Markov Chains in parallel is shown below.
 @item Save the configuration file somwhere. The name and file ending do not matter 
     if you are providing it with the @code{conffile} command line option. The only restrictions are that the 
@@ -10942,8 +11276,8 @@ This section outlines the steps necessary on most Windows systems to set up Dyna
     For the configuration file to be accessible without providing an explicit path at the command line, you must save it 
     under the name @file{dynare.ini} into your user account's @code{Application Data} folder.
 @item Install the @file{PSTools} from @uref{https://technet.microsoft.com/sysinternals/pstools.aspx} 
-    to your system, e.g. into @file{C:\PSTools}.
-@item Set the Windows System Path to the @file{PSTools}-folder (e.g. using something along the line of pressing Windows Key+Pause to 
+    to your system, @i{e.g.} into @file{C:\PSTools}.
+@item Set the Windows System Path to the @file{PSTools}-folder (@i{e.g.} using something along the line of pressing Windows Key+Pause to 
     open the System Configuration, then go to Advanced -> Environment Variables -> Path, see also @uref{https://technet.microsoft.com/sysinternals/pstools.aspx}).
 @item Restart your computer to make the path change effective.
 @item Open Matlab and type into the command window 
@@ -11905,7 +12239,7 @@ plot(ts2.data,'--r');           % Plot of the filtered y.
 hold off
 axis tight
 id = get(gca,'XTick');
-set(gca,'XTickLabel',strings(ts.dates(id)));
+set(gca,'XTickLabel',strings(ts1.dates(id)));
 @end example
 
 @iftex
@@ -13269,7 +13603,7 @@ Instantiates a @code{Report} object.
 The full path to the @LaTeX{} compiler on your system. If this option
 is not provided, Dynare will try to find the appropriate program to
 compile @LaTeX{} on your system. Default is system dependent: Windows:
-the result of @code{findtexmf --file-type=exe pdflatex}, Mac OS X and
+the result of @code{findtexmf --file-type=exe pdflatex}, macOS and
 Linux: the result of @code{which pdflatex}
 
 @item showDate, @code{BOOLEAN}
@@ -13838,7 +14172,7 @@ Print the compiler output to the screen. Useful for debugging your code as the
 @ref{showOutput}
 
 @item showReport, @code{BOOLEAN}
-Open the compiled report (works on Windows and OS X on Matlab). Default:
+Open the compiled report (works on Windows and macOS on Matlab). Default:
 @code{true}
 
 @end table
@@ -14402,6 +14736,10 @@ Smets, Frank and Rafael Wouters (2003): ``An Estimated Dynamic
 Stochastic General Equilibrium Model of the Euro Area,'' @i{Journal of
 the European Economic Association}, 1(5), 1123--1175
 
+@item
+Stock, James H. and Mark W. Watson (1999). ``Forecasting Inflation,'', @i{Journal of Monetary
+Economics}, 44(2), 293--335.
+
 @item
 Uhlig, Harald (2001): ``A Toolkit for Analysing Nonlinear Dynamic Stochastic Models Easily,''
 in @i{Computational Methods for the Study of Dynamic
diff --git a/dynare++/kord/journal.cweb b/dynare++/kord/journal.cweb
index b43b27bcc9ae2c428e8baf9df430b7f54d3c78b7..3fb666bb759caee5bdfe14b3e6350955f354d9ae 100644
--- a/dynare++/kord/journal.cweb
+++ b/dynare++/kord/journal.cweb
@@ -101,7 +101,11 @@ void SystemResources::getRUS(double& load_avg, long int& pg_avail,
 	majflt = -1;
 #endif
 
-#if !defined(__MINGW32__) && !defined(__CYGWIN32__) && !defined(__CYGWIN__) && !defined(__MINGW64__) && !defined(__CYGWIN64__)
+
+#define MINGCYGTMP (!defined(__MINGW32__) && !defined(__CYGWIN32__) && !defined(__CYGWIN__))
+#define MINGCYG (MINGCYGTMP && !defined(__MINGW64__) && !defined(__CYGWIN64__))
+
+#if MINGCYG
 	getloadavg(&load_avg, 1);
 #else
 	load_avg = -1.0;
diff --git a/dynare++/parser/cc/atom_assignings.h b/dynare++/parser/cc/atom_assignings.h
index 2151f9bccbf545a7dcccdf627cfd702dd26a36bc..14f11b2cbf247d1df5e7d3193ab0e3bbd5b0f0f3 100644
--- a/dynare++/parser/cc/atom_assignings.h
+++ b/dynare++/parser/cc/atom_assignings.h
@@ -12,114 +12,126 @@
 #include <vector>
 #include <map>
 
-namespace ogp {
+namespace ogp
+{
 
-	class AtomAsgnEvaluator;
+  class AtomAsgnEvaluator;
 
-	/** This class represents atom assignments used in parameters
-	 * settings and initval initialization. It maintains atoms of the
-	 * all expressions on the right hand side, the parsed formulas of
-	 * the right hand sides, and the information about the left hand
-	 * sides. See documentation to the order member below. */
-	class AtomAssignings {
-		friend class AtomAsgnEvaluator;
-	protected:
-		typedef std::map<const char*, int, ltstr> Tvarintmap;
-		/** All atoms which should be sufficient for formulas at the
-		 * right hand sides. The atoms should be filled with names
-		 * (preregistered). This is a responsibility of the caller. */
-		StaticAtoms& atoms;
-		/** The formulas of right hand sides. */
-		FormulaParser expr;
-		/** Name storage of the names from left hand sides. */
-		NameStorage left_names;
-		/** Information on left hand sides. This maps a name to the
-		 * index of its assigned expression in expr. More than one
-		 * name may reference to the same expression. */
-		Tvarintmap lname2expr;
-		/** Information on left hand sides. If order[i] >= 0, then it
-		 * says that i-th expression in expr is assigned to atom with
-		 * order[i] tree index. */
-		std::vector<int> order;
-	public:
-		/** Construct the object using the provided static atoms. */
-		AtomAssignings(StaticAtoms& a) : atoms(a), expr(atoms)
-			{}
-		/** Make a copy with provided reference to (posibly different)
-		 * static atoms. */
-		AtomAssignings(const AtomAssignings& aa, StaticAtoms& a);
-		virtual ~AtomAssignings()
-			{}
-		/** Parse the assignments from the given string. */
-		void parse(int length, const char* stream);
-		/** Process a syntax error from bison. */
-		void error(const char* mes);
-		/** Add an assignment of the given name to the given
-		 * double. Can be called by a user, anytime. */
-		void add_assignment_to_double(const char* name, double val);
-		/** Add an assignment. Called from assign.y. */
-		void add_assignment(int asgn_off, const char* str, int name_len,
-							int right_off, int right_len);
-		/** This applies old2new map (possibly from atom
-		 * substitutions) to this object. It registers new variables
-		 * in the atoms, and adds the expressions to expr, and left
-		 * names to lname2expr. The information about dynamical part
-		 * of substitutions is ignored, since we are now in the static
-		 * world. */
-		void apply_subst(const AtomSubstitutions::Toldnamemap& mm);
-		/** Debug print. */
-		void print() const;
-	};
+  /** This class represents atom assignments used in parameters
+   * settings and initval initialization. It maintains atoms of the
+   * all expressions on the right hand side, the parsed formulas of
+   * the right hand sides, and the information about the left hand
+   * sides. See documentation to the order member below. */
+  class AtomAssignings
+  {
+    friend class AtomAsgnEvaluator;
+  protected:
+    typedef std::map<const char *, int, ltstr> Tvarintmap;
+    /** All atoms which should be sufficient for formulas at the
+     * right hand sides. The atoms should be filled with names
+     * (preregistered). This is a responsibility of the caller. */
+    StaticAtoms &atoms;
+    /** The formulas of right hand sides. */
+    FormulaParser expr;
+    /** Name storage of the names from left hand sides. */
+    NameStorage left_names;
+    /** Information on left hand sides. This maps a name to the
+     * index of its assigned expression in expr. More than one
+     * name may reference to the same expression. */
+    Tvarintmap lname2expr;
+    /** Information on left hand sides. If order[i] >= 0, then it
+     * says that i-th expression in expr is assigned to atom with
+     * order[i] tree index. */
+    std::vector<int> order;
+  public:
+    /** Construct the object using the provided static atoms. */
+    AtomAssignings(StaticAtoms &a) : atoms(a), expr(atoms)
+    {
+    }
+    /** Make a copy with provided reference to (posibly different)
+     * static atoms. */
+    AtomAssignings(const AtomAssignings &aa, StaticAtoms &a);
+    virtual ~AtomAssignings()
+    {
+    }
+    /** Parse the assignments from the given string. */
+    void parse(int length, const char *stream);
+    /** Process a syntax error from bison. */
+    void error(const char *mes);
+    /** Add an assignment of the given name to the given
+     * double. Can be called by a user, anytime. */
+    void add_assignment_to_double(const char *name, double val);
+    /** Add an assignment. Called from assign.y. */
+    void add_assignment(int asgn_off, const char *str, int name_len,
+                        int right_off, int right_len);
+    /** This applies old2new map (possibly from atom
+     * substitutions) to this object. It registers new variables
+     * in the atoms, and adds the expressions to expr, and left
+     * names to lname2expr. The information about dynamical part
+     * of substitutions is ignored, since we are now in the static
+     * world. */
+    void apply_subst(const AtomSubstitutions::Toldnamemap &mm);
+    /** Debug print. */
+    void print() const;
+  };
 
-	/** This class basically evaluates the atom assignments
-	 * AtomAssignings, so it inherits from ogp::FormulaEvaluator. It
-	 * is also a storage for the results of the evaluation stored as a
-	 * vector, so the class inherits from std::vector<double> and
-	 * ogp::FormulaEvalLoader. As the expressions for atoms are
-	 * evaluated, the results are values for atoms which will be
-	 * used in subsequent evaluations. For this reason, the class
-	 * inherits also from AtomValues. */
-	class AtomAsgnEvaluator : public FormulaEvalLoader,
-							  public AtomValues,
-							  protected FormulaEvaluator,
-							  public std::vector<double> {
-	protected:
-		typedef std::map<int, double> Tusrvalmap;
-		Tusrvalmap user_values;
-		const AtomAssignings& aa;
-	public:
-		AtomAsgnEvaluator(const AtomAssignings& a)
-			: FormulaEvaluator(a.expr),
-			  std::vector<double>(a.expr.nformulas()), aa(a) {}
-		virtual ~AtomAsgnEvaluator() {}
-		/** This sets all initial values to NaNs, all constants and
-		 * all values set by user by call set_value. This is called by
-		 * FormulaEvaluator::eval() method, which is called by eval()
-		 * method passing this argument as AtomValues. So the
-		 * ogp::EvalTree will be always this->etree. */
-		void setValues(EvalTree& et) const;
-		/** User setting of the values. For example in initval,
-		 * parameters are known and should be set to their values. In
-		 * constrast endogenous variables are set initially to NaNs by
-		 * AtomValues::setValues. */
-		void set_user_value(const char* name, double val);
-		/** This sets the result of i-th expression in aa to res, and
-		 * also checks whether the i-th expression is an atom. If so,
-		 * it sets the value of the atom in ogp::EvalTree
-		 * this->etree. */
-		void load(int i, double res);
-		/** After the user values have been set, the assignments can
-		 * be evaluated. For this purpose we have eval() method. The
-		 * result is that this object as std::vector<double> will
-		 * contain the values. It is ordered given by formulas in
-		 * expr. */
-		void eval()
-			{FormulaEvaluator::eval(*this, *this);}
-		/** This returns a value for a given name. If the name is not
-		 * found among atoms, or there is no assignment for the atom,
-		 * NaN is returned. */
-		double get_value(const char* name) const;
-	};
+  /** This class basically evaluates the atom assignments
+   * AtomAssignings, so it inherits from ogp::FormulaEvaluator. It
+   * is also a storage for the results of the evaluation stored as a
+   * vector, so the class inherits from std::vector<double> and
+   * ogp::FormulaEvalLoader. As the expressions for atoms are
+   * evaluated, the results are values for atoms which will be
+   * used in subsequent evaluations. For this reason, the class
+   * inherits also from AtomValues. */
+  class AtomAsgnEvaluator : public FormulaEvalLoader,
+                            public AtomValues,
+                            protected FormulaEvaluator,
+                            public std::vector<double>
+  {
+  protected:
+    typedef std::map<int, double> Tusrvalmap;
+    Tusrvalmap user_values;
+    const AtomAssignings &aa;
+  public:
+    AtomAsgnEvaluator(const AtomAssignings &a)
+      : FormulaEvaluator(a.expr),
+        std::vector<double>(a.expr.nformulas()), aa(a)
+    {
+    }
+    virtual ~AtomAsgnEvaluator()
+    {
+    }
+    /** This sets all initial values to NaNs, all constants and
+     * all values set by user by call set_value. This is called by
+     * FormulaEvaluator::eval() method, which is called by eval()
+     * method passing this argument as AtomValues. So the
+     * ogp::EvalTree will be always this->etree. */
+    void setValues(EvalTree &et) const;
+    /** User setting of the values. For example in initval,
+     * parameters are known and should be set to their values. In
+     * constrast endogenous variables are set initially to NaNs by
+     * AtomValues::setValues. */
+    void set_user_value(const char *name, double val);
+    /** This sets the result of i-th expression in aa to res, and
+     * also checks whether the i-th expression is an atom. If so,
+     * it sets the value of the atom in ogp::EvalTree
+     * this->etree. */
+    void load(int i, double res);
+    /** After the user values have been set, the assignments can
+     * be evaluated. For this purpose we have eval() method. The
+     * result is that this object as std::vector<double> will
+     * contain the values. It is ordered given by formulas in
+     * expr. */
+    void
+    eval()
+    {
+      FormulaEvaluator::eval(*this, *this);
+    }
+    /** This returns a value for a given name. If the name is not
+     * found among atoms, or there is no assignment for the atom,
+     * NaN is returned. */
+    double get_value(const char *name) const;
+  };
 
 };
 
diff --git a/dynare++/parser/cc/atom_substitutions.h b/dynare++/parser/cc/atom_substitutions.h
index 82c99946b08e47840b4f98995ab062fd85e472fd..a0e060960d7e3abbdfd73c82bc67ed391d4d99a3 100644
--- a/dynare++/parser/cc/atom_substitutions.h
+++ b/dynare++/parser/cc/atom_substitutions.h
@@ -9,148 +9,185 @@
 
 #include <string>
 
-namespace ogp {
+namespace ogp
+{
 
-	using std::string;
-	using std::map;
-	using std::pair;
+  using std::string;
+  using std::map;
+  using std::pair;
 
-	/** This class tracts an information about the performed
-	 * substitutions. In fact, there is only one number to keep track
-	 * about, this is a number of substitutions. */
-	struct SubstInfo {
-		int num_substs;
-		SubstInfo() : num_substs(0) {}
-	};
+  /** This class tracts an information about the performed
+   * substitutions. In fact, there is only one number to keep track
+   * about, this is a number of substitutions. */
+  struct SubstInfo
+  {
+    int num_substs;
+    SubstInfo() : num_substs(0)
+    {
+    }
+  };
 
-	/** This class tracks all atom substitutions during the job and
-	 * then builds structures when all substitutions are finished. */
-	class AtomSubstitutions {
-	public:
-		typedef pair<const char*, int> Tshiftname;
-		typedef map<const char*, Tshiftname, ltstr> Tshiftmap;
-		typedef set<Tshiftname> Tshiftnameset;
-		typedef map<const char*, Tshiftnameset, ltstr> Toldnamemap;
-	protected:
-		/** This maps a new name to a shifted old name. This is, one
-		 * entry looks as "a_m3 ==> a(-3)", saying that a variable
-		 * "a_m3" corresponds to a variable "a" lagged by 3. */
-		Tshiftmap new2old;
-		/** This is inverse to new2old, which is not unique. For old
-		 * name, say "a", it says what new names are derived with what
-		 * shifts from the "a". For example, it can map "a" to a two
-		 * element set {["a_m3", +3], ["a_p2", -2]}. This says that
-		 * leading "a_m3" by 3 one gets old "a" and lagging "a_p2" by
-		 * 2 one gets also old "a". */
-		Toldnamemap old2new;
-		/** This is a reference to old atoms with multiple leads and
-		 * lags. They are supposed to be used with parsing finished
-		 * being had called, so that the external ordering is
-		 * available. */
-		const FineAtoms& old_atoms;
-		/** This is a reference to new atoms. All name pointers point
-		 * to storage of these atoms. */
-		FineAtoms& new_atoms;
-		/** Substitutions information. */
-		SubstInfo info;
-	public:
-		/** Create the object with reference to the old and new
-		 * atoms. In the beginning, old atoms are supposed to be with
-		 * parsing_finished() called, and new atoms a simple copy of
-		 * old atoms. The new atoms will be an instance of SAtoms. All
-		 * substitution job is done by a substitution method of the
-		 * new atoms. */
-		AtomSubstitutions(const FineAtoms& oa, FineAtoms& na)
-			: old_atoms(oa), new_atoms(na) {}
-		/** Construct a copy of the object using a different instances
-		 * of old atoms and new atoms, which are supposed to be
-		 * semantically same as the atoms from as. */
-		AtomSubstitutions(const AtomSubstitutions& as, const FineAtoms& oa, FineAtoms& na);
-		virtual ~AtomSubstitutions() {}
-		/** This is called during the substitution job from the
-		 * substitution method of the new atoms. This says that the
-		 * new name, say "a_m3" is a substitution of old name "a"
-		 * shifted by -3. */
-		void add_substitution(const char* newname, const char* oldname, int tshift);
-		/** This is called when all substitutions are finished. This
-		 * forms the new external ordering of the new atoms and calls
-		 * parsing_finished() for the new atoms with the given ordering type. */
-		void substitutions_finished(VarOrdering::ord_type ot);
-		/** Returns a new name for old name and given tshift. For "a"
-		 * and tshift=-3, it returns "a_m3". If there is no such
-		 * substitution, it returns NULL. */
-		const char* get_new4old(const char* oldname, int tshift) const;
-		/** Return new2old. */
-		const Tshiftmap& get_new2old() const
-			{return new2old;}
-		/** Return old2new. */
-		const Toldnamemap& get_old2new() const
-			{return old2new;}
-		/** Return substitution info. */
-		const SubstInfo& get_info() const
-			{return info;}
-		/** Return old atoms. */
-		const FineAtoms& get_old_atoms() const
-			{return old_atoms;}
-		/** Return new atoms. */
-		const FineAtoms& get_new_atoms() const
-			{return new_atoms;}
-		/** Debug print. */
-		void print() const;
-	};
+  /** This class tracks all atom substitutions during the job and
+   * then builds structures when all substitutions are finished. */
+  class AtomSubstitutions
+  {
+  public:
+    typedef pair<const char *, int> Tshiftname;
+    typedef map<const char *, Tshiftname, ltstr> Tshiftmap;
+    typedef set<Tshiftname> Tshiftnameset;
+    typedef map<const char *, Tshiftnameset, ltstr> Toldnamemap;
+  protected:
+    /** This maps a new name to a shifted old name. This is, one
+     * entry looks as "a_m3 ==> a(-3)", saying that a variable
+     * "a_m3" corresponds to a variable "a" lagged by 3. */
+    Tshiftmap new2old;
+    /** This is inverse to new2old, which is not unique. For old
+     * name, say "a", it says what new names are derived with what
+     * shifts from the "a". For example, it can map "a" to a two
+     * element set {["a_m3", +3], ["a_p2", -2]}. This says that
+     * leading "a_m3" by 3 one gets old "a" and lagging "a_p2" by
+     * 2 one gets also old "a". */
+    Toldnamemap old2new;
+    /** This is a reference to old atoms with multiple leads and
+     * lags. They are supposed to be used with parsing finished
+     * being had called, so that the external ordering is
+     * available. */
+    const FineAtoms &old_atoms;
+    /** This is a reference to new atoms. All name pointers point
+     * to storage of these atoms. */
+    FineAtoms &new_atoms;
+    /** Substitutions information. */
+    SubstInfo info;
+  public:
+    /** Create the object with reference to the old and new
+     * atoms. In the beginning, old atoms are supposed to be with
+     * parsing_finished() called, and new atoms a simple copy of
+     * old atoms. The new atoms will be an instance of SAtoms. All
+     * substitution job is done by a substitution method of the
+     * new atoms. */
+    AtomSubstitutions(const FineAtoms &oa, FineAtoms &na)
+      : old_atoms(oa), new_atoms(na)
+    {
+    }
+    /** Construct a copy of the object using a different instances
+     * of old atoms and new atoms, which are supposed to be
+     * semantically same as the atoms from as. */
+    AtomSubstitutions(const AtomSubstitutions &as, const FineAtoms &oa, FineAtoms &na);
+    virtual ~AtomSubstitutions()
+    {
+    }
+    /** This is called during the substitution job from the
+     * substitution method of the new atoms. This says that the
+     * new name, say "a_m3" is a substitution of old name "a"
+     * shifted by -3. */
+    void add_substitution(const char *newname, const char *oldname, int tshift);
+    /** This is called when all substitutions are finished. This
+     * forms the new external ordering of the new atoms and calls
+     * parsing_finished() for the new atoms with the given ordering type. */
+    void substitutions_finished(VarOrdering::ord_type ot);
+    /** Returns a new name for old name and given tshift. For "a"
+     * and tshift=-3, it returns "a_m3". If there is no such
+     * substitution, it returns NULL. */
+    const char *get_new4old(const char *oldname, int tshift) const;
+    /** Return new2old. */
+    const Tshiftmap &
+    get_new2old() const
+    {
+      return new2old;
+    }
+    /** Return old2new. */
+    const Toldnamemap &
+    get_old2new() const
+    {
+      return old2new;
+    }
+    /** Return substitution info. */
+    const SubstInfo &
+    get_info() const
+    {
+      return info;
+    }
+    /** Return old atoms. */
+    const FineAtoms &
+    get_old_atoms() const
+    {
+      return old_atoms;
+    }
+    /** Return new atoms. */
+    const FineAtoms &
+    get_new_atoms() const
+    {
+      return new_atoms;
+    }
+    /** Debug print. */
+    void print() const;
+  };
 
-	class SAtoms : public FineAtoms {
-	public:
-		SAtoms()
-			: FineAtoms() {}
-		SAtoms(const SAtoms& sa)
-			: FineAtoms(sa) {}
-		virtual ~SAtoms() {}
-		/** This substitutes all lags and leads for all exogenous and
-		 * all lags and leads greater than 1 for all endogenous
-		 * variables. This is useful for perfect foresight problems
-		 * where we can do that. */
-		void substituteAllLagsAndLeads(FormulaParser& fp, AtomSubstitutions& as);
-		/** This substitutes all lags of all endo and exo and one step
-		 * leads of all exo variables. This is useful for stochastic
-		 * models where we cannot solve leads more than 1. */
-		void substituteAllLagsAndExo1Leads(FormulaParser& fp, AtomSubstitutions& as);
-	protected:
-		/** This finds an endogenous variable name which occurs between
-		 * ll1 and ll2 included. */
-		const char* findEndoWithLeadInInterval(int ll1, int ll2) const
-			{return findNameWithLeadInInterval(get_endovars(), ll1, ll2);}
-		/** This finds an exogenous variable name which occurs between
-		 * ll1 and ll2 included. */
-		const char* findExoWithLeadInInterval(int ll1, int ll2) const
-			{return findNameWithLeadInInterval(get_exovars(), ll1, ll2);}
+  class SAtoms : public FineAtoms
+  {
+  public:
+    SAtoms()
+      : FineAtoms()
+    {
+    }
+    SAtoms(const SAtoms &sa)
+      : FineAtoms(sa)
+    {
+    }
+    virtual ~SAtoms()
+    {
+    }
+    /** This substitutes all lags and leads for all exogenous and
+     * all lags and leads greater than 1 for all endogenous
+     * variables. This is useful for perfect foresight problems
+     * where we can do that. */
+    void substituteAllLagsAndLeads(FormulaParser &fp, AtomSubstitutions &as);
+    /** This substitutes all lags of all endo and exo and one step
+     * leads of all exo variables. This is useful for stochastic
+     * models where we cannot solve leads more than 1. */
+    void substituteAllLagsAndExo1Leads(FormulaParser &fp, AtomSubstitutions &as);
+  protected:
+    /** This finds an endogenous variable name which occurs between
+     * ll1 and ll2 included. */
+    const char *
+    findEndoWithLeadInInterval(int ll1, int ll2) const
+    {
+      return findNameWithLeadInInterval(get_endovars(), ll1, ll2);
+    }
+    /** This finds an exogenous variable name which occurs between
+     * ll1 and ll2 included. */
+    const char *
+    findExoWithLeadInInterval(int ll1, int ll2) const
+    {
+      return findNameWithLeadInInterval(get_exovars(), ll1, ll2);
+    }
 
-		/** This attempts to find a non registered name of the form
-		 * <str>_m<abs(ll)> or <str>_p<abs(ll)>. A letter 'p' is
-		 * chosen if ll is positive, 'm' if negative. If a name of
-		 * such form is already registered, one more character (either
-		 * 'p' or 'm') is added and the test is performed again. The
-		 * resulting name is returned in a string out. */ 
-		void attemptAuxName(const char* str, int ll, string& out) const;
+    /** This attempts to find a non registered name of the form
+     * <str>_m<abs(ll)> or <str>_p<abs(ll)>. A letter 'p' is
+     * chosen if ll is positive, 'm' if negative. If a name of
+     * such form is already registered, one more character (either
+     * 'p' or 'm') is added and the test is performed again. The
+     * resulting name is returned in a string out. */
+    void attemptAuxName(const char *str, int ll, string &out) const;
 
-		/** This makes auxiliary variables to eliminate all leads/lags
-		 * greater/less than or equal to start up to the limit_lead
-		 * for a variable with the given name. If the limit_lead is
-		 * greater/less than the maxlead/minlag of the variable, than
-		 * maxlead/minlag is used. This process is recorded in
-		 * AtomSubstitutions. The new auxiliary variables and their
-		 * atoms are created in this object. The auxiliary equations
-		 * are created in the given FormulaParser. The value of step
-		 * is allowed to be either -1 (lags) or +1 (leads). */
-		void makeAuxVariables(const char* name, int step, int start, int limit_lead,
-							  FormulaParser& fp, AtomSubstitutions& as);
-	private:
-		/** This is a worker routine for findEndoWithLeadInInterval
-		 * and findExoWithLeadInInterval. */
-		const char* findNameWithLeadInInterval(const vector<const char*>& names,
-											   int ll1, int ll2) const;
+    /** This makes auxiliary variables to eliminate all leads/lags
+     * greater/less than or equal to start up to the limit_lead
+     * for a variable with the given name. If the limit_lead is
+     * greater/less than the maxlead/minlag of the variable, than
+     * maxlead/minlag is used. This process is recorded in
+     * AtomSubstitutions. The new auxiliary variables and their
+     * atoms are created in this object. The auxiliary equations
+     * are created in the given FormulaParser. The value of step
+     * is allowed to be either -1 (lags) or +1 (leads). */
+    void makeAuxVariables(const char *name, int step, int start, int limit_lead,
+                          FormulaParser &fp, AtomSubstitutions &as);
+  private:
+    /** This is a worker routine for findEndoWithLeadInInterval
+     * and findExoWithLeadInInterval. */
+    const char *findNameWithLeadInInterval(const vector<const char *> &names,
+                                           int ll1, int ll2) const;
 
-	};
+  };
 
 };
 
diff --git a/dynare++/parser/cc/csv_parser.h b/dynare++/parser/cc/csv_parser.h
index 3edc52a4e92f6d6d0f0ce830943ae330da09d942..95b12354e995b8976fc7b14221c082b3bf400e29 100644
--- a/dynare++/parser/cc/csv_parser.h
+++ b/dynare++/parser/cc/csv_parser.h
@@ -5,38 +5,58 @@
 #ifndef OGP_CSV_PARSER
 #define OGP_CSV_PARSER
 
-namespace ogp {
-
-	class CSVParserPeer {
-	public:
-		virtual ~CSVParserPeer() {}
-		virtual void item(int irow, int icol, const char* str, int length) = 0;
-	};
-
-	class CSVParser {
-	private:
-		CSVParserPeer& peer;
-		int row;
-		int col;
-		const char* parsed_string;
-	public:
-		CSVParser(CSVParserPeer& p)
-			: peer(p), row(0), col(0), parsed_string(0) {}
-		CSVParser(const CSVParser& csvp)
-			: peer(csvp.peer), row(csvp.row),
-			  col(csvp.col), parsed_string(csvp.parsed_string) {}
-		virtual ~CSVParser() {}
-
-		void csv_error(const char* mes);
-		void csv_parse(int length, const char* str);
-
-		void nextrow()
-			{row++; col = 0;}
-		void nextcol()
-			{col++;}
-		void item(int off, int length)
-			{peer.item(row, col, parsed_string+off, length);}
-	};
+namespace ogp
+{
+
+  class CSVParserPeer
+  {
+  public:
+    virtual ~CSVParserPeer()
+    {
+    }
+    virtual void item(int irow, int icol, const char *str, int length) = 0;
+  };
+
+  class CSVParser
+  {
+  private:
+    CSVParserPeer &peer;
+    int row;
+    int col;
+    const char *parsed_string;
+  public:
+    CSVParser(CSVParserPeer &p)
+      : peer(p), row(0), col(0), parsed_string(0)
+    {
+    }
+    CSVParser(const CSVParser &csvp)
+      : peer(csvp.peer), row(csvp.row),
+        col(csvp.col), parsed_string(csvp.parsed_string)
+    {
+    }
+    virtual ~CSVParser()
+    {
+    }
+
+    void csv_error(const char *mes);
+    void csv_parse(int length, const char *str);
+
+    void
+    nextrow()
+    {
+      row++; col = 0;
+    }
+    void
+    nextcol()
+    {
+      col++;
+    }
+    void
+    item(int off, int length)
+    {
+      peer.item(row, col, parsed_string+off, length);
+    }
+  };
 };
 
 #endif
diff --git a/dynare++/parser/cc/dynamic_atoms.h b/dynare++/parser/cc/dynamic_atoms.h
index 7d44d6dcc2e71faa4066145281b9229dbd6c7bc5..cf28da2ef67b5e74b9125919c6bc251881d09a21 100644
--- a/dynare++/parser/cc/dynamic_atoms.h
+++ b/dynare++/parser/cc/dynamic_atoms.h
@@ -13,389 +13,462 @@
 #include <string>
 #include <cstring>
 
-namespace ogp {
-	using std::vector;
-	using std::map;
-	using std::set;
-	using std::string;
+namespace ogp
+{
+  using std::vector;
+  using std::map;
+  using std::set;
+  using std::string;
 
-	struct ltstr {
-		bool operator()(const char* a1, const char* a2) const
-			{ return strcmp(a1, a2) < 0; }
-	};
+  struct ltstr
+  {
+    bool
+    operator()(const char *a1, const char *a2) const
+    {
+      return strcmp(a1, a2) < 0;
+    }
+  };
 
-	/** Class storing names. We will keep names of variables in
-	 * various places, and all these pointers will point to one
-	 * storage, which will be responsible for allocation and
-	 * deallocation. The main function of the class is to allocate
-	 * space for names, and return a pointer of the stored name if
-	 * required. */
-	class NameStorage {
-	protected:
-		/** Vector of names allocated, this is the storage. */
-		vector<char*> name_store;
-		/** Map useful to quickly decide if the name is already
-		 * allocated or not. */
-		set<const char*, ltstr> name_set;
-	public:
-		NameStorage() {}
-		NameStorage(const NameStorage& stor);
-		virtual ~NameStorage();
-		/** Query for the name. If the name has been stored, it
-		 * returns its address, otherwise 0. */
-		const char* query(const char* name) const;
-		/** Insert the name if it has not been inserted yet, and
-		 * return its new or old allocation. */
-		const char* insert(const char* name);
-		int num() const
-			{return (int)name_store.size();}
-		const char* get_name(int i) const
-			{return name_store[i];}
-		/** Debug print. */
-		void print() const;
-	};
+  /** Class storing names. We will keep names of variables in
+   * various places, and all these pointers will point to one
+   * storage, which will be responsible for allocation and
+   * deallocation. The main function of the class is to allocate
+   * space for names, and return a pointer of the stored name if
+   * required. */
+  class NameStorage
+  {
+  protected:
+    /** Vector of names allocated, this is the storage. */
+    vector<char *> name_store;
+    /** Map useful to quickly decide if the name is already
+     * allocated or not. */
+    set<const char *, ltstr> name_set;
+  public:
+    NameStorage()
+    {
+    }
+    NameStorage(const NameStorage &stor);
+    virtual
+    ~NameStorage();
+    /** Query for the name. If the name has been stored, it
+     * returns its address, otherwise 0. */
+    const char *query(const char *name) const;
+    /** Insert the name if it has not been inserted yet, and
+     * return its new or old allocation. */
+    const char *insert(const char *name);
+    int
+    num() const
+    {
+      return (int) name_store.size();
+    }
+    const char *
+    get_name(int i) const
+    {
+      return name_store[i];
+    }
+    /** Debug print. */
+    void print() const;
+  };
 
-	class Constants : public AtomValues {
-	public:
-		/** Type for a map mapping tree indices to double values. */
-		typedef map<int,double> Tconstantmap;
-		typedef map<int,int> Tintintmap;
-	protected:
-		/** Map mapping a tree index of a constant to its double value. */ 
-		Tconstantmap cmap;
-	public:
-		Constants() {}
-		/** Copy constructor. */
-		Constants(const Constants& c)
-			: cmap(c.cmap), cinvmap(c.cinvmap) {}
-		/** Copy constructor registering the constants in the given
-		 * tree. The mapping from old tree indices to new ones is
-		 * traced in tmap. */
-		Constants(const Constants& c, OperationTree& otree, Tintintmap& tmap)
-			{import_constants(c, otree, tmap);}
-		/** Import constants registering their tree indices in the
-		 * given tree. The mapping form old tree indices to new ones
-		 * is traced in tmap. */
-		void import_constants(const Constants& c, OperationTree& otree, Tintintmap& tmap);
-		/** Implements AtomValues interface. This sets the values to
-		 * the evaluation tree EvalTree. */
-		void setValues(EvalTree& et) const;
-		/** This adds a constant with the given tree index. The
-		 * constant must be checked previously and asserted that it
-		 * does not exist. */
-		void add_constant(int t, double val);
-		/** Returns true if the tree index is either an hardwired
-		 * constant (initial number OperationTree:num_constants in
-		 * OperationTree) or the tree index is a registered constant
-		 * by add_constant method. */
-		bool is_constant(int t) const;
-		double get_constant_value(int t) const;
-		/** Return -1 if the given string representation of a constant
-		 * is not among the constants (double represenations). If it
-		 * is, its tree index is returned. */ 
-		int check(const char* str) const;
-		/** Debug print. */
-		void print() const;
-		const Tconstantmap& get_constantmap() const
-			{return cmap;}
-	private:
-		/** Inverse map to Tconstantmap. */
-		typedef map<double,int> Tconstantinvmap;
-		/** This is an inverse map to cmap. This is only used for fast
-		 * queries for the existing double constants in check
-		 * method and add_constant. */
-		Tconstantinvmap cinvmap;
-	};
+  class Constants : public AtomValues
+  {
+  public:
+    /** Type for a map mapping tree indices to double values. */
+    typedef map<int, double> Tconstantmap;
+    typedef map<int, int> Tintintmap;
+  protected:
+    /** Map mapping a tree index of a constant to its double value. */
+    Tconstantmap cmap;
+  public:
+    Constants()
+    {
+    }
+    /** Copy constructor. */
+    Constants(const Constants &c)
+      : cmap(c.cmap), cinvmap(c.cinvmap)
+    {
+    }
+    /** Copy constructor registering the constants in the given
+     * tree. The mapping from old tree indices to new ones is
+     * traced in tmap. */
+    Constants(const Constants &c, OperationTree &otree, Tintintmap &tmap)
+    {
+      import_constants(c, otree, tmap);
+    }
+    /** Import constants registering their tree indices in the
+     * given tree. The mapping form old tree indices to new ones
+     * is traced in tmap. */
+    void import_constants(const Constants &c, OperationTree &otree, Tintintmap &tmap);
+    /** Implements AtomValues interface. This sets the values to
+     * the evaluation tree EvalTree. */
+    void setValues(EvalTree &et) const;
+    /** This adds a constant with the given tree index. The
+     * constant must be checked previously and asserted that it
+     * does not exist. */
+    void add_constant(int t, double val);
+    /** Returns true if the tree index is either an hardwired
+     * constant (initial number OperationTree:num_constants in
+     * OperationTree) or the tree index is a registered constant
+     * by add_constant method. */
+    bool is_constant(int t) const;
+    double get_constant_value(int t) const;
+    /** Return -1 if the given string representation of a constant
+     * is not among the constants (double represenations). If it
+     * is, its tree index is returned. */
+    int check(const char *str) const;
+    /** Debug print. */
+    void print() const;
+    const Tconstantmap &
+    get_constantmap() const
+    {
+      return cmap;
+    }
+  private:
+    /** Inverse map to Tconstantmap. */
+    typedef map<double, int> Tconstantinvmap;
+    /** This is an inverse map to cmap. This is only used for fast
+     * queries for the existing double constants in check
+     * method and add_constant. */
+    Tconstantinvmap cinvmap;
+  };
 
-    /** This class is a parent to Atoms classes which distinguish between
-	 * constants (numerical literals), and variables with lags and
-	 * leads. This abstraction does not distinguish between a parameter
-	 * and a variable without lag or lead. In this sense, everything is a
-	 * variable.*/
-	class DynamicAtoms : public Atoms, public Constants {
-	public:
-		/** Definition of a type mapping lags to the indices of the variables. */
-		typedef map<int,int> Tlagmap;
-	protected:
-		/** Definition of a type mapping names of the atoms to Tlagmap. */
-		typedef map<const char*, Tlagmap, ltstr> Tvarmap;
-		/** Definition of a type mapping indices of variables to the variable names. */
-		typedef map<int, const char*> Tindexmap;
-		/** This is just a storage for variable names, since all other
-		 * instances of a variable name just point to the memory
-		 * allocated by this object. */
-		NameStorage varnames;
-		/** This is the map for variables. Each variable name is
-		 * mapped to the Tlagmap, which maps lags/leads to the nulary
-		 * term indices in the tree. */
-		Tvarmap vars;
-		/** This is almost inverse map to the vars. It maps variable
-		 * indices to the names. A returned name can be in turn used
-		 * as a key in vars. */
-		Tindexmap indices;
+  /** This class is a parent to Atoms classes which distinguish between
+   * constants (numerical literals), and variables with lags and
+   * leads. This abstraction does not distinguish between a parameter
+   * and a variable without lag or lead. In this sense, everything is a
+   * variable.*/
+  class DynamicAtoms : public Atoms, public Constants
+  {
+  public:
+    /** Definition of a type mapping lags to the indices of the variables. */
+    typedef map<int, int> Tlagmap;
+  protected:
+    /** Definition of a type mapping names of the atoms to Tlagmap. */
+    typedef map<const char *, Tlagmap, ltstr> Tvarmap;
+    /** Definition of a type mapping indices of variables to the variable names. */
+    typedef map<int, const char *> Tindexmap;
+    /** This is just a storage for variable names, since all other
+     * instances of a variable name just point to the memory
+     * allocated by this object. */
+    NameStorage varnames;
+    /** This is the map for variables. Each variable name is
+     * mapped to the Tlagmap, which maps lags/leads to the nulary
+     * term indices in the tree. */
+    Tvarmap vars;
+    /** This is almost inverse map to the vars. It maps variable
+     * indices to the names. A returned name can be in turn used
+     * as a key in vars. */
+    Tindexmap indices;
 
-		/** Number of variables. */
-		int nv;
-		/** Minimum lag, if there is at least one lag, than this is a negative number. */
-		int minlag;
-		/** Maximum lead, if there is at least one lead, than this is a positive number. */
-		int maxlead;
-	public:
-		/** Construct empty DynamicAtoms. */
-		DynamicAtoms();
-		DynamicAtoms(const DynamicAtoms& da);
-		virtual ~DynamicAtoms() {}
-		/** Check the nulary term identified by its string
-		 * representation. The nulary term can be either a constant or
-		 * a variable. If constant, -1 is returned so that it could be
-		 * assigned regardless if the same constant has already
-		 * appeared or not. If variable, then -1 is returned only if
-		 * the variable has not been assigned an index, otherwise the
-		 * assigned index is returned. */ 
-		int check(const char* name) const;
-		/** Assign the nulary term identified by its string
-		 * representation. This method should be called when check()
-		 * returns -1. */
-		void assign(const char* name, int t);
-		/** Return a number of all variables. */
-		int nvar() const
-			{ return nv; }
-		/** Return the vector of variable indices. */
-		vector<int> variables() const;
-		/** Return max lead and min lag for a variable given by the
-		 * index. If a variable cannot be found, the method retursn
-		 * the smallest integer as maxlead and the largest integer as
-		 * minlag. */
-		void varspan(int t, int& mlead, int& mlag) const;
-		/** Return max lead and min lag for a variable given by the
-		 * name (without lead, lag). The same is valid if the variable
-		 * name cannot be found. */
-		void varspan(const char* name, int& mlead, int& mlag) const;
-		/** Return max lead and min lag for a vector of variables given by the names. */
-		void varspan(const vector<const char*>& names, int& mlead, int& mlag) const;
-		/** Return true for all tree indices corresponding to a
-		 * variable in the sense of this class. (This is parameters,
-		 * exo and endo). Since the semantics of 'variable' will be
-		 * changed in subclasses, we use name 'named atom'. These are
-		 * all atoms but constants. */
-		bool is_named_atom(int t) const;
-		/** 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
-		 * exception if the tree index t is not a named atom. */
-		const char* name(int t) const;
-		/** Return the lead/lag for the tree index. It throws an
-		 * exception if the tree index t is not a named atom. */
-		int lead(int t) const;
-		/** Return maximum lead. */
-		int get_maxlead() const
-			{return maxlead;}
-		/** Return minimum lag. */
-		int get_minlag() const
-			{return minlag;}
-		/** Return the name storage to allow querying to other
-		 * classes. */
-		const NameStorage& get_name_storage() const
-			{return varnames;}
-		/** Assign the variable with a given lead. The varname must be
-		 * from the varnames storage. The method checks if the
-		 * variable iwht the given lead/lag is not assigned. If so, an
-		 * exception is thrown. */
-		void assign_variable(const char* varname, int ll, int t);
-		/** Unassign the variable with a given lead and given tree
-		 * index. The tree index is only provided as a check. An
-		 * exception is thrown if the name, ll, and the tree index t
-		 * are not consistent. The method also updates nv, indices,
-		 * maxlead and minlag. The varname must be from the varnames
-		 * storage. */
-		void unassign_variable(const char* varname, int ll, int t);
-		/** Debug print. */
-		void print() const;
-	protected:
-		/** Do the check for the variable. A subclass may need to
-		 * reimplement this so that it could raise an error if the
-		 * variable is not among a given list. */
-		virtual int check_variable(const char* name) const;
-		/** Assign the constant. */
-		void assign_constant(const char* name, int t);
-		/** Assign the variable. */
-		void assign_variable(const char* name, int t);
-		/** The method just updates minlag or/and maxlead. Note that
-		 * when assigning variables, the update is done when inserting
-		 * to the maps, however, if removing a variable, we need to
-		 * call this method. */
-		void update_minmaxll();
-		/** The method parses the string to recover a variable name
-		 * and lag/lead ll. The variable name doesn't contain a lead/lag. */
-		virtual void parse_variable(const char* in, string& out, int& ll) const = 0;
-	public:
-		/** Return true if the str represents a double.*/ 
-		static bool is_string_constant(const char* str);
-	};
+    /** Number of variables. */
+    int nv;
+    /** Minimum lag, if there is at least one lag, than this is a negative number. */
+    int minlag;
+    /** Maximum lead, if there is at least one lead, than this is a positive number. */
+    int maxlead;
+  public:
+    /** Construct empty DynamicAtoms. */
+    DynamicAtoms();
+    DynamicAtoms(const DynamicAtoms &da);
+    virtual ~DynamicAtoms()
+    {
+    }
+    /** Check the nulary term identified by its string
+     * representation. The nulary term can be either a constant or
+     * a variable. If constant, -1 is returned so that it could be
+     * assigned regardless if the same constant has already
+     * appeared or not. If variable, then -1 is returned only if
+     * the variable has not been assigned an index, otherwise the
+     * assigned index is returned. */
+    int check(const char *name) const;
+    /** Assign the nulary term identified by its string
+     * representation. This method should be called when check()
+     * returns -1. */
+    void assign(const char *name, int t);
+    /** Return a number of all variables. */
+    int
+    nvar() const
+    {
+      return nv;
+    }
+    /** Return the vector of variable indices. */
+    vector<int> variables() const;
+    /** Return max lead and min lag for a variable given by the
+     * index. If a variable cannot be found, the method retursn
+     * the smallest integer as maxlead and the largest integer as
+     * minlag. */
+    void varspan(int t, int &mlead, int &mlag) const;
+    /** Return max lead and min lag for a variable given by the
+     * name (without lead, lag). The same is valid if the variable
+     * name cannot be found. */
+    void varspan(const char *name, int &mlead, int &mlag) const;
+    /** Return max lead and min lag for a vector of variables given by the names. */
+    void varspan(const vector<const char *> &names, int &mlead, int &mlag) const;
+    /** Return true for all tree indices corresponding to a
+     * variable in the sense of this class. (This is parameters,
+     * exo and endo). Since the semantics of 'variable' will be
+     * changed in subclasses, we use name 'named atom'. These are
+     * all atoms but constants. */
+    bool is_named_atom(int t) const;
+    /** 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
+     * exception if the tree index t is not a named atom. */
+    const char *name(int t) const;
+    /** Return the lead/lag for the tree index. It throws an
+     * exception if the tree index t is not a named atom. */
+    int lead(int t) const;
+    /** Return maximum lead. */
+    int
+    get_maxlead() const
+    {
+      return maxlead;
+    }
+    /** Return minimum lag. */
+    int
+    get_minlag() const
+    {
+      return minlag;
+    }
+    /** Return the name storage to allow querying to other
+     * classes. */
+    const NameStorage &
+    get_name_storage() const
+    {
+      return varnames;
+    }
+    /** Assign the variable with a given lead. The varname must be
+     * from the varnames storage. The method checks if the
+     * variable iwht the given lead/lag is not assigned. If so, an
+     * exception is thrown. */
+    void assign_variable(const char *varname, int ll, int t);
+    /** Unassign the variable with a given lead and given tree
+     * index. The tree index is only provided as a check. An
+     * exception is thrown if the name, ll, and the tree index t
+     * are not consistent. The method also updates nv, indices,
+     * maxlead and minlag. The varname must be from the varnames
+     * storage. */
+    void unassign_variable(const char *varname, int ll, int t);
+    /** Debug print. */
+    void print() const;
+  protected:
+    /** Do the check for the variable. A subclass may need to
+     * reimplement this so that it could raise an error if the
+     * variable is not among a given list. */
+    virtual int check_variable(const char *name) const;
+    /** Assign the constant. */
+    void assign_constant(const char *name, int t);
+    /** Assign the variable. */
+    void assign_variable(const char *name, int t);
+    /** The method just updates minlag or/and maxlead. Note that
+     * when assigning variables, the update is done when inserting
+     * to the maps, however, if removing a variable, we need to
+     * call this method. */
+    void update_minmaxll();
+    /** The method parses the string to recover a variable name
+     * and lag/lead ll. The variable name doesn't contain a lead/lag. */
+    virtual void parse_variable(const char *in, string &out, int &ll) const = 0;
+  public:
+    /** Return true if the str represents a double.*/
+    static bool is_string_constant(const char *str);
+  };
 
-
-	/** This class is a parent of all orderings of the dynamic atoms
-	 * of variables which can appear before t, at t, or after t. It
-	 * encapsulates the ordering, and the information about the number
-	 * of static (appearing only at time t) predetermined (appearing
-	 * before t and possibly at t), both (appearing before t and after
-	 * t and possibly at t) and forward looking (appearing after t and
-	 * possibly at t).
-	 *
-	 * The constructor takes a list of variable names. The class also
-	 * provides mapping from the ordering of the variables in the list
-	 * (outer) to the new ordering (at time t) and back.
-	 *
-	 * The user of the subclass must call do_ordering() after
-	 * initialization.
-	 *
-	 * The class contains a few preimplemented methods for
-	 * ordering. The class is used in this way: Make a subclass, and
-	 * implement pure virtual do_ordering() by just plugging a
-	 * preimplemented method, or plugging your own implementation. The
-	 * method do_ordering() is called by the user after the constructor.
-	 */
-	class VarOrdering {
-	protected:
-		/** Number of static variables. */
-		int n_stat;
-		/** Number of predetermined variables. */
-		int n_pred;
-		/** Number of both variables. */
-		int n_both;
-		/** Number of forward looking variables. */
-		int n_forw;
-		/** This is a set of tree indices corresponding to the
-		 * variables at all times as they occur in the formulas. In
-		 * fact, since this is used only for derivatives, the ordering
-		 * of this vector is only important for ordering of the
-		 * derivatives, in other contexts the ordering is not
-		 * important, so it is rather a set of indices.*/
-		vector<int> der_atoms;
-		/** This maps tree index of the variable to the position in
-		 * the row of the ordering. One should be careful with making
-		 * space in the positions for variables not appearing at time
-		 * t. For instance in the pred(t-1), both(t-1), stat(t),
-		 * pred(t), both(t), forw(t), both(t+1), forw(t+1) ordering,
-		 * the variables x(t-1), y(t-1), x(t+1), z(t-1), z(t), and
-		 * z(t+1) having tree indices 6,5,4,3,2,1 will be ordered as
-		 * follows: y(t-1), x(t-1), z(t-1), [y(t)], [x(t)], z(t),
-		 * x(t+1), where a bracketed expresion means non-existent by
-		 * occupying a space. The map thus will look as follows:
-		 * {5->0, 6->1, 3->2, 2->5, 3->6}. Note that nothing is mapped
-		 * to positions 3 and 4. */ 
-		map<int,int> positions;
-		/** This maps an ordering of the list of variables in
-		 * constructor to the new ordering (at time t). The length is
-		 * the number of variables. */
-		vector<int> outer2y;
-		/** This maps a new ordering to the ordering of the list of
-		 * variables in constructor (at time t). The length is the
-		 * number of variables. */
-		vector<int> y2outer;
-		/** This is just a reference for variable names to keep it
-		 * from constructor to do_ordering() implementations. */
-		const vector<const char*>& varnames;
-		/** This is just a reference to atoms to keep it from
-		 * constructor to do_ordering() implementations. */
-		const DynamicAtoms& atoms;
-	public:
-		/** This is an enum type for an ordering type implemented by
-		 * do_general. */
-		enum ord_type {pbspbfbf, bfspbfpb};
-		/** Construct the ordering of the variables given by the names
-		 * with their dynamic occurrences defined by the atoms. It
-		 * calls the virtual method do_ordering which can be
-		 * reimplemented. */
-		VarOrdering(const vector<const char*>& vnames, const DynamicAtoms& a)
-			: n_stat(0), n_pred(0), n_both(0), n_forw(0), varnames(vnames), atoms(a)
-			{}
-		VarOrdering(const VarOrdering& vo, const vector<const char*>& vnames,
-					const DynamicAtoms& a);
-		virtual VarOrdering* clone(const vector<const char*>& vnames,
-								   const DynamicAtoms& a) const = 0;
-		/** Destructor does nothing here. */
-		virtual ~VarOrdering() {}
-		/** This is the method setting the ordering and the map. A
-		 * subclass must reimplement it, possibly using a
-		 * preimplemented ordering. This method must be called by the
-		 * user after the class has been created. */
-		virtual void do_ordering() = 0;
-		/** Return number of static. */
-		int nstat() const
-			{return n_stat;}
-		/** Return number of predetermined. */
-		int npred() const
-			{return n_pred;}
-		/** Return number of both. */
-		int nboth() const
-			{return n_both;}
-		/** Return number of forward looking. */
-		int nforw() const
-			{return n_forw;}
-		/** Return the set of tree indices for derivatives. */
-		const vector<int>& get_der_atoms() const
-			{return der_atoms;}
-		/** Return the y2outer. */
-		const vector<int>& get_y2outer() const
-			{return y2outer;}
-		/** Return the outer2y. */
-		const vector<int>& get_outer2y() const
-			{return outer2y;}
-		/** Query the atom given by the tree index. True is returned
-		 * if the atom is one of the variables in the object. */
-		bool check(int t) const;
-		/** Return the position of the atom (nulary term) given by a
-		 * tree index. It is a lookup to the map. If the atom cannot
-		 * be found, the exception is raised. */
-		int get_pos_of(int t) const;
-		/** This returns a length of ordered row of atoms. In all
-		 * cases so far, it does not depend on the ordering and it is
-		 * as follows. */
-		int length() const
-			{return n_stat+2*n_pred+3*n_both+2*n_forw;}
-		/** Debug print. */
-		void print() const;
-	protected:
-		/** This is a general ordering method which orders the
-		 * variables by the given ordering ord_type. See documentation
-		 * for respective do_ methods. */
-		void do_general(ord_type ordering);
-		/** This is a preimplemented ordering for do_ordering()
-		 * method. It assumes that the variables appear only at time
-		 * t-1, t, t+1. It orders the atoms as pred(t-1), both(t-1),
-		 * stat(t), pred(t), both(t), forw(t), both(t+1),
-		 * forw(t+1). It builds the der_atoms, the map of positions,
-		 * as well as y2outer and outer2y. */
-		void do_pbspbfbf()
-			{do_general(pbspbfbf);}
-		/** This is a preimplemented ordering for do_ordering()
-		 * method. It assumes that the variables appear only at time
-		 * t-1, t, t+1. It orders the atoms as both(t+1), forw(t+1),
-		 * stat(t), pred(t), both(t), forw(t), pred(t-1),
-		 * both(t-1). It builds the der_atoms, the map of positions,
-		 * as well as y2outer and outer2y. */
-		void do_bfspbfpb()
-			{do_general(bfspbfpb);}
-		/** This is a preimplemented ordering for do_ordering()
-		 * method. It makes no assumptions about occurences of
-		 * variables at different times. It orders the atoms with
-		 * increasing time keeping the given ordering within one
-		 * time. This implies that y2outer and outer2y will be
-		 * identities. The der_atoms will be just a sequence of atoms
-		 * from the least to the most time preserving the order of atoms
-		 * within one time. */
-		void do_increasing_time();
-	private:
-		/** Declare this copy constructor as private to hide it. */
-		VarOrdering(const VarOrdering& vo);
-	};
+  /** This class is a parent of all orderings of the dynamic atoms
+   * of variables which can appear before t, at t, or after t. It
+   * encapsulates the ordering, and the information about the number
+   * of static (appearing only at time t) predetermined (appearing
+   * before t and possibly at t), both (appearing before t and after
+   * t and possibly at t) and forward looking (appearing after t and
+   * possibly at t).
+   *
+   * The constructor takes a list of variable names. The class also
+   * provides mapping from the ordering of the variables in the list
+   * (outer) to the new ordering (at time t) and back.
+   *
+   * The user of the subclass must call do_ordering() after
+   * initialization.
+   *
+   * The class contains a few preimplemented methods for
+   * ordering. The class is used in this way: Make a subclass, and
+   * implement pure virtual do_ordering() by just plugging a
+   * preimplemented method, or plugging your own implementation. The
+   * method do_ordering() is called by the user after the constructor.
+   */
+  class VarOrdering
+  {
+  protected:
+    /** Number of static variables. */
+    int n_stat;
+    /** Number of predetermined variables. */
+    int n_pred;
+    /** Number of both variables. */
+    int n_both;
+    /** Number of forward looking variables. */
+    int n_forw;
+    /** This is a set of tree indices corresponding to the
+     * variables at all times as they occur in the formulas. In
+     * fact, since this is used only for derivatives, the ordering
+     * of this vector is only important for ordering of the
+     * derivatives, in other contexts the ordering is not
+     * important, so it is rather a set of indices.*/
+    vector<int> der_atoms;
+    /** This maps tree index of the variable to the position in
+     * the row of the ordering. One should be careful with making
+     * space in the positions for variables not appearing at time
+     * t. For instance in the pred(t-1), both(t-1), stat(t),
+     * pred(t), both(t), forw(t), both(t+1), forw(t+1) ordering,
+     * the variables x(t-1), y(t-1), x(t+1), z(t-1), z(t), and
+     * z(t+1) having tree indices 6,5,4,3,2,1 will be ordered as
+     * follows: y(t-1), x(t-1), z(t-1), [y(t)], [x(t)], z(t),
+     * x(t+1), where a bracketed expresion means non-existent by
+     * occupying a space. The map thus will look as follows:
+     * {5->0, 6->1, 3->2, 2->5, 3->6}. Note that nothing is mapped
+     * to positions 3 and 4. */
+    map<int, int> positions;
+    /** This maps an ordering of the list of variables in
+     * constructor to the new ordering (at time t). The length is
+     * the number of variables. */
+    vector<int> outer2y;
+    /** This maps a new ordering to the ordering of the list of
+     * variables in constructor (at time t). The length is the
+     * number of variables. */
+    vector<int> y2outer;
+    /** This is just a reference for variable names to keep it
+     * from constructor to do_ordering() implementations. */
+    const vector<const char *> &varnames;
+    /** This is just a reference to atoms to keep it from
+     * constructor to do_ordering() implementations. */
+    const DynamicAtoms &atoms;
+  public:
+    /** This is an enum type for an ordering type implemented by
+     * do_general. */
+    enum ord_type {pbspbfbf, bfspbfpb};
+    /** Construct the ordering of the variables given by the names
+     * with their dynamic occurrences defined by the atoms. It
+     * calls the virtual method do_ordering which can be
+     * reimplemented. */
+    VarOrdering(const vector<const char *> &vnames, const DynamicAtoms &a)
+      : n_stat(0), n_pred(0), n_both(0), n_forw(0), varnames(vnames), atoms(a)
+    {
+    }
+    VarOrdering(const VarOrdering &vo, const vector<const char *> &vnames,
+                const DynamicAtoms &a);
+    virtual VarOrdering *clone(const vector<const char *> &vnames,
+                               const DynamicAtoms &a) const = 0;
+    /** Destructor does nothing here. */
+    virtual ~VarOrdering()
+    {
+    }
+    /** This is the method setting the ordering and the map. A
+     * subclass must reimplement it, possibly using a
+     * preimplemented ordering. This method must be called by the
+     * user after the class has been created. */
+    virtual void do_ordering() = 0;
+    /** Return number of static. */
+    int
+    nstat() const
+    {
+      return n_stat;
+    }
+    /** Return number of predetermined. */
+    int
+    npred() const
+    {
+      return n_pred;
+    }
+    /** Return number of both. */
+    int
+    nboth() const
+    {
+      return n_both;
+    }
+    /** Return number of forward looking. */
+    int
+    nforw() const
+    {
+      return n_forw;
+    }
+    /** Return the set of tree indices for derivatives. */
+    const vector<int> &
+    get_der_atoms() const
+    {
+      return der_atoms;
+    }
+    /** Return the y2outer. */
+    const vector<int> &
+    get_y2outer() const
+    {
+      return y2outer;
+    }
+    /** Return the outer2y. */
+    const vector<int> &
+    get_outer2y() const
+    {
+      return outer2y;
+    }
+    /** Query the atom given by the tree index. True is returned
+     * if the atom is one of the variables in the object. */
+    bool check(int t) const;
+    /** Return the position of the atom (nulary term) given by a
+     * tree index. It is a lookup to the map. If the atom cannot
+     * be found, the exception is raised. */
+    int get_pos_of(int t) const;
+    /** This returns a length of ordered row of atoms. In all
+     * cases so far, it does not depend on the ordering and it is
+     * as follows. */
+    int
+    length() const
+    {
+      return n_stat+2*n_pred+3*n_both+2*n_forw;
+    }
+    /** Debug print. */
+    void print() const;
+  protected:
+    /** This is a general ordering method which orders the
+     * variables by the given ordering ord_type. See documentation
+     * for respective do_ methods. */
+    void do_general(ord_type ordering);
+    /** This is a preimplemented ordering for do_ordering()
+     * method. It assumes that the variables appear only at time
+     * t-1, t, t+1. It orders the atoms as pred(t-1), both(t-1),
+     * stat(t), pred(t), both(t), forw(t), both(t+1),
+     * forw(t+1). It builds the der_atoms, the map of positions,
+     * as well as y2outer and outer2y. */
+    void
+    do_pbspbfbf()
+    {
+      do_general(pbspbfbf);
+    }
+    /** This is a preimplemented ordering for do_ordering()
+     * method. It assumes that the variables appear only at time
+     * t-1, t, t+1. It orders the atoms as both(t+1), forw(t+1),
+     * stat(t), pred(t), both(t), forw(t), pred(t-1),
+     * both(t-1). It builds the der_atoms, the map of positions,
+     * as well as y2outer and outer2y. */
+    void
+    do_bfspbfpb()
+    {
+      do_general(bfspbfpb);
+    }
+    /** This is a preimplemented ordering for do_ordering()
+     * method. It makes no assumptions about occurences of
+     * variables at different times. It orders the atoms with
+     * increasing time keeping the given ordering within one
+     * time. This implies that y2outer and outer2y will be
+     * identities. The der_atoms will be just a sequence of atoms
+     * from the least to the most time preserving the order of atoms
+     * within one time. */
+    void do_increasing_time();
+  private:
+    /** Declare this copy constructor as private to hide it. */
+    VarOrdering(const VarOrdering &vo);
+  };
 
 };
 
diff --git a/dynare++/parser/cc/fine_atoms.h b/dynare++/parser/cc/fine_atoms.h
index 7cc82560864d4771823370e38895363ab9a3a5b3..27e5a384165e3c6e3b34a005d8d38eb435aae6aa 100644
--- a/dynare++/parser/cc/fine_atoms.h
+++ b/dynare++/parser/cc/fine_atoms.h
@@ -10,337 +10,417 @@
 #include <vector>
 #include <string>
 
-namespace ogp {
+namespace ogp
+{
 
-	using std::vector;
-	using std::string;
+  using std::vector;
+  using std::string;
 
-	/** This is just ordering used for endogenous variables. It
-	 * assumes that we have only time t-1, t, and t+1, orders them as
-	 * pred(t-1), both(t-1), stat(t), pred(t), both(t), forw(t),
-	 * both(t+1), forw(t+1). */
-	class EndoVarOrdering1 : public VarOrdering {
-	public:
-		EndoVarOrdering1(const vector<const char*>& vnames, const DynamicAtoms& a)
-			: VarOrdering(vnames, a) {}
-		EndoVarOrdering1(const EndoVarOrdering1& vo, const vector<const char*>& vnames,
-						 const DynamicAtoms& a)
-			: VarOrdering(vo, vnames, a) {}
-		VarOrdering* clone(const vector<const char*>& vnames, const DynamicAtoms& a) const
-			{return new EndoVarOrdering1(*this, vnames, a);}
-		void do_ordering()
-			{do_pbspbfbf();}
-	};
+  /** This is just ordering used for endogenous variables. It
+   * assumes that we have only time t-1, t, and t+1, orders them as
+   * pred(t-1), both(t-1), stat(t), pred(t), both(t), forw(t),
+   * both(t+1), forw(t+1). */
+  class EndoVarOrdering1 : public VarOrdering
+  {
+  public:
+    EndoVarOrdering1(const vector<const char *> &vnames, const DynamicAtoms &a)
+      : VarOrdering(vnames, a)
+    {
+    }
+    EndoVarOrdering1(const EndoVarOrdering1 &vo, const vector<const char *> &vnames,
+                     const DynamicAtoms &a)
+      : VarOrdering(vo, vnames, a)
+    {
+    }
+    VarOrdering *
+    clone(const vector<const char *> &vnames, const DynamicAtoms &a) const
+    {
+      return new EndoVarOrdering1(*this, vnames, a);
+    }
+    void
+    do_ordering()
+    {
+      do_pbspbfbf();
+    }
+  };
 
-	/** This is just another ordering used for endogenous
-	 * variables. It assumes that we have only time t-1, t, and t+1,
-	 * orders them as both(t+1), forw(t+1), pred(t-1), both(t-1),
-	 * stat(t), pred(t), both(t), forw(t). */
-	class EndoVarOrdering2 : public VarOrdering {
-	public:
-		EndoVarOrdering2(const vector<const char*>& vnames, const DynamicAtoms& a)
-			: VarOrdering(vnames, a) {}
-		EndoVarOrdering2(const EndoVarOrdering2& vo, const vector<const char*>& vnames,
-						 const DynamicAtoms& a)
-			: VarOrdering(vo, vnames, a) {}
-		VarOrdering* clone(const vector<const char*>& vnames, const DynamicAtoms& a) const
-			{return new EndoVarOrdering2(*this, vnames, a);}
-		void do_ordering()
-			{do_bfspbfpb();}
-	};
+  /** This is just another ordering used for endogenous
+   * variables. It assumes that we have only time t-1, t, and t+1,
+   * orders them as both(t+1), forw(t+1), pred(t-1), both(t-1),
+   * stat(t), pred(t), both(t), forw(t). */
+  class EndoVarOrdering2 : public VarOrdering
+  {
+  public:
+    EndoVarOrdering2(const vector<const char *> &vnames, const DynamicAtoms &a)
+      : VarOrdering(vnames, a)
+    {
+    }
+    EndoVarOrdering2(const EndoVarOrdering2 &vo, const vector<const char *> &vnames,
+                     const DynamicAtoms &a)
+      : VarOrdering(vo, vnames, a)
+    {
+    }
+    VarOrdering *
+    clone(const vector<const char *> &vnames, const DynamicAtoms &a) const
+    {
+      return new EndoVarOrdering2(*this, vnames, a);
+    }
+    void
+    do_ordering()
+    {
+      do_bfspbfpb();
+    }
+  };
 
-	/** This is just ordering used for exogenous variables. It makes
-	 * no assumptions about their timing. It orders them from the
-	 * least time to the latest time. */
-	class ExoVarOrdering : public VarOrdering {
-	public:
-		ExoVarOrdering(const vector<const char*>& vnames, const DynamicAtoms& a)
-			: VarOrdering(vnames, a) {}
-		ExoVarOrdering(const ExoVarOrdering& vo, const vector<const char*>& vnames,
-					   const DynamicAtoms& a)
-			: VarOrdering(vo, vnames, a) {}
-		VarOrdering* clone(const vector<const char*>& vnames, const DynamicAtoms& a) const
-			{return new ExoVarOrdering(*this, vnames, a);}
-		void do_ordering()
-			{do_increasing_time();}
-	};
+  /** This is just ordering used for exogenous variables. It makes
+   * no assumptions about their timing. It orders them from the
+   * least time to the latest time. */
+  class ExoVarOrdering : public VarOrdering
+  {
+  public:
+    ExoVarOrdering(const vector<const char *> &vnames, const DynamicAtoms &a)
+      : VarOrdering(vnames, a)
+    {
+    }
+    ExoVarOrdering(const ExoVarOrdering &vo, const vector<const char *> &vnames,
+                   const DynamicAtoms &a)
+      : VarOrdering(vo, vnames, a)
+    {
+    }
+    VarOrdering *
+    clone(const vector<const char *> &vnames, const DynamicAtoms &a) const
+    {
+      return new ExoVarOrdering(*this, vnames, a);
+    }
+    void
+    do_ordering()
+    {
+      do_increasing_time();
+    }
+  };
 
-	class FineAtoms;
+  class FineAtoms;
 
-	/** This class provides an outer ordering of all variables (endo
-	 * and exo). It maps the ordering to the particular outer
-	 * orderings of endo and exo. It works tightly with the FineAtoms
-	 * class. */
-	class AllvarOuterOrdering {
-	protected:
-		/** Type for a map mapping a variable name to an integer. */
-		typedef map<const char*, int, ltstr> Tvarintmap;
-		/** Reference to atoms. */
-		const FineAtoms& atoms;
-		/** The vector of all endo and exo variables in outer
-		 * ordering. The pointers point to storage in atoms. */
-		vector<const char*> allvar;
-		/** The mapping from outer endogenous to outer all. For
-		 * example endo2all[0] is the order of the first outer
-		 * endogenous variable in the allvar ordering. */
-		vector<int> endo2all;
-		/** The mapping from outer exogenous to outer all. For example
-		 * exo2all[0] is the order of the first outer exogenous
-		 * variables in the allvar ordering. */
-		vector<int> exo2all;
-	public:
-		/** Construct the allvar outer ordering from the provided
-		 * sequence of endo and exo names. The names can have an
-		 * arbitrary storage, the storage is transformed to the atoms
-		 * storage. An exception is thrown if either the list is not
-		 * exhaustive, or some string is not a variable. */
-		AllvarOuterOrdering(const vector<const char*>& allvar_outer, const FineAtoms& a);
-		/** Copy constructor using the storage of provided atoms. */
-		AllvarOuterOrdering(const AllvarOuterOrdering& allvar_outer, const FineAtoms& a);
-		/** Return endo2all mapping. */
-		const vector<int>& get_endo2all() const
-			{return endo2all;}
-		/** Return exo2all mapping. */
-		const vector<int>& get_exo2all() const
-			{return exo2all;}
-		/** Return the allvar ordering. */
-		const vector<const char*>& get_allvar() const
-			{return allvar;}
-	};
+  /** This class provides an outer ordering of all variables (endo
+   * and exo). It maps the ordering to the particular outer
+   * orderings of endo and exo. It works tightly with the FineAtoms
+   * class. */
+  class AllvarOuterOrdering
+  {
+  protected:
+    /** Type for a map mapping a variable name to an integer. */
+    typedef map<const char *, int, ltstr> Tvarintmap;
+    /** Reference to atoms. */
+    const FineAtoms &atoms;
+    /** The vector of all endo and exo variables in outer
+     * ordering. The pointers point to storage in atoms. */
+    vector<const char *> allvar;
+    /** The mapping from outer endogenous to outer all. For
+     * example endo2all[0] is the order of the first outer
+     * endogenous variable in the allvar ordering. */
+    vector<int> endo2all;
+    /** The mapping from outer exogenous to outer all. For example
+     * exo2all[0] is the order of the first outer exogenous
+     * variables in the allvar ordering. */
+    vector<int> exo2all;
+  public:
+    /** Construct the allvar outer ordering from the provided
+     * sequence of endo and exo names. The names can have an
+     * arbitrary storage, the storage is transformed to the atoms
+     * storage. An exception is thrown if either the list is not
+     * exhaustive, or some string is not a variable. */
+    AllvarOuterOrdering(const vector<const char *> &allvar_outer, const FineAtoms &a);
+    /** Copy constructor using the storage of provided atoms. */
+    AllvarOuterOrdering(const AllvarOuterOrdering &allvar_outer, const FineAtoms &a);
+    /** Return endo2all mapping. */
+    const vector<int> &
+    get_endo2all() const
+    {
+      return endo2all;
+    }
+    /** Return exo2all mapping. */
+    const vector<int> &
+    get_exo2all() const
+    {
+      return exo2all;
+    }
+    /** Return the allvar ordering. */
+    const vector<const char *> &
+    get_allvar() const
+    {
+      return allvar;
+    }
+  };
 
-	/** This class refines the DynamicAtoms by distinguishing among
-	 * parameters (no lag and leads) and endogenous and exogenous
-	 * variables (with lags and leads). For parameters, endogenous and
-	 * exogenous, it defines outer orderings and internal
-	 * orderings. The internal orderings are created by
-	 * parsing_finished() method when it is sure that no new variables
-	 * would be registered. The outer orderings are given by the order
-	 * of calls of registering methods.
-     * 
-     * In addition, the class also defines outer ordering of
-     * endogenous and exogenous variables. This is input as a
-     * parameter to parsing_finished(). By default, this whole outer
-     * ordering is just a concatenation of outer ordering of
-     * endogenous and exogenous variables.
-	 *
-	 * The internal ordering of all endo and exo variables is just a
-	 * concatenation of endo and exo variables in their internal
-	 * orderings. This is the ordering with respect to which all
-	 * derivatives are taken. */
-	class FineAtoms : public DynamicAtoms {
-		friend class AllvarOuterOrdering;
-	protected:
-		typedef map<const char*, int, ltstr> Tvarintmap;
-	private:
-		/** The vector of parameters names. The order gives the order
-		 * the data is communicated with outside world. */
-		vector<const char*> params;
-		/** A map mapping a name of a parameter to an index in the outer
-		 * ordering. */
-		Tvarintmap param_outer_map;
-		/** The vector of endogenous variables. This defines the order
-		 * like parameters. */
-		vector<const char*> endovars;
-		/** A map mapping a name of an endogenous variable to an index
-		 * in the outer ordering. */
-		Tvarintmap endo_outer_map;
-		/** The vector of exogenous variables. Also defines the order
-		 * like parameters and endovars. */
-		vector<const char*> exovars;
-		/** A map mapping a name of an exogenous variable to an index
-		 * in the outer ordering. */
-		Tvarintmap exo_outer_map;
+  /** This class refines the DynamicAtoms by distinguishing among
+   * parameters (no lag and leads) and endogenous and exogenous
+   * variables (with lags and leads). For parameters, endogenous and
+   * exogenous, it defines outer orderings and internal
+   * orderings. The internal orderings are created by
+   * parsing_finished() method when it is sure that no new variables
+   * would be registered. The outer orderings are given by the order
+   * of calls of registering methods.
+   *
+   * In addition, the class also defines outer ordering of
+   * endogenous and exogenous variables. This is input as a
+   * parameter to parsing_finished(). By default, this whole outer
+   * ordering is just a concatenation of outer ordering of
+   * endogenous and exogenous variables.
+   *
+   * The internal ordering of all endo and exo variables is just a
+   * concatenation of endo and exo variables in their internal
+   * orderings. This is the ordering with respect to which all
+   * derivatives are taken. */
+  class FineAtoms : public DynamicAtoms
+  {
+    friend class AllvarOuterOrdering;
+  protected:
+    typedef map<const char *, int, ltstr> Tvarintmap;
+  private:
+    /** The vector of parameters names. The order gives the order
+     * the data is communicated with outside world. */
+    vector<const char *> params;
+    /** A map mapping a name of a parameter to an index in the outer
+     * ordering. */
+    Tvarintmap param_outer_map;
+    /** The vector of endogenous variables. This defines the order
+     * like parameters. */
+    vector<const char *> endovars;
+    /** A map mapping a name of an endogenous variable to an index
+     * in the outer ordering. */
+    Tvarintmap endo_outer_map;
+    /** The vector of exogenous variables. Also defines the order
+     * like parameters and endovars. */
+    vector<const char *> exovars;
+    /** A map mapping a name of an exogenous variable to an index
+     * in the outer ordering. */
+    Tvarintmap exo_outer_map;
 
-	protected:
-		/** This is the internal ordering of all atoms corresponding
-		 * to endogenous variables. It is constructed by
-		 * parsing_finished() method, which should be called after all
-		 * parsing jobs have been finished. */ 
-		VarOrdering* endo_order;
-		/** This is the internal ordering of all atoms corresponding
-		 * to exogenous variables. It has the same handling as
-		 * endo_order. */
-		VarOrdering* exo_order;
-		/** This is the all variables outer ordering. It is
-		 * constructed by parsing finished. */
-		AllvarOuterOrdering* allvar_order;
-		/** This vector defines a set of atoms as tree indices used
-		 * for differentiation. The order of the atoms in this vector
-		 * defines ordering of the derivative tensors. The ordering is
-		 * a concatenation of atoms from endo_order and then
-		 * exo_order. This vector is setup by parsing_finished() and
-		 * is returned by variables(). */
-		vector<int> der_atoms;
-		/** This is a mapping from endogenous atoms to all atoms in
-		 * der_atoms member. The mapping maps index in endogenous atom
-		 * ordering to index (not value) in der_atoms. It is useful if
-		 * one wants to evaluate derivatives wrt only endogenous
-		 * variables. It is set by parsing_finished(). By definition,
-		 * it is monotone. */
-		vector<int> endo_atoms_map;
-		/** This is a mapping from exogenous atoms to all atoms in
-		 * der_atoms member. It is the same as endo_atoms_map for
-		 * atoms of exogenous variables. */
-		vector<int> exo_atoms_map;
-	public:
-		FineAtoms()
-			: endo_order(NULL), exo_order(NULL), allvar_order(NULL) {}
-		FineAtoms(const FineAtoms& fa);
-		/** Deletes endo_order and exo_order. */
-		virtual ~FineAtoms()
-			{
-				if (endo_order) delete endo_order;
-				if (exo_order) delete exo_order;
-				if (allvar_order) delete allvar_order;
-			}
-		/** Overrides DynamicAtoms::check_variable so that the error
-		 * would be raised if the variable name is not declared. A
-		 * variable is declared by inserting it to
-		 * DynamicAtoms::varnames. This is a responsibility of a
-		 * subclass. */
-		int check_variable(const char* name) const;
-		/** This calculates min lag and max lead of endogenous variables. */
-		void endovarspan(int& mlead, int& mlag) const
-			{varspan(endovars, mlead, mlag);}
-		/** This calculates mim lag and max lead of exogenous variables. */
-		void exovarspan(int& mlead, int& mlag) const
-			{varspan(exovars, mlead, mlag);}
-		/** This calculates the number of periods in which at least
-		 * one exogenous variable occurs. */
-		int num_exo_periods() const;
-		/** Return an (external) ordering of parameters. */
-		const vector<const char*>& get_params() const
-			{return params;}
-		/** Return an external ordering of endogenous variables. */
-		const vector<const char*>& get_endovars() const
-			{return endovars;}
-		/** Return an external ordering of exogenous variables. */
-		const vector<const char*>& get_exovars() const
-			{return exovars;}
-		/** This constructs internal orderings and makes the indices
-		 * returned by variables method available. Further it
-		 * constructs outer ordering of all variables by a simple
-		 * concatenation of outer endogenous and outer exogenous. In
-		 * addition, it makes nstat, npred, nboth, nforw available. */
-		void parsing_finished(VarOrdering::ord_type ot);
-		/** This does the same thing as
-		 * parsing_finished(VarOrdering::ord_type) plus it allows for
-		 * inputing a different outer ordering of all variables. The
-		 * ordering is input as a list of strings, their storage can
-		 * be arbitrary. */
-		void parsing_finished(VarOrdering::ord_type ot, const vector<const char*> avo);
-		/** Return the external ordering of all variables (endo and
-		 * exo). This is either the second argument to
-		 * parsing_finished or the default external ordering. This
-		 * must be called only after parsing_finished. */
-		const vector<const char*>& get_allvar() const;
-		/** Return the map from outer ordering of endo variables to
-		 * the allvar ordering. This must be called only after
-		 * parsing_finished. */
-		const vector<int>& outer_endo2all() const;
-		/** Return the map from outer ordering of exo variables to
-		 * the allvar ordering. This must be called only after
-		 * parsing_finished. */
-		const vector<int>& outer_exo2all() const;
-		/** Return the atoms with respect to which we are going to
-		 * differentiate. This must be called after
-		 * parsing_finished. */
-		vector<int> variables() const;
-		/** Return the number of static. */
-		int nstat() const;
-		/** Return the number of predetermined. */
-		int npred() const;
-		/** Return the number of both. */
-		int nboth() const;
-		/** Return the number of forward looking. */
-		int nforw() const;
-		/** Return the index of an endogenous atom given by tree index in
-		 * the endo ordering. This must be also called only after
-		 * parsing_finished(). */
-		int get_pos_of_endo(int t) const;
-		/** Return the index of an exogenous atom given by tree index in
-		 * the exo ordering. This must be also called only after
-		 * parsing_finished(). */
-		int get_pos_of_exo(int t) const;
-		/** Return the index of either endogenous or exogenous atom
-		 * given by tree index in the concatenated ordering of
-		 * endogenous and exogenous atoms. This must be also called
-		 * only after parsing_finished(). */
-		int get_pos_of_all(int t) const;
-		/** Return the mapping from endogenous at time t to outer
-		 * ordering of endogenous. */
-		const vector<int>& y2outer_endo() const;
-		/** Return the mapping from the outer ordering of endogenous to endogenous
-		 * at time t. */
-		const vector<int>& outer2y_endo() const;
-		/** Return the mapping from exogenous at time t to outer
-		 * ordering of exogenous. */
-		const vector<int>& y2outer_exo() const;
-		/** Return the mapping from the outer ordering of exogenous to exogenous
-		 * at time t. */
-		const vector<int>& outer2y_exo() const;
-		/** Return the endo_atoms_map. */
-		const vector<int>& get_endo_atoms_map() const;
-		/** Return the exo_atoms_map. */
-		const vector<int>& get_exo_atoms_map() const;
-		/** Return an index in the outer ordering of a given
-		 * parameter. An exception is thrown if the name is not a
-		 * parameter. */
-		int name2outer_param(const char* name) const;
-		/** Return an index in the outer ordering of a given
-		 * endogenous variable. An exception is thrown if the name is not a
-		 * and endogenous variable. */
-		int name2outer_endo(const char* name) const;
-		/** Return an index in the outer ordering of a given
-		 * exogenous variable. An exception is thrown if the name is not a
-		 * and exogenous variable. */
-		int name2outer_exo(const char* name) const;
-		/** Return an index in the outer ordering of all variables
-		 * (endo and exo) for a given name. An exception is thrown if
-		 * the name is not a variable. This must be called only after
-		 * parsing_finished(). */
-		int name2outer_allvar(const char* name) const;
-		/** Return the number of endogenous variables at time t-1, these are state
-		 * variables. */
-		int nys() const
-			{return npred()+nboth();}
-		/** Return the number of endogenous variables at time t+1. */
-		int nyss() const
-			{return nboth()+nforw();}
-		/** Return the number of endogenous variables. */
-		int ny() const
-			{return endovars.size();}
-		/** Return the number of exogenous variables. */
-		int nexo() const
-			{return (int)exovars.size();}
-		/** Return the number of parameters. */
-		int np() const
-			{return (int)(params.size());}
-		/** Register unique endogenous variable name. The order of
-		 * calls defines the endo outer ordering. The method is
-		 * virtual, since a superclass may want to do some additional
-		 * action. */
-		virtual void register_uniq_endo(const char* name);
-		/** Register unique exogenous variable name. The order of
-		 * calls defines the exo outer ordering. The method is
-		 * virtual, since a superclass may want to do somem additional
-		 * action. */
-		virtual void register_uniq_exo(const char* name);
-		/** Register unique parameter name. The order of calls defines
-		 * the param outer ordering. The method is
-		 * virtual, since a superclass may want to do somem additional
-		 * action. */
-		virtual void register_uniq_param(const char* name);
-		/** Debug print. */
-		void print() const;
-	private:
-		/** This performs the common part of parsing_finished(), which
-		 * is a construction of internal orderings. */
-		void make_internal_orderings(VarOrdering::ord_type ot);
-	protected:
-		/** This remembers the ordering type of the last call make_internal_ordering. */
-		VarOrdering::ord_type order_type;
-	};
+  protected:
+    /** This is the internal ordering of all atoms corresponding
+     * to endogenous variables. It is constructed by
+     * parsing_finished() method, which should be called after all
+     * parsing jobs have been finished. */
+    VarOrdering *endo_order;
+    /** This is the internal ordering of all atoms corresponding
+     * to exogenous variables. It has the same handling as
+     * endo_order. */
+    VarOrdering *exo_order;
+    /** This is the all variables outer ordering. It is
+     * constructed by parsing finished. */
+    AllvarOuterOrdering *allvar_order;
+    /** This vector defines a set of atoms as tree indices used
+     * for differentiation. The order of the atoms in this vector
+     * defines ordering of the derivative tensors. The ordering is
+     * a concatenation of atoms from endo_order and then
+     * exo_order. This vector is setup by parsing_finished() and
+     * is returned by variables(). */
+    vector<int> der_atoms;
+    /** This is a mapping from endogenous atoms to all atoms in
+     * der_atoms member. The mapping maps index in endogenous atom
+     * ordering to index (not value) in der_atoms. It is useful if
+     * one wants to evaluate derivatives wrt only endogenous
+     * variables. It is set by parsing_finished(). By definition,
+     * it is monotone. */
+    vector<int> endo_atoms_map;
+    /** This is a mapping from exogenous atoms to all atoms in
+     * der_atoms member. It is the same as endo_atoms_map for
+     * atoms of exogenous variables. */
+    vector<int> exo_atoms_map;
+  public:
+    FineAtoms()
+      : endo_order(NULL), exo_order(NULL), allvar_order(NULL)
+    {
+    }
+    FineAtoms(const FineAtoms &fa);
+    /** Deletes endo_order and exo_order. */
+    virtual ~FineAtoms()
+    {
+      if (endo_order)
+        delete endo_order;
+      if (exo_order)
+        delete exo_order;
+      if (allvar_order)
+        delete allvar_order;
+    }
+    /** Overrides DynamicAtoms::check_variable so that the error
+     * would be raised if the variable name is not declared. A
+     * variable is declared by inserting it to
+     * DynamicAtoms::varnames. This is a responsibility of a
+     * subclass. */
+    int check_variable(const char *name) const;
+    /** This calculates min lag and max lead of endogenous variables. */
+    void
+    endovarspan(int &mlead, int &mlag) const
+    {
+      varspan(endovars, mlead, mlag);
+    }
+    /** This calculates mim lag and max lead of exogenous variables. */
+    void
+    exovarspan(int &mlead, int &mlag) const
+    {
+      varspan(exovars, mlead, mlag);
+    }
+    /** This calculates the number of periods in which at least
+     * one exogenous variable occurs. */
+    int num_exo_periods() const;
+    /** Return an (external) ordering of parameters. */
+    const vector<const char *> &
+    get_params() const
+    {
+      return params;
+    }
+    /** Return an external ordering of endogenous variables. */
+    const vector<const char *> &
+    get_endovars() const
+    {
+      return endovars;
+    }
+    /** Return an external ordering of exogenous variables. */
+    const vector<const char *> &
+    get_exovars() const
+    {
+      return exovars;
+    }
+    /** This constructs internal orderings and makes the indices
+     * returned by variables method available. Further it
+     * constructs outer ordering of all variables by a simple
+     * concatenation of outer endogenous and outer exogenous. In
+     * addition, it makes nstat, npred, nboth, nforw available. */
+    void parsing_finished(VarOrdering::ord_type ot);
+    /** This does the same thing as
+     * parsing_finished(VarOrdering::ord_type) plus it allows for
+     * inputing a different outer ordering of all variables. The
+     * ordering is input as a list of strings, their storage can
+     * be arbitrary. */
+    void parsing_finished(VarOrdering::ord_type ot, const vector<const char *> avo);
+    /** Return the external ordering of all variables (endo and
+     * exo). This is either the second argument to
+     * parsing_finished or the default external ordering. This
+     * must be called only after parsing_finished. */
+    const vector<const char *>&get_allvar() const;
+    /** Return the map from outer ordering of endo variables to
+     * the allvar ordering. This must be called only after
+     * parsing_finished. */
+    const vector<int>&outer_endo2all() const;
+    /** Return the map from outer ordering of exo variables to
+     * the allvar ordering. This must be called only after
+     * parsing_finished. */
+    const vector<int>&outer_exo2all() const;
+    /** Return the atoms with respect to which we are going to
+     * differentiate. This must be called after
+     * parsing_finished. */
+    vector<int> variables() const;
+    /** Return the number of static. */
+    int nstat() const;
+    /** Return the number of predetermined. */
+    int npred() const;
+    /** Return the number of both. */
+    int nboth() const;
+    /** Return the number of forward looking. */
+    int nforw() const;
+    /** Return the index of an endogenous atom given by tree index in
+     * the endo ordering. This must be also called only after
+     * parsing_finished(). */
+    int get_pos_of_endo(int t) const;
+    /** Return the index of an exogenous atom given by tree index in
+     * the exo ordering. This must be also called only after
+     * parsing_finished(). */
+    int get_pos_of_exo(int t) const;
+    /** Return the index of either endogenous or exogenous atom
+     * given by tree index in the concatenated ordering of
+     * endogenous and exogenous atoms. This must be also called
+     * only after parsing_finished(). */
+    int get_pos_of_all(int t) const;
+    /** Return the mapping from endogenous at time t to outer
+     * ordering of endogenous. */
+    const vector<int>&y2outer_endo() const;
+    /** Return the mapping from the outer ordering of endogenous to endogenous
+     * at time t. */
+    const vector<int>&outer2y_endo() const;
+    /** Return the mapping from exogenous at time t to outer
+     * ordering of exogenous. */
+    const vector<int>&y2outer_exo() const;
+    /** Return the mapping from the outer ordering of exogenous to exogenous
+     * at time t. */
+    const vector<int>&outer2y_exo() const;
+    /** Return the endo_atoms_map. */
+    const vector<int>&get_endo_atoms_map() const;
+    /** Return the exo_atoms_map. */
+    const vector<int>&get_exo_atoms_map() const;
+    /** Return an index in the outer ordering of a given
+     * parameter. An exception is thrown if the name is not a
+     * parameter. */
+    int name2outer_param(const char *name) const;
+    /** Return an index in the outer ordering of a given
+     * endogenous variable. An exception is thrown if the name is not a
+     * and endogenous variable. */
+    int name2outer_endo(const char *name) const;
+    /** Return an index in the outer ordering of a given
+     * exogenous variable. An exception is thrown if the name is not a
+     * and exogenous variable. */
+    int name2outer_exo(const char *name) const;
+    /** Return an index in the outer ordering of all variables
+     * (endo and exo) for a given name. An exception is thrown if
+     * the name is not a variable. This must be called only after
+     * parsing_finished(). */
+    int name2outer_allvar(const char *name) const;
+    /** Return the number of endogenous variables at time t-1, these are state
+     * variables. */
+    int
+    nys() const
+    {
+      return npred()+nboth();
+    }
+    /** Return the number of endogenous variables at time t+1. */
+    int
+    nyss() const
+    {
+      return nboth()+nforw();
+    }
+    /** Return the number of endogenous variables. */
+    int
+    ny() const
+    {
+      return endovars.size();
+    }
+    /** Return the number of exogenous variables. */
+    int
+    nexo() const
+    {
+      return (int) exovars.size();
+    }
+    /** Return the number of parameters. */
+    int
+    np() const
+    {
+      return (int) (params.size());
+    }
+    /** Register unique endogenous variable name. The order of
+     * calls defines the endo outer ordering. The method is
+     * virtual, since a superclass may want to do some additional
+     * action. */
+    virtual void register_uniq_endo(const char *name);
+    /** Register unique exogenous variable name. The order of
+     * calls defines the exo outer ordering. The method is
+     * virtual, since a superclass may want to do somem additional
+     * action. */
+    virtual void register_uniq_exo(const char *name);
+    /** Register unique parameter name. The order of calls defines
+     * the param outer ordering. The method is
+     * virtual, since a superclass may want to do somem additional
+     * action. */
+    virtual void register_uniq_param(const char *name);
+    /** Debug print. */
+    void print() const;
+  private:
+    /** This performs the common part of parsing_finished(), which
+     * is a construction of internal orderings. */
+    void make_internal_orderings(VarOrdering::ord_type ot);
+  protected:
+    /** This remembers the ordering type of the last call make_internal_ordering. */
+    VarOrdering::ord_type order_type;
+  };
 };
 
 #endif
diff --git a/dynare++/parser/cc/formula_parser.h b/dynare++/parser/cc/formula_parser.h
index 0f5c965c6aeb4c5a55c6d95f20856947d91dd799..5cd4476e5103ac2d4d14eb278b2205670deb9118 100644
--- a/dynare++/parser/cc/formula_parser.h
+++ b/dynare++/parser/cc/formula_parser.h
@@ -5,408 +5,492 @@
 
 #include "tree.h"
 
-namespace ogp {
-	using std::vector;
+namespace ogp
+{
+  using std::vector;
 
-	/** Pure virtual class defining a minimal interface for
-	 * representation of nulary terms within FormulaParser. */
-	class Atoms {
-	public:
-		Atoms() {}
-		virtual ~Atoms() {}
-		/** This returns previously assigned internal index to the
-		 * given atom, or returns -1 if the atom has not been assigned
-		 * yet. The method can raise an exception, if the Atoms
-		 * implementation is strict and the name is not among
-		 * prescribed possible values. */
-		virtual int check(const char* name) const = 0;
-		/** This method assigns an internal index to the nulary term
-		 * described by the name. The internal index is allocated by
-		 * OperationTree class. */
-		virtual void assign(const char* name, int t) = 0;
-		/** Returns a number of variables which will be used for
-		 * differentiations. */
-		virtual int nvar() const = 0;
-		/** Returns a vector of variable's internal indices which will
-		 * be used for differentiations. */
-		virtual vector<int> variables() const = 0;
-		/** Debug print. */
-		virtual void print() const = 0;
-	};
+  /** Pure virtual class defining a minimal interface for
+   * representation of nulary terms within FormulaParser. */
+  class Atoms
+  {
+  public:
+    Atoms()
+    {
+    }
+    virtual ~Atoms()
+    {
+    }
+    /** This returns previously assigned internal index to the
+     * given atom, or returns -1 if the atom has not been assigned
+     * yet. The method can raise an exception, if the Atoms
+     * implementation is strict and the name is not among
+     * prescribed possible values. */
+    virtual int check(const char *name) const = 0;
+    /** This method assigns an internal index to the nulary term
+     * described by the name. The internal index is allocated by
+     * OperationTree class. */
+    virtual void assign(const char *name, int t) = 0;
+    /** Returns a number of variables which will be used for
+     * differentiations. */
+    virtual int nvar() const = 0;
+    /** Returns a vector of variable's internal indices which will
+     * be used for differentiations. */
+    virtual vector<int> variables() const = 0;
+    /** Debug print. */
+    virtual void print() const = 0;
+  };
 
-	/** Pure virtual class defining interface for all classes able to
-	 * set nulary terms to evaluation tree EvalTree. The
-	 * implementations of this class will have to be connected with
-	 * Atoms to have knowledge about the atoms and their indices in
-	 * the tree, and will call EvalTree::set_nulary. */
-	class AtomValues {
-	public:
-		virtual ~AtomValues() {}
-		virtual void setValues(EvalTree& et) const = 0;
-	};
+  /** Pure virtual class defining interface for all classes able to
+   * set nulary terms to evaluation tree EvalTree. The
+   * implementations of this class will have to be connected with
+   * Atoms to have knowledge about the atoms and their indices in
+   * the tree, and will call EvalTree::set_nulary. */
+  class AtomValues
+  {
+  public:
+    virtual ~AtomValues()
+    {
+    }
+    virtual void setValues(EvalTree &et) const = 0;
+  };
 
-	class FormulaDerEvaluator;
-	class FoldMultiIndex;
-	/** For ordering FoldMultiIndex in the std::map. */
-	struct ltfmi {
-		bool operator()(const FoldMultiIndex& i1, const FoldMultiIndex& i2) const;
-	};
+  class FormulaDerEvaluator;
+  class FoldMultiIndex;
+  /** For ordering FoldMultiIndex in the std::map. */
+  struct ltfmi
+  {
+    bool operator()(const FoldMultiIndex &i1, const FoldMultiIndex &i2) const;
+  };
 
-	/** This class stores derivatives (tree indices) of one formula
-	 * for all orders upto a given one. It stores the derivatives as a
-	 * sequence (vector) of these tree indices and sequence of the
-	 * multidimensional indices of variables wrt which the derivatives
-	 * were taken. In order to speed up querying for a derivative
-	 * given the variables, we have a map mapping the multidimensional
-	 * index to the order of the derivative in the sequence.
-	 * 
-	 * The only reason we do not have only this map is that the
-	 * iterators of the map do not survive the insertions to the map,
-	 * and implementation of the constructor has to be very difficult.
-	 */
-	class FormulaDerivatives {
-		friend class FormulaDerEvaluator;
-	protected:
-		/** Vector of derivatives. This is a list of derivatives (tree
-		 * indices), the ordering is given by the algorithm used to
-		 * create it. Currently, it starts with zero-th derivative,
-		 * the formula itself and carries with first order, second,
-		 * etc. */
-		vector<int> tder;
-		/** Vector of multiindices corresponding to the vector of
-		 * derivatives. */
-		vector<FoldMultiIndex> indices;
-		/** For retrieving derivatives via a multiindex, we have a map
-		 * mapping a multiindex to a derivative in the tder
-		 * ordering. This means that indices[ind2der[index]] == index. */
-		typedef map<FoldMultiIndex, int, ltfmi> Tfmiintmap;
-		Tfmiintmap ind2der;
-		/** The number of variables. */
-		int nvar;
-		/** The maximum order of derivatives. */
-		int order;
-	public:
-		/** The constructor allocates and fills the sequence of the
-		 * indices of derivatives for a formula.
-		 * @param otree the OperationTree for which all work is done
-		 * and to which the derivatives are added.
-		 * @param vars the vector of nulary terms in the tree; the
-		 * derivatives are taken with respect to these variables in
-		 * the ordering given by the vector.
-		 * @param f the index of the formula being differentiated. The
-		 * zero derivative is set to f.
-		 * @param max_order the maximum order of differentiation.
-		 */ 
-		FormulaDerivatives(OperationTree& otree, const vector<int>& vars, int f, int max_order);
-		/** Copy constructor. */
-		FormulaDerivatives(const FormulaDerivatives& fd);
-		virtual ~FormulaDerivatives(){}
-		/** Random access to the derivatives via multiindex. */
-		int derivative(const FoldMultiIndex& mi) const;
-		/** Return the order. */
-		int get_order() const
-			{return order;}
-		/** Debug print. */
-		void print(const OperationTree& otree) const;
-	};
+  /** This class stores derivatives (tree indices) of one formula
+   * for all orders upto a given one. It stores the derivatives as a
+   * sequence (vector) of these tree indices and sequence of the
+   * multidimensional indices of variables wrt which the derivatives
+   * were taken. In order to speed up querying for a derivative
+   * given the variables, we have a map mapping the multidimensional
+   * index to the order of the derivative in the sequence.
+   *
+   * The only reason we do not have only this map is that the
+   * iterators of the map do not survive the insertions to the map,
+   * and implementation of the constructor has to be very difficult.
+   */
+  class FormulaDerivatives
+  {
+    friend class FormulaDerEvaluator;
+  protected:
+    /** Vector of derivatives. This is a list of derivatives (tree
+     * indices), the ordering is given by the algorithm used to
+     * create it. Currently, it starts with zero-th derivative,
+     * the formula itself and carries with first order, second,
+     * etc. */
+    vector<int> tder;
+    /** Vector of multiindices corresponding to the vector of
+     * derivatives. */
+    vector<FoldMultiIndex> indices;
+    /** For retrieving derivatives via a multiindex, we have a map
+     * mapping a multiindex to a derivative in the tder
+     * ordering. This means that indices[ind2der[index]] == index. */
+    typedef map<FoldMultiIndex, int, ltfmi> Tfmiintmap;
+    Tfmiintmap ind2der;
+    /** The number of variables. */
+    int nvar;
+    /** The maximum order of derivatives. */
+    int order;
+  public:
+    /** The constructor allocates and fills the sequence of the
+     * indices of derivatives for a formula.
+     * @param otree the OperationTree for which all work is done
+     * and to which the derivatives are added.
+     * @param vars the vector of nulary terms in the tree; the
+     * derivatives are taken with respect to these variables in
+     * the ordering given by the vector.
+     * @param f the index of the formula being differentiated. The
+     * zero derivative is set to f.
+     * @param max_order the maximum order of differentiation.
+     */
+    FormulaDerivatives(OperationTree &otree, const vector<int> &vars, int f, int max_order);
+    /** Copy constructor. */
+    FormulaDerivatives(const FormulaDerivatives &fd);
+    virtual ~FormulaDerivatives()
+    {
+    }
+    /** Random access to the derivatives via multiindex. */
+    int derivative(const FoldMultiIndex &mi) const;
+    /** Return the order. */
+    int
+    get_order() const
+    {
+      return order;
+    }
+    /** Debug print. */
+    void print(const OperationTree &otree) const;
+  };
 
-	class FormulaEvaluator;
+  class FormulaEvaluator;
 
-	/** This class is able to parse a number of formulas and
-	 * differentiate them. The life cycle of the object is as follows:
-	 * After it is created, a few calls to parse will add formulas
-	 * (zero derivatives) to the object. Then a method differentiate()
-	 * can be called and a vector of pointers to derivatives for each
-	 * formula is created. After this, no one should call other
-	 * parse() or differentiate(). A const reference of the object can
-	 * be used in constructors of FormulaEvaluator and
-	 * FormulaDerEvaluator in order to evaluate formulas (zero
-	 * derivatives) and higher derivatives resp. */
-	class FormulaParser {
-		friend class FormulaCustomEvaluator;
-		friend class FormulaDerEvaluator;
-	protected:
-		/** The OperationTree of all formulas, including derivatives. */
-		OperationTree otree;
-		/** Reference to Atoms. The Atoms are filled with nulary terms
-		 * during execution of parse(). */
-		Atoms& atoms;
-		/** Vector of formulas (zero derivatives) in the order as they
-		 * have been parsed. */
-		vector<int> formulas;
-		/** The vector to derivatives, each vector corresponds to a
-		 * formula in the vector formulas. */
-		vector<FormulaDerivatives*> ders;
-	public:
-		/** Construct an empty formula parser. */
-		FormulaParser(Atoms& a)
-			: atoms(a) {}
-		/** Copy constructor using a different instance of Atoms. */
-		FormulaParser(const FormulaParser& fp, Atoms& a);
-		virtual ~FormulaParser();
+  /** This class is able to parse a number of formulas and
+   * differentiate them. The life cycle of the object is as follows:
+   * After it is created, a few calls to parse will add formulas
+   * (zero derivatives) to the object. Then a method differentiate()
+   * can be called and a vector of pointers to derivatives for each
+   * formula is created. After this, no one should call other
+   * parse() or differentiate(). A const reference of the object can
+   * be used in constructors of FormulaEvaluator and
+   * FormulaDerEvaluator in order to evaluate formulas (zero
+   * derivatives) and higher derivatives resp. */
+  class FormulaParser
+  {
+    friend class FormulaCustomEvaluator;
+    friend class FormulaDerEvaluator;
+  protected:
+    /** The OperationTree of all formulas, including derivatives. */
+    OperationTree otree;
+    /** Reference to Atoms. The Atoms are filled with nulary terms
+     * during execution of parse(). */
+    Atoms &atoms;
+    /** Vector of formulas (zero derivatives) in the order as they
+     * have been parsed. */
+    vector<int> formulas;
+    /** The vector to derivatives, each vector corresponds to a
+     * formula in the vector formulas. */
+    vector<FormulaDerivatives *> ders;
+  public:
+    /** Construct an empty formula parser. */
+    FormulaParser(Atoms &a)
+      : atoms(a)
+    {
+    }
+    /** Copy constructor using a different instance of Atoms. */
+    FormulaParser(const FormulaParser &fp, Atoms &a);
+    virtual
+    ~FormulaParser();
 
-		/** Requires an addition of the formula; called from the
-		 * parser. */
-		void add_formula(int t);
-		/** Requires an addition of the binary operation; called from
-		 * the parser. */
-		int add_binary(code_t code, int t1, int t2);
-		/** Requires an addition of the unary operation; called from
-		 * the parser. */
-		int add_unary(code_t code, int t);
-		/** Requires an addition of the nulary operation given by the
-		 * string. The Atoms are consulted for uniquness and are given
-		 * an internal index generated by the OperationTree. This is
-		 * the channel through which the Atoms are filled. */
-		int add_nulary(const char* str);
+    /** Requires an addition of the formula; called from the
+     * parser. */
+    void add_formula(int t);
+    /** Requires an addition of the binary operation; called from
+     * the parser. */
+    int add_binary(code_t code, int t1, int t2);
+    /** Requires an addition of the unary operation; called from
+     * the parser. */
+    int add_unary(code_t code, int t);
+    /** Requires an addition of the nulary operation given by the
+     * string. The Atoms are consulted for uniquness and are given
+     * an internal index generated by the OperationTree. This is
+     * the channel through which the Atoms are filled. */
+    int add_nulary(const char *str);
 
-		/** Adds a derivative to the tree. This just calls
-		 * OperationTree::add_derivative. */
-		int add_derivative(int t, int v)
-			{return otree.add_derivative(t, v);}
-		/** Adds a substitution. This just calls
-		 * OperationTree::add_substitution. */
-		int add_substitution(int t, const map<int,int>& subst)
-			{return otree.add_substitution(t, subst);}
-		/** Add the substitution given by the map where left sides of
-		 * substitutions come from another parser. The right sides are
-		 * from this object. The given t is from the given parser fp. */
-		int add_substitution(int t, const map<int,int>& subst,
-							 const FormulaParser& fp)
-			{return otree.add_substitution(t, subst, fp.otree);}
-		/** This adds formulas from the given parser with (possibly)
-		 * different atoms applying substitutions from the given map
-		 * mapping atoms from fp to atoms of the object. */
-		void add_subst_formulas(const map<int,int>& subst, const FormulaParser& fp);
-		/** Substitute formulas. For each i from 1 through all
-		 * formulas, it adds a substitution of the i-th formula and
-		 * make it to be i-th formula.*/
-		void substitute_formulas(const std::map<int,int>& subst);
-		/** This method turns the given term to nulary operation. It
-		 * should be used with caution, since this method does not
-		 * anything do with atoms, but usually some action is also
-		 * needed (at leat to assign the tree index t to some
-		 * atom). */
-		void nularify(int t)
-			{otree.nularify(t);}
-		/** Returns a set of nulary terms of the given term. Just
-		 * calls OperationTree::nulary_of_term. */
-		const unordered_set<int>& nulary_of_term(int t) const
-			{return otree.nulary_of_term(t);}
+    /** Adds a derivative to the tree. This just calls
+     * OperationTree::add_derivative. */
+    int
+    add_derivative(int t, int v)
+    {
+      return otree.add_derivative(t, v);
+    }
+    /** Adds a substitution. This just calls
+     * OperationTree::add_substitution. */
+    int
+    add_substitution(int t, const map<int, int> &subst)
+    {
+      return otree.add_substitution(t, subst);
+    }
+    /** Add the substitution given by the map where left sides of
+     * substitutions come from another parser. The right sides are
+     * from this object. The given t is from the given parser fp. */
+    int
+    add_substitution(int t, const map<int, int> &subst,
+                     const FormulaParser &fp)
+    {
+      return otree.add_substitution(t, subst, fp.otree);
+    }
+    /** This adds formulas from the given parser with (possibly)
+     * different atoms applying substitutions from the given map
+     * mapping atoms from fp to atoms of the object. */
+    void add_subst_formulas(const map<int, int> &subst, const FormulaParser &fp);
+    /** Substitute formulas. For each i from 1 through all
+     * formulas, it adds a substitution of the i-th formula and
+     * make it to be i-th formula.*/
+    void substitute_formulas(const std::map<int, int> &subst);
+    /** This method turns the given term to nulary operation. It
+     * should be used with caution, since this method does not
+     * anything do with atoms, but usually some action is also
+     * needed (at leat to assign the tree index t to some
+     * atom). */
+    void
+    nularify(int t)
+    {
+      otree.nularify(t);
+    }
+    /** Returns a set of nulary terms of the given term. Just
+     * calls OperationTree::nulary_of_term. */
+    const unordered_set<int> &
+    nulary_of_term(int t) const
+    {
+      return otree.nulary_of_term(t);
+    }
 
-		/** Parse a given string containing one or more formulas. The
-		 * formulas are parsed and added to the OperationTree and to
-		 * the formulas vector. */
-		void parse(int length, const char* stream);
-		/** Processes a syntax error from bison. */
-		void error(const char* mes) const;
-		/** Differentiate all the formulas up to the given order. The
-		 * variables with respect to which the derivatives are taken
-		 * are obtained by Atoms::variables(). If the derivates exist,
-		 * they are destroyed and created again (with possibly
-		 * different order). */
-		void differentiate(int max_order);
-		/** Return i-th formula derivatives. */
-		const FormulaDerivatives& derivatives(int i) const;
+    /** Parse a given string containing one or more formulas. The
+     * formulas are parsed and added to the OperationTree and to
+     * the formulas vector. */
+    void parse(int length, const char *stream);
+    /** Processes a syntax error from bison. */
+    void error(const char *mes) const;
+    /** Differentiate all the formulas up to the given order. The
+     * variables with respect to which the derivatives are taken
+     * are obtained by Atoms::variables(). If the derivates exist,
+     * they are destroyed and created again (with possibly
+     * different order). */
+    void differentiate(int max_order);
+    /** Return i-th formula derivatives. */
+    const FormulaDerivatives&derivatives(int i) const;
 
-		/** This returns a maximum index of zero derivative formulas
-		 * including all nulary terms. This is a mimumum length of the
-		 * tree for which it is safe to evaluate zero derivatives of
-		 * the formulas. */
-		int last_formula() const;
-		/** This returns a tree index of the i-th formula in the
-		 * vector. */
-		int formula(int i) const
-			{return formulas[i];}
+    /** This returns a maximum index of zero derivative formulas
+     * including all nulary terms. This is a mimumum length of the
+     * tree for which it is safe to evaluate zero derivatives of
+     * the formulas. */
+    int last_formula() const;
+    /** This returns a tree index of the i-th formula in the
+     * vector. */
+    int
+    formula(int i) const
+    {
+      return formulas[i];
+    }
 
+    /** This returns a tree index of the last formula and pops its
+     * item from the formulas vector. The number of formulas is
+     * then less by one. Returns -1 if there is no formula. If
+     * there are derivatives of the last formula, they are
+     * destroyed and the vector ders is popped from the back. */
+    int pop_last_formula();
 
-		/** This returns a tree index of the last formula and pops its
-		 * item from the formulas vector. The number of formulas is
-		 * then less by one. Returns -1 if there is no formula. If
-		 * there are derivatives of the last formula, they are
-		 * destroyed and the vector ders is popped from the back. */
-		int pop_last_formula();
+    /** This returns a number of formulas. */
+    int
+    nformulas() const
+    {
+      return (int) (formulas.size());
+    }
 
-		/** This returns a number of formulas. */
-		int nformulas() const
-			{return (int)(formulas.size());}
+    /** This returns a reference to atoms. */
+    const Atoms &
+    getAtoms() const
+    {
+      return atoms;
+    }
+    Atoms &
+    getAtoms()
+    {
+      return atoms;
+    }
+    /** This returns the tree. */
+    const OperationTree &
+    getTree() const
+    {
+      return otree;
+    }
+    OperationTree &
+    getTree()
+    {
+      return otree;
+    }
 
-		/** This returns a reference to atoms. */
-		const Atoms& getAtoms() const
-			{return atoms;}
-		Atoms& getAtoms()
-			{return atoms;}
-		/** This returns the tree. */
-		const OperationTree& getTree() const
-			{return otree;}
-		OperationTree& getTree()
-			{return otree;}
+    /** Debug print. */
+    void print() const;
+  private:
+    /** Hide this copy constructor declaration by declaring it as
+     * private. */
+    FormulaParser(const FormulaParser &fp);
+    /** Destroy all derivatives. */
+    void destroy_derivatives();
+  };
 
-		/** Debug print. */
-		void print() const;
-	private:
-		/** Hide this copy constructor declaration by declaring it as
-		 * private. */
-		FormulaParser(const FormulaParser& fp);
-		/** Destroy all derivatives. */
-		void destroy_derivatives();
-	};
+  /** This is a pure virtual class defining an interface for all
+   * classes which will load the results of formula (zero
+   * derivative) evaluations. A primitive implementation of this
+   * class can be a vector of doubles. */
+  class FormulaEvalLoader
+  {
+  public:
+    virtual ~FormulaEvalLoader()
+    {
+    }
+    /** Set the value res for the given formula. The formula is
+     * identified by an index corresponding to the ordering in
+     * which the formulas have been parsed (starting from
+     * zero). */
+    virtual void load(int i, double res) = 0;
+  };
 
-	/** This is a pure virtual class defining an interface for all
-	 * classes which will load the results of formula (zero
-	 * derivative) evaluations. A primitive implementation of this
-	 * class can be a vector of doubles. */
-	class FormulaEvalLoader {
-	public:
-		virtual ~FormulaEvalLoader() {}
-		/** Set the value res for the given formula. The formula is
-		 * identified by an index corresponding to the ordering in
-		 * which the formulas have been parsed (starting from
-		 * zero). */
-		virtual void load(int i, double res) = 0;
-	};
+  /** This class evaluates a selected subset of terms of the
+   * tree. In the protected constructor, one can constraint the
+   * initialization of the evaluation tree to a given number of
+   * terms in the beginning. Using this constructor, one has to make
+   * sure, that the terms in the beginning do not refer to terms
+   * behind the initial part. */
+  class FormulaCustomEvaluator
+  {
+  protected:
+    /** The evaluation tree. */
+    EvalTree etree;
+    /** The custom tree indices to be evaluated. */
+    vector<int> terms;
+  public:
+    /** Construct from FormulaParser and given list of terms. */
+    FormulaCustomEvaluator(const FormulaParser &fp, const vector<int> &ts)
+      : etree(fp.otree), terms(ts)
+    {
+    }
+    /** Construct from OperationTree and given list of terms. */
+    FormulaCustomEvaluator(const OperationTree &ot, const vector<int> &ts)
+      : etree(ot), terms(ts)
+    {
+    }
+    /** Evaluate the terms using the given AtomValues and load the
+     * results using the given loader. The loader is called for
+     * each term in the order of the terms. */
+    void eval(const AtomValues &av, FormulaEvalLoader &loader);
+  protected:
+    FormulaCustomEvaluator(const FormulaParser &fp)
+      : etree(fp.otree, fp.last_formula()), terms(fp.formulas)
+    {
+    }
+  };
 
-	/** This class evaluates a selected subset of terms of the
-	 * tree. In the protected constructor, one can constraint the
-	 * initialization of the evaluation tree to a given number of
-	 * terms in the beginning. Using this constructor, one has to make
-	 * sure, that the terms in the beginning do not refer to terms
-	 * behind the initial part. */
-	class FormulaCustomEvaluator {
-	protected:
-		/** The evaluation tree. */
-		EvalTree etree;
-		/** The custom tree indices to be evaluated. */
-		vector<int> terms;
-	public:
-		/** Construct from FormulaParser and given list of terms. */
-		FormulaCustomEvaluator(const FormulaParser& fp, const vector<int>& ts)
-			: etree(fp.otree), terms(ts)
-			{}
-		/** Construct from OperationTree and given list of terms. */
-		FormulaCustomEvaluator(const OperationTree& ot, const vector<int>& ts)
-			: etree(ot), terms(ts)
-			{}
-		/** Evaluate the terms using the given AtomValues and load the
-		 * results using the given loader. The loader is called for
-		 * each term in the order of the terms. */
-		void eval(const AtomValues& av, FormulaEvalLoader& loader);
-	protected:
-		FormulaCustomEvaluator(const FormulaParser& fp)
-			: etree(fp.otree, fp.last_formula()), terms(fp.formulas)
-			{}
-	};
+  /** This class evaluates zero derivatives of the FormulaParser. */
+  class FormulaEvaluator : public FormulaCustomEvaluator
+  {
+  public:
+    /** Construct from FormulaParser. */
+    FormulaEvaluator(const FormulaParser &fp)
+      : FormulaCustomEvaluator(fp)
+    {
+    }
+  };
 
-	/** This class evaluates zero derivatives of the FormulaParser. */
-	class FormulaEvaluator : public FormulaCustomEvaluator {
-	public:
-		/** Construct from FormulaParser. */
-		FormulaEvaluator(const FormulaParser& fp)
-			: FormulaCustomEvaluator(fp) {}
-	};
+  /** This is a pure virtual class defining an interface for all
+   * classes which will load the results of formula derivative
+   * evaluations. */
+  class FormulaDerEvalLoader
+  {
+  public:
+    virtual ~FormulaDerEvalLoader()
+    {
+    }
+    /** This loads the result of the derivative of the given
+     * order. The semantics of i is the same as in
+     * FormulaEvalLoader::load. The indices of variables with
+     * respect to which the derivative was taken are stored in
+     * memory pointed by vars. These are the tree indices of the
+     * variables. */
+    virtual void load(int i, int order, const int *vars, double res) = 0;
+  };
 
-	/** This is a pure virtual class defining an interface for all
-	 * classes which will load the results of formula derivative
-	 * evaluations. */
-	class FormulaDerEvalLoader {
-	public:
-		virtual ~FormulaDerEvalLoader() {}
-		/** This loads the result of the derivative of the given
-		 * order. The semantics of i is the same as in
-		 * FormulaEvalLoader::load. The indices of variables with
-		 * respect to which the derivative was taken are stored in
-		 * memory pointed by vars. These are the tree indices of the
-		 * variables. */
-		virtual void load(int i, int order, const int* vars, double res) = 0;
-	};
+  /** This class is a utility class representing the tensor
+   * multindex. It can basically increment itself, and calculate
+   * its offset in the folded tensor. */
+  class FoldMultiIndex
+  {
+    /** Number of variables. */
+    int nvar;
+    /** Dimension. */
+    int ord;
+    /** The multiindex. */
+    int *data;
+  public:
+    /** Initializes to the zero derivative. Order is 0, data is
+     * empty. */
+    FoldMultiIndex(int nv);
+    /** Initializes the multiindex to zeros or given i. */
+    FoldMultiIndex(int nv, int order, int i = 0);
+    /** Makes a new multiindex of the same order applying a given
+     * mapping to the indices. The mapping is supposed to be monotone. */
+    FoldMultiIndex(int nv, const FoldMultiIndex &mi, const vector<int> &mp);
+    /** Shifting constructor. This adds a given number of orders
+     * to the end, copying the last item to the newly added items,
+     * keeping the index ordered. If the index was empty (zero-th
+     * dimension), then zeros are added. */
+    FoldMultiIndex(const FoldMultiIndex &fmi, int new_orders);
+    /** Copy constructor. */
+    FoldMultiIndex(const FoldMultiIndex &fmi);
+    /** Desctructor. */
+    virtual ~FoldMultiIndex()
+    {
+      delete [] data;
+    }
+    /** Assignment operator. */
+    const FoldMultiIndex &operator=(const FoldMultiIndex &fmi);
+    /** Operator < implementing lexicographic ordering within one
+     * order, increasing order across orders. */
+    bool operator<(const FoldMultiIndex &fmi) const;
+    bool operator==(const FoldMultiIndex &fmi) const;
+    /** Increment the multiindex. */
+    void increment();
+    /** Return offset of the multiindex in the folded tensor. */
+    int offset() const;
+    const int &
+    operator[](int i) const
+    {
+      return data[i];
+    }
+    /** Return order of the multiindex, i.e. dimension of the
+     * tensor. */
+    int
+    order() const
+    {
+      return ord;
+    }
+    /** Return the number of variables. */
+    int
+    nv() const
+    {
+      return nvar;
+    }
+    /** Return the data. */
+    const int *
+    ind() const
+    {
+      return data;
+    }
+    /** Return true if the end of the tensor is reached. The
+     * result of a subsequent increment should be considered
+     * unpredictable. */
+    bool
+    past_the_end() const
+    {
+      return (ord == 0) || (data[0] == nvar);
+    }
+    /** Prints the multiindex in the brackets. */
+    void print() const;
+  private:
+    static int offset_recurse(int *data, int len, int nv);
+  };
 
-	/** This class is a utility class representing the tensor
-	 * multindex. It can basically increment itself, and calculate
-	 * its offset in the folded tensor. */
-	class FoldMultiIndex {
-		/** Number of variables. */
-		int nvar;
-		/** Dimension. */
-		int ord;
-		/** The multiindex. */
-		int* data;
-	public:
-		/** Initializes to the zero derivative. Order is 0, data is
-		 * empty. */
-		FoldMultiIndex(int nv);
-		/** Initializes the multiindex to zeros or given i. */
-		FoldMultiIndex(int nv, int order, int i = 0);
-		/** Makes a new multiindex of the same order applying a given
-		 * mapping to the indices. The mapping is supposed to be monotone. */
-		FoldMultiIndex(int nv, const FoldMultiIndex& mi, const vector<int>& mp);
-		/** Shifting constructor. This adds a given number of orders
-		 * to the end, copying the last item to the newly added items,
-		 * keeping the index ordered. If the index was empty (zero-th
-		 * dimension), then zeros are added. */
-		FoldMultiIndex(const FoldMultiIndex& fmi, int new_orders);
-		/** Copy constructor. */
-		FoldMultiIndex(const FoldMultiIndex& fmi);
-		/** Desctructor. */
-		virtual ~FoldMultiIndex()
-			{delete [] data;}
-		/** Assignment operator. */
-		const FoldMultiIndex& operator=(const FoldMultiIndex& fmi);
-		/** Operator < implementing lexicographic ordering within one
-		 * order, increasing order across orders. */
-		bool operator<(const FoldMultiIndex& fmi) const;
-		bool operator==(const FoldMultiIndex& fmi) const;
-		/** Increment the multiindex. */
-		void increment();
-		/** Return offset of the multiindex in the folded tensor. */ 
-		int offset() const;
-		const int& operator[](int i) const
-			{return data[i];}
-		/** Return order of the multiindex, i.e. dimension of the
-		 * tensor. */ 
-		int order() const
-			{return ord;}
-		/** Return the number of variables. */
-		int nv() const
-			{return nvar;}
-		/** Return the data. */
-		const int* ind() const
-			{return data;}
-		/** Return true if the end of the tensor is reached. The
-		 * result of a subsequent increment should be considered
-		 * unpredictable. */
-		bool past_the_end() const
-			{return (ord == 0) || (data[0] == nvar);}
-		/** Prints the multiindex in the brackets. */
-		void print() const;
-	private:
-		static int offset_recurse(int* data, int len, int nv);
-	};
-
-	/** This class evaluates derivatives of the FormulaParser. */
-	class FormulaDerEvaluator {
-		/** Its own instance of EvalTree. */
-		EvalTree etree;
-		/** The indices of derivatives for each formula. This is a
-		 * const copy FormulaParser::ders. We do not allocate nor
-		 * deallocate anything here. */
-		vector<const FormulaDerivatives*> ders;
-		/** A copy of tree indices corresponding to atoms to with
-		 * respect the derivatives were taken. */
-		vector<int> der_atoms;
-	public:
-		/** Construct the object from FormulaParser. */
-		FormulaDerEvaluator(const FormulaParser& fp);
-		/** Evaluate the derivatives from the FormulaParser wrt to all
-		 * atoms in variables vector at the given AtomValues. The
-		 * given loader is used for output. */
-		void eval(const AtomValues& av, FormulaDerEvalLoader& loader, int order);
-		/** Evaluate the derivatives from the FormulaParser wrt to a
-		 * selection of atoms of the atoms in der_atoms vector at the
-		 * given AtomValues. The selection is given by a monotone
-		 * mapping to the indices (not values) of the der_atoms. */
-		void eval(const vector<int>& mp, const AtomValues& av, FormulaDerEvalLoader& loader,
-				  int order);
-	};
+  /** This class evaluates derivatives of the FormulaParser. */
+  class FormulaDerEvaluator
+  {
+    /** Its own instance of EvalTree. */
+    EvalTree etree;
+    /** The indices of derivatives for each formula. This is a
+     * const copy FormulaParser::ders. We do not allocate nor
+     * deallocate anything here. */
+    vector<const FormulaDerivatives *> ders;
+    /** A copy of tree indices corresponding to atoms to with
+     * respect the derivatives were taken. */
+    vector<int> der_atoms;
+  public:
+    /** Construct the object from FormulaParser. */
+    FormulaDerEvaluator(const FormulaParser &fp);
+    /** Evaluate the derivatives from the FormulaParser wrt to all
+     * atoms in variables vector at the given AtomValues. The
+     * given loader is used for output. */
+    void eval(const AtomValues &av, FormulaDerEvalLoader &loader, int order);
+    /** Evaluate the derivatives from the FormulaParser wrt to a
+     * selection of atoms of the atoms in der_atoms vector at the
+     * given AtomValues. The selection is given by a monotone
+     * mapping to the indices (not values) of the der_atoms. */
+    void eval(const vector<int> &mp, const AtomValues &av, FormulaDerEvalLoader &loader,
+              int order);
+  };
 };
 
 #endif
diff --git a/dynare++/parser/cc/location.h b/dynare++/parser/cc/location.h
index 55182942bc337483f273ce1e2840656ce87f06cd..93b51cf1705b6891e486075dcfe46b005970e3cb 100644
--- a/dynare++/parser/cc/location.h
+++ b/dynare++/parser/cc/location.h
@@ -15,29 +15,32 @@
 // in EVERY action consuming material (this can be done with #define
 // YY_USER_ACTION) and in bison you must use option %locations.
 
-
 #ifndef OG_LOCATION_H
 #define OG_LOCATION_H
 
-namespace ogp {
+namespace ogp
+{
 
-	struct location_type {
-		int off; // offset of the token
-		int ll; // length ot the token
-		location_type() : off(0), ll(0) {}
-	};
+  struct location_type
+  {
+    int off; // offset of the token
+    int ll; // length ot the token
+    location_type() : off(0), ll(0)
+    {
+    }
+  };
 
 };
 
 #define YYLTYPE ogp::location_type
 
 // set current off to the first off and add all lengths
-#define YYLLOC_DEFAULT(Current, Rhs, N) \
-  {(Current).off    =  (Rhs)[1].off;    \
-   (Current).ll     =  0;               \
-   for (int i = 1; i <= N; i++) (Current).ll += (Rhs)[i].ll;}
+#define YYLLOC_DEFAULT(Current, Rhs, N)                         \
+  {(Current).off    =  (Rhs)[1].off;                            \
+    (Current).ll     =  0;                                      \
+    for (int i = 1; i <= N; i++) (Current).ll += (Rhs)[i].ll; }
 
-#define SET_LLOC(prefix) (prefix##lloc.off += prefix##lloc.ll, prefix##lloc.ll = prefix##leng)
+#define SET_LLOC(prefix) (prefix ## lloc.off += prefix ## lloc.ll, prefix ## lloc.ll = prefix ## leng)
 
 #endif
 
diff --git a/dynare++/parser/cc/matrix_parser.h b/dynare++/parser/cc/matrix_parser.h
index f2c85d2eb5d9562de53fa5db44d1cc9d2f84a49f..e86f57f0e5af737c63782d6118039fa02c8fbf2a 100644
--- a/dynare++/parser/cc/matrix_parser.h
+++ b/dynare++/parser/cc/matrix_parser.h
@@ -8,110 +8,143 @@
 #include <cstdlib> // For NULL
 #include <vector>
 
-namespace ogp {
-	using std::vector;
+namespace ogp
+{
+  using std::vector;
 
-	/** This class reads the given string and parses it as a
-	 * matrix. The matrix is read row by row. The row delimiter is
-	 * either a newline character or semicolon (first newline
-	 * character after the semicolon is ignored), the column delimiter
-	 * is either blank character or comma. A different number of items
-	 * in the row is not reconciliated, we do not construct a matrix
-	 * here. The class provides only an iterator to go through all
-	 * read items, the iterator provides information on row number and
-	 * column number of the item. */
-	class MPIterator;
-	class MatrixParser {
-		friend class MPIterator;
-	protected:
-		/** Raw data as they were read. */
-		vector<double> data;
-		/** Number of items in each row. */
-		vector<int> row_lengths;
-		/** Maximum number of row lengths. */
-		int nc;
-	public:
-		MatrixParser()
-			: nc(0) {}
-		MatrixParser(const MatrixParser& mp)
-			: data(mp.data), row_lengths(mp.row_lengths), nc(mp.nc) {}
-		virtual ~MatrixParser() {}
-		/** Return a number of read rows. */
-		int nrows() const
-			{return (int) row_lengths.size();}
-		/** Return a maximum number of items in the rows. */
-		int ncols() const
-			{return nc;}
-		/** Parses a given data. This initializes the object data. */
-		void parse(int length, const char* stream);
-		/** Adds newly read item. This should be called from bison
-		 * parser. */
-		void add_item(double v);
-		/** Starts a new row. This should be called from bison
-		 * parser. */
-		void start_row();
-		/** Process a parse error from the parser. */
-		void error(const char* mes) const;
-		/** Return begin iterator. */
-		MPIterator begin() const;
-		/** Return end iterator. */
-		MPIterator end() const;
-	protected:
-		/** Returns an index of the first non-empty row starting at
-		 * start. If the start row is non-empty, returns the start. If
-		 * there is no other non-empty row, returns
-		 * row_lengths.size(). */
-		int find_first_non_empty_row(int start = 0) const;
-	};
+  /** This class reads the given string and parses it as a
+   * matrix. The matrix is read row by row. The row delimiter is
+   * either a newline character or semicolon (first newline
+   * character after the semicolon is ignored), the column delimiter
+   * is either blank character or comma. A different number of items
+   * in the row is not reconciliated, we do not construct a matrix
+   * here. The class provides only an iterator to go through all
+   * read items, the iterator provides information on row number and
+   * column number of the item. */
+  class MPIterator;
+  class MatrixParser
+  {
+    friend class MPIterator;
+  protected:
+    /** Raw data as they were read. */
+    vector<double> data;
+    /** Number of items in each row. */
+    vector<int> row_lengths;
+    /** Maximum number of row lengths. */
+    int nc;
+  public:
+    MatrixParser()
+      : nc(0)
+    {
+    }
+    MatrixParser(const MatrixParser &mp)
+      : data(mp.data), row_lengths(mp.row_lengths), nc(mp.nc)
+    {
+    }
+    virtual ~MatrixParser()
+    {
+    }
+    /** Return a number of read rows. */
+    int
+    nrows() const
+    {
+      return (int) row_lengths.size();
+    }
+    /** Return a maximum number of items in the rows. */
+    int
+    ncols() const
+    {
+      return nc;
+    }
+    /** Parses a given data. This initializes the object data. */
+    void parse(int length, const char *stream);
+    /** Adds newly read item. This should be called from bison
+     * parser. */
+    void add_item(double v);
+    /** Starts a new row. This should be called from bison
+     * parser. */
+    void start_row();
+    /** Process a parse error from the parser. */
+    void error(const char *mes) const;
+    /** Return begin iterator. */
+    MPIterator begin() const;
+    /** Return end iterator. */
+    MPIterator end() const;
+  protected:
+    /** Returns an index of the first non-empty row starting at
+     * start. If the start row is non-empty, returns the start. If
+     * there is no other non-empty row, returns
+     * row_lengths.size(). */
+    int find_first_non_empty_row(int start = 0) const;
+  };
 
-	/** This is an iterator intended to iterate through a matrix parsed
-	 * by MatrixParser. The iterator provides only read-only access. */
-	class MPIterator {
-		friend class MatrixParser;
-	protected:
-		/** Reference to the matrix parser. */
-		const MatrixParser* p;
-		/** The index of the pointed item in the matrix parser. */
-		unsigned int i;
-		/** The column number of the pointed item starting from zero. */
-		int c;
-		/** The row number of the pointed item starting from zero. */
-		int r;
+  /** This is an iterator intended to iterate through a matrix parsed
+   * by MatrixParser. The iterator provides only read-only access. */
+  class MPIterator
+  {
+    friend class MatrixParser;
+  protected:
+    /** Reference to the matrix parser. */
+    const MatrixParser *p;
+    /** The index of the pointed item in the matrix parser. */
+    unsigned int i;
+    /** The column number of the pointed item starting from zero. */
+    int c;
+    /** The row number of the pointed item starting from zero. */
+    int r;
 
-	public:
-		MPIterator() : p(NULL), i(0), c(0), r(0) {}
-		/** Constructs an iterator pointing to the beginning of the
-		 * parsed matrix. */
-		MPIterator(const MatrixParser& mp);
-		/** Constructs an iterator pointing to the past-the-end of the
-		 * parsed matrix. */
-		MPIterator(const MatrixParser& mp, const char* dummy);
-		/** Return read-only reference to the pointed item. */
-		const double& operator*() const
-			{return p->data[i];}
-		/** Return a row index of the pointed item. */
-		int row() const
-			{return r;}
-		/** Return a column index of the pointed item. */
-		int col() const
-			{return c;}
-		/** Assignment operator. */
-		const MPIterator& operator=(const MPIterator& it)
-			{p = it.p; i = it.i; c = it.c; r = it.r; return *this;}
-		/** Return true if the iterators are the same, this is if they
-		 * have the same underlying object and the same item index. */ 
-		bool operator==(const MPIterator& it) const
-			{return it.p == p && it.i == i;}
-		/** Negative of the operator==. */
-		bool operator!=(const MPIterator& it) const
-			{return ! (it == *this);} 
-		/** Increment operator. */
-		MPIterator& operator++();
-	};
+  public:
+    MPIterator() : p(NULL), i(0), c(0), r(0)
+    {
+    }
+    /** Constructs an iterator pointing to the beginning of the
+     * parsed matrix. */
+    MPIterator(const MatrixParser &mp);
+    /** Constructs an iterator pointing to the past-the-end of the
+     * parsed matrix. */
+    MPIterator(const MatrixParser &mp, const char *dummy);
+    /** Return read-only reference to the pointed item. */
+    const double &
+    operator*() const
+    {
+      return p->data[i];
+    }
+    /** Return a row index of the pointed item. */
+    int
+    row() const
+    {
+      return r;
+    }
+    /** Return a column index of the pointed item. */
+    int
+    col() const
+    {
+      return c;
+    }
+    /** Assignment operator. */
+    const MPIterator &
+    operator=(const MPIterator &it)
+    {
+      p = it.p; i = it.i; c = it.c; r = it.r; return *this;
+    }
+    /** Return true if the iterators are the same, this is if they
+     * have the same underlying object and the same item index. */
+    bool
+    operator==(const MPIterator &it) const
+    {
+      return it.p == p && it.i == i;
+    }
+    /** Negative of the operator==. */
+    bool
+    operator!=(const MPIterator &it) const
+    {
+      return !(it == *this);
+    }
+    /** Increment operator. */
+    MPIterator &operator++();
+  };
 };
 
-
-
 #endif
 
 // Local Variables:
diff --git a/dynare++/parser/cc/namelist.h b/dynare++/parser/cc/namelist.h
index 0bde1232582221c4477ddcdb0073f35569d6c486..e704c8f677b785f138ab872366f480f3d2e987e6 100644
--- a/dynare++/parser/cc/namelist.h
+++ b/dynare++/parser/cc/namelist.h
@@ -5,24 +5,28 @@
 #ifndef OGP_NAMELIST
 #define OGP_NAMELIST
 
-namespace ogp {
+namespace ogp
+{
 
-	/** Parent class of all parsers parsing a namelist. They must
-	 * implement add_name() method and error() method, which is called
-	 * when an parse error occurs. 
-	 *
-	 * Parsing a name list is done as follows: implement
-	 * NameListParser interface, create the object, and call
-	 * NameListParser::namelist_parse(int lengt, const char*
-	 * text). When implementing error(), one may consult global
-	 * location_type namelist_lloc. */
-	class NameListParser {
-	public:
-		virtual ~NameListParser() {}
-		virtual void add_name(const char* name) = 0;
-		virtual void namelist_error(const char* mes) = 0;
-		void namelist_parse(int length, const char* text);
-	};
+  /** Parent class of all parsers parsing a namelist. They must
+   * implement add_name() method and error() method, which is called
+   * when an parse error occurs.
+   *
+   * Parsing a name list is done as follows: implement
+   * NameListParser interface, create the object, and call
+   * NameListParser::namelist_parse(int lengt, const char*
+   * text). When implementing error(), one may consult global
+   * location_type namelist_lloc. */
+  class NameListParser
+  {
+  public:
+    virtual ~NameListParser()
+    {
+    }
+    virtual void add_name(const char *name) = 0;
+    virtual void namelist_error(const char *mes) = 0;
+    void namelist_parse(int length, const char *text);
+  };
 };
 
 #endif
diff --git a/dynare++/parser/cc/parser_exception.h b/dynare++/parser/cc/parser_exception.h
index 2a8668a93037fae03dab9acbb1d69fa4772eaf5c..5b77664061996ce7e7664e78c7e891b493788d9a 100644
--- a/dynare++/parser/cc/parser_exception.h
+++ b/dynare++/parser/cc/parser_exception.h
@@ -7,61 +7,88 @@
 
 #include <string>
 
-namespace ogp {
-	using std::string;
+namespace ogp
+{
+  using std::string;
 
-	/** This is an easy exception, which, besides the message, stores
-	 * also an offset of the parse error. Since we might need to track
-	 * the argument number and for example the filed in the argument
-	 * which caused the error, we add three integers, which have no
-	 * semantics here. They should be documented in the function which
-	 * throws an exception and sets them. Their default value is -1,
-	 * which means they have not been set. */
-	class ParserException {
-	protected:
-		char* mes;
-		int off;
-		int aux_i1;
-		int aux_i2;
-		int aux_i3;
-	public:
-		ParserException(const char* m, int offset);
-		ParserException(const string& m, int offset);
-		ParserException(const string& m, const char* dum, int i1);
-		ParserException(const string& m, const char* dum, int i1, int i2);
-		ParserException(const string& m, const char* dum, int i1, int i2, int i3);
-		ParserException(const ParserException& e, int plus_offset);
-		/** Makes a copy and pushes given integer to aux_i1 shuffling
-		 * others and forgetting the last. */
-		ParserException(const ParserException& e, const char* dum, int i);
-		/** Makes a copy and pushes given two integers to aux_i1 and aux_i2  shuffling
-		 * others and forgetting the last two. */
-		ParserException(const ParserException& e, const char* dum, int i1, int i2);
-		/** Makes a copy and pushes given three integers to aux_i1, aux_i2, aus_i3 shuffling
-		 * others and forgetting the last three. */
-		ParserException(const ParserException& e, const char* dum, int i1, int i2, int i3);
-		ParserException(const ParserException& e);
-		virtual ~ParserException();
-		void print(FILE* fd) const;
-		const char* message() const
-			{return mes;}
-		int offset() const
-			{return off;}
-		const int& i1() const
-			{return aux_i1;}
-		int& i1()
-			{return aux_i1;}
-		const int& i2() const
-			{return aux_i2;}
-		int& i2()
-			{return aux_i2;}
-		const int& i3() const
-			{return aux_i3;}
-		int& i3()
-			{return aux_i3;}
-	protected:
-		void copy(const ParserException& e);
-	};
+  /** This is an easy exception, which, besides the message, stores
+   * also an offset of the parse error. Since we might need to track
+   * the argument number and for example the filed in the argument
+   * which caused the error, we add three integers, which have no
+   * semantics here. They should be documented in the function which
+   * throws an exception and sets them. Their default value is -1,
+   * which means they have not been set. */
+  class ParserException
+  {
+  protected:
+    char *mes;
+    int off;
+    int aux_i1;
+    int aux_i2;
+    int aux_i3;
+  public:
+    ParserException(const char *m, int offset);
+    ParserException(const string &m, int offset);
+    ParserException(const string &m, const char *dum, int i1);
+    ParserException(const string &m, const char *dum, int i1, int i2);
+    ParserException(const string &m, const char *dum, int i1, int i2, int i3);
+    ParserException(const ParserException &e, int plus_offset);
+    /** Makes a copy and pushes given integer to aux_i1 shuffling
+     * others and forgetting the last. */
+    ParserException(const ParserException &e, const char *dum, int i);
+    /** Makes a copy and pushes given two integers to aux_i1 and aux_i2  shuffling
+     * others and forgetting the last two. */
+    ParserException(const ParserException &e, const char *dum, int i1, int i2);
+    /** Makes a copy and pushes given three integers to aux_i1, aux_i2, aus_i3 shuffling
+     * others and forgetting the last three. */
+    ParserException(const ParserException &e, const char *dum, int i1, int i2, int i3);
+    ParserException(const ParserException &e);
+    virtual
+    ~ParserException();
+    void print(FILE *fd) const;
+    const char *
+    message() const
+    {
+      return mes;
+    }
+    int
+    offset() const
+    {
+      return off;
+    }
+    const int &
+    i1() const
+    {
+      return aux_i1;
+    }
+    int &
+    i1()
+    {
+      return aux_i1;
+    }
+    const int &
+    i2() const
+    {
+      return aux_i2;
+    }
+    int &
+    i2()
+    {
+      return aux_i2;
+    }
+    const int &
+    i3() const
+    {
+      return aux_i3;
+    }
+    int &
+    i3()
+    {
+      return aux_i3;
+    }
+  protected:
+    void copy(const ParserException &e);
+  };
 };
 
 #endif
diff --git a/dynare++/parser/cc/static_atoms.h b/dynare++/parser/cc/static_atoms.h
index dbe58017a3d2c735658d1aecaeb4ca5d4014fb4a..e94825d2933f49f2f7e5b2c72ce7732ad03a385e 100644
--- a/dynare++/parser/cc/static_atoms.h
+++ b/dynare++/parser/cc/static_atoms.h
@@ -7,79 +7,95 @@
 
 #include "dynamic_atoms.h"
 
-namespace ogp {
+namespace ogp
+{
 
-	class StaticAtoms : public Atoms, public Constants {
-	protected:
-		typedef map<const char*, int, ltstr> Tvarmap;
-		typedef map<int, const char*> Tinvmap;
-		/** Storage for names. */
-		NameStorage varnames;
-		/** Outer order of variables. */
-		vector<const char*> varorder;
-		/** This is the map mapping a variable name to the tree
-		 * index. */
-		Tvarmap vars;
-		/** This is the inverse mapping. It maps a tree index to the
-		 * variable name. */
-		Tinvmap indices;
-	public:
-		StaticAtoms() : Atoms(), Constants(), varnames(), varorder(), vars()
-			{}
-		/* Copy constructor. */
-		StaticAtoms(const StaticAtoms& a);
-		/** Conversion from DynamicAtoms. This takes all atoms from
-		 * the DynamicAtoms and adds its static version. The new tree
-		 * indices are allocated in the passed OperationTree. Whole
-		 * the process is traced in the map mapping old tree indices
-		 * to new tree indices. */
-		StaticAtoms(const DynamicAtoms& da, OperationTree& otree, Tintintmap& tmap)
-			: Atoms(), Constants(), varnames(), varorder(), vars()
-			{import_atoms(da, otree, tmap);}
-		/* Destructor. */
-		virtual ~StaticAtoms() {}
-		/** This imports atoms from dynamic atoms inserting the new
-		 * tree indices to the given tree (including constants). The
-		 * mapping from old atoms to new atoms is traced in tmap. */
-		void import_atoms(const DynamicAtoms& da, OperationTree& otree,
-						  Tintintmap& tmap);
-		/** If the name is constant, it returns its tree index if the
-		 * constant is registered in Constants, it returns -1
-		 * otherwise. If the name is not constant, it returns result
-		 * from check_variable, which is implemented by a subclass. */
-		int check(const char* name) const;
-		/** This assigns a given tree index to the variable name. The
-		 * name should have been checked before the call. */
-		void assign(const char* name, int t);
-		int nvar() const
-			{return varnames.num();}
-		/** This returns a vector of all variables. */
-		vector<int> variables() const;
-		/** This returns a tree index of the given variable. */
-		int index(const char* name) const;
-		/** This returns a name from the given tree index. NULL is
-		 * returned if the tree index doesn't exist. */
-		const char* inv_index(int t) const;
-		/** This returns a name in a outer ordering. (There is no other ordering.) */
-		const char* name(int i) const
-			{return varorder[i];}
-		/** Debug print. */
-		void print() const;
-		/** This registers a variable. A subclass can reimplement
-		 * this, for example, to ensure uniqueness of the
-		 * name. However, this method should be always called in
-		 * overriding methods to do the registering job. */
-		virtual void register_name(const char* name);
-		/** Return the name storage to allow querying to other
-		 * classes. */
-		const NameStorage& get_name_storage() const
-			{return varnames;}
-	protected:
-		/** This checks the variable. The implementing subclass might
-		 * want to throw an exception if the variable has not been
-		 * registered. */
-		virtual int check_variable(const char* name) const = 0;
-	};
+  class StaticAtoms : public Atoms, public Constants
+  {
+  protected:
+    typedef map<const char *, int, ltstr> Tvarmap;
+    typedef map<int, const char *> Tinvmap;
+    /** Storage for names. */
+    NameStorage varnames;
+    /** Outer order of variables. */
+    vector<const char *> varorder;
+    /** This is the map mapping a variable name to the tree
+     * index. */
+    Tvarmap vars;
+    /** This is the inverse mapping. It maps a tree index to the
+     * variable name. */
+    Tinvmap indices;
+  public:
+    StaticAtoms() : Atoms(), Constants(), varnames(), varorder(), vars()
+    {
+    }
+    /* Copy constructor. */
+    StaticAtoms(const StaticAtoms &a);
+    /** Conversion from DynamicAtoms. This takes all atoms from
+     * the DynamicAtoms and adds its static version. The new tree
+     * indices are allocated in the passed OperationTree. Whole
+     * the process is traced in the map mapping old tree indices
+     * to new tree indices. */
+    StaticAtoms(const DynamicAtoms &da, OperationTree &otree, Tintintmap &tmap)
+      : Atoms(), Constants(), varnames(), varorder(), vars()
+    {
+      import_atoms(da, otree, tmap);
+    }
+    /* Destructor. */
+    virtual ~StaticAtoms()
+    {
+    }
+    /** This imports atoms from dynamic atoms inserting the new
+     * tree indices to the given tree (including constants). The
+     * mapping from old atoms to new atoms is traced in tmap. */
+    void import_atoms(const DynamicAtoms &da, OperationTree &otree,
+                      Tintintmap &tmap);
+    /** If the name is constant, it returns its tree index if the
+     * constant is registered in Constants, it returns -1
+     * otherwise. If the name is not constant, it returns result
+     * from check_variable, which is implemented by a subclass. */
+    int check(const char *name) const;
+    /** This assigns a given tree index to the variable name. The
+     * name should have been checked before the call. */
+    void assign(const char *name, int t);
+    int
+    nvar() const
+    {
+      return varnames.num();
+    }
+    /** This returns a vector of all variables. */
+    vector<int> variables() const;
+    /** This returns a tree index of the given variable. */
+    int index(const char *name) const;
+    /** This returns a name from the given tree index. NULL is
+     * returned if the tree index doesn't exist. */
+    const char *inv_index(int t) const;
+    /** This returns a name in a outer ordering. (There is no other ordering.) */
+    const char *
+    name(int i) const
+    {
+      return varorder[i];
+    }
+    /** Debug print. */
+    void print() const;
+    /** This registers a variable. A subclass can reimplement
+     * this, for example, to ensure uniqueness of the
+     * name. However, this method should be always called in
+     * overriding methods to do the registering job. */
+    virtual void register_name(const char *name);
+    /** Return the name storage to allow querying to other
+     * classes. */
+    const NameStorage &
+    get_name_storage() const
+    {
+      return varnames;
+    }
+  protected:
+    /** This checks the variable. The implementing subclass might
+     * want to throw an exception if the variable has not been
+     * registered. */
+    virtual int check_variable(const char *name) const = 0;
+  };
 };
 
 #endif
diff --git a/dynare++/parser/cc/static_fine_atoms.h b/dynare++/parser/cc/static_fine_atoms.h
index e80af1eaed9becec0ff9ab0e45ef6d9f38190a7a..c4247f4a737b815e08fb00e91b97b4710248c572 100644
--- a/dynare++/parser/cc/static_fine_atoms.h
+++ b/dynare++/parser/cc/static_fine_atoms.h
@@ -8,165 +8,202 @@
 #include "static_atoms.h"
 #include "fine_atoms.h"
 
-namespace ogp {
+namespace ogp
+{
 
-	/** This class represents static atoms distinguishing between
-	 * parameters, endogenous and exogenous variables. The class
-	 * maintains also ordering of all three categories (referenced as
-	 * outer or inner, since there is only one ordering). It can be
-	 * constructed either from scratch, or from fine dynamic atoms. In
-	 * the latter case, one can decide if the ordering of this static
-	 * atoms should be internal or external ordering of the original
-	 * dynamic fine atoms. */
-	class StaticFineAtoms : public StaticAtoms {
-	public:
-		typedef map<int,int> Tintintmap;
-	protected:
-		typedef map<const char*, int, ltstr> Tvarintmap;
-	private:
-		/** The vector of parameter names, gives the parameter
-		 * ordering. */
-		vector<const char*> params;
-		/** A map mappping a parameter name to an index in the ordering. */
-		Tvarintmap param_outer_map;
-		/** The vector of endogenous variables. This defines the order
-		 * like parameters. */
-		vector<const char*> endovars;
-		/** A map mapping a name of an endogenous variable to an index
-		 * in the ordering. */
-		Tvarintmap endo_outer_map;
-		/** The vector of exogenous variables. Also defines the order
-		 * like parameters and endovars. */
-		vector<const char*> exovars;
-		/** A map mapping a name of an exogenous variable to an index
-		 * in the outer ordering. */
-		Tvarintmap exo_outer_map;
-		/** This vector defines a set of atoms as tree indices used
-		 * for differentiation. The order of the atoms in is the
-		 * concatenation of the outer ordering of endogenous and
-		 * exogenous. This vector is setup by parsing_finished() and
-		 * is returned by variables(). */
-		vector<int> der_atoms;
-		/** This is a mapping from endogenous atoms to all atoms in
-		 * der_atoms member. The mapping maps index in endogenous atom
-		 * ordering to index (not value) in der_atoms. It is useful if
-		 * one wants to evaluate derivatives wrt only endogenous
-		 * variables. It is set by parsing_finished(). By definition,
-		 * it is monotone. */
-		vector<int> endo_atoms_map;
-		/** This is a mapping from exogenous atoms to all atoms in
-		 * der_atoms member. It is the same as endo_atoms_map for
-		 * atoms of exogenous variables. */
-		vector<int> exo_atoms_map;		
-	public:
-		StaticFineAtoms() {}
-		/** Copy constructor making a new storage for atom names. */
-		StaticFineAtoms(const StaticFineAtoms& sfa);
-		/** Conversion from dynamic FineAtoms taking its outer
-		 * ordering as ordering of parameters, endogenous and
-		 * exogenous. A biproduct is an integer to integer map mapping
-		 * tree indices of the dynamic atoms to tree indices of the
-		 * static atoms. */
-		StaticFineAtoms(const FineAtoms& fa, OperationTree& otree, Tintintmap& tmap)
-			{StaticFineAtoms::import_atoms(fa, otree, tmap);}
-		/** Conversion from dynamic FineAtoms taking its internal
-		 * ordering as ordering of parameters, endogenous and
-		 * exogenous. A biproduct is an integer to integer map mapping
-		 * tree indices of the dynamic atoms to tree indices of the
-		 * static atoms. */
-		StaticFineAtoms(const FineAtoms& fa, OperationTree& otree, Tintintmap& tmap,
-						const char* dummy)
-			{StaticFineAtoms::import_atoms(fa, otree, tmap, dummy);}
-		virtual ~StaticFineAtoms() {}
-		/** This adds atoms from dynamic atoms inserting new tree
-		 * indices to the given tree and tracing the mapping from old
-		 * atoms to new atoms in tmap. The ordering of the static
-		 * atoms is the same as outer ordering of dynamic atoms. */
-		void import_atoms(const FineAtoms& fa, OperationTree& otree, Tintintmap& tmap);
-		/** This adds atoms from dynamic atoms inserting new tree
-		 * indices to the given tree and tracing the mapping from old
-		 * atoms to new atoms in tmap. The ordering of the static
-		 * atoms is the same as internal ordering of dynamic atoms. */
-		void import_atoms(const FineAtoms& fa, OperationTree& otree, Tintintmap& tmap,
-						  const char* dummy);
-		/** Overrides StaticAtoms::check_variable so that the error
-		 * would be raised if the variable name is not declared. A
-		 * variable is declared by inserting it to
-		 * StaticAtoms::varnames, which is done with registering
-		 * methods. This a responsibility of a subclass. */
-		int check_variable(const char* name) const;
-		/** Return an (external) ordering of parameters. */
-		const vector<const char*>& get_params() const
-			{return params;}
-		/** Return an external ordering of endogenous variables. */
-		const vector<const char*>& get_endovars() const
-			{return endovars;}
-		/** Return an external ordering of exogenous variables. */
-		const vector<const char*>& get_exovars() const
-			{return exovars;}
-		/** This constructs der_atoms, and the endo_endoms_map and
-		 * exo_atoms_map, which can be created only after the parsing
-		 * is finished. */
-		void parsing_finished();
-		/** Return the atoms with respect to which we are going to
-		 * differentiate. */
-		vector<int> variables() const
-			{return der_atoms;}
-		/** Return the endo_atoms_map. */
-		const vector<int>& get_endo_atoms_map() const
-			{return endo_atoms_map;}
-		/** Return the exo_atoms_map. */
-		const vector<int>& get_exo_atoms_map() const
-			{return endo_atoms_map;}
-		/** Return an index in the outer ordering of a given
-		 * parameter. An exception is thrown if the name is not a
-		 * parameter. */
-		int name2outer_param(const char* name) const;
-		/** Return an index in the outer ordering of a given
-		 * endogenous variable. An exception is thrown if the name is not a
-		 * and endogenous variable. */
-		int name2outer_endo(const char* name) const;
-		/** Return an index in the outer ordering of a given
-		 * exogenous variable. An exception is thrown if the name is not a
-		 * and exogenous variable. */
-		int name2outer_exo(const char* name) const;
-		/** Return the number of endogenous variables. */
-		int ny() const
-			{return endovars.size();}
-		/** Return the number of exogenous variables. */
-		int nexo() const
-			{return (int)exovars.size();}
-		/** Return the number of parameters. */
-		int np() const
-			{return (int)(params.size());}
-		/** Register unique endogenous variable name. The order of
-		 * calls defines the endo outer ordering. The method is
-		 * virtual, since a superclass may want to do some additional
-		 * action. */
-		virtual void register_uniq_endo(const char* name);
-		/** Register unique exogenous variable name. The order of
-		 * calls defines the exo outer ordering. The method is
-		 * virtual, since a superclass may want to do somem additional
-		 * action. */
-		virtual void register_uniq_exo(const char* name);
-		/** Register unique parameter name. The order of calls defines
-		 * the param outer ordering. The method is
-		 * virtual, since a superclass may want to do somem additional
-		 * action. */
-		virtual void register_uniq_param(const char* name);
-		/** Debug print. */
-		void print() const;
-	private:
-		/** Add endogenous variable name, which is already in the name
-		 * storage. */
-		void register_endo(const char* name);
-		/** Add exogenous variable name, which is already in the name
-		 * storage. */
-		void register_exo(const char* name);
-		/** Add parameter name, which is already in the name
-		 * storage. */
-		void register_param(const char* name);
-	};
+  /** This class represents static atoms distinguishing between
+   * parameters, endogenous and exogenous variables. The class
+   * maintains also ordering of all three categories (referenced as
+   * outer or inner, since there is only one ordering). It can be
+   * constructed either from scratch, or from fine dynamic atoms. In
+   * the latter case, one can decide if the ordering of this static
+   * atoms should be internal or external ordering of the original
+   * dynamic fine atoms. */
+  class StaticFineAtoms : public StaticAtoms
+  {
+  public:
+    typedef map<int, int> Tintintmap;
+  protected:
+    typedef map<const char *, int, ltstr> Tvarintmap;
+  private:
+    /** The vector of parameter names, gives the parameter
+     * ordering. */
+    vector<const char *> params;
+    /** A map mappping a parameter name to an index in the ordering. */
+    Tvarintmap param_outer_map;
+    /** The vector of endogenous variables. This defines the order
+     * like parameters. */
+    vector<const char *> endovars;
+    /** A map mapping a name of an endogenous variable to an index
+     * in the ordering. */
+    Tvarintmap endo_outer_map;
+    /** The vector of exogenous variables. Also defines the order
+     * like parameters and endovars. */
+    vector<const char *> exovars;
+    /** A map mapping a name of an exogenous variable to an index
+     * in the outer ordering. */
+    Tvarintmap exo_outer_map;
+    /** This vector defines a set of atoms as tree indices used
+     * for differentiation. The order of the atoms in is the
+     * concatenation of the outer ordering of endogenous and
+     * exogenous. This vector is setup by parsing_finished() and
+     * is returned by variables(). */
+    vector<int> der_atoms;
+    /** This is a mapping from endogenous atoms to all atoms in
+     * der_atoms member. The mapping maps index in endogenous atom
+     * ordering to index (not value) in der_atoms. It is useful if
+     * one wants to evaluate derivatives wrt only endogenous
+     * variables. It is set by parsing_finished(). By definition,
+     * it is monotone. */
+    vector<int> endo_atoms_map;
+    /** This is a mapping from exogenous atoms to all atoms in
+     * der_atoms member. It is the same as endo_atoms_map for
+     * atoms of exogenous variables. */
+    vector<int> exo_atoms_map;
+  public:
+    StaticFineAtoms()
+    {
+    }
+    /** Copy constructor making a new storage for atom names. */
+    StaticFineAtoms(const StaticFineAtoms &sfa);
+    /** Conversion from dynamic FineAtoms taking its outer
+     * ordering as ordering of parameters, endogenous and
+     * exogenous. A biproduct is an integer to integer map mapping
+     * tree indices of the dynamic atoms to tree indices of the
+     * static atoms. */
+    StaticFineAtoms(const FineAtoms &fa, OperationTree &otree, Tintintmap &tmap)
+    {
+      StaticFineAtoms::import_atoms(fa, otree, tmap);
+    }
+    /** Conversion from dynamic FineAtoms taking its internal
+     * ordering as ordering of parameters, endogenous and
+     * exogenous. A biproduct is an integer to integer map mapping
+     * tree indices of the dynamic atoms to tree indices of the
+     * static atoms. */
+    StaticFineAtoms(const FineAtoms &fa, OperationTree &otree, Tintintmap &tmap,
+                    const char *dummy)
+    {
+      StaticFineAtoms::import_atoms(fa, otree, tmap, dummy);
+    }
+    virtual ~StaticFineAtoms()
+    {
+    }
+    /** This adds atoms from dynamic atoms inserting new tree
+     * indices to the given tree and tracing the mapping from old
+     * atoms to new atoms in tmap. The ordering of the static
+     * atoms is the same as outer ordering of dynamic atoms. */
+    void import_atoms(const FineAtoms &fa, OperationTree &otree, Tintintmap &tmap);
+    /** This adds atoms from dynamic atoms inserting new tree
+     * indices to the given tree and tracing the mapping from old
+     * atoms to new atoms in tmap. The ordering of the static
+     * atoms is the same as internal ordering of dynamic atoms. */
+    void import_atoms(const FineAtoms &fa, OperationTree &otree, Tintintmap &tmap,
+                      const char *dummy);
+    /** Overrides StaticAtoms::check_variable so that the error
+     * would be raised if the variable name is not declared. A
+     * variable is declared by inserting it to
+     * StaticAtoms::varnames, which is done with registering
+     * methods. This a responsibility of a subclass. */
+    int check_variable(const char *name) const;
+    /** Return an (external) ordering of parameters. */
+    const vector<const char *> &
+    get_params() const
+    {
+      return params;
+    }
+    /** Return an external ordering of endogenous variables. */
+    const vector<const char *> &
+    get_endovars() const
+    {
+      return endovars;
+    }
+    /** Return an external ordering of exogenous variables. */
+    const vector<const char *> &
+    get_exovars() const
+    {
+      return exovars;
+    }
+    /** This constructs der_atoms, and the endo_endoms_map and
+     * exo_atoms_map, which can be created only after the parsing
+     * is finished. */
+    void parsing_finished();
+    /** Return the atoms with respect to which we are going to
+     * differentiate. */
+    vector<int>
+    variables() const
+    {
+      return der_atoms;
+    }
+    /** Return the endo_atoms_map. */
+    const vector<int> &
+    get_endo_atoms_map() const
+    {
+      return endo_atoms_map;
+    }
+    /** Return the exo_atoms_map. */
+    const vector<int> &
+    get_exo_atoms_map() const
+    {
+      return endo_atoms_map;
+    }
+    /** Return an index in the outer ordering of a given
+     * parameter. An exception is thrown if the name is not a
+     * parameter. */
+    int name2outer_param(const char *name) const;
+    /** Return an index in the outer ordering of a given
+     * endogenous variable. An exception is thrown if the name is not a
+     * and endogenous variable. */
+    int name2outer_endo(const char *name) const;
+    /** Return an index in the outer ordering of a given
+     * exogenous variable. An exception is thrown if the name is not a
+     * and exogenous variable. */
+    int name2outer_exo(const char *name) const;
+    /** Return the number of endogenous variables. */
+    int
+    ny() const
+    {
+      return endovars.size();
+    }
+    /** Return the number of exogenous variables. */
+    int
+    nexo() const
+    {
+      return (int) exovars.size();
+    }
+    /** Return the number of parameters. */
+    int
+    np() const
+    {
+      return (int) (params.size());
+    }
+    /** Register unique endogenous variable name. The order of
+     * calls defines the endo outer ordering. The method is
+     * virtual, since a superclass may want to do some additional
+     * action. */
+    virtual void register_uniq_endo(const char *name);
+    /** Register unique exogenous variable name. The order of
+     * calls defines the exo outer ordering. The method is
+     * virtual, since a superclass may want to do somem additional
+     * action. */
+    virtual void register_uniq_exo(const char *name);
+    /** Register unique parameter name. The order of calls defines
+     * the param outer ordering. The method is
+     * virtual, since a superclass may want to do somem additional
+     * action. */
+    virtual void register_uniq_param(const char *name);
+    /** Debug print. */
+    void print() const;
+  private:
+    /** Add endogenous variable name, which is already in the name
+     * storage. */
+    void register_endo(const char *name);
+    /** Add exogenous variable name, which is already in the name
+     * storage. */
+    void register_exo(const char *name);
+    /** Add parameter name, which is already in the name
+     * storage. */
+    void register_param(const char *name);
+  };
 
 };
 
diff --git a/dynare++/parser/cc/tree.h b/dynare++/parser/cc/tree.h
index a01b441fd02602822be6b4f69f089bbd4828be42..d8def988915fe1a64157f923f24fc63ffd993193 100644
--- a/dynare++/parser/cc/tree.h
+++ b/dynare++/parser/cc/tree.h
@@ -10,442 +10,511 @@
 #include <boost/unordered_set.hpp>
 #include <cstdio>
 
-namespace ogp {
-
-	using boost::unordered_set;
-	using boost::unordered_map;
-	using std::vector;
-	using std::set;
-	using std::map;
-
-	/** Enumerator representing nulary, unary and binary operation
-	 * codes. For nulary, 'none' is used. When one is adding a new
-	 * codes, he should update the code of #OperationTree::add_unary,
-	 * #OperationTree::add_binary, and of course
-	 * #OperationTree::add_derivative. */
-	enum code_t {NONE, UMINUS, LOG, EXP, SIN, COS, TAN, SQRT, ERF,
-				 ERFC, PLUS, MINUS, TIMES, DIVIDE, POWER};
-
-	/** Class representing a nulary, unary, or binary operation. */
-	class Operation {
-	protected:
-		/** Code of the operation. */
-		code_t code;
-		/** First operand. If none, then it is -1. */
-		int op1;
-		/** Second operand. If none, then it is -1. */
-		int op2;
-
-	public:
-		/** Constructs a binary operation. */
-		Operation(code_t cd, int oper1, int oper2)
-			: code(cd), op1(oper1), op2(oper2) {}
-		/** Constructs a unary operation. */
-		Operation(code_t cd, int oper1)
-			: code(cd), op1(oper1), op2(-1) {}
-		/** Constructs a nulary operation. */
-		Operation()
-			: code(NONE), op1(-1), op2(-1) {}
-		/** A copy constructor. */
-		Operation(const Operation& op)
-			: code(op.code), op1(op.op1), op2(op.op2) {}
-
-		/** Operator =. */
-		const Operation& operator=(const Operation& op)
-			{
-				code = op.code;
-				op1 = op.op1;
-				op2 = op.op2;
-				return *this;
-			}
-		/** Operator ==. */
-		bool operator==(const Operation& op) const
-			{
-				return code == op.code && op1 == op.op1 && op2 == op.op2;
-			}
-		/** Operator < implementing lexicographic ordering. */
-		bool operator<(const Operation& op) const
-			{
-				return (code < op.code ||
-						code == op.code &&
-						(op1 < op.op1 || op1 == op.op1 && op2 < op.op2));
-			}
-		/** Returns a number of operands. */
-		int nary() const
-			{
-				return (op2 == -1)? ((op1 == -1) ? 0 : 1) : 2;
-			}
-		/** Returns a hash value of the operation. */
-		size_t hashval() const
-			{
-				return op2+1 + (op1+1)^15 + code^30;
-			}
-
-		code_t getCode() const
-			{ return code; }
-		int getOp1() const
-			{ return op1; }
-		int getOp2() const
-			{ return op2; }
-
-	};
-
-	/** This struct is a predicate for ordering of the operations in
-	 * OperationTree class. now obsolete */
-	struct ltoper {
-		bool operator()(const Operation& oper1, const Operation& oper2) const
-			{return oper1 < oper2;}
-	};
-
-	/** Hash function object for Operation. */
-	struct ophash {
-		size_t operator()(const Operation& op) const
-			{ return op.hashval(); }
-	};
-
-	/** This struct is a function object selecting some
-	 * operations. The operation is given by a tree index. */
-	struct opselector {
-		virtual bool operator()(int t) const = 0;
-		virtual ~opselector() {}
-	};
-
-	/** Forward declaration of OperationFormatter. */
-	class OperationFormatter;
-	class DefaultOperationFormatter;
-
-	/** Forward declaration of EvalTree to make it friend of OperationTree. */
-	class EvalTree;
-
-	/** Class representing a set of trees for terms. Each term is
-	 * given a unique non-negative integer. The terms are basically
-	 * operations whose (integer) operands point to another terms in
-	 * the tree. The terms are stored in the vector. Equivalent unary
-	 * and binary terms are stored only once. This class guarantees
-	 * the uniqueness. The uniqueness of nulary terms is guaranteed by
-	 * the caller, since at this level of Operation abstraction, one
-	 * cannot discriminate between different nulary operations
-	 * (constants, variables). The uniqueness is enforced by the
-	 * unordered_map whose keys are operations and values are integers
-	 * (indices of the terms).
-
-	 * This class can also make derivatives of a given term with
-	 * respect to a given nulary term. I order to be able to quickly
-	 * recognize zero derivativates, we maintain a list of nulary
-	 * terms contained in the term. A possible zero derivative is then quickly
-	 * recognized by looking at the list. The list is implemented as a
-	 * unordered_set of integers.
-	 *
-	 * In addition, many term can be differentiated multiple times wrt
-	 * one variable since they can be referenced multiple times. To
-	 * avoid this, for each term we maintain a map mapping variables
-	 * to the derivatives of the term. As the caller will
-	 * differentiate wrt more and more variables, these maps will
-	 * become richer and richer.
-	 */
-	class OperationTree {
-		friend class EvalTree;
-		friend class DefaultOperationFormatter;
-	protected:
-		/** This is the vector of the terms. An index to this vector
-		 * uniquelly determines the term. */
-		vector<Operation> terms;
-
-		/** This defines a type for a map mapping the unary and binary
-		 * operations to their indices. */
-		typedef unordered_map<Operation, int, ophash> _Topmap;
-		typedef _Topmap::value_type _Topval;
-
-		/** This is the map mapping the unary and binary operations to
-		 * the indices of the terms.*/
-		_Topmap opmap;
-
-		/** This is a type for a set of integers. */
-		typedef unordered_set<int> _Tintset;
-		/** This is a vector of integer sets corresponding to the
-		 * nulary terms contained in the term. */
-		vector<_Tintset> nul_incidence;
-
-		/** This is a type of the map from variables (nulary terms) to
-		 * the terms. */
-		typedef unordered_map<int, int> _Tderivmap;
-		/** This is a vector of derivative mappings. For each term, it
-		 * maps variables to the derivatives of the term with respect
-		 * to the variables. */
-		vector<_Tderivmap> derivatives;
-
-		/** The tree index of the last nulary term. */
-		int last_nulary;
-	public:
-		/** This is a number of constants set in the following
-		 * enum. This number reserves space in a vector of terms for
-		 * the constants. */
-		static const int num_constants = 4;
-		/** Enumeration for special terms. We need zero, one, nan and
-		 * 2/pi.  These will be always first four terms having indices
-		 * zero, one and two, three. If adding anything to this
-		 * enumeration, make sure you have updated num_constants above.*/
-		enum {zero=0, one=1, nan=2, two_over_pi=3};
-
-		/** The unique constructor which initializes the object to
-		 * contain only zero, one and nan and two_over_pi.*/
-		OperationTree();
-
-		/** Copy constructor. */
-		OperationTree(const OperationTree& ot)
-			: terms(ot.terms), opmap(ot.opmap), nul_incidence(ot.nul_incidence),
-			  derivatives(ot.derivatives),
-			  last_nulary(ot.last_nulary)
-			{}
-
-		/** Add a nulary operation. The caller is responsible for not
-		 * inserting two semantically equivalent nulary operations.
-		 * @return newly allocated index
-		 */
-		int add_nulary();
-
-		/** Add a unary operation. The uniqness is checked, if it
-		 * already exists, then it is not added.
-		 * @param code the code of the unary operation
-		 * @param op the index of the operand
-		 * @return the index of the operation
-		*/
-		int add_unary(code_t code, int op);
-
-		/** Add a binary operation. The uniqueness is checked, if it
-		 * already exists, then it is not added. 
-		 * @param code the code of the binary operation
-		 * @param op1 the index of the first operand
-		 * @param op2 the index of the second operand
-		 * @return the index of the operation
-		 */
-		int add_binary(code_t code, int op1, int op2);
-
-		/** Add the derivative of the given term with respect to the
-		 * given nulary operation.
-		 * @param t the index of the operation being differentiated
-		 * @param v the index of the nulary operation
-		 * @return the index of the derivative
-		 */
-		int add_derivative(int t, int v);
-
-		/** Add the substitution given by the map. This adds a new
-		 * term which is equal to the given term with applied
-		 * substitutions given by the map replacing each term on the
-		 * left by a term on the right. We do not check that the terms
-		 * on the left are not subterms of the terms on the right. If
-		 * so, the substituted terms are not subject of further
-		 * substitution. */
-		int add_substitution(int t, const map<int,int>& subst);
-
-		/** Add the substitution given by the map where left sides of
-		 * substitutions come from another tree. The right sides are
-		 * from this tree. The given t is from the given otree. */
-		int add_substitution(int t, const map<int,int>& subst,
-							 const OperationTree& otree);
-
-		/** This method turns the given term to a nulary
-		 * operation. This is an only method, which changes already
-		 * existing term (all other methods add something new). User
-		 * should use this with caution and must make sure that
-		 * something similar has happened for atoms. In addition, it
-		 * does not do anything with derivatives, so it should not be
-		 * used after some derivatives were created, and derivatives
-		 * already created and saved in derivatives mappings should be
-		 * forgotten with forget_derivative_maps. */
-		void nularify(int t);
-
-		/** Return the set of nulary terms of the given term. */
-		const unordered_set<int>& nulary_of_term(int t) const
-			{return nul_incidence[t];}
-
-		/** Select subterms of the given term according a given
-		 * operation selector and return the set of terms that
-		 * correspond to the compounded operations. The given term is
-		 * a compound function of the returned subterms and the
-		 * function consists only from operations which yield false in
-		 * the selector. */
-		unordered_set<int> select_terms(int t, const opselector& sel) const;
-
-		/** Select subterms of the given term according a given
-		 * operation selector and return the set of terms that
-		 * correspond to the compounded operations. The given term is
-		 * a compound function of the returned subterms and the
-		 * subterms are maximal subterms consisting from operations
-		 * yielding true in the selector. */
-		unordered_set<int> select_terms_inv(int t, const opselector& sel) const;
-
-		/** This forgets all the derivative mappings. It is used after
-		 * a term has been nularified, and then the derivative
-		 * mappings carry wrong information. Note that the derivatives
-		 * mappings serve only as a tool for quick returns in
-		 * add_derivative. Resseting the mappings is harmless, all the
-		 * information is rebuilt in add_derivative without any
-		 * additional nodes (trees). */
-		void forget_derivative_maps();
-
-		/** This returns an operation of a given term. */
-		const Operation& operation(int t) const
-			{return terms[t];}
-
-		/** This outputs the operation to the given file descriptor
-		 * using the given OperationFormatter. */
-		void print_operation_tree(int t, FILE* fd, OperationFormatter& f) const;
-
-		/** Debug print of a given operation: */
-		void print_operation(int t) const;
-
-		/** Return the last tree index of a nulary term. */
-		int get_last_nulary() const
-			{return last_nulary;}
-
-		/** Get the number of all operations. */
-		int get_num_op() const
-			{return (int)(terms.size());}
-	private:
-		/** This registers a calculated derivative of the term in the
-		 * #derivatives vector.
-		 * @param t the index of the term for which we register the derivative
-		 * @param v the index of the nulary term (variable) to which
-		 * respect the derivative was taken
-		 * @param tder the index of the resulting derivative
-		 */
-		void register_derivative(int t, int v, int tder);
-		/** This does the same job as select_terms with the only
-		 * difference, that it adds the terms to the given set and
-		 * hence can be used recursivelly. */
-		void select_terms(int t, const opselector& sel, unordered_set<int>& subterms) const; 
-		/** This does the same job as select_terms_inv with the only
-		 * difference, that it adds the terms to the given set and
-		 * hence can be used recursivelly and returns true if the term
-		 * was selected. */
-		bool select_terms_inv(int t, const opselector& sel, unordered_set<int>& subterms) const; 
-		/** This updates nul_incidence information after the term t
-		 * was turned to a nulary term in all terms. It goes through
-		 * the tree from simplest terms to teh more complex ones and
-		 * changes the nul_incidence information where necesary. It
-		 * maintains a set where the changes have been made.*/
-		void update_nul_incidence_after_nularify(int t);
-	};
-
-	/** EvalTree class allows for an evaluation of the given tree for
-	 * a given values of nulary terms. For each term in the
-	 * OperationTree the class maintains a resulting value and a flag
-	 * if the value has been calculated or set. The life cycle of the
-	 * class is the following: After it is initialized, the user must
-	 * set values for necessary nulary terms. Then the object can be
-	 * requested to evaluate particular terms. During this process,
-	 * the number of evaluated terms is increasing. Then the user can
-	 * request overall reset of evaluation flags, set the nulary terms
-	 * to new values and evaluate a number of terms.
-	 *
-	 * Note that currently the user cannot request a reset of
-	 * evaluation flags only for those terms depending on a given
-	 * nulary term. This might be added in future and handeled by a
-	 * subclasses of OperationTree and EvalTree, since we need a
-	 * support for this in OperationTree.
-	 */
-	class EvalTree {
-	protected:
-		/** Reference to the OperationTree over which all evaluations
-		 * are done. */
-		const OperationTree& otree;
-		/** The array of values. */
-		double* const values;
-		/** The array of evaluation flags. */
-		bool* const flags;
-		/** The index of last operation in the EvalTree. Length of
-		 * values and flags will be then last_operation+1. */
-		int last_operation;
-	public:
-		/** Initializes the evaluation tree for the given operation
-		 * tree. If last is greater than -1, that the evaluation tree
-		 * will contain only formulas up to the given last index
-		 * (included). */
-		EvalTree(const OperationTree& otree, int last = -1);
-		virtual ~EvalTree()
-			{ delete [] values; delete [] flags; }
-		/** Set evaluation flag to all terms (besides the first
-		 * special terms) to false. */
-		void reset_all();
-		/** Set value for a given nulary term. */
-		void set_nulary(int t, double val);
-		/** Evaluate the given term with nulary terms set so far. */
-		double eval(int t);
-		/** Debug print. */
-		void print() const;
-		/* Return the operation tree. */
-		const OperationTree& getOperationTree() const
-			{return otree;}
-	private:
-		EvalTree(const EvalTree&);
-	};
-
-	/** This is an interface describing how a given operation is
-	 * formatted for output. */
-	class OperationFormatter {
-	public:
-		/** Empty virtual destructor. */
-		virtual ~OperationFormatter() {}
-		/** Print the formatted operation op with a given tree index t
-		 * to a given descriptor. (See class OperationTree to know
-		 * what is a tree index.) This prints all the tree. This
-		 * always writes equation, left hand side is a string
-		 * represenation (a variable, temporary, whatever) of the
-		 * term, the right hand side is a string representation of the
-		 * operation (which will refer to other string representation
-		 * of subterms). */
-		virtual void format(const Operation& op, int t, FILE* fd)=0;
-	};
-
-	/** The default formatter formats the formulas with a usual syntax
-	 * (for example Matlab). A formatting of atoms and terms might be
-	 * reimplemented by a subclass. In addition, during its life, the
-	 * object maintains a set of tree indices which have been output
-	 * and they are not output any more. */
-	class DefaultOperationFormatter : public OperationFormatter {
-	protected:
-		const OperationTree& otree;
-		set<int> stop_set;
-	public:
-		DefaultOperationFormatter(const OperationTree& ot)
-			: otree(ot) {}
-		/** Format the operation with the default syntax. */
-		void format(const Operation& op, int t, FILE* fd);
-		/** This prints a string represenation of the given term, for
-		 * example 'tmp10' for term 10. In this implementation it
-		 * prints $10. */
-		virtual void format_term(int t, FILE* fd) const;
-		/** Print a string representation of the nulary term. */
-		virtual void format_nulary(int t, FILE* fd) const;
-		/** Print a delimiter between two statements. By default it is
-		 * "\n". */
-		virtual void print_delim(FILE* fd) const;
-	};
-
-	class NularyStringConvertor {
-	public:
-		virtual ~NularyStringConvertor() {}
-		/** Return the string representation of the atom with the tree
-		 * index t. */
-		virtual std::string convert(int t) const = 0;
-	};
-
-	/** This class converts the given term to its mathematical string representation. */
-	class OperationStringConvertor {
-	protected:
-		const NularyStringConvertor& nulsc;
-		const OperationTree& otree;
-	public:
-		OperationStringConvertor(const NularyStringConvertor& nsc, const OperationTree& ot)
-			: nulsc(nsc), otree(ot) {}
-		/** Empty virtual destructor. */
-		virtual ~OperationStringConvertor() {}
-		/** Convert the operation to the string mathematical
-		 * representation. This does not write any equation, just
-		 * returns a string representation of the formula. */
-		std::string convert(const Operation& op, int t) const;
-	};
+namespace ogp
+{
+
+  using boost::unordered_set;
+  using boost::unordered_map;
+  using std::vector;
+  using std::set;
+  using std::map;
+
+  /** Enumerator representing nulary, unary and binary operation
+   * codes. For nulary, 'none' is used. When one is adding a new
+   * codes, he should update the code of #OperationTree::add_unary,
+   * #OperationTree::add_binary, and of course
+   * #OperationTree::add_derivative. */
+  enum code_t {NONE, UMINUS, LOG, EXP, SIN, COS, TAN, SQRT, ERF,
+               ERFC, PLUS, MINUS, TIMES, DIVIDE, POWER};
+
+  /** Class representing a nulary, unary, or binary operation. */
+  class Operation
+  {
+  protected:
+    /** Code of the operation. */
+    code_t code;
+    /** First operand. If none, then it is -1. */
+    int op1;
+    /** Second operand. If none, then it is -1. */
+    int op2;
+
+  public:
+    /** Constructs a binary operation. */
+    Operation(code_t cd, int oper1, int oper2)
+      : code(cd), op1(oper1), op2(oper2)
+    {
+    }
+    /** Constructs a unary operation. */
+    Operation(code_t cd, int oper1)
+      : code(cd), op1(oper1), op2(-1)
+    {
+    }
+    /** Constructs a nulary operation. */
+    Operation()
+      : code(NONE), op1(-1), op2(-1)
+    {
+    }
+    /** A copy constructor. */
+    Operation(const Operation &op)
+      : code(op.code), op1(op.op1), op2(op.op2)
+    {
+    }
+
+    /** Operator =. */
+    const Operation &
+    operator=(const Operation &op)
+    {
+      code = op.code;
+      op1 = op.op1;
+      op2 = op.op2;
+      return *this;
+    }
+    /** Operator ==. */
+    bool
+    operator==(const Operation &op) const
+    {
+      return code == op.code && op1 == op.op1 && op2 == op.op2;
+    }
+    /** Operator < implementing lexicographic ordering. */
+    bool
+    operator<(const Operation &op) const
+    {
+      return (code < op.code
+              || code == op.code
+              && (op1 < op.op1 || op1 == op.op1 && op2 < op.op2));
+    }
+    /** Returns a number of operands. */
+    int
+    nary() const
+    {
+      return (op2 == -1) ? ((op1 == -1) ? 0 : 1) : 2;
+    }
+    /** Returns a hash value of the operation. */
+    size_t
+    hashval() const
+    {
+      return op2+1 + (op1+1)^15 + code^30;
+    }
+
+    code_t
+    getCode() const
+    {
+      return code;
+    }
+    int
+    getOp1() const
+    {
+      return op1;
+    }
+    int
+    getOp2() const
+    {
+      return op2;
+    }
+
+  };
+
+  /** This struct is a predicate for ordering of the operations in
+   * OperationTree class. now obsolete */
+  struct ltoper
+  {
+    bool
+    operator()(const Operation &oper1, const Operation &oper2) const
+    {
+      return oper1 < oper2;
+    }
+  };
+
+  /** Hash function object for Operation. */
+  struct ophash
+  {
+    size_t
+    operator()(const Operation &op) const
+    {
+      return op.hashval();
+    }
+  };
+
+  /** This struct is a function object selecting some
+   * operations. The operation is given by a tree index. */
+  struct opselector
+  {
+    virtual bool operator()(int t) const = 0;
+    virtual ~opselector()
+    {
+    }
+  };
+
+  /** Forward declaration of OperationFormatter. */
+  class OperationFormatter;
+  class DefaultOperationFormatter;
+
+  /** Forward declaration of EvalTree to make it friend of OperationTree. */
+  class EvalTree;
+
+  /** Class representing a set of trees for terms. Each term is
+   * given a unique non-negative integer. The terms are basically
+   * operations whose (integer) operands point to another terms in
+   * the tree. The terms are stored in the vector. Equivalent unary
+   * and binary terms are stored only once. This class guarantees
+   * the uniqueness. The uniqueness of nulary terms is guaranteed by
+   * the caller, since at this level of Operation abstraction, one
+   * cannot discriminate between different nulary operations
+   * (constants, variables). The uniqueness is enforced by the
+   * unordered_map whose keys are operations and values are integers
+   * (indices of the terms).
+
+   * This class can also make derivatives of a given term with
+   * respect to a given nulary term. I order to be able to quickly
+   * recognize zero derivativates, we maintain a list of nulary
+   * terms contained in the term. A possible zero derivative is then quickly
+   * recognized by looking at the list. The list is implemented as a
+   * unordered_set of integers.
+   *
+   * In addition, many term can be differentiated multiple times wrt
+   * one variable since they can be referenced multiple times. To
+   * avoid this, for each term we maintain a map mapping variables
+   * to the derivatives of the term. As the caller will
+   * differentiate wrt more and more variables, these maps will
+   * become richer and richer.
+   */
+  class OperationTree
+  {
+    friend class EvalTree;
+    friend class DefaultOperationFormatter;
+  protected:
+    /** This is the vector of the terms. An index to this vector
+     * uniquelly determines the term. */
+    vector<Operation> terms;
+
+    /** This defines a type for a map mapping the unary and binary
+     * operations to their indices. */
+    typedef unordered_map<Operation, int, ophash> _Topmap;
+    typedef _Topmap::value_type _Topval;
+
+    /** This is the map mapping the unary and binary operations to
+     * the indices of the terms.*/
+    _Topmap opmap;
+
+    /** This is a type for a set of integers. */
+    typedef unordered_set<int> _Tintset;
+    /** This is a vector of integer sets corresponding to the
+     * nulary terms contained in the term. */
+    vector<_Tintset> nul_incidence;
+
+    /** This is a type of the map from variables (nulary terms) to
+     * the terms. */
+    typedef unordered_map<int, int> _Tderivmap;
+    /** This is a vector of derivative mappings. For each term, it
+     * maps variables to the derivatives of the term with respect
+     * to the variables. */
+    vector<_Tderivmap> derivatives;
+
+    /** The tree index of the last nulary term. */
+    int last_nulary;
+  public:
+    /** This is a number of constants set in the following
+     * enum. This number reserves space in a vector of terms for
+     * the constants. */
+    static const int num_constants = 4;
+    /** Enumeration for special terms. We need zero, one, nan and
+     * 2/pi.  These will be always first four terms having indices
+     * zero, one and two, three. If adding anything to this
+     * enumeration, make sure you have updated num_constants above.*/
+    enum {zero = 0, one = 1, nan = 2, two_over_pi = 3};
+
+    /** The unique constructor which initializes the object to
+     * contain only zero, one and nan and two_over_pi.*/
+    OperationTree();
+
+    /** Copy constructor. */
+    OperationTree(const OperationTree &ot)
+      : terms(ot.terms), opmap(ot.opmap), nul_incidence(ot.nul_incidence),
+        derivatives(ot.derivatives),
+        last_nulary(ot.last_nulary)
+    {
+    }
+
+    /** Add a nulary operation. The caller is responsible for not
+     * inserting two semantically equivalent nulary operations.
+     * @return newly allocated index
+     */
+    int add_nulary();
+
+    /** Add a unary operation. The uniqness is checked, if it
+     * already exists, then it is not added.
+     * @param code the code of the unary operation
+     * @param op the index of the operand
+     * @return the index of the operation
+     */
+    int add_unary(code_t code, int op);
+
+    /** Add a binary operation. The uniqueness is checked, if it
+     * already exists, then it is not added.
+     * @param code the code of the binary operation
+     * @param op1 the index of the first operand
+     * @param op2 the index of the second operand
+     * @return the index of the operation
+     */
+    int add_binary(code_t code, int op1, int op2);
+
+    /** Add the derivative of the given term with respect to the
+     * given nulary operation.
+     * @param t the index of the operation being differentiated
+     * @param v the index of the nulary operation
+     * @return the index of the derivative
+     */
+    int add_derivative(int t, int v);
+
+    /** Add the substitution given by the map. This adds a new
+     * term which is equal to the given term with applied
+     * substitutions given by the map replacing each term on the
+     * left by a term on the right. We do not check that the terms
+     * on the left are not subterms of the terms on the right. If
+     * so, the substituted terms are not subject of further
+     * substitution. */
+    int add_substitution(int t, const map<int, int> &subst);
+
+    /** Add the substitution given by the map where left sides of
+     * substitutions come from another tree. The right sides are
+     * from this tree. The given t is from the given otree. */
+    int add_substitution(int t, const map<int, int> &subst,
+                         const OperationTree &otree);
+
+    /** This method turns the given term to a nulary
+     * operation. This is an only method, which changes already
+     * existing term (all other methods add something new). User
+     * should use this with caution and must make sure that
+     * something similar has happened for atoms. In addition, it
+     * does not do anything with derivatives, so it should not be
+     * used after some derivatives were created, and derivatives
+     * already created and saved in derivatives mappings should be
+     * forgotten with forget_derivative_maps. */
+    void nularify(int t);
+
+    /** Return the set of nulary terms of the given term. */
+    const unordered_set<int> &
+    nulary_of_term(int t) const
+    {
+      return nul_incidence[t];
+    }
+
+    /** Select subterms of the given term according a given
+     * operation selector and return the set of terms that
+     * correspond to the compounded operations. The given term is
+     * a compound function of the returned subterms and the
+     * function consists only from operations which yield false in
+     * the selector. */
+    unordered_set<int> select_terms(int t, const opselector &sel) const;
+
+    /** Select subterms of the given term according a given
+     * operation selector and return the set of terms that
+     * correspond to the compounded operations. The given term is
+     * a compound function of the returned subterms and the
+     * subterms are maximal subterms consisting from operations
+     * yielding true in the selector. */
+    unordered_set<int> select_terms_inv(int t, const opselector &sel) const;
+
+    /** This forgets all the derivative mappings. It is used after
+     * a term has been nularified, and then the derivative
+     * mappings carry wrong information. Note that the derivatives
+     * mappings serve only as a tool for quick returns in
+     * add_derivative. Resseting the mappings is harmless, all the
+     * information is rebuilt in add_derivative without any
+     * additional nodes (trees). */
+    void forget_derivative_maps();
+
+    /** This returns an operation of a given term. */
+    const Operation &
+    operation(int t) const
+    {
+      return terms[t];
+    }
+
+    /** This outputs the operation to the given file descriptor
+     * using the given OperationFormatter. */
+    void print_operation_tree(int t, FILE *fd, OperationFormatter &f) const;
+
+    /** Debug print of a given operation: */
+    void print_operation(int t) const;
+
+    /** Return the last tree index of a nulary term. */
+    int
+    get_last_nulary() const
+    {
+      return last_nulary;
+    }
+
+    /** Get the number of all operations. */
+    int
+    get_num_op() const
+    {
+      return (int) (terms.size());
+    }
+  private:
+    /** This registers a calculated derivative of the term in the
+     * #derivatives vector.
+     * @param t the index of the term for which we register the derivative
+     * @param v the index of the nulary term (variable) to which
+     * respect the derivative was taken
+     * @param tder the index of the resulting derivative
+     */
+    void register_derivative(int t, int v, int tder);
+    /** This does the same job as select_terms with the only
+     * difference, that it adds the terms to the given set and
+     * hence can be used recursivelly. */
+    void select_terms(int t, const opselector &sel, unordered_set<int> &subterms) const;
+    /** This does the same job as select_terms_inv with the only
+     * difference, that it adds the terms to the given set and
+     * hence can be used recursivelly and returns true if the term
+     * was selected. */
+    bool select_terms_inv(int t, const opselector &sel, unordered_set<int> &subterms) const;
+    /** This updates nul_incidence information after the term t
+     * was turned to a nulary term in all terms. It goes through
+     * the tree from simplest terms to teh more complex ones and
+     * changes the nul_incidence information where necesary. It
+     * maintains a set where the changes have been made.*/
+    void update_nul_incidence_after_nularify(int t);
+  };
+
+  /** EvalTree class allows for an evaluation of the given tree for
+   * a given values of nulary terms. For each term in the
+   * OperationTree the class maintains a resulting value and a flag
+   * if the value has been calculated or set. The life cycle of the
+   * class is the following: After it is initialized, the user must
+   * set values for necessary nulary terms. Then the object can be
+   * requested to evaluate particular terms. During this process,
+   * the number of evaluated terms is increasing. Then the user can
+   * request overall reset of evaluation flags, set the nulary terms
+   * to new values and evaluate a number of terms.
+   *
+   * Note that currently the user cannot request a reset of
+   * evaluation flags only for those terms depending on a given
+   * nulary term. This might be added in future and handeled by a
+   * subclasses of OperationTree and EvalTree, since we need a
+   * support for this in OperationTree.
+   */
+  class EvalTree
+  {
+  protected:
+    /** Reference to the OperationTree over which all evaluations
+     * are done. */
+    const OperationTree &otree;
+    /** The array of values. */
+    double *const values;
+    /** The array of evaluation flags. */
+    bool *const flags;
+    /** The index of last operation in the EvalTree. Length of
+     * values and flags will be then last_operation+1. */
+    int last_operation;
+  public:
+    /** Initializes the evaluation tree for the given operation
+     * tree. If last is greater than -1, that the evaluation tree
+     * will contain only formulas up to the given last index
+     * (included). */
+    EvalTree(const OperationTree &otree, int last = -1);
+    virtual ~EvalTree()
+    {
+      delete [] values; delete [] flags;
+    }
+    /** Set evaluation flag to all terms (besides the first
+     * special terms) to false. */
+    void reset_all();
+    /** Set value for a given nulary term. */
+    void set_nulary(int t, double val);
+    /** Evaluate the given term with nulary terms set so far. */
+    double eval(int t);
+    /** Debug print. */
+    void print() const;
+    /* Return the operation tree. */
+    const OperationTree &
+    getOperationTree() const
+    {
+      return otree;
+    }
+  private:
+    EvalTree(const EvalTree &);
+  };
+
+  /** This is an interface describing how a given operation is
+   * formatted for output. */
+  class OperationFormatter
+  {
+  public:
+    /** Empty virtual destructor. */
+    virtual ~OperationFormatter()
+    {
+    }
+    /** Print the formatted operation op with a given tree index t
+     * to a given descriptor. (See class OperationTree to know
+     * what is a tree index.) This prints all the tree. This
+     * always writes equation, left hand side is a string
+     * represenation (a variable, temporary, whatever) of the
+     * term, the right hand side is a string representation of the
+     * operation (which will refer to other string representation
+     * of subterms). */
+    virtual void format(const Operation &op, int t, FILE *fd) = 0;
+  };
+
+  /** The default formatter formats the formulas with a usual syntax
+   * (for example Matlab). A formatting of atoms and terms might be
+   * reimplemented by a subclass. In addition, during its life, the
+   * object maintains a set of tree indices which have been output
+   * and they are not output any more. */
+  class DefaultOperationFormatter : public OperationFormatter
+  {
+  protected:
+    const OperationTree &otree;
+    set<int> stop_set;
+  public:
+    DefaultOperationFormatter(const OperationTree &ot)
+      : otree(ot)
+    {
+    }
+    /** Format the operation with the default syntax. */
+    void format(const Operation &op, int t, FILE *fd);
+    /** This prints a string represenation of the given term, for
+     * example 'tmp10' for term 10. In this implementation it
+     * prints $10. */
+    virtual void format_term(int t, FILE *fd) const;
+    /** Print a string representation of the nulary term. */
+    virtual void format_nulary(int t, FILE *fd) const;
+    /** Print a delimiter between two statements. By default it is
+     * "\n". */
+    virtual void print_delim(FILE *fd) const;
+  };
+
+  class NularyStringConvertor
+  {
+  public:
+    virtual ~NularyStringConvertor()
+    {
+    }
+    /** Return the string representation of the atom with the tree
+     * index t. */
+    virtual std::string convert(int t) const = 0;
+  };
+
+  /** This class converts the given term to its mathematical string representation. */
+  class OperationStringConvertor
+  {
+  protected:
+    const NularyStringConvertor &nulsc;
+    const OperationTree &otree;
+  public:
+    OperationStringConvertor(const NularyStringConvertor &nsc, const OperationTree &ot)
+      : nulsc(nsc), otree(ot)
+    {
+    }
+    /** Empty virtual destructor. */
+    virtual ~OperationStringConvertor()
+    {
+    }
+    /** Convert the operation to the string mathematical
+     * representation. This does not write any equation, just
+     * returns a string representation of the formula. */
+    std::string convert(const Operation &op, int t) const;
+  };
 };
 
 #endif
diff --git a/dynare++/src/dynare3.h b/dynare++/src/dynare3.h
index a106f52aa78fb725b289f54c6381250b924d0f62..723060a955b2f5f48a1f5cbd08951feaa1cb5233 100644
--- a/dynare++/src/dynare3.h
+++ b/dynare++/src/dynare3.h
@@ -18,175 +18,286 @@
 
 class Dynare;
 
-class DynareNameList : public NameList {
-	vector<const char*> names;
+class DynareNameList : public NameList
+{
+  vector<const char *> names;
 public:
-	DynareNameList(const Dynare& dynare);
-	int getNum() const
-		{return (int)names.size();}
-	const char* getName(int i) const
-		{return names[i];}
-	/** This for each string of the input vector calculates its index
-	 * in the names. And returns the resulting vector of indices. If
-	 * the name cannot be found, then an exception is raised. */
-	vector<int> selectIndices(const vector<const char*>& ns) const;
+  DynareNameList(const Dynare &dynare);
+  int
+  getNum() const
+  {
+    return (int) names.size();
+  }
+  const char *
+  getName(int i) const
+  {
+    return names[i];
+  }
+  /** This for each string of the input vector calculates its index
+   * in the names. And returns the resulting vector of indices. If
+   * the name cannot be found, then an exception is raised. */
+  vector<int> selectIndices(const vector<const char *> &ns) const;
 };
 
-class DynareExogNameList : public NameList {
-	vector<const char*> names;
+class DynareExogNameList : public NameList
+{
+  vector<const char *> names;
 public:
-	DynareExogNameList(const Dynare& dynare);
-	int getNum() const
-		{return (int)names.size();}
-	const char* getName(int i) const
-		{return names[i];}
+  DynareExogNameList(const Dynare &dynare);
+  int
+  getNum() const
+  {
+    return (int) names.size();
+  }
+  const char *
+  getName(int i) const
+  {
+    return names[i];
+  }
 };
 
-class DynareStateNameList : public NameList {
-	vector<const char*> names;
+class DynareStateNameList : public NameList
+{
+  vector<const char *> names;
 public:
-	DynareStateNameList(const Dynare& dynare, const DynareNameList& dnl,
-						const DynareExogNameList& denl);
-	int getNum() const
-		{return (int)names.size();}
-	const char* getName(int i) const
-		{return names[i];}
+  DynareStateNameList(const Dynare &dynare, const DynareNameList &dnl,
+                      const DynareExogNameList &denl);
+  int
+  getNum() const
+  {
+    return (int) names.size();
+  }
+  const char *
+  getName(int i) const
+  {
+    return names[i];
+  }
 };
 
 // The following only implements DynamicModel with help of ogdyn::DynareModel
 
 class DynareJacobian;
-class Dynare : public DynamicModel {
-	friend class DynareNameList;
-	friend class DynareExogNameList;
-	friend class DynareStateNameList;
-	friend class DynareJacobian;
-	Journal& journal;
-	ogdyn::DynareModel* model;
-	Vector* ysteady;
-	TensorContainer<FSSparseTensor> md;
-	DynareNameList* dnl;
-	DynareExogNameList* denl;
-	DynareStateNameList* dsnl;
-	ogp::FormulaEvaluator* fe;
-	ogp::FormulaDerEvaluator* fde;
-	const double ss_tol;
+class Dynare : public DynamicModel
+{
+  friend class DynareNameList;
+  friend class DynareExogNameList;
+  friend class DynareStateNameList;
+  friend class DynareJacobian;
+  Journal &journal;
+  ogdyn::DynareModel *model;
+  Vector *ysteady;
+  TensorContainer<FSSparseTensor> md;
+  DynareNameList *dnl;
+  DynareExogNameList *denl;
+  DynareStateNameList *dsnl;
+  ogp::FormulaEvaluator *fe;
+  ogp::FormulaDerEvaluator *fde;
+  const double ss_tol;
 public:
-	/** Parses the given model file and uses the given order to
-	 * override order from the model file (if it is != -1). */
-	Dynare(const char* modname, int ord, double sstol, Journal& jr);
-	/** Parses the given equations with explicitly given names. */
-	Dynare(const char** endo, int num_endo,
-		   const char** exo, int num_exo,
-		   const char** par, int num_par,
-		   const char* equations, int len, int ord,
-		   double sstol, Journal& jr);
-	/** Makes a deep copy of the object. */
-	Dynare(const Dynare& dyn);
-	DynamicModel* clone() const
-		{return new Dynare(*this);}
-	virtual ~Dynare();
-	int nstat() const
-		{return model->getAtoms().nstat();}
-	int nboth() const
-		{return model->getAtoms().nboth();}
-	int npred() const
-		{return model->getAtoms().npred();}
-	int nforw() const
-		{return model->getAtoms().nforw();}
-	int nexog() const
-		{return model->getAtoms().nexo();}
-	int nys() const
-		{return model->getAtoms().nys();}
-	int nyss() const
-		{return model->getAtoms().nyss();}
-	int ny() const
-		{return model->getAtoms().ny();}
-	int order() const
-		{return model->getOrder();}
-
-	const NameList& getAllEndoNames() const
-		{return *dnl;}
-	const NameList& getStateNames() const
-		{return *dsnl;}
-	const NameList& getExogNames() const
-		{return *denl;}
-
-	TwoDMatrix& getVcov()
-		{return model->getVcov();}
-	const TwoDMatrix& getVcov() const
-		{return model->getVcov();}
-	Vector& getParams()
-		{return model->getParams();}
-	const Vector& getParams() const
-		{return model->getParams();}
-	void setInitOuter(const Vector& x)
-		{model->setInitOuter(x);}
-
-	const TensorContainer<FSSparseTensor>& getModelDerivatives() const
-		{return md;}
-	const Vector& getSteady() const
-		{return *ysteady;}
-	Vector& getSteady()
-		{return *ysteady;}
-	const ogdyn::DynareModel& getModel() const
-		{return *model;}
-
-	// here is true public interface
-	void solveDeterministicSteady(Vector& steady);
-	void solveDeterministicSteady()
-		{solveDeterministicSteady(*ysteady);}
-	void evaluateSystem(Vector& out, const Vector& yy, const Vector& xx);
-	void evaluateSystem(Vector& out, const Vector& yym, const Vector& yy,
-						const Vector& yyp, const Vector& xx);
-	void calcDerivatives(const Vector& yy, const Vector& xx);
-	void calcDerivativesAtSteady();
-
-	void writeMat(mat_t *fd, const char* prefix) const;
-	void writeDump(const std::string& basename) const;
+  /** Parses the given model file and uses the given order to
+   * override order from the model file (if it is != -1). */
+  Dynare(const char *modname, int ord, double sstol, Journal &jr);
+  /** Parses the given equations with explicitly given names. */
+  Dynare(const char **endo, int num_endo,
+         const char **exo, int num_exo,
+         const char **par, int num_par,
+         const char *equations, int len, int ord,
+         double sstol, Journal &jr);
+  /** Makes a deep copy of the object. */
+  Dynare(const Dynare &dyn);
+  DynamicModel *
+  clone() const
+  {
+    return new Dynare(*this);
+  }
+  virtual
+  ~Dynare();
+  int
+  nstat() const
+  {
+    return model->getAtoms().nstat();
+  }
+  int
+  nboth() const
+  {
+    return model->getAtoms().nboth();
+  }
+  int
+  npred() const
+  {
+    return model->getAtoms().npred();
+  }
+  int
+  nforw() const
+  {
+    return model->getAtoms().nforw();
+  }
+  int
+  nexog() const
+  {
+    return model->getAtoms().nexo();
+  }
+  int
+  nys() const
+  {
+    return model->getAtoms().nys();
+  }
+  int
+  nyss() const
+  {
+    return model->getAtoms().nyss();
+  }
+  int
+  ny() const
+  {
+    return model->getAtoms().ny();
+  }
+  int
+  order() const
+  {
+    return model->getOrder();
+  }
+
+  const NameList &
+  getAllEndoNames() const
+  {
+    return *dnl;
+  }
+  const NameList &
+  getStateNames() const
+  {
+    return *dsnl;
+  }
+  const NameList &
+  getExogNames() const
+  {
+    return *denl;
+  }
+
+  TwoDMatrix &
+  getVcov()
+  {
+    return model->getVcov();
+  }
+  const TwoDMatrix &
+  getVcov() const
+  {
+    return model->getVcov();
+  }
+  Vector &
+  getParams()
+  {
+    return model->getParams();
+  }
+  const Vector &
+  getParams() const
+  {
+    return model->getParams();
+  }
+  void
+  setInitOuter(const Vector &x)
+  {
+    model->setInitOuter(x);
+  }
+
+  const TensorContainer<FSSparseTensor> &
+  getModelDerivatives() const
+  {
+    return md;
+  }
+  const Vector &
+  getSteady() const
+  {
+    return *ysteady;
+  }
+  Vector &
+  getSteady()
+  {
+    return *ysteady;
+  }
+  const ogdyn::DynareModel &
+  getModel() const
+  {
+    return *model;
+  }
+
+  // here is true public interface
+  void solveDeterministicSteady(Vector &steady);
+  void
+  solveDeterministicSteady()
+  {
+    solveDeterministicSteady(*ysteady);
+  }
+  void evaluateSystem(Vector &out, const Vector &yy, const Vector &xx);
+  void evaluateSystem(Vector &out, const Vector &yym, const Vector &yy,
+                      const Vector &yyp, const Vector &xx);
+  void calcDerivatives(const Vector &yy, const Vector &xx);
+  void calcDerivativesAtSteady();
+
+  void writeMat(mat_t *fd, const char *prefix) const;
+  void writeDump(const std::string &basename) const;
 private:
-	void writeModelInfo(Journal& jr) const;
+  void writeModelInfo(Journal &jr) const;
 };
 
-class DynareEvalLoader : public ogp::FormulaEvalLoader, public Vector {
+class DynareEvalLoader : public ogp::FormulaEvalLoader, public Vector
+{
 public:
-	DynareEvalLoader(const ogp::FineAtoms& a, Vector& out);
-	void load(int i, double res)
-		{operator[](i) = res;}
+  DynareEvalLoader(const ogp::FineAtoms &a, Vector &out);
+  void
+  load(int i, double res)
+  {
+    operator[](i) = res;
+  }
 };
 
-class DynareDerEvalLoader : public ogp::FormulaDerEvalLoader {
+class DynareDerEvalLoader : public ogp::FormulaDerEvalLoader
+{
 protected:
-	const ogp::FineAtoms& atoms;
-	TensorContainer<FSSparseTensor>& md;
+  const ogp::FineAtoms &atoms;
+  TensorContainer<FSSparseTensor> &md;
 public:
-	DynareDerEvalLoader(const ogp::FineAtoms& a, TensorContainer<FSSparseTensor>& mod_ders,
-						int order);
-	void load(int i, int iord, const int* vars, double res);
+  DynareDerEvalLoader(const ogp::FineAtoms &a, TensorContainer<FSSparseTensor> &mod_ders,
+                      int order);
+  void load(int i, int iord, const int *vars, double res);
 };
 
-class DynareJacobian : public ogu::Jacobian, public ogp::FormulaDerEvalLoader {
+class DynareJacobian : public ogu::Jacobian, public ogp::FormulaDerEvalLoader
+{
 protected:
-	Dynare& d;
+  Dynare &d;
 public:
-	DynareJacobian(Dynare& dyn);
-	virtual ~DynareJacobian() {}
-	void load(int i, int iord, const int* vars, double res);
-	void eval(const Vector& in);
+  DynareJacobian(Dynare &dyn);
+  virtual ~DynareJacobian()
+  {
+  }
+  void load(int i, int iord, const int *vars, double res);
+  void eval(const Vector &in);
 };
 
-class DynareVectorFunction : public ogu::VectorFunction {
+class DynareVectorFunction : public ogu::VectorFunction
+{
 protected:
-	Dynare& d;
+  Dynare &d;
 public:
-	DynareVectorFunction(Dynare& dyn)
-		: d(dyn) {}
-	virtual ~DynareVectorFunction() {}
-	int inDim() const
-		{return d.ny();}
-	int outDim() const
-		{return d.ny();}
-	void eval(const ConstVector& in, Vector& out);
+  DynareVectorFunction(Dynare &dyn)
+    : d(dyn)
+  {
+  }
+  virtual ~DynareVectorFunction()
+  {
+  }
+  int
+  inDim() const
+  {
+    return d.ny();
+  }
+  int
+  outDim() const
+  {
+    return d.ny();
+  }
+  void eval(const ConstVector &in, Vector &out);
 };
 
 #endif
diff --git a/dynare++/src/dynare_atoms.h b/dynare++/src/dynare_atoms.h
index 7cdcce6c249392b49a97096c8e1f0458e1c0ef3b..68b9381990a3afbdec4897906e0958001815dad8 100644
--- a/dynare++/src/dynare_atoms.h
+++ b/dynare++/src/dynare_atoms.h
@@ -15,196 +15,222 @@
 #include <map>
 #include <vector>
 
-namespace ogdyn {
-
-	using std::map;
-	using std::vector;
-
-	/** A definition of a type mapping a string to an integer. Used as
-	 * a substitution map, saying what names are substituted for what
-	 * expressions represented by tree indices. */
-	typedef map<const char*, int, ogp::ltstr> Tsubstmap;
-
-	class DynareStaticAtoms : public ogp::StaticAtoms {
-	public:
-		DynareStaticAtoms()
-			: StaticAtoms() {}
-		DynareStaticAtoms(const DynareStaticAtoms& a)
-			: StaticAtoms(a) {}
-		virtual ~DynareStaticAtoms() {}
-		/** This registers a unique varname identifier. It throws an
-		 * exception if the variable name is duplicate. It checks the
-		 * uniqueness and then it calls StaticAtoms::register_name. */
-		void register_name(const char* name);
-	protected:
-		/** This returns a tree index of the given variable, and if
-		 * the variable has not been registered, it throws an
-		 * exception. */
-		int check_variable(const char* name) const;
-	};
-
-
-	class DynareDynamicAtoms : public ogp::SAtoms, public ogp::NularyStringConvertor {
-	public:
-		enum atype {endovar, exovar, param};
-	protected:
-		typedef map<const char*, atype, ogp::ltstr> Tatypemap;
-		/** The map assigining a type to each name. */
-		Tatypemap atom_type;
-	public:
-		DynareDynamicAtoms()
-			: ogp::SAtoms() {}
-		DynareDynamicAtoms(const DynareDynamicAtoms& dda);
-		virtual ~DynareDynamicAtoms() {}
-		/** This parses a variable of the forms: varname(+3),
-		 * varname(3), varname, varname(-3), varname(0), varname(+0),
-		 * varname(-0). */
-		virtual void parse_variable(const char* in, std::string& out, int& ll) const;
-		/** Registers unique name of endogenous variable. */
-		void register_uniq_endo(const char* name);
-		/** Registers unique name of exogenous variable. */
-		void register_uniq_exo(const char* name);
-		/** Registers unique name of parameter. */
-		void register_uniq_param(const char* name);
-		/** Return true if the name is a given type. */
-		bool is_type(const char* name, atype tp) const;
-		/** Debug print. */
-		void print() const;
-		/** Implement NularyStringConvertor::convert. */
-		std::string convert(int t) const;
-	};
-
-
-	/** This class represents the atom values for dynare, where
-	 * exogenous variables can occur only at time t, and endogenous at
-	 * times t-1, t, and t+1. */
-	class DynareAtomValues : public ogp::AtomValues {
-	protected:
-		/** Reference to the atoms (we suppose that they are only at
-		 * t-1,t,t+1. */
-		const ogp::FineAtoms& atoms;
-		/** De facto reference to the values of parameters. */
-		const ConstVector paramvals;
-		/** De facto reference to the values of endogenous at time t-1. Only
-		 * predetermined and both part. */
-		const ConstVector yym;
-		/** De facto reference to the values of endogenous at time t. Ordering
-		 * given by the atoms. */
-		const ConstVector yy;
-		/** De facto reference to the values of endogenous at time t+1. Only
-		 * both and forward looking part. */
-		const ConstVector yyp;
-		/** De facto reference to the values of exogenous at time t. */
-		const ConstVector xx;
-	public:
-		DynareAtomValues(const ogp::FineAtoms& a, const Vector& pvals, const Vector& ym,
-						 const Vector& y, const Vector& yp, const Vector& x)
-			: atoms(a), paramvals(pvals), yym(ym), yy(y), yyp(yp), xx(x) {}
-		DynareAtomValues(const ogp::FineAtoms& a, const Vector& pvals, const ConstVector& ym,
-						 const Vector& y, const ConstVector& yp, const Vector& x)
-			: atoms(a), paramvals(pvals), yym(ym), yy(y), yyp(yp), xx(x) {}
-		void setValues(ogp::EvalTree& et) const;
-	};
-
-	/** This class represents the atom values at the steady state. It
-	 * makes only appropriate subvector yym and yyp of the y vector,
-	 * makes a vector of zero exogenous variables and uses
-	 * DynareAtomValues with more general interface. */ 
-	class DynareSteadyAtomValues : public ogp::AtomValues {
-	protected:
-		/** Subvector of yy. */
-		const ConstVector yym;
-		/** Subvector of yy. */
-		const ConstVector yyp;
-		/** Vector of zeros for exogenous variables. */
-		Vector xx;
-		/** Atom values using this yym, yyp and xx. */
-		DynareAtomValues av;
-	public:
-		DynareSteadyAtomValues(const ogp::FineAtoms& a, const Vector& pvals, const Vector& y)
-			: yym(y, a.nstat(), a.nys()),
-			  yyp(y, a.nstat()+a.npred(), a.nyss()),
-			  xx(a.nexo()),
-			  av(a, pvals, yym, y, yyp, xx)
-			{xx.zeros();}
-		void setValues(ogp::EvalTree& et) const
-			{av.setValues(et);}
-	};
-
-	class DynareStaticSteadyAtomValues : public ogp::AtomValues {
-	protected:
-		/** Reference to static atoms over which the tree, where the
-		 * values go, is defined. */
-		const ogp::StaticFineAtoms& atoms_static;
-		/** Reference to dynamic atoms for which the class gets input
-		 * data. */
-		const ogp::FineAtoms& atoms;
-		/** De facto reference to input data, this is a vector of
-		 * endogenous variables in internal ordering of the dynamic
-		 * atoms. */
-		ConstVector yy;
-		/** De facto reference to input parameters corresponding to
-		 * ordering defined by the dynamic atoms. */
-		ConstVector paramvals;
-	public:
-		/** Construct the object. */
-		DynareStaticSteadyAtomValues(const ogp::FineAtoms& a, const ogp::StaticFineAtoms& sa,
-									 const Vector& pvals, const Vector& yyy)
-			: atoms_static(sa),
-			  atoms(a),
-			  yy(yyy),
-			  paramvals(pvals) {}
-		/** Set the values to the tree defined over the static atoms. */
-		void setValues(ogp::EvalTree& et) const;
-	};
-
-	/** This class takes a vector of endogenous variables and a
-	 * substitution map. It supposes that variables at the right hand
-	 * sides of the substitutions are set in the endogenous vector. It
-	 * evaluates the substitutions and if the variables corresponding
-	 * to left hand sides are not set in the endogenous vector it sets
-	 * them to calculated values. If a variable is already set, it
-	 * does not override its value. It has no methods, everything is
-	 * done in the constructor. */ 
-	class DynareSteadySubstitutions : public ogp::FormulaEvalLoader {
-	protected:
-		const ogp::FineAtoms& atoms;
-	public:
-		DynareSteadySubstitutions(const ogp::FineAtoms& a, const ogp::OperationTree& tree,
-								  const Tsubstmap& subst,
-								  const Vector& pvals, Vector& yy);
-		void load(int i, double res);
-	protected:
-		Vector& y;
-		vector<const char*> left_hand_sides;
-		vector<int> right_hand_sides;
-	};
-
-	/** This class is a static version of DynareSteadySustitutions. It
-	 * works for static atoms and static tree and substitution map
-	 * over the static tree. It also needs dynamic version of the
-	 * atoms, since it defines ordering of the vectors pvals, and
-	 * yy. */ 
-	class DynareStaticSteadySubstitutions : public ogp::FormulaEvalLoader {
-	protected:
-		const ogp::FineAtoms& atoms;
-		const ogp::StaticFineAtoms& atoms_static;
-	public:
-		DynareStaticSteadySubstitutions(const ogp::FineAtoms& a,
-										const ogp::StaticFineAtoms& sa,
-										const ogp::OperationTree& tree,
-										const Tsubstmap& subst,
-										const Vector& pvals, Vector& yy);
-		void load(int i, double res);
-	protected:
-		Vector& y;
-		vector<const char*> left_hand_sides;
-		vector<int> right_hand_sides;
-	};
+namespace ogdyn
+{
+
+  using std::map;
+  using std::vector;
+
+  /** A definition of a type mapping a string to an integer. Used as
+   * a substitution map, saying what names are substituted for what
+   * expressions represented by tree indices. */
+  typedef map<const char *, int, ogp::ltstr> Tsubstmap;
+
+  class DynareStaticAtoms : public ogp::StaticAtoms
+  {
+  public:
+    DynareStaticAtoms()
+      : StaticAtoms()
+    {
+    }
+    DynareStaticAtoms(const DynareStaticAtoms &a)
+      : StaticAtoms(a)
+    {
+    }
+    virtual ~DynareStaticAtoms()
+    {
+    }
+    /** This registers a unique varname identifier. It throws an
+     * exception if the variable name is duplicate. It checks the
+     * uniqueness and then it calls StaticAtoms::register_name. */
+    void register_name(const char *name);
+  protected:
+    /** This returns a tree index of the given variable, and if
+     * the variable has not been registered, it throws an
+     * exception. */
+    int check_variable(const char *name) const;
+  };
+
+  class DynareDynamicAtoms : public ogp::SAtoms, public ogp::NularyStringConvertor
+  {
+  public:
+    enum atype {endovar, exovar, param};
+  protected:
+    typedef map<const char *, atype, ogp::ltstr> Tatypemap;
+    /** The map assigining a type to each name. */
+    Tatypemap atom_type;
+  public:
+    DynareDynamicAtoms()
+      : ogp::SAtoms()
+    {
+    }
+    DynareDynamicAtoms(const DynareDynamicAtoms &dda);
+    virtual ~DynareDynamicAtoms()
+    {
+    }
+    /** This parses a variable of the forms: varname(+3),
+     * varname(3), varname, varname(-3), varname(0), varname(+0),
+     * varname(-0). */
+    virtual void parse_variable(const char *in, std::string &out, int &ll) const;
+    /** Registers unique name of endogenous variable. */
+    void register_uniq_endo(const char *name);
+    /** Registers unique name of exogenous variable. */
+    void register_uniq_exo(const char *name);
+    /** Registers unique name of parameter. */
+    void register_uniq_param(const char *name);
+    /** Return true if the name is a given type. */
+    bool is_type(const char *name, atype tp) const;
+    /** Debug print. */
+    void print() const;
+    /** Implement NularyStringConvertor::convert. */
+    std::string convert(int t) const;
+  };
+
+  /** This class represents the atom values for dynare, where
+   * exogenous variables can occur only at time t, and endogenous at
+   * times t-1, t, and t+1. */
+  class DynareAtomValues : public ogp::AtomValues
+  {
+  protected:
+    /** Reference to the atoms (we suppose that they are only at
+     * t-1,t,t+1. */
+    const ogp::FineAtoms &atoms;
+    /** De facto reference to the values of parameters. */
+    const ConstVector paramvals;
+    /** De facto reference to the values of endogenous at time t-1. Only
+     * predetermined and both part. */
+    const ConstVector yym;
+    /** De facto reference to the values of endogenous at time t. Ordering
+     * given by the atoms. */
+    const ConstVector yy;
+    /** De facto reference to the values of endogenous at time t+1. Only
+     * both and forward looking part. */
+    const ConstVector yyp;
+    /** De facto reference to the values of exogenous at time t. */
+    const ConstVector xx;
+  public:
+    DynareAtomValues(const ogp::FineAtoms &a, const Vector &pvals, const Vector &ym,
+                     const Vector &y, const Vector &yp, const Vector &x)
+      : atoms(a), paramvals(pvals), yym(ym), yy(y), yyp(yp), xx(x)
+    {
+    }
+    DynareAtomValues(const ogp::FineAtoms &a, const Vector &pvals, const ConstVector &ym,
+                     const Vector &y, const ConstVector &yp, const Vector &x)
+      : atoms(a), paramvals(pvals), yym(ym), yy(y), yyp(yp), xx(x)
+    {
+    }
+    void setValues(ogp::EvalTree &et) const;
+  };
+
+  /** This class represents the atom values at the steady state. It
+   * makes only appropriate subvector yym and yyp of the y vector,
+   * makes a vector of zero exogenous variables and uses
+   * DynareAtomValues with more general interface. */
+  class DynareSteadyAtomValues : public ogp::AtomValues
+  {
+  protected:
+    /** Subvector of yy. */
+    const ConstVector yym;
+    /** Subvector of yy. */
+    const ConstVector yyp;
+    /** Vector of zeros for exogenous variables. */
+    Vector xx;
+    /** Atom values using this yym, yyp and xx. */
+    DynareAtomValues av;
+  public:
+    DynareSteadyAtomValues(const ogp::FineAtoms &a, const Vector &pvals, const Vector &y)
+      : yym(y, a.nstat(), a.nys()),
+        yyp(y, a.nstat()+a.npred(), a.nyss()),
+        xx(a.nexo()),
+        av(a, pvals, yym, y, yyp, xx)
+    {
+      xx.zeros();
+    }
+    void
+    setValues(ogp::EvalTree &et) const
+    {
+      av.setValues(et);
+    }
+  };
+
+  class DynareStaticSteadyAtomValues : public ogp::AtomValues
+  {
+  protected:
+    /** Reference to static atoms over which the tree, where the
+     * values go, is defined. */
+    const ogp::StaticFineAtoms &atoms_static;
+    /** Reference to dynamic atoms for which the class gets input
+     * data. */
+    const ogp::FineAtoms &atoms;
+    /** De facto reference to input data, this is a vector of
+     * endogenous variables in internal ordering of the dynamic
+     * atoms. */
+    ConstVector yy;
+    /** De facto reference to input parameters corresponding to
+     * ordering defined by the dynamic atoms. */
+    ConstVector paramvals;
+  public:
+    /** Construct the object. */
+    DynareStaticSteadyAtomValues(const ogp::FineAtoms &a, const ogp::StaticFineAtoms &sa,
+                                 const Vector &pvals, const Vector &yyy)
+      : atoms_static(sa),
+        atoms(a),
+        yy(yyy),
+        paramvals(pvals)
+    {
+    }
+    /** Set the values to the tree defined over the static atoms. */
+    void setValues(ogp::EvalTree &et) const;
+  };
+
+  /** This class takes a vector of endogenous variables and a
+   * substitution map. It supposes that variables at the right hand
+   * sides of the substitutions are set in the endogenous vector. It
+   * evaluates the substitutions and if the variables corresponding
+   * to left hand sides are not set in the endogenous vector it sets
+   * them to calculated values. If a variable is already set, it
+   * does not override its value. It has no methods, everything is
+   * done in the constructor. */
+  class DynareSteadySubstitutions : public ogp::FormulaEvalLoader
+  {
+  protected:
+    const ogp::FineAtoms &atoms;
+  public:
+    DynareSteadySubstitutions(const ogp::FineAtoms &a, const ogp::OperationTree &tree,
+                              const Tsubstmap &subst,
+                              const Vector &pvals, Vector &yy);
+    void load(int i, double res);
+  protected:
+    Vector &y;
+    vector<const char *> left_hand_sides;
+    vector<int> right_hand_sides;
+  };
+
+  /** This class is a static version of DynareSteadySustitutions. It
+   * works for static atoms and static tree and substitution map
+   * over the static tree. It also needs dynamic version of the
+   * atoms, since it defines ordering of the vectors pvals, and
+   * yy. */
+  class DynareStaticSteadySubstitutions : public ogp::FormulaEvalLoader
+  {
+  protected:
+    const ogp::FineAtoms &atoms;
+    const ogp::StaticFineAtoms &atoms_static;
+  public:
+    DynareStaticSteadySubstitutions(const ogp::FineAtoms &a,
+                                    const ogp::StaticFineAtoms &sa,
+                                    const ogp::OperationTree &tree,
+                                    const Tsubstmap &subst,
+                                    const Vector &pvals, Vector &yy);
+    void load(int i, double res);
+  protected:
+    Vector &y;
+    vector<const char *> left_hand_sides;
+    vector<int> right_hand_sides;
+  };
 
 };
 
-
 #endif
 
 // Local Variables:
diff --git a/dynare++/src/dynare_exception.h b/dynare++/src/dynare_exception.h
index c91048a3a8a528656a5da1a44eaa460e864ce181..682b661320c96bedb1ec7d0299fc16b65db86423 100644
--- a/dynare++/src/dynare_exception.h
+++ b/dynare++/src/dynare_exception.h
@@ -7,31 +7,39 @@
 
 #include <string>
 
-class DynareException {
-	char* mes;
+class DynareException
+{
+  char *mes;
 public:
-	DynareException(const char* m, const char* fname, int line, int col)
-		{
-			mes = new char[strlen(m) + strlen(fname) + 100];
-			sprintf(mes, "Parse error at %s, line %d, column %d: %s", fname, line, col, m);
-		}
-	DynareException(const char* fname, int line, const std::string& m)
-		{
-			mes = new char[m.size() + strlen(fname) + 50];
-			sprintf(mes, "%s:%d: %s", fname, line, m.c_str());
-		}
-	DynareException(const char* m, int offset)
-		{
-			mes = new char[strlen(m) + 100];
-			sprintf(mes, "Parse error in provided string at offset %d: %s", offset, m);
-		}
-	DynareException(const DynareException& e)
-		: mes(new char[strlen(e.mes)+1])
-		{strcpy(mes, e.mes);}
-	virtual ~DynareException()
-		{delete [] mes;}
-	const char* message() const
-		{return mes;}
+  DynareException(const char *m, const char *fname, int line, int col)
+  {
+    mes = new char[strlen(m) + strlen(fname) + 100];
+    sprintf(mes, "Parse error at %s, line %d, column %d: %s", fname, line, col, m);
+  }
+  DynareException(const char *fname, int line, const std::string &m)
+  {
+    mes = new char[m.size() + strlen(fname) + 50];
+    sprintf(mes, "%s:%d: %s", fname, line, m.c_str());
+  }
+  DynareException(const char *m, int offset)
+  {
+    mes = new char[strlen(m) + 100];
+    sprintf(mes, "Parse error in provided string at offset %d: %s", offset, m);
+  }
+  DynareException(const DynareException &e)
+    : mes(new char[strlen(e.mes)+1])
+  {
+    strcpy(mes, e.mes);
+  }
+  virtual ~DynareException()
+  {
+    delete [] mes;
+  }
+  const char *
+  message() const
+  {
+    return mes;
+  }
 };
 
 #endif
diff --git a/dynare++/src/dynare_model.h b/dynare++/src/dynare_model.h
index 8fb87ce217ae618c104004ed908b4878ff283429..d5c1834467ed68b38538bec0f5873a4beba05701 100644
--- a/dynare++/src/dynare_model.h
+++ b/dynare++/src/dynare_model.h
@@ -15,377 +15,463 @@
 #include <map>
 #include <boost/unordered_set.hpp>
 
-namespace ogdyn {
-	using boost::unordered_set;
-	using std::map;
+namespace ogdyn
+{
+  using boost::unordered_set;
+  using std::map;
 
-	/** This represents an interval in a string by the pair of
-	 * positions (including the first, excluding the second). A
-	 * position is given by the line and the column within the line
-	 * (both starting from 1). */
-	struct PosInterval {
-		int fl;
-		int fc;
-		int ll;
-		int lc;
-		PosInterval() {}
-		PosInterval(int ifl, int ifc, int ill, int ilc)
-			: fl(ifl), fc(ifc), ll(ill), lc(ilc) {}
-		const PosInterval& operator=(const PosInterval& pi)
-			{fl = pi.fl; fc = pi.fc; ll = pi.ll; lc = pi.lc; return *this;}
-		/** This returns the interval beginning and interval length
-		 * within the given string. */
-		void translate(const char* beg, int len, const char*& ibeg, int& ilen) const;
-		/** Debug print. */
-		void print() const
-			{printf("fl=%d fc=%d ll=%d lc=%d\n",fl,fc,ll,lc);}
-	};
+  /** This represents an interval in a string by the pair of
+   * positions (including the first, excluding the second). A
+   * position is given by the line and the column within the line
+   * (both starting from 1). */
+  struct PosInterval
+  {
+    int fl;
+    int fc;
+    int ll;
+    int lc;
+    PosInterval()
+    {
+    }
+    PosInterval(int ifl, int ifc, int ill, int ilc)
+      : fl(ifl), fc(ifc), ll(ill), lc(ilc)
+    {
+    }
+    const PosInterval &
+    operator=(const PosInterval &pi)
+    {
+      fl = pi.fl; fc = pi.fc; ll = pi.ll; lc = pi.lc; return *this;
+    }
+    /** This returns the interval beginning and interval length
+     * within the given string. */
+    void translate(const char *beg, int len, const char * &ibeg, int &ilen) const;
+    /** Debug print. */
+    void
+    print() const
+    {
+      printf("fl=%d fc=%d ll=%d lc=%d\n", fl, fc, ll, lc);
+    }
+  };
 
-	/** This class is basically a GeneralMatrix but is created from
-	 * parsed matrix data. */
-	class ParsedMatrix : public TwoDMatrix {
-	public:
-		/** Construct the object from the parsed data of ogp::MatrixParser. */
-		ParsedMatrix(const ogp::MatrixParser& mp);
-	};
+  /** This class is basically a GeneralMatrix but is created from
+   * parsed matrix data. */
+  class ParsedMatrix : public TwoDMatrix
+  {
+  public:
+    /** Construct the object from the parsed data of ogp::MatrixParser. */
+    ParsedMatrix(const ogp::MatrixParser &mp);
+  };
 
+  class PlannerBuilder;
+  class PlannerInfo;
+  class ForwSubstBuilder;
+  class ForwSubstInfo;
+  class MultInitSS;
+  class ModelSSWriter;
 
-	class PlannerBuilder;
-	class PlannerInfo;
-	class ForwSubstBuilder;
-	class ForwSubstInfo;
-	class MultInitSS;
-	class ModelSSWriter;
+  /** A subclass is responsible for creating param_vals, init_vals,
+   * and vcov_mat. */
+  class DynareModel
+  {
+    friend class PlannerBuilder;
+    friend class ForwSubstBuilder;
+    friend class MultInitSS;
+    friend class ModelSSWriter;
+  protected:
+    /** All atoms for whole model. */
+    DynareDynamicAtoms atoms;
+    /** Parsed model equations. */
+    ogp::FormulaParser eqs;
+    /** Order of approximation. */
+    int order;
+    /** A vector of parameters values created by a subclass. It
+     * is stored with natural ordering (outer) of the parameters
+     * given by atoms. */
+    Vector *param_vals;
+    /** A vector of initial values created by a subclass. It is
+     * stored with internal ordering given by atoms. */
+    Vector *init_vals;
+    /** A matrix for vcov. It is created by a subclass. */
+    TwoDMatrix *vcov_mat;
+    /** Tree index of the planner objective. If there was no
+     * planner objective keyword, the value is set to -1. */
+    int t_plobjective;
+    /** Tree index of the planner discount. If there was no
+     * planner discount keyword, the value is set to -1. */
+    int t_pldiscount;
+    /** Pointer to PlannerBuilder, which is created only if the
+     * planner's FOC are added to the model. */
+    PlannerBuilder *pbuilder;
+    /** Pointer to an object which builds auxiliary variables and
+     * equations to rewrite a model containing multiple leads to
+     * an equivalent model having only +1 leads. */
+    ForwSubstBuilder *fbuilder;
+    /** Pointer to AtomSubstitutions which are created when the
+     * atoms are being substituted because of multiple lags
+     * etc. It uses also an old copy of atoms, which is
+     * created. */
+    ogp::AtomSubstitutions *atom_substs;
+    /** Pointer to a copy of original atoms before substitutions
+     * took place. */
+    ogp::SAtoms *old_atoms;
+  public:
+    /** Initializes the object to an empty state. */
+    DynareModel();
+    /** Construct a new deep copy. */
+    DynareModel(const DynareModel &dm);
+    virtual
+    ~DynareModel();
+    virtual DynareModel *clone() const = 0;
+    const DynareDynamicAtoms &
+    getAtoms() const
+    {
+      return atoms;
+    }
+    const ogp::FormulaParser &
+    getParser() const
+    {
+      return eqs;
+    }
+    int
+    getOrder() const
+    {
+      return order;
+    }
+    /** Return the vector of parameter values. */
+    const Vector &
+    getParams() const
+    {
+      return *param_vals;
+    }
+    Vector &
+    getParams()
+    {
+      return *param_vals;
+    }
+    /** Return the vector of initial values of endo variables. */
+    const Vector &
+    getInit() const
+    {
+      return *init_vals;
+    }
+    Vector &
+    getInit()
+    {
+      return *init_vals;
+    }
+    /** Return the vcov matrix. */
+    const TwoDMatrix &
+    getVcov() const
+    {
+      return *vcov_mat;
+    }
+    TwoDMatrix &
+    getVcov()
+    {
+      return *vcov_mat;
+    }
+    /** Return planner info. */
+    const PlannerInfo *get_planner_info() const;
+    /** Return forward substitutions info. */
+    const ForwSubstInfo *get_forw_subst_info() const;
+    /** Return substitutions info. */
+    const ogp::SubstInfo *get_subst_info() const;
+    /** This sets initial values given in outer ordering. */
+    void setInitOuter(const Vector &x);
+    /** This returns true if the given term is a function of
+     * hardwired constants, numerical constants and parameters. */
+    bool is_constant_term(int t) const;
+    /** Debug print. */
+    void print() const;
+    /** Dump the model to the output stream. This includes
+     * variable declarations, parameter values, model code,
+     * initval, vcov and order. */
+    void dump_model(std::ostream &os) const;
+  protected:
+    /** Adds a name of endogenous, exogenous or a parameter. The
+     * sort is governed by the flag. See dynglob.y for values of
+     * the flag. This is used by a subclass when declaring the
+     * names. */
+    void add_name(const char *name, int flag);
+    /** This checks the model consistency. Thus includes: number
+     * of endo variables and number of equations, min and max lag
+     * of endogenous variables and occurrrences of exogenous
+     * variables. It throws an exception, if there is a problem. */
+    void check_model() const;
+    /** This shifts the given variable identified by the tree
+     * index in time. So if the given tree index represents a(+3)
+     * and the tshift is -4, the method returns tree index of the
+     * a(-1). If a(-1) doesn't exist, it is added to the tree. If
+     * it exists, its tree index is returned. If the tree index
+     * doesn't correspond to an endogenous nor exogenous variable,
+     * an exception is thrown. */
+    int variable_shift(int t, int tshift);
+    /** For the given set of atoms identified by tree indices and
+     * given time shift, this method returns a map mapping each
+     * variable in the given set to its time shifted variable. The
+     * map is passed through the reference and is cleared in the
+     * beginning. */
+    void variable_shift_map(const unordered_set<int> &a_set, int tshift,
+                            map<int, int> &s_map);
+    /** This returns maximum lead and minimum lag of an endogenous
+     * or exogenous variable in the given term. If there are no
+     * endo or exo variables, than it returns the least integer as
+     * max lead and the greatest integer as min lag. */
+    void termspan(int t, int &mlead, int &mlag) const;
+    /** This function returns a set of non-linear subterms of the
+     * given term, these are terms whose linear combination
+     * constitutes the given term. */
+    unordered_set<int> get_nonlinear_subterms(int t) const;
+    /** This method assigns already used tree index of some term
+     * to the not-yet used atom name with the given lead/lag. In
+     * this way, all occurrences of term t are substituted with
+     * the atom name(ll). The method handles also rewriting
+     * operation tree including derivatives of the term t. */
+    void substitute_atom_for_term(const char *name, int ll, int t);
+    /** This performs a final job after the model is parsed. It
+     * creates the PlannerBuilder object if the planner's FOC are
+     * needed, then it creates ForwSubstBuilder handling multiple
+     * leads and finally it creates the substitution object saving
+     * old atoms and performs the substitutions. */
+    void final_job();
+  };
 
-	/** A subclass is responsible for creating param_vals, init_vals,
-	 * and vcov_mat. */
-	class DynareModel {
-		friend class PlannerBuilder;
-		friend class ForwSubstBuilder;
-		friend class MultInitSS;
-		friend class ModelSSWriter;
-	protected:
-		/** All atoms for whole model. */
-		DynareDynamicAtoms atoms;
-		/** Parsed model equations. */
-		ogp::FormulaParser eqs;
-		/** Order of approximation. */
-		int order;
-		/** A vector of parameters values created by a subclass. It
-		 * is stored with natural ordering (outer) of the parameters
-		 * given by atoms. */
-		Vector* param_vals;
-		/** A vector of initial values created by a subclass. It is
-		 * stored with internal ordering given by atoms. */
-		Vector* init_vals;
-		/** A matrix for vcov. It is created by a subclass. */
-		TwoDMatrix* vcov_mat;
-		/** Tree index of the planner objective. If there was no
-		 * planner objective keyword, the value is set to -1. */
-		int t_plobjective;
-		/** Tree index of the planner discount. If there was no
-		 * planner discount keyword, the value is set to -1. */
-		int t_pldiscount;
-		/** Pointer to PlannerBuilder, which is created only if the
-		 * planner's FOC are added to the model. */
-		PlannerBuilder* pbuilder;
-		/** Pointer to an object which builds auxiliary variables and
-		 * equations to rewrite a model containing multiple leads to
-		 * an equivalent model having only +1 leads. */
-		ForwSubstBuilder* fbuilder;
-		/** Pointer to AtomSubstitutions which are created when the
-		 * atoms are being substituted because of multiple lags
-		 * etc. It uses also an old copy of atoms, which is
-		 * created. */
-		ogp::AtomSubstitutions* atom_substs;
-		/** Pointer to a copy of original atoms before substitutions
-		 * took place. */
-		ogp::SAtoms* old_atoms;
-	public:
-		/** Initializes the object to an empty state. */
-		DynareModel();
-		/** Construct a new deep copy. */
-		DynareModel(const DynareModel& dm);
-		virtual ~DynareModel();		
-		virtual DynareModel* clone() const = 0;
-		const DynareDynamicAtoms& getAtoms() const
-			{return atoms;}
-		const ogp::FormulaParser& getParser() const
-			{return eqs;}
-		int getOrder() const
-			{return order;}
-		/** Return the vector of parameter values. */
-		const Vector& getParams() const
-			{return *param_vals;}
-		Vector& getParams()
-			{return *param_vals;}
-		/** Return the vector of initial values of endo variables. */
-		const Vector& getInit() const
-			{return *init_vals;} 
-		Vector& getInit()
-			{return *init_vals;}
-		/** Return the vcov matrix. */
-		const TwoDMatrix& getVcov() const
-			{return *vcov_mat;}
-		TwoDMatrix& getVcov()
-			{return *vcov_mat;}
-		/** Return planner info. */
-		const PlannerInfo* get_planner_info() const;
-		/** Return forward substitutions info. */
-		const ForwSubstInfo* get_forw_subst_info() const;
-		/** Return substitutions info. */
-		const ogp::SubstInfo* get_subst_info() const;
-		/** This sets initial values given in outer ordering. */
-		void setInitOuter(const Vector& x);
-		/** This returns true if the given term is a function of
-		 * hardwired constants, numerical constants and parameters. */
-		bool is_constant_term(int t) const;
-		/** Debug print. */
-		void print() const;
-		/** Dump the model to the output stream. This includes
-		 * variable declarations, parameter values, model code,
-		 * initval, vcov and order. */
-		void dump_model(std::ostream& os) const;
-	protected:
-		/** Adds a name of endogenous, exogenous or a parameter. The
-		 * sort is governed by the flag. See dynglob.y for values of
-		 * the flag. This is used by a subclass when declaring the
-		 * names. */
-		void add_name(const char* name, int flag);
-		/** This checks the model consistency. Thus includes: number
-		 * of endo variables and number of equations, min and max lag
-		 * of endogenous variables and occurrrences of exogenous
-		 * variables. It throws an exception, if there is a problem. */
-		void check_model() const;
-		/** This shifts the given variable identified by the tree
-		 * index in time. So if the given tree index represents a(+3)
-		 * and the tshift is -4, the method returns tree index of the
-		 * a(-1). If a(-1) doesn't exist, it is added to the tree. If
-		 * it exists, its tree index is returned. If the tree index
-		 * doesn't correspond to an endogenous nor exogenous variable,
-		 * an exception is thrown. */
-		int variable_shift(int t, int tshift);
-		/** For the given set of atoms identified by tree indices and
-		 * given time shift, this method returns a map mapping each
-		 * variable in the given set to its time shifted variable. The
-		 * map is passed through the reference and is cleared in the
-		 * beginning. */
-		void variable_shift_map(const unordered_set<int>& a_set, int tshift,
-								map<int,int>& s_map);
-		/** This returns maximum lead and minimum lag of an endogenous
-		 * or exogenous variable in the given term. If there are no
-		 * endo or exo variables, than it returns the least integer as
-		 * max lead and the greatest integer as min lag. */ 
-		void termspan(int t, int& mlead, int& mlag) const;
-		/** This function returns a set of non-linear subterms of the
-		 * given term, these are terms whose linear combination
-		 * constitutes the given term. */
-		unordered_set<int> get_nonlinear_subterms(int t) const;
-		/** This method assigns already used tree index of some term
-		 * to the not-yet used atom name with the given lead/lag. In
-		 * this way, all occurrences of term t are substituted with
-		 * the atom name(ll). The method handles also rewriting
-		 * operation tree including derivatives of the term t. */
-		void substitute_atom_for_term(const char* name, int ll, int t);
-		/** This performs a final job after the model is parsed. It
-		 * creates the PlannerBuilder object if the planner's FOC are
-		 * needed, then it creates ForwSubstBuilder handling multiple
-		 * leads and finally it creates the substitution object saving
-		 * old atoms and performs the substitutions. */
-		void final_job();
-	};
+  /** This class constructs DynareModel from dynare++ model file. It
+   * parses variable declarations, model equations, parameter
+   * assignments, initval assignments, vcov matrix and order of
+   * approximation. */
+  class DynareParser : public DynareModel
+  {
+  protected:
+    /** Static atoms for parameter assignments. */
+    DynareStaticAtoms pa_atoms;
+    /** Assignments for the parameters. */
+    ogp::AtomAssignings paramset;
+    /** Static atoms for initval assignments. */
+    DynareStaticAtoms ia_atoms;
+    /** Assignments for the initval. */
+    ogp::AtomAssignings initval;
+    /** Matrix parser for vcov. */
+    ogp::MatrixParser vcov;
+  public:
+    /** This, in fact, creates DynareModel from the given string
+     * of the given length corresponding to the Dynare++ model
+     * file. If the given ord is not -1, then it overrides setting
+     * in the model file. */
+    DynareParser(const char *str, int len, int ord);
+    DynareParser(const DynareParser &p);
+    virtual
+    ~DynareParser();
+    DynareModel *
+    clone() const
+    {
+      return new DynareParser(*this);
+    }
+    /** Adds a name of endogenous, exogenous or a parameter. This
+     * addss the name to the parent class DynareModel and also
+     * registers the name to either paramset, or initval. */
+    void add_name(const char *name, int flag);
+    /** Sets position of the model section. Called from
+     * dynglob.y. */
+    void
+    set_model_pos(int off1, int off2)
+    {
+      model_beg = off1; model_end = off2;
+    }
+    /** Sets position of the section setting parameters. Called
+     * from dynglob.y. */
+    void
+    set_paramset_pos(int off1, int off2)
+    {
+      paramset_beg = off1; paramset_end = off2;
+    }
+    /** Sets position of the initval section. Called from
+     * dynglob.y. */
+    void
+    set_initval_pos(int off1, int off2)
+    {
+      initval_beg = off1; initval_end = off2;
+    }
+    /** Sets position of the vcov section. Called from
+     * dynglob.y. */
+    void
+    set_vcov_pos(int off1, int off2)
+    {
+      vcov_beg = off1; vcov_end = off2;
+    }
+    /** Parser the given string as integer and set to as the
+     * order. */
+    void
+    set_order_pos(int off1, int off2)
+    {
+      order_beg = off1; order_end = off2;
+    }
+    /** Sets position of the planner_objective section. Called
+     * from dynglob.y. */
+    void
+    set_pl_objective_pos(int off1, int off2)
+    {
+      plobjective_beg = off1; plobjective_end = off2;
+    }
+    /** Sets position of the planner_discount section. Called from
+     * dynglob.y. */
+    void
+    set_pl_discount_pos(int off1, int off2)
+    {
+      pldiscount_beg = off1; pldiscount_end = off2;
+    }
+    /** Processes a syntax error from bison. */
+    void error(const char *mes);
+    /** Debug print. */
+    void print() const;
+  protected:
+    void parse_glob(int length, const char *stream);
+    int parse_order(int length, const char *stream);
+    int parse_pldiscount(int length, const char *stream);
+    /** Evaluate paramset assignings and set param_vals. */
+    void calc_params();
+    /** Evaluate initval assignings and set init_vals. */
+    void calc_init();
+    /** Do the final job. This includes building the planner
+     * problem (if any) and substituting for multiple lags, and
+     * one period leads of exogenous variables, and calculating
+     * initial guess of lagrange multipliers in the social planner
+     * problem. Precondtion: everything parsed and calculated
+     * parameters, postcondition: calculated initvals vector and
+     * parsing_finished for expanded vectors. */
+    void final_job();
+  private:
+    int model_beg, model_end;
+    int paramset_beg, paramset_end;
+    int initval_beg, initval_end;
+    int vcov_beg, vcov_end;
+    int order_beg, order_end;
+    int plobjective_beg, plobjective_end;
+    int pldiscount_beg, pldiscount_end;
+  };
 
-	/** This class constructs DynareModel from dynare++ model file. It
-	 * parses variable declarations, model equations, parameter
-	 * assignments, initval assignments, vcov matrix and order of
-	 * approximation. */
-	class DynareParser : public DynareModel {
-	protected:
-		/** Static atoms for parameter assignments. */
-		DynareStaticAtoms pa_atoms;
-		/** Assignments for the parameters. */
-		ogp::AtomAssignings paramset;
-		/** Static atoms for initval assignments. */
-		DynareStaticAtoms ia_atoms;
-		/** Assignments for the initval. */
-		ogp::AtomAssignings initval;
-		/** Matrix parser for vcov. */
-		ogp::MatrixParser vcov;
-	public:
-		/** This, in fact, creates DynareModel from the given string
-		 * of the given length corresponding to the Dynare++ model
-		 * file. If the given ord is not -1, then it overrides setting
-		 * in the model file. */
-		DynareParser(const char* str, int len, int ord);
-		DynareParser(const DynareParser& p);
-		virtual ~DynareParser();
-		DynareModel* clone() const
-			{return new DynareParser(*this);}
-		/** Adds a name of endogenous, exogenous or a parameter. This
-		 * addss the name to the parent class DynareModel and also
-		 * registers the name to either paramset, or initval. */
-		void add_name(const char* name, int flag);
-		/** Sets position of the model section. Called from
-		 * dynglob.y. */
-		void set_model_pos(int off1, int off2)
-			{model_beg = off1; model_end = off2;}
-		/** Sets position of the section setting parameters. Called
-		 * from dynglob.y. */
-		void set_paramset_pos(int off1, int off2)
-			{paramset_beg = off1; paramset_end = off2;}
-		/** Sets position of the initval section. Called from
-		 * dynglob.y. */
-		void set_initval_pos(int off1, int off2)
-			{initval_beg = off1; initval_end = off2;}
-		/** Sets position of the vcov section. Called from
-		 * dynglob.y. */
-		void set_vcov_pos(int off1, int off2)
-			{vcov_beg = off1; vcov_end = off2;}
-		/** Parser the given string as integer and set to as the
-		 * order. */
-		void set_order_pos(int off1, int off2)
-			{order_beg = off1; order_end = off2;}
-		/** Sets position of the planner_objective section. Called
-		 * from dynglob.y. */
-		void set_pl_objective_pos(int off1, int off2)
-			{plobjective_beg = off1; plobjective_end = off2;}
-		/** Sets position of the planner_discount section. Called from
-		 * dynglob.y. */
-		void set_pl_discount_pos(int off1, int off2)
-			{pldiscount_beg = off1; pldiscount_end = off2;}		
-		/** Processes a syntax error from bison. */
-		void error(const char* mes);
-		/** Debug print. */
-		void print() const;
-	protected:
-		void parse_glob(int length, const char* stream);
-		int parse_order(int length, const char* stream);
-		int parse_pldiscount(int length, const char* stream);
-		/** Evaluate paramset assignings and set param_vals. */
-		void calc_params();
-		/** Evaluate initval assignings and set init_vals. */
-		void calc_init();
-		/** Do the final job. This includes building the planner
-		 * problem (if any) and substituting for multiple lags, and
-		 * one period leads of exogenous variables, and calculating
-		 * initial guess of lagrange multipliers in the social planner
-		 * problem. Precondtion: everything parsed and calculated
-		 * parameters, postcondition: calculated initvals vector and
-		 * parsing_finished for expanded vectors. */
-		void final_job();
-	private:
-		int model_beg, model_end;
-		int paramset_beg, paramset_end;
-		int initval_beg, initval_end;
-		int vcov_beg, vcov_end;
-		int order_beg, order_end;
-		int plobjective_beg, plobjective_end;
-		int pldiscount_beg, pldiscount_end;
-	};
+  /** Semiparsed model. The equations are given by a string,
+   * everything other by C/C++ objects. The initial values are set
+   * manually after the creation of this object. This implies that
+   * no automatic substitutions cannot be done here, which in turn
+   * implies that we cannot do here a social planner nor substitutions
+   * of multiple lags. */
+  class DynareSPModel : public DynareModel
+  {
+  public:
+    DynareSPModel(const char **endo, int num_endo,
+                  const char **exo, int num_exo,
+                  const char **par, int num_par,
+                  const char *equations, int len, int ord);
+    DynareSPModel(const DynareSPModel &dm)
+      : DynareModel(dm)
+    {
+    }
+    ~DynareSPModel()
+    {
+    }
+    virtual DynareModel *
+    clone() const
+    {
+      return new DynareSPModel(*this);
+    }
+  };
 
-	/** Semiparsed model. The equations are given by a string,
-	 * everything other by C/C++ objects. The initial values are set
-	 * manually after the creation of this object. This implies that
-	 * no automatic substitutions cannot be done here, which in turn
-	 * implies that we cannot do here a social planner nor substitutions
-	 * of multiple lags. */
-	class DynareSPModel : public DynareModel {
-	public:
-		DynareSPModel(const char** endo, int num_endo,
-					  const char** exo, int num_exo,
-					  const char** par, int num_par,
-					  const char* equations, int len, int ord);
-		DynareSPModel(const DynareSPModel& dm)
-			: DynareModel(dm) {}
-		~DynareSPModel() {}
-		virtual DynareModel* clone() const
-			{return new DynareSPModel(*this);}
-	};
+  /** This class implements a selector of operations which correspond
+   * to non-linear functions. This inherits from ogp::opselector and
+   * is used to calculate non-linear subterms in
+   * DynareModel::get_nonlinear_subterms(). */
+  class NLSelector : public ogp::opselector
+  {
+  private:
+    const DynareModel &model;
+  public:
+    NLSelector(const DynareModel &m) : model(m)
+    {
+    }
+    bool operator()(int t) const;
+  };
 
-	/** This class implements a selector of operations which correspond
-	 * to non-linear functions. This inherits from ogp::opselector and
-	 * is used to calculate non-linear subterms in
-	 * DynareModel::get_nonlinear_subterms(). */
-	class NLSelector : public ogp::opselector {
-	private:
-		const DynareModel& model;
-	public:
-		NLSelector(const DynareModel& m) : model(m) {}
-		bool operator()(int t) const;
-	};
+  /** This class writes a mathematical code evaluating the system of
+   * equations and the first derivatives at zero shocks and at the
+   * given (static) state. Static means that lags and leads are
+   * ignored. */
+  class ModelSSWriter : public ogp::DefaultOperationFormatter
+  {
+  protected:
+    const DynareModel &model;
+  public:
+    ModelSSWriter(const DynareModel &m)
+      : DefaultOperationFormatter(m.eqs.getTree()),
+        model(m)
+    {
+    }
+    /** This writes the evaluation of the system. It calls pure
+     * virtual methods for writing a preamble, then assignment of
+     * atoms, and then assignment for resulting object. These are
+     * language dependent and are implemented in the subclass. */
+    void write_der0(FILE *fd);
+    /** This writes the evaluation of the first order derivative of
+        the system. It calls pure virtual methods for writing a
+        preamble, assignment, and assignemnt of the resulting
+        objects. */
+    void write_der1(FILE *fd);
+  protected:
+    virtual void write_der0_preamble(FILE *fd) const = 0;
+    virtual void write_der1_preamble(FILE *fd) const = 0;
+    virtual void write_atom_assignment(FILE *fd) const = 0;
+    virtual void write_der0_assignment(FILE *fd) const = 0;
+    virtual void write_der1_assignment(FILE *fd) const = 0;
+  };
 
-	/** This class writes a mathematical code evaluating the system of
-	 * equations and the first derivatives at zero shocks and at the
-	 * given (static) state. Static means that lags and leads are
-	 * ignored. */
-	class ModelSSWriter : public ogp::DefaultOperationFormatter {
-	protected:
-		const DynareModel& model;
-	public:
-		ModelSSWriter(const DynareModel& m)
-			: DefaultOperationFormatter(m.eqs.getTree()),
-			  model(m) {}
-		/** This writes the evaluation of the system. It calls pure
-		 * virtual methods for writing a preamble, then assignment of
-		 * atoms, and then assignment for resulting object. These are
-		 * language dependent and are implemented in the subclass. */
-		void write_der0(FILE* fd);
-		/** This writes the evaluation of the first order derivative of
-		the system. It calls pure virtual methods for writing a
-		preamble, assignment, and assignemnt of the resulting
-		objects. */
-		void write_der1(FILE* fd);
-	protected:
-		virtual void write_der0_preamble(FILE* fd) const =0;
-		virtual void write_der1_preamble(FILE* fd) const =0;
-		virtual void write_atom_assignment(FILE* fd) const =0;
-		virtual void write_der0_assignment(FILE* fd) const =0;
-		virtual void write_der1_assignment(FILE* fd) const =0;
-	};
+  class MatlabSSWriter : public ModelSSWriter
+  {
+  protected:
+    /** Identifier used in function names. */
+    char *id;
+  public:
+    MatlabSSWriter(const DynareModel &dm, const char *idd);
+    virtual ~MatlabSSWriter()
+    {
+      delete [] id;
+    }
+  protected:
+    // from ModelSSWriter
+    void write_der0_preamble(FILE *fd) const;
+    void write_der1_preamble(FILE *fd) const;
+    /** This writes atom assignments. We have four kinds of atoms
+     * set here: endogenous vars coming from one parameter,
+     * parameter values given by the second parameter, constants,
+     * and the OperationTree::num_constants hardwired constants in
+     * ogp::OperationTree. */
+    void write_atom_assignment(FILE *fd) const;
+    void write_der0_assignment(FILE *fd) const;
+    void write_der1_assignment(FILE *fd) const;
+    /** This prints t10 for t=10. */
+    void format_term(int t, FILE *fd) const;
+    /** This prints a10 for t=10. The atoms a10 are supposed to be
+     * set by write_atom_assignments(). */
+    void format_nulary(int t, FILE *fd) const;
+  private:
+    void write_common1_preamble(FILE *fd) const;
+    void write_common2_preamble(FILE *fd) const;
+  };
 
-
-	class MatlabSSWriter : public ModelSSWriter {
-	protected:
-		/** Identifier used in function names. */
-		char* id;
-	public:
-		MatlabSSWriter(const DynareModel& dm, const char* idd);
-		virtual ~MatlabSSWriter()
-			{delete [] id;}
-	protected:
-		// from ModelSSWriter
-		void write_der0_preamble(FILE* fd) const;
-		void write_der1_preamble(FILE* fd) const;
-		/** This writes atom assignments. We have four kinds of atoms
-		 * set here: endogenous vars coming from one parameter,
-		 * parameter values given by the second parameter, constants,
-		 * and the OperationTree::num_constants hardwired constants in
-		 * ogp::OperationTree. */
-		void write_atom_assignment(FILE* fd) const;
-		void write_der0_assignment(FILE* fd) const;
-		void write_der1_assignment(FILE* fd) const;
-		/** This prints t10 for t=10. */
-		void format_term(int t, FILE* fd) const;
-		/** This prints a10 for t=10. The atoms a10 are supposed to be
-		 * set by write_atom_assignments(). */
-		void format_nulary(int t, FILE* fd) const;
-	private:
-		void write_common1_preamble(FILE* fd) const;
-		void write_common2_preamble(FILE* fd) const;
-	};
-
-	/** This class implements OperationFormatter for debugging
-	 * purposes. It renders atoms in a more friendly way than the
-	 * ogp::DefaulOperationFormatter. */
-	class DebugOperationFormatter : public ogp::DefaultOperationFormatter {
-	protected:
-		const DynareModel& model;
-	public:
-		DebugOperationFormatter(const DynareModel& m)
-			: DefaultOperationFormatter(m.getParser().getTree()),
-			  model(m) {}
-		void format_nulary(int t, FILE* fd) const;
-	};
+  /** This class implements OperationFormatter for debugging
+   * purposes. It renders atoms in a more friendly way than the
+   * ogp::DefaulOperationFormatter. */
+  class DebugOperationFormatter : public ogp::DefaultOperationFormatter
+  {
+  protected:
+    const DynareModel &model;
+  public:
+    DebugOperationFormatter(const DynareModel &m)
+      : DefaultOperationFormatter(m.getParser().getTree()),
+        model(m)
+    {
+    }
+    void format_nulary(int t, FILE *fd) const;
+  };
 };
 
 #endif
diff --git a/dynare++/src/dynare_params.h b/dynare++/src/dynare_params.h
index 594c35ea278a514c0444aea2e08c62a2cd083198..113e48fb0dd886bc40cb551b5f97dee433da4002 100644
--- a/dynare++/src/dynare_params.h
+++ b/dynare++/src/dynare_params.h
@@ -3,71 +3,87 @@
 // Copyright 2004, Ondra Kamenik
 
 /*
-along shocks: m    mult    max_evals
-ellipse:      m    mult    max_evals  (10*m) (0.5*mult)
-simul:        m            max_evals  (10*m)
+  along shocks: m    mult    max_evals
+  ellipse:      m    mult    max_evals  (10*m) (0.5*mult)
+  simul:        m            max_evals  (10*m)
 
---check-scale 2.0 --check-evals 1000 --check-num 10 --check PES
- */
+  --check-scale 2.0 --check-evals 1000 --check-num 10 --check PES
+*/
 
 #include <vector>
 #include <string>
 
-struct DynareParams {
-	const char* modname;
-	std::string basename;
-	int num_per;
-	int num_burn;
-	int num_sim;
-	int num_rtper;
-	int num_rtsim;
-	int num_condper;
-	int num_condsim;
-	int num_threads;
-	int num_steps;
-	const char* prefix;
-	int seed;
-	int order;
-	/** Tolerance used for steady state calcs. */
-	double ss_tol;
-	bool check_along_path;
-	bool check_along_shocks;
-	bool check_on_ellipse;
-	int check_evals;
-	int check_num;
-	double check_scale;
-	/** Flag for doing IRFs even if the irf_list is empty. */
-	bool do_irfs_all;
-	/** List of shocks for which IRF will be calculated. */
-	std::vector<const char*> irf_list;
-	bool do_centralize;
-	double qz_criterium;
-	bool help;
-	bool version;
-	DynareParams(int argc, char** argv);
-	void printHelp() const;
-	int getCheckShockPoints() const
-		{return check_num;}
-	double getCheckShockScale() const
-		{return check_scale;}
-	int getCheckEllipsePoints() const
-		{return 10*check_num;}
-	double getCheckEllipseScale() const
-		{return 0.5*check_scale;}
-	int getCheckPathPoints() const
-		{return 10*check_num;}
+struct DynareParams
+{
+  const char *modname;
+  std::string basename;
+  int num_per;
+  int num_burn;
+  int num_sim;
+  int num_rtper;
+  int num_rtsim;
+  int num_condper;
+  int num_condsim;
+  int num_threads;
+  int num_steps;
+  const char *prefix;
+  int seed;
+  int order;
+  /** Tolerance used for steady state calcs. */
+  double ss_tol;
+  bool check_along_path;
+  bool check_along_shocks;
+  bool check_on_ellipse;
+  int check_evals;
+  int check_num;
+  double check_scale;
+  /** Flag for doing IRFs even if the irf_list is empty. */
+  bool do_irfs_all;
+  /** List of shocks for which IRF will be calculated. */
+  std::vector<const char *> irf_list;
+  bool do_centralize;
+  double qz_criterium;
+  bool help;
+  bool version;
+  DynareParams(int argc, char **argv);
+  void printHelp() const;
+  int
+  getCheckShockPoints() const
+  {
+    return check_num;
+  }
+  double
+  getCheckShockScale() const
+  {
+    return check_scale;
+  }
+  int
+  getCheckEllipsePoints() const
+  {
+    return 10*check_num;
+  }
+  double
+  getCheckEllipseScale() const
+  {
+    return 0.5*check_scale;
+  }
+  int
+  getCheckPathPoints() const
+  {
+    return 10*check_num;
+  }
 private:
-	enum {opt_per, opt_burn, opt_sim, opt_rtper, opt_rtsim, opt_condper, opt_condsim,
-		  opt_prefix, opt_threads,
-		  opt_steps, opt_seed, opt_order, opt_ss_tol, opt_check,
-		  opt_check_along_path, opt_check_along_shocks, opt_check_on_ellipse,
-		  opt_check_evals, opt_check_scale, opt_check_num, opt_noirfs, opt_irfs,
-                  opt_help, opt_version, opt_centralize, opt_no_centralize, opt_qz_criterium};
-	void processCheckFlags(const char* flags);
-	/** This gathers strings from argv[optind] and on not starting
-	 * with '-' to the irf_list. It stops one item before the end,
-	 * since this is the model file. */  
-	void processIRFList(int argc, char** argv);
+  enum {opt_per, opt_burn, opt_sim, opt_rtper, opt_rtsim, opt_condper, opt_condsim,
+        opt_prefix, opt_threads,
+        opt_steps, opt_seed, opt_order, opt_ss_tol, opt_check,
+        opt_check_along_path, opt_check_along_shocks, opt_check_on_ellipse,
+        opt_check_evals, opt_check_scale, opt_check_num, opt_noirfs, opt_irfs,
+        opt_help, opt_version, opt_centralize, opt_no_centralize, opt_qz_criterium};
+  void processCheckFlags(const char *flags);
+  /** This gathers strings from argv[optind] and on not starting
+   * with '-' to the irf_list. It stops one item before the end,
+   * since this is the model file. */
+  void processIRFList(int argc, char **argv);
 };
 
 // Local Variables:
diff --git a/dynare++/src/forw_subst_builder.h b/dynare++/src/forw_subst_builder.h
index 7f703092d8d7bb6d9aa7749ea7d90f79e7000be6..9a51c2cbce1f114aac6ea756ea670dec2c58e091 100644
--- a/dynare++/src/forw_subst_builder.h
+++ b/dynare++/src/forw_subst_builder.h
@@ -5,75 +5,85 @@
 #ifndef FORW_SUBST_BUILDER_H
 #define FORW_SUBST_BUILDER_H
 
-
 #include "dynare_model.h"
 
-namespace ogdyn {
+namespace ogdyn
+{
 
-	/** This struct encapsulates information about the process of
-	 * forward substitutions. */
-	struct ForwSubstInfo {
-		int num_affected_equations;
-		int num_subst_terms;
-		int num_aux_variables;
-		int num_new_terms;
-		ForwSubstInfo()
-			: num_affected_equations(0),
-			  num_subst_terms(0),
-			  num_aux_variables(0),
-			  num_new_terms(0) {}
-	};
+  /** This struct encapsulates information about the process of
+   * forward substitutions. */
+  struct ForwSubstInfo
+  {
+    int num_affected_equations;
+    int num_subst_terms;
+    int num_aux_variables;
+    int num_new_terms;
+    ForwSubstInfo()
+      : num_affected_equations(0),
+        num_subst_terms(0),
+        num_aux_variables(0),
+        num_new_terms(0)
+    {
+    }
+  };
 
-	class ForwSubstBuilder {
-		typedef map<int, const char*> Ttermauxmap;
-	protected:
-		/** Reference to the model, to which we will add equations and
-		 * change some equations. */
-		DynareModel& model;
-		/** A map mapping new auxiliary variables to the terms in the
-		 * tree in the DynareModel. */
-		Tsubstmap aux_map;
-		/** Information about the substitutions. */
-		ForwSubstInfo info;
-	public:
-		/** Do all the jobs needed. This scans all equations in the
-		 * model, and for equations containing forward looking
-		 * variables greater than 1 lead, it makes corresponding
-		 * substitutions. Basically, it breaks each equation to its
-		 * non-linear components and creates substitutions for these
-		 * components, not for whole equation. This is because the
-		 * expectation operator can go through the linear part of the
-		 * function. This will save us many occurrences of other
-		 * variables involved in the equation. */
-		ForwSubstBuilder(DynareModel& m);
-		/** Copy constructor with a new instance of the model. */
-		ForwSubstBuilder(const ForwSubstBuilder& b, DynareModel& m);
-		/** Return the auxiliary variable mapping. */
-		const Tsubstmap& get_aux_map() const
-			{return aux_map;}
-		/** Return the information. */
-		const ForwSubstInfo& get_info() const
-			{return info;}
-	private:
-		ForwSubstBuilder(const ForwSubstBuilder& b);
-		/** This method takes a nonlinear term t, and if it has leads
-		 * of greater than 1, then it substitutes the term for the new
-		 * variable (or string of variables). Note that the
-		 * substitution is done by DynamicAtoms::assign_variable. This
-		 * means that the substitution is made for all other
-		 * ocurrences of t in the model. So there is no need of
-		 * tracking already substituted terms. The other two
-		 * parameters are just for identification of the new auxiliary
-		 * variables. When called from the constructor, i is an
-		 * equation number, j is an order of the non-linear term in
-		 * the equation. */
-		void substitute_for_term(int t, int i, int j);
-		/** This is called just at the end of the job. It unassigns
-		 * all nulary terms with a lead greater than 1. */
-		void unassign_gt_1_leads();
-		/** This unassigns all leads greater than 1 of the given name. */
-		void unassign_gt_1_leads(const char* name);
-	};
+  class ForwSubstBuilder
+  {
+    typedef map<int, const char *> Ttermauxmap;
+  protected:
+    /** Reference to the model, to which we will add equations and
+     * change some equations. */
+    DynareModel &model;
+    /** A map mapping new auxiliary variables to the terms in the
+     * tree in the DynareModel. */
+    Tsubstmap aux_map;
+    /** Information about the substitutions. */
+    ForwSubstInfo info;
+  public:
+    /** Do all the jobs needed. This scans all equations in the
+     * model, and for equations containing forward looking
+     * variables greater than 1 lead, it makes corresponding
+     * substitutions. Basically, it breaks each equation to its
+     * non-linear components and creates substitutions for these
+     * components, not for whole equation. This is because the
+     * expectation operator can go through the linear part of the
+     * function. This will save us many occurrences of other
+     * variables involved in the equation. */
+    ForwSubstBuilder(DynareModel &m);
+    /** Copy constructor with a new instance of the model. */
+    ForwSubstBuilder(const ForwSubstBuilder &b, DynareModel &m);
+    /** Return the auxiliary variable mapping. */
+    const Tsubstmap &
+    get_aux_map() const
+    {
+      return aux_map;
+    }
+    /** Return the information. */
+    const ForwSubstInfo &
+    get_info() const
+    {
+      return info;
+    }
+  private:
+    ForwSubstBuilder(const ForwSubstBuilder &b);
+    /** This method takes a nonlinear term t, and if it has leads
+     * of greater than 1, then it substitutes the term for the new
+     * variable (or string of variables). Note that the
+     * substitution is done by DynamicAtoms::assign_variable. This
+     * means that the substitution is made for all other
+     * ocurrences of t in the model. So there is no need of
+     * tracking already substituted terms. The other two
+     * parameters are just for identification of the new auxiliary
+     * variables. When called from the constructor, i is an
+     * equation number, j is an order of the non-linear term in
+     * the equation. */
+    void substitute_for_term(int t, int i, int j);
+    /** This is called just at the end of the job. It unassigns
+     * all nulary terms with a lead greater than 1. */
+    void unassign_gt_1_leads();
+    /** This unassigns all leads greater than 1 of the given name. */
+    void unassign_gt_1_leads(const char *name);
+  };
 };
 
 #endif
diff --git a/dynare++/src/nlsolve.h b/dynare++/src/nlsolve.h
index 0cd19b1f3d4d3f6986ade8ea5dd921bc19dd0487..b8de181d441d9890ab34f0518e2c4d813fa1e9cb 100644
--- a/dynare++/src/nlsolve.h
+++ b/dynare++/src/nlsolve.h
@@ -8,82 +8,102 @@
 #include "twod_matrix.h"
 #include "journal.h"
 
-namespace ogu {
+namespace ogu
+{
 
-	class OneDFunction {
-	public:
-		virtual ~OneDFunction() {}
-		virtual double eval(double) = 0;
-	};
+  class OneDFunction
+  {
+  public:
+    virtual ~OneDFunction()
+    {
+    }
+    virtual double eval(double) = 0;
+  };
 
-	class GoldenSectionSearch {
-	protected:
-		static double tol;
-		static double golden;
-	public:
-		static double search(OneDFunction& f, double x1, double x2);
-	protected:
-		/** This initializes a bracket by moving x2 and b (as a golden
-		 * section of x1,x2) so that f(x1)>f(b) && f(b)<f(x2). The point
-		 * x1 is not moved, since it is considered as reliable and f(x1)
-		 * is supposed to be finite. If initialization of a bracket
-		 * succeeded, then [x1, b, x2] is the bracket and true is
-		 * returned. Otherwise, b is the minimum found and false is
-		 * returned. */
-		static bool init_bracket(OneDFunction& f, double x1, double& x2, double& b);
-		/** This supposes that f(x1) is finite and it moves x2 toward x1
-		 * until x2 and b (as a golden section of x1,x2) are finite. If
-		 * succeeded, the routine returns true and x2, and b. Otherwise,
-		 * it returns false. */
-		static bool search_for_finite(OneDFunction& f, double x1, double& x2, double& b);
-	};
+  class GoldenSectionSearch
+  {
+  protected:
+    static double tol;
+    static double golden;
+  public:
+    static double search(OneDFunction &f, double x1, double x2);
+  protected:
+    /** This initializes a bracket by moving x2 and b (as a golden
+     * section of x1,x2) so that f(x1)>f(b) && f(b)<f(x2). The point
+     * x1 is not moved, since it is considered as reliable and f(x1)
+     * is supposed to be finite. If initialization of a bracket
+     * succeeded, then [x1, b, x2] is the bracket and true is
+     * returned. Otherwise, b is the minimum found and false is
+     * returned. */
+    static bool init_bracket(OneDFunction &f, double x1, double &x2, double &b);
+    /** This supposes that f(x1) is finite and it moves x2 toward x1
+     * until x2 and b (as a golden section of x1,x2) are finite. If
+     * succeeded, the routine returns true and x2, and b. Otherwise,
+     * it returns false. */
+    static bool search_for_finite(OneDFunction &f, double x1, double &x2, double &b);
+  };
 
-	class VectorFunction {
-	public:
-		VectorFunction() {}
-		virtual ~VectorFunction() {}
-		virtual int inDim() const = 0;
-		virtual int outDim() const = 0;
-		/** Check dimensions of eval parameters. */
-		void check_for_eval(const ConstVector& in, Vector& out) const;
-		/** Evaluate the vector function. */
-		virtual void eval(const ConstVector& in, Vector& out) = 0;
-	};
+  class VectorFunction
+  {
+  public:
+    VectorFunction()
+    {
+    }
+    virtual ~VectorFunction()
+    {
+    }
+    virtual int inDim() const = 0;
+    virtual int outDim() const = 0;
+    /** Check dimensions of eval parameters. */
+    void check_for_eval(const ConstVector &in, Vector &out) const;
+    /** Evaluate the vector function. */
+    virtual void eval(const ConstVector &in, Vector &out) = 0;
+  };
 
-	class Jacobian : public TwoDMatrix {
-	public:
-		Jacobian(int n)
-			: TwoDMatrix(n,n) {}
-		virtual ~Jacobian() {}
-		virtual void eval(const Vector& in) = 0;
-	};
+  class Jacobian : public TwoDMatrix
+  {
+  public:
+    Jacobian(int n)
+      : TwoDMatrix(n, n)
+    {
+    }
+    virtual ~Jacobian()
+    {
+    }
+    virtual void eval(const Vector &in) = 0;
+  };
 
-	class NLSolver : public OneDFunction {
-	protected:
-		Journal& journal;
-		VectorFunction& func;
-		Jacobian& jacob;
-		const int max_iter;
-		const double tol;
-	private:
-		Vector xnewton;
-		Vector xcauchy;
-		Vector x;
-	public:
-		NLSolver(VectorFunction& f, Jacobian& j, int maxit, double tl, Journal& jr)
-			: journal(jr), func(f), jacob(j), max_iter(maxit), tol(tl),
-			  xnewton(f.inDim()), xcauchy(f.inDim()), x(f.inDim())
-			{xnewton.zeros(); xcauchy.zeros(); x.zeros();}
-		virtual ~NLSolver() {}
-		/** Returns true if the problem has converged. xx as input is the
-		 * starting value, as output it is a solution. */
-		bool solve(Vector& xx, int& iter);
-		/** To implement OneDFunction interface. It returns
-		 * func(xx)^T*func(xx), where
-		 * xx=x+lambda*xcauchy+(1-lambda)*xnewton. It is non-const only
-		 * because it calls func, x, xnewton, xcauchy is not changed. */
-		double eval(double lambda);
-	};
+  class NLSolver : public OneDFunction
+  {
+  protected:
+    Journal &journal;
+    VectorFunction &func;
+    Jacobian &jacob;
+    const int max_iter;
+    const double tol;
+  private:
+    Vector xnewton;
+    Vector xcauchy;
+    Vector x;
+  public:
+    NLSolver(VectorFunction &f, Jacobian &j, int maxit, double tl, Journal &jr)
+      : journal(jr), func(f), jacob(j), max_iter(maxit), tol(tl),
+        xnewton(f.inDim()), xcauchy(f.inDim()), x(f.inDim())
+    {
+      xnewton.zeros(); xcauchy.zeros(); x.zeros();
+    }
+    virtual ~NLSolver()
+    {
+    }
+    /** Returns true if the problem has converged. xx as input is the
+     * starting value, as output it is a solution. */
+    bool solve(Vector &xx, int &iter);
+    /** To implement OneDFunction interface. It returns
+     * func(xx)^T*func(xx), where
+     * xx=x+lambda*xcauchy+(1-lambda)*xnewton. It is non-const only
+     * because it calls func, x, xnewton, xcauchy is not changed. */
+    double eval(double lambda);
+  };
 
 };
 
diff --git a/dynare++/src/planner_builder.h b/dynare++/src/planner_builder.h
index 9e46832d7396c60318e55bdba3b59081c9eec5ed..4d888d9051c300706761f879890de059d623ed14 100644
--- a/dynare++/src/planner_builder.h
+++ b/dynare++/src/planner_builder.h
@@ -5,273 +5,322 @@
 
 #include "dynare_model.h"
 
-namespace ogdyn {
+namespace ogdyn
+{
 
-	using boost::unordered_set;
-	using std::map;
-	using std::vector;
+  using boost::unordered_set;
+  using std::map;
+  using std::vector;
 
-	/** This is a two dimensional array of integers. Nothing
-	 * difficult. */ 
-	class IntegerMatrix {
-	protected:
-		/** Number of rows. */
-		int nr;
-		/** Number of columns. */
-		int nc;
-		/** The pointer to the data. */
-		int* data;
-	public:
-		/** Construct uninitialized array. */
-		IntegerMatrix(int nrr, int ncc)
-			: nr(nrr), nc(ncc), data(new int[nr*nc]) {}
-		/** Copy constructor. */
-		IntegerMatrix(const IntegerMatrix& im)
-			: nr(im.nr), nc(im.nc), data(new int[nr*nc])
-			{memcpy(data, im.data, nr*nc*sizeof(int));}
-		virtual ~IntegerMatrix()
-			{delete [] data;}
-		/** Assignment operator. It can only assing array with the
-		 * same dimensions. */
-		const IntegerMatrix& operator=(const IntegerMatrix& im);
-		int& operator()(int i, int j)
-			{return data[i+j*nr];}
-		const int& operator()(int i, int j) const
-			{return data[i+j*nr];}
-		int nrows() const
-			{return nr;}
-		int ncols() const
-			{return nc;}
-	};
+  /** This is a two dimensional array of integers. Nothing
+   * difficult. */
+  class IntegerMatrix
+  {
+  protected:
+    /** Number of rows. */
+    int nr;
+    /** Number of columns. */
+    int nc;
+    /** The pointer to the data. */
+    int *data;
+  public:
+    /** Construct uninitialized array. */
+    IntegerMatrix(int nrr, int ncc)
+      : nr(nrr), nc(ncc), data(new int[nr*nc])
+    {
+    }
+    /** Copy constructor. */
+    IntegerMatrix(const IntegerMatrix &im)
+      : nr(im.nr), nc(im.nc), data(new int[nr*nc])
+    {
+      memcpy(data, im.data, nr*nc*sizeof(int));
+    }
+    virtual ~IntegerMatrix()
+    {
+      delete [] data;
+    }
+    /** Assignment operator. It can only assing array with the
+     * same dimensions. */
+    const IntegerMatrix &operator=(const IntegerMatrix &im);
+    int &
+    operator()(int i, int j)
+    {
+      return data[i+j*nr];
+    }
+    const int &
+    operator()(int i, int j) const
+    {
+      return data[i+j*nr];
+    }
+    int
+    nrows() const
+    {
+      return nr;
+    }
+    int
+    ncols() const
+    {
+      return nc;
+    }
+  };
 
-	/** The three dimensional array of integers. Nothing difficult. */
-	class IntegerArray3 {
-	protected:
-		/** First dimension. */
-		int n1;
-		/** Second dimension. */
-		int n2;
-		/** Third dimension. */
-		int n3;
-		/** The data. */
-		int* data;
-	public:
-		/** Constrcut unitialized array. */
-		IntegerArray3(int nn1, int nn2, int nn3)
-			: n1(nn1), n2(nn2), n3(nn3), data(new int[n1*n2*n3]) {}
-		/** Copy constructor. */
-		IntegerArray3(const IntegerArray3& ia3)
-			: n1(ia3.n1), n2(ia3.n2), n3(ia3.n3), data(new int[n1*n2*n3])
-			{memcpy(data, ia3.data, n1*n2*n3*sizeof(int));}
-		virtual ~IntegerArray3()
-			{delete [] data;}
-		/** Assignment operator assigning the arrays with the same dimensions. */
-		const IntegerArray3& operator=(const IntegerArray3& ia3);
-		int& operator()(int i, int j, int k)
-			{return data[i+j*n1+k*n1*n2];}
-		const int& operator()(int i, int j, int k) const
-			{return data[i+j*n1+k*n1*n2];}
-		int dim1() const
-			{return n1;}
-		int dim2() const
-			{return n2;}
-		int dim3() const
-			{return n3;}
-	};
+  /** The three dimensional array of integers. Nothing difficult. */
+  class IntegerArray3
+  {
+  protected:
+    /** First dimension. */
+    int n1;
+    /** Second dimension. */
+    int n2;
+    /** Third dimension. */
+    int n3;
+    /** The data. */
+    int *data;
+  public:
+    /** Constrcut unitialized array. */
+    IntegerArray3(int nn1, int nn2, int nn3)
+      : n1(nn1), n2(nn2), n3(nn3), data(new int[n1*n2*n3])
+    {
+    }
+    /** Copy constructor. */
+    IntegerArray3(const IntegerArray3 &ia3)
+      : n1(ia3.n1), n2(ia3.n2), n3(ia3.n3), data(new int[n1*n2*n3])
+    {
+      memcpy(data, ia3.data, n1*n2*n3*sizeof(int));
+    }
+    virtual ~IntegerArray3()
+    {
+      delete [] data;
+    }
+    /** Assignment operator assigning the arrays with the same dimensions. */
+    const IntegerArray3 &operator=(const IntegerArray3 &ia3);
+    int &
+    operator()(int i, int j, int k)
+    {
+      return data[i+j*n1+k*n1*n2];
+    }
+    const int &
+    operator()(int i, int j, int k) const
+    {
+      return data[i+j*n1+k*n1*n2];
+    }
+    int
+    dim1() const
+    {
+      return n1;
+    }
+    int
+    dim2() const
+    {
+      return n2;
+    }
+    int
+    dim3() const
+    {
+      return n3;
+    }
+  };
 
-	/** This struct encapsulates information about the building of a
-	 * planner's problem. */
-	struct PlannerInfo {
-		int num_lagrange_mults;
-		int num_aux_variables;
-		int num_new_terms;
-		PlannerInfo()
-			: num_lagrange_mults(0),
-			  num_aux_variables(0),
-			  num_new_terms(0) {}
-	};
+  /** This struct encapsulates information about the building of a
+   * planner's problem. */
+  struct PlannerInfo
+  {
+    int num_lagrange_mults;
+    int num_aux_variables;
+    int num_new_terms;
+    PlannerInfo()
+      : num_lagrange_mults(0),
+        num_aux_variables(0),
+        num_new_terms(0)
+    {
+    }
+  };
 
-	class MultInitSS;
+  class MultInitSS;
 
-	/** This class builds the first order conditions of the social
-	 * planner problem with constraints being the equations in the
-	 * model. The model is non-const parameter to the constructor
-	 * which adds appropriate FOCs to the system. It also allows for
-	 * an estimation of the lagrange multipliers given all other
-	 * endogenous variables of the static system. For this purpose we
-	 * need to create static atoms and static versions of all the tree
-	 * index matrices. The algorithm and algebra are documented in
-	 * dynare++-ramsey.pdf. */  
-	class PlannerBuilder {
-		friend class MultInitSS;
-	public:
-		/** Type for a set of variable names. */
-		typedef unordered_set<const char*> Tvarset;
-		/** Type for a set of equations. An equation is identified by
-		 * an index to an equation in the equation vector given by
-		 * DynareModel::eqs. The tree index of the i-th formula is
-		 * retrieved as DynareModel::egs.formula(i). */
-		typedef vector<int> Teqset;
-	protected:
-		/** This is a set of variables wrt which the planner
-		 * optimizes. These could be all endogenous variables, but it
-		 * is beneficial to exclude all variables which are
-		 * deterministic transformations of past exogenous variables,
-		 * since the planner cannot influence them. This could save a
-		 * few equations. This is not changed after it is constructed,
-		 * but it is constructed manually, so it cannot be declared as
-		 * const. */
-		Tvarset yset;
-		/** These are the equation indices constituing the constraints
-		 * for the planner. Again, it is beneficial to exclude all
-		 * equations defining exogenous variables excluded from
-		 * yset. */
-		const Teqset fset;
-		/** Reference to the model. */ 
-		ogdyn::DynareModel& model;
-		/** Tree index of the planner objective. */
-		int tb;
-		/** Tree index of the planner discount parameter. */
-		int tbeta;
-		/** The maximum lead in the model including the planner's
-		 * objective before building the planner's FOCs. */
-		const int maxlead;
-		/** The minimum lag in the model including the planner's objective
-		 * before building the planner's FOCs. */
-		const int minlag;
-		/** Tree indices of formulas in the planner FOCs involving
-		 * derivatives of the planner's objective. Rows correspond to the
-		 * endogenous variables, columns correspond to lags in the
-		 * objective function. The contents of the matrix will evolve as
-		 * the algorithm proceeds. */
-		IntegerMatrix diff_b;
-		/** Tree indices of formulas in the planner FOCs involving
-		 * derivatives of the model equations (constraints). The first
-		 * dimension corresponds to endogenous variables, the second to
-		 * the constraints, the third to lags or leads of endogenous
-		 * variables in the constraints. The contents of the array will
-		 * evolve as the algorithm proceeds.*/
-		IntegerArray3 diff_f;
-		/** Static version of the model atoms. It is needed to build
-		 * static version of diff_b and diff_f. */
-		ogp::StaticFineAtoms static_atoms;
-		/** Static version of all the trees of diff_b and diff_f build
-		 * over static_atoms. */
-		ogp::OperationTree static_tree;
-		/** Tree indices of static version of diff_b over static_atoms and static_tree. */
-		IntegerMatrix diff_b_static;
-		/** Tree indices of static version of diff_f over static_atoms
-		 * and static_tree. This member is created before calling
-		 * lagrange_mult_f(), so it does not contain the
-		 * multiplication with the lagrange multipliers. */
-		IntegerArray3 diff_f_static;
-		/** Auxiliary variables mapping. During the algorithm, some
-		 * auxiliary variables for the terms might be created, so we
-		 * remember their names and tree indices of the terms. This
-		 * maps a name to the tree index of an expression equal to the
-		 * auxiliary variable at time zero. The auxiliary variables
-		 * names point to the dynamic atoms storage, tree inidices to
-		 * the dynamic model tree. */
-		Tsubstmap aux_map;
-		/** Static version of aux_map. The names point to static_atoms
-		 * storage, the tree indices to the static_tree. */
-		Tsubstmap static_aux_map;
-		/** Information about the number of various things. */
-		PlannerInfo info;
-	public:
-		/** Build the planner problem for the given model optimizing
-		 * through the given endogenous variables with the given
-		 * constraints. We allow for a selection of a subset of
-		 * equations and variables in order to eliminate exogenous
-		 * predetermined process which cannot be influenced by the
-		 * social planner. */
-		PlannerBuilder(ogdyn::DynareModel& m, const Tvarset& yyset,
-					   const Teqset& ffset);
-		/** Construct a copy of the builder with provided model, which
-		 * is supposed to be the copy of the model in the builder. */
-		PlannerBuilder(const PlannerBuilder& pb, ogdyn::DynareModel& m);
-		/** Return the information. */
-		const PlannerInfo& get_info() const
-			{return info;}
-	protected:
-		/** Differentiate the planner objective wrt endogenous
-		 * variables with different lags. */
-		void add_derivatives_of_b();
-		/** Differentiate the constraints wrt endogenous variables
-		 * with different lags and leads. */
-		void add_derivatives_of_f();
-		/** Shift derivatives of diff_b. */
-		void shift_derivatives_of_b();
-		/** Shift derivatives of diff_ff. */
-		void shift_derivatives_of_f();
-		/** Multiply with the discount factor terms in diff_b. */
-		void beta_multiply_b();
-		/** Multiply with the discount factor terms in diff_f. */
-		void beta_multiply_f();
-		/** Fill static_atoms and static_tree and build diff_b_static,
-		 * diff_f_static and aux_map_static with static versions of diff_b,
-		 * diff_f and aux_map. */
-		void make_static_version();
-		/** Multiply diff_f with Langrange multipliers. */
-		void lagrange_mult_f();
-		/** Add the equations to the mode, including equation for auxiliary variables. */
-		void form_equations();
-	private:
-		/** Fill yset for a given yyset and given name storage. */
-		void fill_yset(const ogp::NameStorage& ns, const Tvarset& yyset);
-		/** Fill aux_map and aux_map_static for a given aaux_map and
-		 * aaux_map_static for a given storage of dynamic atoms (used
-		 * for aux_map) and static atoms storage from this object for
-		 * aux_map_static. */
-		void fill_aux_map(const ogp::NameStorage& ns, const Tsubstmap& aaux_map,
-						  const Tsubstmap& astatic_aux_map);
-		/** Avoid copying from only PlannerBuilder. */
-		PlannerBuilder(const PlannerBuilder& pb);
-  	};
+  /** This class builds the first order conditions of the social
+   * planner problem with constraints being the equations in the
+   * model. The model is non-const parameter to the constructor
+   * which adds appropriate FOCs to the system. It also allows for
+   * an estimation of the lagrange multipliers given all other
+   * endogenous variables of the static system. For this purpose we
+   * need to create static atoms and static versions of all the tree
+   * index matrices. The algorithm and algebra are documented in
+   * dynare++-ramsey.pdf. */
+  class PlannerBuilder
+  {
+    friend class MultInitSS;
+  public:
+    /** Type for a set of variable names. */
+    typedef unordered_set<const char *> Tvarset;
+    /** Type for a set of equations. An equation is identified by
+     * an index to an equation in the equation vector given by
+     * DynareModel::eqs. The tree index of the i-th formula is
+     * retrieved as DynareModel::egs.formula(i). */
+    typedef vector<int> Teqset;
+  protected:
+    /** This is a set of variables wrt which the planner
+     * optimizes. These could be all endogenous variables, but it
+     * is beneficial to exclude all variables which are
+     * deterministic transformations of past exogenous variables,
+     * since the planner cannot influence them. This could save a
+     * few equations. This is not changed after it is constructed,
+     * but it is constructed manually, so it cannot be declared as
+     * const. */
+    Tvarset yset;
+    /** These are the equation indices constituing the constraints
+     * for the planner. Again, it is beneficial to exclude all
+     * equations defining exogenous variables excluded from
+     * yset. */
+    const Teqset fset;
+    /** Reference to the model. */
+    ogdyn::DynareModel &model;
+    /** Tree index of the planner objective. */
+    int tb;
+    /** Tree index of the planner discount parameter. */
+    int tbeta;
+    /** The maximum lead in the model including the planner's
+     * objective before building the planner's FOCs. */
+    const int maxlead;
+    /** The minimum lag in the model including the planner's objective
+     * before building the planner's FOCs. */
+    const int minlag;
+    /** Tree indices of formulas in the planner FOCs involving
+     * derivatives of the planner's objective. Rows correspond to the
+     * endogenous variables, columns correspond to lags in the
+     * objective function. The contents of the matrix will evolve as
+     * the algorithm proceeds. */
+    IntegerMatrix diff_b;
+    /** Tree indices of formulas in the planner FOCs involving
+     * derivatives of the model equations (constraints). The first
+     * dimension corresponds to endogenous variables, the second to
+     * the constraints, the third to lags or leads of endogenous
+     * variables in the constraints. The contents of the array will
+     * evolve as the algorithm proceeds.*/
+    IntegerArray3 diff_f;
+    /** Static version of the model atoms. It is needed to build
+     * static version of diff_b and diff_f. */
+    ogp::StaticFineAtoms static_atoms;
+    /** Static version of all the trees of diff_b and diff_f build
+     * over static_atoms. */
+    ogp::OperationTree static_tree;
+    /** Tree indices of static version of diff_b over static_atoms and static_tree. */
+    IntegerMatrix diff_b_static;
+    /** Tree indices of static version of diff_f over static_atoms
+     * and static_tree. This member is created before calling
+     * lagrange_mult_f(), so it does not contain the
+     * multiplication with the lagrange multipliers. */
+    IntegerArray3 diff_f_static;
+    /** Auxiliary variables mapping. During the algorithm, some
+     * auxiliary variables for the terms might be created, so we
+     * remember their names and tree indices of the terms. This
+     * maps a name to the tree index of an expression equal to the
+     * auxiliary variable at time zero. The auxiliary variables
+     * names point to the dynamic atoms storage, tree inidices to
+     * the dynamic model tree. */
+    Tsubstmap aux_map;
+    /** Static version of aux_map. The names point to static_atoms
+     * storage, the tree indices to the static_tree. */
+    Tsubstmap static_aux_map;
+    /** Information about the number of various things. */
+    PlannerInfo info;
+  public:
+    /** Build the planner problem for the given model optimizing
+     * through the given endogenous variables with the given
+     * constraints. We allow for a selection of a subset of
+     * equations and variables in order to eliminate exogenous
+     * predetermined process which cannot be influenced by the
+     * social planner. */
+    PlannerBuilder(ogdyn::DynareModel &m, const Tvarset &yyset,
+                   const Teqset &ffset);
+    /** Construct a copy of the builder with provided model, which
+     * is supposed to be the copy of the model in the builder. */
+    PlannerBuilder(const PlannerBuilder &pb, ogdyn::DynareModel &m);
+    /** Return the information. */
+    const PlannerInfo &
+    get_info() const
+    {
+      return info;
+    }
+  protected:
+    /** Differentiate the planner objective wrt endogenous
+     * variables with different lags. */
+    void add_derivatives_of_b();
+    /** Differentiate the constraints wrt endogenous variables
+     * with different lags and leads. */
+    void add_derivatives_of_f();
+    /** Shift derivatives of diff_b. */
+    void shift_derivatives_of_b();
+    /** Shift derivatives of diff_ff. */
+    void shift_derivatives_of_f();
+    /** Multiply with the discount factor terms in diff_b. */
+    void beta_multiply_b();
+    /** Multiply with the discount factor terms in diff_f. */
+    void beta_multiply_f();
+    /** Fill static_atoms and static_tree and build diff_b_static,
+     * diff_f_static and aux_map_static with static versions of diff_b,
+     * diff_f and aux_map. */
+    void make_static_version();
+    /** Multiply diff_f with Langrange multipliers. */
+    void lagrange_mult_f();
+    /** Add the equations to the mode, including equation for auxiliary variables. */
+    void form_equations();
+  private:
+    /** Fill yset for a given yyset and given name storage. */
+    void fill_yset(const ogp::NameStorage &ns, const Tvarset &yyset);
+    /** Fill aux_map and aux_map_static for a given aaux_map and
+     * aaux_map_static for a given storage of dynamic atoms (used
+     * for aux_map) and static atoms storage from this object for
+     * aux_map_static. */
+    void fill_aux_map(const ogp::NameStorage &ns, const Tsubstmap &aaux_map,
+                      const Tsubstmap &astatic_aux_map);
+    /** Avoid copying from only PlannerBuilder. */
+    PlannerBuilder(const PlannerBuilder &pb);
+  };
 
-	/** This class only calculates for the given initial guess of
-	 * endogenous variables, initial guess of the Langrange
-	 * multipliers of the social planner problem yielding the least
-	 * square error. It is used by just calling its constructor. The
-	 * constructor takes non-const reference to the vector of
-	 * endogenous variables, calculates lambdas and put the values of
-	 * lambdas to the vector. The algbera is found in
-	 * dynare++-ramsey.pdf.
-	 *
-	 * The code can be run only after the parsing has been finished in
-	 * atoms. */
-	class MultInitSS : public ogp::FormulaEvalLoader {
-	protected:
-		/** The constant reference to the builder. */
-		const PlannerBuilder& builder;
-		/** The constant term of the problem. Its length is the number
-		 * of endogenous variable wrt the planner optimizes. */
-		Vector b;
-		/** The matrix of the overdetermined problem. The number of
-		 * rows is equal to the number of endogenous variables wrt
-		 * which the planner optimizes, the number of columns is equal
-		 * to the number of Langrange multipliers which is equal to
-		 * the number of constraints which is smaller than the number
-		 * of endogenous variables. Hence the system b+F*lambda=0 is
-		 * overdetermined. */
-		GeneralMatrix F;
-	public:
-		/** The constructor of the object which does everything. Its
-		 * main goal is to update yy. Note that if an item of yy
-		 * corresponding to a lagrange multiplier is already set, it
-		 * is not reset. */
-		MultInitSS(const PlannerBuilder& pb, const Vector& pvals, Vector& yy);
-		/** This loads evaluated parts of b or F and decodes i and
-		 * advances b or F depending on the decoded i. The decoding is
-		 * dependent on the way how the terms of builder.diff_b and
-		 * builder.diff_f_save have been put the the
-		 * ogp::FormulaCustomEvaluator. This is documented in the code
-		 * of the constructor. */
-		void load(int i, double res);
-	};
+  /** This class only calculates for the given initial guess of
+   * endogenous variables, initial guess of the Langrange
+   * multipliers of the social planner problem yielding the least
+   * square error. It is used by just calling its constructor. The
+   * constructor takes non-const reference to the vector of
+   * endogenous variables, calculates lambdas and put the values of
+   * lambdas to the vector. The algbera is found in
+   * dynare++-ramsey.pdf.
+   *
+   * The code can be run only after the parsing has been finished in
+   * atoms. */
+  class MultInitSS : public ogp::FormulaEvalLoader
+  {
+  protected:
+    /** The constant reference to the builder. */
+    const PlannerBuilder &builder;
+    /** The constant term of the problem. Its length is the number
+     * of endogenous variable wrt the planner optimizes. */
+    Vector b;
+    /** The matrix of the overdetermined problem. The number of
+     * rows is equal to the number of endogenous variables wrt
+     * which the planner optimizes, the number of columns is equal
+     * to the number of Langrange multipliers which is equal to
+     * the number of constraints which is smaller than the number
+     * of endogenous variables. Hence the system b+F*lambda=0 is
+     * overdetermined. */
+    GeneralMatrix F;
+  public:
+    /** The constructor of the object which does everything. Its
+     * main goal is to update yy. Note that if an item of yy
+     * corresponding to a lagrange multiplier is already set, it
+     * is not reset. */
+    MultInitSS(const PlannerBuilder &pb, const Vector &pvals, Vector &yy);
+    /** This loads evaluated parts of b or F and decodes i and
+     * advances b or F depending on the decoded i. The decoding is
+     * dependent on the way how the terms of builder.diff_b and
+     * builder.diff_f_save have been put the the
+     * ogp::FormulaCustomEvaluator. This is documented in the code
+     * of the constructor. */
+    void load(int i, double res);
+  };
 };
 
-
 #endif
 
 // Local Variables:
diff --git a/dynare++/sylv/cc/BlockDiagonal.h b/dynare++/sylv/cc/BlockDiagonal.h
index c2b94313a21e5b70c88872ba3ca981acf19804c4..f449653385da4d385d4b7af825d4411784523944 100644
--- a/dynare++/sylv/cc/BlockDiagonal.h
+++ b/dynare++/sylv/cc/BlockDiagonal.h
@@ -7,47 +7,55 @@
 
 #include "QuasiTriangular.h"
 
-
-class BlockDiagonal : public QuasiTriangular {
-	int* const row_len;
-	int* const col_len;
+class BlockDiagonal : public QuasiTriangular
+{
+  int *const row_len;
+  int *const col_len;
 public:
-	BlockDiagonal(const double* d, int d_size);
-	BlockDiagonal(int p, const BlockDiagonal& b);
-	BlockDiagonal(const BlockDiagonal& b);
-	BlockDiagonal(const QuasiTriangular& t);
-	const BlockDiagonal& operator=(const QuasiTriangular& t)
-		{GeneralMatrix::operator=(t); return *this;}
-	const BlockDiagonal& operator=(const BlockDiagonal& b);
-	~BlockDiagonal() {delete [] row_len; delete [] col_len;}
-	void setZeroBlockEdge(diag_iter edge);
-	int getNumZeros() const;
-	int getNumBlocks() const;
-	int getLargestBlock() const;
-	void printInfo() const;
-
-	void multKron(KronVector& x) const;
-	void multKronTrans(KronVector& x) const;
-
-	const_col_iter col_begin(const DiagonalBlock& b) const;
-	col_iter col_begin(const DiagonalBlock& b);
-	const_row_iter row_end(const DiagonalBlock& b) const;
-	row_iter row_end(const DiagonalBlock& b);
-	QuasiTriangular* clone() const
-		{return new BlockDiagonal(*this);}
+  BlockDiagonal(const double *d, int d_size);
+  BlockDiagonal(int p, const BlockDiagonal &b);
+  BlockDiagonal(const BlockDiagonal &b);
+  BlockDiagonal(const QuasiTriangular &t);
+  const BlockDiagonal &
+  operator=(const QuasiTriangular &t)
+  {
+    GeneralMatrix::operator=(t); return *this;
+  }
+  const BlockDiagonal &operator=(const BlockDiagonal &b);
+  ~BlockDiagonal()
+  {
+    delete [] row_len; delete [] col_len;
+  }
+  void setZeroBlockEdge(diag_iter edge);
+  int getNumZeros() const;
+  int getNumBlocks() const;
+  int getLargestBlock() const;
+  void printInfo() const;
+
+  void multKron(KronVector &x) const;
+  void multKronTrans(KronVector &x) const;
+
+  const_col_iter col_begin(const DiagonalBlock &b) const;
+  col_iter col_begin(const DiagonalBlock &b);
+  const_row_iter row_end(const DiagonalBlock &b) const;
+  row_iter row_end(const DiagonalBlock &b);
+  QuasiTriangular *
+  clone() const
+  {
+    return new BlockDiagonal(*this);
+  }
 private:
-	void setZerosToRU(diag_iter edge);
-	const_diag_iter findBlockStart(const_diag_iter from) const;
-	static void savePartOfX(int si, int ei, const KronVector& x, Vector& work);
-	void multKronBlock(const_diag_iter start, const_diag_iter end,
-					   KronVector& x, Vector& work) const;
-	void multKronBlockTrans(const_diag_iter start, const_diag_iter end,
-							KronVector& x, Vector& work) const;
+  void setZerosToRU(diag_iter edge);
+  const_diag_iter findBlockStart(const_diag_iter from) const;
+  static void savePartOfX(int si, int ei, const KronVector &x, Vector &work);
+  void multKronBlock(const_diag_iter start, const_diag_iter end,
+                     KronVector &x, Vector &work) const;
+  void multKronBlockTrans(const_diag_iter start, const_diag_iter end,
+                          KronVector &x, Vector &work) const;
 };
 
 #endif /* BLOCK_DIAGONAL_H */
 
-
 // Local Variables:
 // mode:C++
 // End:
diff --git a/dynare++/sylv/cc/GeneralMatrix.h b/dynare++/sylv/cc/GeneralMatrix.h
index d24c11cad951535efdce167133c6d72bc9a28b2f..494dcf40677956d9df97d4eada2e5a84b6efc373 100644
--- a/dynare++/sylv/cc/GeneralMatrix.h
+++ b/dynare++/sylv/cc/GeneralMatrix.h
@@ -11,310 +11,484 @@
 
 class GeneralMatrix;
 
-class ConstGeneralMatrix {
-	friend class GeneralMatrix;
+class ConstGeneralMatrix
+{
+  friend class GeneralMatrix;
 protected:
-	ConstVector data;
-	int rows;
-	int cols;
-	int ld;
+  ConstVector data;
+  int rows;
+  int cols;
+  int ld;
 public:
-	ConstGeneralMatrix(const double* d, int m, int n)
-		: data(d, m*n), rows(m), cols(n), ld(m) {}
-	ConstGeneralMatrix(const GeneralMatrix& m);
-	ConstGeneralMatrix(const GeneralMatrix& m, int i, int j, int nrows, int ncols);
-	ConstGeneralMatrix(const ConstGeneralMatrix& m, int i, int j, int nrows, int ncols);
-	virtual ~ConstGeneralMatrix() {}
-
-	const double& get(int i, int j) const
-		{return data[j*ld+i];}
-	int numRows() const {return rows;}
-	int numCols() const {return cols;}
-	int getLD() const {return ld;}
-	const double* base() const {return data.base();}
-	const ConstVector& getData() const {return data;}
-
-	double getNormInf() const;
-	double getNorm1() const;
-	/* x = scalar(a)*x + scalar(b)*this*d */
-	void multVec(double a, Vector& x, double b, const ConstVector& d) const;
-	/* x = scalar(a)*x + scalar(b)*this'*d */
-	void multVecTrans(double a, Vector& x, double b, const ConstVector& d) const;
-	/* x = x + this*d */
-	void multaVec(Vector& x, const ConstVector& d) const
-		{multVec(1.0, x, 1.0, d);}
-	/* x = x + this'*d */
-	void multaVecTrans(Vector& x, const ConstVector& d) const
-		{multVecTrans(1.0, x, 1.0, d);}
-	/* x = x - this*d */
-	void multsVec(Vector& x, const ConstVector& d) const
-		{multVec(1.0, x, -1.0, d);}
-	/* x = x - this'*d */
-	void multsVecTrans(Vector& x, const ConstVector& d) const
-		{multVecTrans(1.0, x, -1.0, d);}
-	/* m = inv(this)*m */
-	void multInvLeft(GeneralMatrix& m) const;
-	/* m = inv(this')*m */
-	void multInvLeftTrans(GeneralMatrix& m) const;
-	/* d = inv(this)*d */
-	void multInvLeft(Vector& d) const;
-	/* d = inv(this')*d */
-	void multInvLeftTrans(Vector& d) const;
-
-	bool isFinite() const;
-	/** Returns true of the matrix is exactly zero. */
-	bool isZero() const;
-
-	virtual void print() const;
+  ConstGeneralMatrix(const double *d, int m, int n)
+    : data(d, m*n), rows(m), cols(n), ld(m)
+  {
+  }
+  ConstGeneralMatrix(const GeneralMatrix &m);
+  ConstGeneralMatrix(const GeneralMatrix &m, int i, int j, int nrows, int ncols);
+  ConstGeneralMatrix(const ConstGeneralMatrix &m, int i, int j, int nrows, int ncols);
+  virtual ~ConstGeneralMatrix()
+  {
+  }
+
+  const double &
+  get(int i, int j) const
+  {
+    return data[j*ld+i];
+  }
+  int
+  numRows() const
+  {
+    return rows;
+  }
+  int
+  numCols() const
+  {
+    return cols;
+  }
+  int
+  getLD() const
+  {
+    return ld;
+  }
+  const double *
+  base() const
+  {
+    return data.base();
+  }
+  const ConstVector &
+  getData() const
+  {
+    return data;
+  }
+
+  double getNormInf() const;
+  double getNorm1() const;
+  /* x = scalar(a)*x + scalar(b)*this*d */
+  void multVec(double a, Vector &x, double b, const ConstVector &d) const;
+  /* x = scalar(a)*x + scalar(b)*this'*d */
+  void multVecTrans(double a, Vector &x, double b, const ConstVector &d) const;
+  /* x = x + this*d */
+  void
+  multaVec(Vector &x, const ConstVector &d) const
+  {
+    multVec(1.0, x, 1.0, d);
+  }
+  /* x = x + this'*d */
+  void
+  multaVecTrans(Vector &x, const ConstVector &d) const
+  {
+    multVecTrans(1.0, x, 1.0, d);
+  }
+  /* x = x - this*d */
+  void
+  multsVec(Vector &x, const ConstVector &d) const
+  {
+    multVec(1.0, x, -1.0, d);
+  }
+  /* x = x - this'*d */
+  void
+  multsVecTrans(Vector &x, const ConstVector &d) const
+  {
+    multVecTrans(1.0, x, -1.0, d);
+  }
+  /* m = inv(this)*m */
+  void multInvLeft(GeneralMatrix &m) const;
+  /* m = inv(this')*m */
+  void multInvLeftTrans(GeneralMatrix &m) const;
+  /* d = inv(this)*d */
+  void multInvLeft(Vector &d) const;
+  /* d = inv(this')*d */
+  void multInvLeftTrans(Vector &d) const;
+
+  bool isFinite() const;
+  /** Returns true of the matrix is exactly zero. */
+  bool isZero() const;
+
+  virtual void print() const;
 protected:
-	void multInvLeft(const char* trans, int mrows, int mcols, int mld, double* d) const;
+  void multInvLeft(const char *trans, int mrows, int mcols, int mld, double *d) const;
 };
 
-
-class GeneralMatrix {
-	friend class ConstGeneralMatrix;
+class GeneralMatrix
+{
+  friend class ConstGeneralMatrix;
 protected:
-	Vector data;
-	int rows;
-	int cols;
-	int ld;
+  Vector data;
+  int rows;
+  int cols;
+  int ld;
 public:
-	GeneralMatrix(int m, int n)
-		: data(m*n), rows(m), cols(n), ld(m) {}
-	GeneralMatrix(const double* d, int m, int n)
-		: data(d, m*n), rows(m), cols(n), ld(m) {}
-	GeneralMatrix(double* d, int m, int n)
-		: data(d, m*n), rows(m), cols(n), ld(m) {}
-	GeneralMatrix(const GeneralMatrix& m);
-	GeneralMatrix(const ConstGeneralMatrix& m);
-	GeneralMatrix(const GeneralMatrix&m, const char* dummy); // transpose
-	GeneralMatrix(const ConstGeneralMatrix&m, const char* dummy); // transpose
-	GeneralMatrix(const GeneralMatrix& m, int i, int j, int nrows, int ncols);
-	GeneralMatrix(GeneralMatrix& m, int i, int j, int nrows, int ncols);
-	/* this = a*b */
-	GeneralMatrix(const GeneralMatrix& a, const GeneralMatrix& b);
-	/* this = a*b' */
-	GeneralMatrix(const GeneralMatrix& a, const GeneralMatrix& b, const char* dum);
-	/* this = a'*b */
-	GeneralMatrix(const GeneralMatrix& a, const char* dum, const GeneralMatrix& b);
-	/* this = a'*b */
-	GeneralMatrix(const GeneralMatrix& a, const char* dum1,
-				  const GeneralMatrix& b, const char* dum2);
-
-	virtual ~GeneralMatrix();
-	const GeneralMatrix& operator=(const GeneralMatrix& m)
-		{data=m.data; rows=m.rows; cols=m.cols; ld=m.ld; return *this;}
-
-	const double& get(int i, int j) const
-		{return data[j*ld+i];}
-	double& get(int i, int j)
-		{return data[j*ld+i];}
-	int numRows() const {return rows;}
-	int numCols() const {return cols;}
-	int getLD() const {return ld;}
-	double* base() {return data.base();}
-	const double* base() const {return data.base();}
-	Vector& getData() {return data;}
-	const Vector& getData() const {return data;}
-
-	double getNormInf() const
-		{return ConstGeneralMatrix(*this).getNormInf();}
-	double getNorm1() const
-		{return ConstGeneralMatrix(*this).getNorm1();}
-
-	/* place matrix m to the position (i,j) */
-	void place(const ConstGeneralMatrix& m, int i, int j);
-	void place(const GeneralMatrix& m, int i, int j)
-		{place(ConstGeneralMatrix(m), i, j);}
-
-	/* this = a*b */
-	void mult(const ConstGeneralMatrix& a, const ConstGeneralMatrix& b);
-	void mult(const GeneralMatrix& a, const GeneralMatrix& b)
-		{mult(ConstGeneralMatrix(a), ConstGeneralMatrix(b));}
-
-	/* this = this + scalar*a*b */
-	void multAndAdd(const ConstGeneralMatrix& a, const ConstGeneralMatrix& b,
-					double mult=1.0);
-	void multAndAdd(const GeneralMatrix& a, const GeneralMatrix& b,
-					double mult=1.0)
-		{multAndAdd(ConstGeneralMatrix(a), ConstGeneralMatrix(b), mult);}
-
-	/* this = this + scalar*a*b' */
-	void multAndAdd(const ConstGeneralMatrix& a, const ConstGeneralMatrix& b,
-					const char* dum, double mult=1.0);
-	void multAndAdd(const GeneralMatrix& a, const GeneralMatrix& b,
-					const char* dum, double mult=1.0)
-		{multAndAdd(ConstGeneralMatrix(a), ConstGeneralMatrix(b), dum, mult);}
-
-	/* this = this + scalar*a'*b */
-	void multAndAdd(const ConstGeneralMatrix& a, const char* dum, const ConstGeneralMatrix& b,
-					double mult=1.0);
-	void multAndAdd(const GeneralMatrix& a, const char* dum, const GeneralMatrix& b,
-					double mult=1.0)
-		{multAndAdd(ConstGeneralMatrix(a), dum, ConstGeneralMatrix(b), mult);}
-
-	/* this = this + scalar*a'*b' */
-	void multAndAdd(const ConstGeneralMatrix& a, const char* dum1,
-					const ConstGeneralMatrix& b, const char* dum2, double mult=1.0);
-	void multAndAdd(const GeneralMatrix& a, const char* dum1,
-					const GeneralMatrix& b, const char* dum2, double mult=1.0)
-		{multAndAdd(ConstGeneralMatrix(a), dum1, ConstGeneralMatrix(b),dum2, mult);}
-
-	/* this = this + scalar*a*a' */
-	void addOuter(const ConstVector& a, double mult=1.0);
-	void addOuter(const Vector& a, double mult=1.0)
-		{addOuter(ConstVector(a), mult);}
-
-	/* this = this * m */
-	void multRight(const ConstGeneralMatrix& m);
-	void multRight(const GeneralMatrix& m)
-		{multRight(ConstGeneralMatrix(m));}
-
-	/* this = m * this */
-	void multLeft(const ConstGeneralMatrix& m);
-	void multLeft(const GeneralMatrix& m)
-		{multLeft(ConstGeneralMatrix(m));}
-
-	/* this = this * m' */
-	void multRightTrans(const ConstGeneralMatrix& m);
-	void multRightTrans(const GeneralMatrix& m)
-		{multRightTrans(ConstGeneralMatrix(m));}
-
-	/* this = m' * this */
-	void multLeftTrans(const ConstGeneralMatrix& m);
-	void multLeftTrans(const GeneralMatrix& m)
-		{multLeftTrans(ConstGeneralMatrix(m));}
-
-	/* x = scalar(a)*x + scalar(b)*this*d */
-	void multVec(double a, Vector& x, double b, const ConstVector& d) const
-		{ConstGeneralMatrix(*this).multVec(a, x, b, d);}
-
-	/* x = scalar(a)*x + scalar(b)*this'*d */
-	void multVecTrans(double a, Vector& x, double b, const ConstVector& d) const
-		{ConstGeneralMatrix(*this).multVecTrans(a, x, b, d);}
-
-	/* x = x + this*d */
-	void multaVec(Vector& x, const ConstVector& d) const
-		{ConstGeneralMatrix(*this).multaVec(x, d);}
-
-	/* x = x + this'*d */
-	void multaVecTrans(Vector& x, const ConstVector& d) const
-		{ConstGeneralMatrix(*this).multaVecTrans(x, d);}
-
-	/* x = x - this*d */
-	void multsVec(Vector& x, const ConstVector& d) const
-		{ConstGeneralMatrix(*this).multsVec(x, d);}
-
-	/* x = x - this'*d */
-	void multsVecTrans(Vector& x, const ConstVector& d) const
-		{ConstGeneralMatrix(*this).multsVecTrans(x, d);}
-
-	/* this = zero */
-	void zeros();
-
-	/** this = unit (on main diagonal) */
-	void unit();
-
-	/* this = NaN */
-	void nans();
-
-	/* this = Inf */
-	void infs();
-
-	/* this = scalar*this */
-	void mult(double a);
-
-	/* this = this + scalar*m */
-	void add(double a, const ConstGeneralMatrix& m);
-	void add(double a, const GeneralMatrix& m)
-		{add(a, ConstGeneralMatrix(m));}
-
-	/* this = this + scalar*m' */
-	void add(double a, const ConstGeneralMatrix& m, const char* dum);
-	void add(double a, const GeneralMatrix& m, const char* dum)
-		{add(a, ConstGeneralMatrix(m), dum);}
-
-	bool isFinite() const
-		{return (ConstGeneralMatrix(*this)).isFinite();}
-
-	bool isZero() const
-		{return (ConstGeneralMatrix(*this)).isZero();}
-
-	virtual void print() const
-		{ConstGeneralMatrix(*this).print();}
+  GeneralMatrix(int m, int n)
+    : data(m*n), rows(m), cols(n), ld(m)
+  {
+  }
+  GeneralMatrix(const double *d, int m, int n)
+    : data(d, m*n), rows(m), cols(n), ld(m)
+  {
+  }
+  GeneralMatrix(double *d, int m, int n)
+    : data(d, m*n), rows(m), cols(n), ld(m)
+  {
+  }
+  GeneralMatrix(const GeneralMatrix &m);
+  GeneralMatrix(const ConstGeneralMatrix &m);
+  GeneralMatrix(const GeneralMatrix &m, const char *dummy); // transpose
+  GeneralMatrix(const ConstGeneralMatrix &m, const char *dummy); // transpose
+  GeneralMatrix(const GeneralMatrix &m, int i, int j, int nrows, int ncols);
+  GeneralMatrix(GeneralMatrix &m, int i, int j, int nrows, int ncols);
+  /* this = a*b */
+  GeneralMatrix(const GeneralMatrix &a, const GeneralMatrix &b);
+  /* this = a*b' */
+  GeneralMatrix(const GeneralMatrix &a, const GeneralMatrix &b, const char *dum);
+  /* this = a'*b */
+  GeneralMatrix(const GeneralMatrix &a, const char *dum, const GeneralMatrix &b);
+  /* this = a'*b */
+  GeneralMatrix(const GeneralMatrix &a, const char *dum1,
+                const GeneralMatrix &b, const char *dum2);
+
+  virtual
+  ~GeneralMatrix();
+  const GeneralMatrix &
+  operator=(const GeneralMatrix &m)
+  {
+    data = m.data; rows = m.rows; cols = m.cols; ld = m.ld; return *this;
+  }
+
+  const double &
+  get(int i, int j) const
+  {
+    return data[j*ld+i];
+  }
+  double &
+  get(int i, int j)
+  {
+    return data[j*ld+i];
+  }
+  int
+  numRows() const
+  {
+    return rows;
+  }
+  int
+  numCols() const
+  {
+    return cols;
+  }
+  int
+  getLD() const
+  {
+    return ld;
+  }
+  double *
+  base()
+  {
+    return data.base();
+  }
+  const double *
+  base() const
+  {
+    return data.base();
+  }
+  Vector &
+  getData()
+  {
+    return data;
+  }
+  const Vector &
+  getData() const
+  {
+    return data;
+  }
+
+  double
+  getNormInf() const
+  {
+    return ConstGeneralMatrix(*this).getNormInf();
+  }
+  double
+  getNorm1() const
+  {
+    return ConstGeneralMatrix(*this).getNorm1();
+  }
+
+  /* place matrix m to the position (i,j) */
+  void place(const ConstGeneralMatrix &m, int i, int j);
+  void
+  place(const GeneralMatrix &m, int i, int j)
+  {
+    place(ConstGeneralMatrix(m), i, j);
+  }
+
+  /* this = a*b */
+  void mult(const ConstGeneralMatrix &a, const ConstGeneralMatrix &b);
+  void
+  mult(const GeneralMatrix &a, const GeneralMatrix &b)
+  {
+    mult(ConstGeneralMatrix(a), ConstGeneralMatrix(b));
+  }
+
+  /* this = this + scalar*a*b */
+  void multAndAdd(const ConstGeneralMatrix &a, const ConstGeneralMatrix &b,
+                  double mult = 1.0);
+  void
+  multAndAdd(const GeneralMatrix &a, const GeneralMatrix &b,
+             double mult = 1.0)
+  {
+    multAndAdd(ConstGeneralMatrix(a), ConstGeneralMatrix(b), mult);
+  }
+
+  /* this = this + scalar*a*b' */
+  void multAndAdd(const ConstGeneralMatrix &a, const ConstGeneralMatrix &b,
+                  const char *dum, double mult = 1.0);
+  void
+  multAndAdd(const GeneralMatrix &a, const GeneralMatrix &b,
+             const char *dum, double mult = 1.0)
+  {
+    multAndAdd(ConstGeneralMatrix(a), ConstGeneralMatrix(b), dum, mult);
+  }
+
+  /* this = this + scalar*a'*b */
+  void multAndAdd(const ConstGeneralMatrix &a, const char *dum, const ConstGeneralMatrix &b,
+                  double mult = 1.0);
+  void
+  multAndAdd(const GeneralMatrix &a, const char *dum, const GeneralMatrix &b,
+             double mult = 1.0)
+  {
+    multAndAdd(ConstGeneralMatrix(a), dum, ConstGeneralMatrix(b), mult);
+  }
+
+  /* this = this + scalar*a'*b' */
+  void multAndAdd(const ConstGeneralMatrix &a, const char *dum1,
+                  const ConstGeneralMatrix &b, const char *dum2, double mult = 1.0);
+  void
+  multAndAdd(const GeneralMatrix &a, const char *dum1,
+             const GeneralMatrix &b, const char *dum2, double mult = 1.0)
+  {
+    multAndAdd(ConstGeneralMatrix(a), dum1, ConstGeneralMatrix(b), dum2, mult);
+  }
+
+  /* this = this + scalar*a*a' */
+  void addOuter(const ConstVector &a, double mult = 1.0);
+  void
+  addOuter(const Vector &a, double mult = 1.0)
+  {
+    addOuter(ConstVector(a), mult);
+  }
+
+  /* this = this * m */
+  void multRight(const ConstGeneralMatrix &m);
+  void
+  multRight(const GeneralMatrix &m)
+  {
+    multRight(ConstGeneralMatrix(m));
+  }
+
+  /* this = m * this */
+  void multLeft(const ConstGeneralMatrix &m);
+  void
+  multLeft(const GeneralMatrix &m)
+  {
+    multLeft(ConstGeneralMatrix(m));
+  }
+
+  /* this = this * m' */
+  void multRightTrans(const ConstGeneralMatrix &m);
+  void
+  multRightTrans(const GeneralMatrix &m)
+  {
+    multRightTrans(ConstGeneralMatrix(m));
+  }
+
+  /* this = m' * this */
+  void multLeftTrans(const ConstGeneralMatrix &m);
+  void
+  multLeftTrans(const GeneralMatrix &m)
+  {
+    multLeftTrans(ConstGeneralMatrix(m));
+  }
+
+  /* x = scalar(a)*x + scalar(b)*this*d */
+  void
+  multVec(double a, Vector &x, double b, const ConstVector &d) const
+  {
+    ConstGeneralMatrix(*this).multVec(a, x, b, d);
+  }
+
+  /* x = scalar(a)*x + scalar(b)*this'*d */
+  void
+  multVecTrans(double a, Vector &x, double b, const ConstVector &d) const
+  {
+    ConstGeneralMatrix(*this).multVecTrans(a, x, b, d);
+  }
+
+  /* x = x + this*d */
+  void
+  multaVec(Vector &x, const ConstVector &d) const
+  {
+    ConstGeneralMatrix(*this).multaVec(x, d);
+  }
+
+  /* x = x + this'*d */
+  void
+  multaVecTrans(Vector &x, const ConstVector &d) const
+  {
+    ConstGeneralMatrix(*this).multaVecTrans(x, d);
+  }
+
+  /* x = x - this*d */
+  void
+  multsVec(Vector &x, const ConstVector &d) const
+  {
+    ConstGeneralMatrix(*this).multsVec(x, d);
+  }
+
+  /* x = x - this'*d */
+  void
+  multsVecTrans(Vector &x, const ConstVector &d) const
+  {
+    ConstGeneralMatrix(*this).multsVecTrans(x, d);
+  }
+
+  /* this = zero */
+  void zeros();
+
+  /** this = unit (on main diagonal) */
+  void unit();
+
+  /* this = NaN */
+  void nans();
+
+  /* this = Inf */
+  void infs();
+
+  /* this = scalar*this */
+  void mult(double a);
+
+  /* this = this + scalar*m */
+  void add(double a, const ConstGeneralMatrix &m);
+  void
+  add(double a, const GeneralMatrix &m)
+  {
+    add(a, ConstGeneralMatrix(m));
+  }
+
+  /* this = this + scalar*m' */
+  void add(double a, const ConstGeneralMatrix &m, const char *dum);
+  void
+  add(double a, const GeneralMatrix &m, const char *dum)
+  {
+    add(a, ConstGeneralMatrix(m), dum);
+  }
+
+  bool
+  isFinite() const
+  {
+    return (ConstGeneralMatrix(*this)).isFinite();
+  }
+
+  bool
+  isZero() const
+  {
+    return (ConstGeneralMatrix(*this)).isZero();
+  }
+
+  virtual void
+  print() const
+  {
+    ConstGeneralMatrix(*this).print();
+  }
 private:
-	void copy(const ConstGeneralMatrix& m, int ioff = 0, int joff = 0);
-	void copy(const GeneralMatrix& m, int ioff = 0, int joff = 0)
-		{copy(ConstGeneralMatrix(m), ioff, joff);}
-
-	void gemm(const char* transa, const ConstGeneralMatrix& a,
-			  const char* transb, const ConstGeneralMatrix& b,
-			  double alpha, double beta);
-	void gemm(const char* transa, const GeneralMatrix& a,
-			  const char* transb, const GeneralMatrix& b,
-			  double alpha, double beta)
-		{gemm(transa, ConstGeneralMatrix(a), transb, ConstGeneralMatrix(b),
-			  alpha, beta);}
-
-	/* this = this * op(m) (without whole copy of this) */
-	void gemm_partial_right(const char* trans, const ConstGeneralMatrix& m,
-							double alpha, double beta);
-	void gemm_partial_right(const char* trans, const GeneralMatrix& m,
-							double alpha, double beta)
-		{gemm_partial_right(trans, ConstGeneralMatrix(m), alpha, beta);}
-
-	/* this = op(m) *this (without whole copy of this) */
-	void gemm_partial_left(const char* trans, const ConstGeneralMatrix& m,
-						   double alpha, double beta);
-	void gemm_partial_left(const char* trans, const GeneralMatrix& m,
-						   double alpha, double beta)
-		{gemm_partial_left(trans, ConstGeneralMatrix(m), alpha, beta);}
-
-	/* number of rows/columns for copy used in gemm_partial_* */
-	static int md_length;
+  void copy(const ConstGeneralMatrix &m, int ioff = 0, int joff = 0);
+  void
+  copy(const GeneralMatrix &m, int ioff = 0, int joff = 0)
+  {
+    copy(ConstGeneralMatrix(m), ioff, joff);
+  }
+
+  void gemm(const char *transa, const ConstGeneralMatrix &a,
+            const char *transb, const ConstGeneralMatrix &b,
+            double alpha, double beta);
+  void
+  gemm(const char *transa, const GeneralMatrix &a,
+       const char *transb, const GeneralMatrix &b,
+       double alpha, double beta)
+  {
+    gemm(transa, ConstGeneralMatrix(a), transb, ConstGeneralMatrix(b),
+         alpha, beta);
+  }
+
+  /* this = this * op(m) (without whole copy of this) */
+  void gemm_partial_right(const char *trans, const ConstGeneralMatrix &m,
+                          double alpha, double beta);
+  void
+  gemm_partial_right(const char *trans, const GeneralMatrix &m,
+                     double alpha, double beta)
+  {
+    gemm_partial_right(trans, ConstGeneralMatrix(m), alpha, beta);
+  }
+
+  /* this = op(m) *this (without whole copy of this) */
+  void gemm_partial_left(const char *trans, const ConstGeneralMatrix &m,
+                         double alpha, double beta);
+  void
+  gemm_partial_left(const char *trans, const GeneralMatrix &m,
+                    double alpha, double beta)
+  {
+    gemm_partial_left(trans, ConstGeneralMatrix(m), alpha, beta);
+  }
+
+  /* number of rows/columns for copy used in gemm_partial_* */
+  static int md_length;
 };
 
-class SVDDecomp {
+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;
+  /** 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);
-        }
+  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);
+  void construct(const GeneralMatrix &A);
 };
 
-
-
-
 #endif /* GENERAL_MATRIX_H */
 
-
 // Local Variables:
 // mode:C++
 // End:
diff --git a/dynare++/sylv/cc/GeneralSylvester.h b/dynare++/sylv/cc/GeneralSylvester.h
index a81f5a2d4561fdf2e0f51dbedb9f7fc3d4f872c7..9e2603f48ce1580861d224b14738c7ca6cb6223a 100644
--- a/dynare++/sylv/cc/GeneralSylvester.h
+++ b/dynare++/sylv/cc/GeneralSylvester.h
@@ -10,52 +10,73 @@
 #include "SimilarityDecomp.h"
 #include "SylvesterSolver.h"
 
-class GeneralSylvester {
-	SylvParams pars;
-	SylvMemoryDriver mem_driver;
-	int order;
-	const SqSylvMatrix a;
-	const SylvMatrix b;
-	const SqSylvMatrix c;
-	SylvMatrix d;
-	bool solved;
-	SchurDecompZero* bdecomp;
-	SimilarityDecomp* cdecomp;
-	SylvesterSolver* sylv;
+class GeneralSylvester
+{
+  SylvParams pars;
+  SylvMemoryDriver mem_driver;
+  int order;
+  const SqSylvMatrix a;
+  const SylvMatrix b;
+  const SqSylvMatrix c;
+  SylvMatrix d;
+  bool solved;
+  SchurDecompZero *bdecomp;
+  SimilarityDecomp *cdecomp;
+  SylvesterSolver *sylv;
 public:
-	/* construct with my copy of d*/
-	GeneralSylvester(int ord, int n, int m, int zero_cols,
-					 const double* da, const double* db,
-					 const double* dc, const double* dd,
-					 const SylvParams& ps);
-	GeneralSylvester(int ord, int n, int m, int zero_cols,
-					 const double* da, const double* db,
-					 const double* dc, const double* dd,
-					 bool alloc_for_check = false);
-	/* construct with provided storage for d */
-	GeneralSylvester(int ord, int n, int m, int zero_cols,
-					 const double* da, const double* db,
-					 const double* dc, double* dd,
-					 bool alloc_for_check = false);
-	GeneralSylvester(int ord, int n, int m, int zero_cols,
-					 const double* da, const double* db,
-					 const double* dc, double* dd,
-					 const SylvParams& ps);
-	virtual ~GeneralSylvester();
-	int getM() const {return c.numRows();}
-	int getN() const {return a.numRows();}
-	const double* getResult() const {return d.base();}
-	const SylvParams& getParams() const {return pars;}
-	SylvParams& getParams() {return pars;}
-	void solve();
-	void check(const double* ds);
+  /* construct with my copy of d*/
+  GeneralSylvester(int ord, int n, int m, int zero_cols,
+                   const double *da, const double *db,
+                   const double *dc, const double *dd,
+                   const SylvParams &ps);
+  GeneralSylvester(int ord, int n, int m, int zero_cols,
+                   const double *da, const double *db,
+                   const double *dc, const double *dd,
+                   bool alloc_for_check = false);
+  /* construct with provided storage for d */
+  GeneralSylvester(int ord, int n, int m, int zero_cols,
+                   const double *da, const double *db,
+                   const double *dc, double *dd,
+                   bool alloc_for_check = false);
+  GeneralSylvester(int ord, int n, int m, int zero_cols,
+                   const double *da, const double *db,
+                   const double *dc, double *dd,
+                   const SylvParams &ps);
+  virtual
+  ~GeneralSylvester();
+  int
+  getM() const
+  {
+    return c.numRows();
+  }
+  int
+  getN() const
+  {
+    return a.numRows();
+  }
+  const double *
+  getResult() const
+  {
+    return d.base();
+  }
+  const SylvParams &
+  getParams() const
+  {
+    return pars;
+  }
+  SylvParams &
+  getParams()
+  {
+    return pars;
+  }
+  void solve();
+  void check(const double *ds);
 private:
-	void init();
+  void init();
 };
 
 #endif /* GENERAL_SYLVESTER_H */
 
-
 // Local Variables:
 // mode:C++
 // End:
diff --git a/dynare++/sylv/cc/IterativeSylvester.h b/dynare++/sylv/cc/IterativeSylvester.h
index cb69fbf7cab6b9ec5e03eb0a044f22255f718b43..6e30d75d0939c1054176e9f1efcb81136f9ea3eb 100644
--- a/dynare++/sylv/cc/IterativeSylvester.h
+++ b/dynare++/sylv/cc/IterativeSylvester.h
@@ -10,24 +10,30 @@
 #include "QuasiTriangular.h"
 #include "SimilarityDecomp.h"
 
-class IterativeSylvester : public SylvesterSolver {
+class IterativeSylvester : public SylvesterSolver
+{
 public:
-	IterativeSylvester(const QuasiTriangular& k, const QuasiTriangular& f)
-		: SylvesterSolver(k, f) {}
-	IterativeSylvester(const SchurDecompZero& kdecomp, const SchurDecomp& fdecomp)
-		: SylvesterSolver(kdecomp, fdecomp) {}
-	IterativeSylvester(const SchurDecompZero& kdecomp, const SimilarityDecomp& fdecomp)
-		: SylvesterSolver(kdecomp, fdecomp) {}
-	void solve(SylvParams& pars, KronVector& x) const;
+  IterativeSylvester(const QuasiTriangular &k, const QuasiTriangular &f)
+    : SylvesterSolver(k, f)
+  {
+  }
+  IterativeSylvester(const SchurDecompZero &kdecomp, const SchurDecomp &fdecomp)
+    : SylvesterSolver(kdecomp, fdecomp)
+  {
+  }
+  IterativeSylvester(const SchurDecompZero &kdecomp, const SimilarityDecomp &fdecomp)
+    : SylvesterSolver(kdecomp, fdecomp)
+  {
+  }
+  void solve(SylvParams &pars, KronVector &x) const;
 private:
-	double performFirstStep(KronVector& x) const;
-	static double performStep(const QuasiTriangular& k, const QuasiTriangular& f,
-							  KronVector& x);
+  double performFirstStep(KronVector &x) const;
+  static double performStep(const QuasiTriangular &k, const QuasiTriangular &f,
+                            KronVector &x);
 };
 
 #endif /* ITERATIVE_SYLVESTER_H */
 
-
 // Local Variables:
 // mode:C++
 // End:
diff --git a/dynare++/sylv/cc/KronUtils.h b/dynare++/sylv/cc/KronUtils.h
index 2ebeeee30cbd7abd70bf70581aa640c311be9b3f..a0d2339f065bb9fe59a6c6b007cc05387549a0a4 100644
--- a/dynare++/sylv/cc/KronUtils.h
+++ b/dynare++/sylv/cc/KronUtils.h
@@ -8,21 +8,22 @@
 #include "KronVector.h"
 #include "QuasiTriangular.h"
 
-class KronUtils {
+class KronUtils
+{
 public:
-	/* multiplies I_m\otimes..\I_m\otimes T\otimes I_m...I_m\otimes I_n
-	   with given b and returns x. T must be (m,m), number of
-	   \otimes is b.getDepth(), level is a number of I_m's between T
-	   and I_n plus 1. If level=0, then we multiply
-       \I_m\otimes ..\otimes I_m\otimes T, T is (n,n) */
-	static void multAtLevel(int level, const QuasiTriangular& t,
-							KronVector& x);
-	static void multAtLevelTrans(int level, const QuasiTriangular& t,
-								 KronVector& x);
+  /* multiplies I_m\otimes..\I_m\otimes T\otimes I_m...I_m\otimes I_n
+     with given b and returns x. T must be (m,m), number of
+     \otimes is b.getDepth(), level is a number of I_m's between T
+     and I_n plus 1. If level=0, then we multiply
+     \I_m\otimes ..\otimes I_m\otimes T, T is (n,n) */
+  static void multAtLevel(int level, const QuasiTriangular &t,
+                          KronVector &x);
+  static void multAtLevelTrans(int level, const QuasiTriangular &t,
+                               KronVector &x);
 
-	/* multiplies x=(F'\otimes F'\otimes..\otimes K)x */
-	static void multKron(const QuasiTriangular& f, const QuasiTriangular& k,
-						 KronVector& x);
+  /* multiplies x=(F'\otimes F'\otimes..\otimes K)x */
+  static void multKron(const QuasiTriangular &f, const QuasiTriangular &k,
+                       KronVector &x);
 };
 
 #endif /* KRON_UTILS_H */
diff --git a/dynare++/sylv/cc/KronVector.h b/dynare++/sylv/cc/KronVector.h
index db721c3b73b928b3ae9443d30baece834a6c6069..dc8b6fb919e4f8fe598935d0d3cae29d53a1879d 100644
--- a/dynare++/sylv/cc/KronVector.h
+++ b/dynare++/sylv/cc/KronVector.h
@@ -9,44 +9,77 @@
 
 class ConstKronVector;
 
-class KronVector : public Vector {
+class KronVector : public Vector
+{
 protected:
-	int m;
-	int n;
-	int depth;
+  int m;
+  int n;
+  int depth;
 public:
-	KronVector() : Vector((double*)0, 0), m(0), n(0), depth(0)  {}
-	KronVector(int mm, int nn, int dp); // new instance
-	KronVector(Vector& v, int mm, int nn, int dp); // conversion
-	KronVector(KronVector&, int i); // picks i-th subvector
-	KronVector(const ConstKronVector& v); // new instance and copy
-	const KronVector& operator=(KronVector& v)
-		{Vector::operator=(v); m=v.m; n=v.n; depth = v.depth; return *this;}
-	const KronVector& operator=(const KronVector& v)
-		{Vector::operator=(v); m=v.m; n=v.n; depth = v.depth; return *this;}
-	const KronVector& operator=(const ConstKronVector& v);
-	const KronVector& operator=(const Vector& v);
-	int getM() const {return m;}
-	int getN() const {return n;}
-	int getDepth() const {return depth;}
+  KronVector() : Vector((double *) 0, 0), m(0), n(0), depth(0)
+  {
+  }
+  KronVector(int mm, int nn, int dp); // new instance
+  KronVector(Vector &v, int mm, int nn, int dp); // conversion
+  KronVector(KronVector &, int i); // picks i-th subvector
+  KronVector(const ConstKronVector &v); // new instance and copy
+  const KronVector &
+  operator=(KronVector &v)
+  {
+    Vector::operator=(v); m = v.m; n = v.n; depth = v.depth; return *this;
+  }
+  const KronVector &
+  operator=(const KronVector &v)
+  {
+    Vector::operator=(v); m = v.m; n = v.n; depth = v.depth; return *this;
+  }
+  const KronVector &operator=(const ConstKronVector &v);
+  const KronVector &operator=(const Vector &v);
+  int
+  getM() const
+  {
+    return m;
+  }
+  int
+  getN() const
+  {
+    return n;
+  }
+  int
+  getDepth() const
+  {
+    return depth;
+  }
 };
 
 class ConstKronVector : public ConstVector
 {
 protected:
-	int m;
-	int n;
-	int depth;
+  int m;
+  int n;
+  int depth;
 public:
-	ConstKronVector(const KronVector& v);
-	ConstKronVector(const ConstKronVector& v);
-	ConstKronVector(const Vector& v, int mm, int nn, int dp);
-	ConstKronVector(const ConstVector& v, int mm, int nn, int dp);
-	ConstKronVector(const KronVector& v, int i);
-	ConstKronVector(const ConstKronVector& v, int i);
-	int getM() const {return m;}
-	int getN() const {return n;}
-	int getDepth() const {return depth;}
+  ConstKronVector(const KronVector &v);
+  ConstKronVector(const ConstKronVector &v);
+  ConstKronVector(const Vector &v, int mm, int nn, int dp);
+  ConstKronVector(const ConstVector &v, int mm, int nn, int dp);
+  ConstKronVector(const KronVector &v, int i);
+  ConstKronVector(const ConstKronVector &v, int i);
+  int
+  getM() const
+  {
+    return m;
+  }
+  int
+  getN() const
+  {
+    return n;
+  }
+  int
+  getDepth() const
+  {
+    return depth;
+  }
 };
 
 int power(int m, int depth);
diff --git a/dynare++/sylv/cc/QuasiTriangular.h b/dynare++/sylv/cc/QuasiTriangular.h
index ff7281141912a1c9e8d15a32e54090ad5f365573..d09fede07021373f32389ee2bb204c01943c4bae 100644
--- a/dynare++/sylv/cc/QuasiTriangular.h
+++ b/dynare++/sylv/cc/QuasiTriangular.h
@@ -15,325 +15,521 @@ using namespace std;
 
 class DiagonalBlock;
 class Diagonal;
-class DiagPair {
+class DiagPair
+{
 private:
-	double* a1;
-	double* a2;
+  double *a1;
+  double *a2;
 public:
-	DiagPair() {}
-	DiagPair(double* aa1, double* aa2) {a1 = aa1; a2 = aa2;}
-	DiagPair(const DiagPair& p) {a1 = p.a1; a2 = p.a2;}
-	const DiagPair& operator=(const DiagPair& p) {a1 = p.a1; a2 = p.a2; return *this;}
-	const DiagPair& operator=(double v) {*a1 = v; *a2 = v; return *this;}
-	const double& operator*() const {return *a1;}
-	/** here we must not define double& operator*(), since it wouldn't 
-	 rewrite both values, we use operator= for this */ 
-	friend class Diagonal;
-	friend class DiagonalBlock;
+  DiagPair()
+  {
+  }
+  DiagPair(double *aa1, double *aa2)
+  {
+    a1 = aa1; a2 = aa2;
+  }
+  DiagPair(const DiagPair &p)
+  {
+    a1 = p.a1; a2 = p.a2;
+  }
+  const DiagPair &
+  operator=(const DiagPair &p)
+  {
+    a1 = p.a1; a2 = p.a2; return *this;
+  }
+  const DiagPair &
+  operator=(double v)
+  {
+    *a1 = v; *a2 = v; return *this;
+  }
+  const double &
+  operator*() const
+  {
+    return *a1;
+  }
+  /** here we must not define double& operator*(), since it wouldn't
+      rewrite both values, we use operator= for this */
+  friend class Diagonal;
+  friend class DiagonalBlock;
 };
 
-class DiagonalBlock {
+class DiagonalBlock
+{
 private:
-	int jbar;
-	bool real;
-	DiagPair alpha;
-	double* beta1;
-	double* beta2;
+  int jbar;
+  bool real;
+  DiagPair alpha;
+  double *beta1;
+  double *beta2;
 
-	void copy(const DiagonalBlock& b) {
-		jbar = b.jbar;
-		real = b.real;
-		alpha = b.alpha;
-		beta1 = b.beta1;
-		beta2 = b.beta2;
-	}
+  void
+  copy(const DiagonalBlock &b)
+  {
+    jbar = b.jbar;
+    real = b.real;
+    alpha = b.alpha;
+    beta1 = b.beta1;
+    beta2 = b.beta2;
+  }
 
 public:
-	DiagonalBlock() {}
-	DiagonalBlock(int jb, bool r, double* a1, double* a2,
-				  double* b1, double* b2)
-		: alpha(a1, a2)
-		{
-			jbar = jb;
-			real = r;
-			beta1 = b1;
-			beta2 = b2;
-		}
-	// construct complex block
-	DiagonalBlock(int jb, double* a1, double* a2)
-		: alpha(a1, a2)
-		{
-			jbar = jb;
-			real = false;
-			beta1 = a2 - 1;
-			beta2 = a1 + 1;
-		}
-	// construct real block
-	DiagonalBlock(int jb, double* a1)
-		: alpha(a1, a1)
-		{
-			jbar = jb;
-			real = true;
-			beta1 = 0;
-			beta2 = 0;
-		}
-	DiagonalBlock(const DiagonalBlock& b)
-		{copy(b);}
-	const DiagonalBlock& operator=(const DiagonalBlock& b)
-		{copy(b); return *this;}
-	int getIndex() const
-		{return jbar;}
-	bool isReal() const
-		{return real;}
-	const DiagPair& getAlpha() const
-		{return alpha;}
-	DiagPair& getAlpha()
-		{return alpha;}
-	double& getBeta1() const
-		{return *beta1;}
-	double& getBeta2() const
-		{return *beta2;}
-	double getDeterminant() const;
-	double getSBeta() const;
-	double getSize() const;
-	void setReal();
-	// for debugging
-	void checkBlock(const double* d, int d_size);
-	friend class Diagonal;
+  DiagonalBlock()
+  {
+  }
+  DiagonalBlock(int jb, bool r, double *a1, double *a2,
+                double *b1, double *b2)
+    : alpha(a1, a2)
+  {
+    jbar = jb;
+    real = r;
+    beta1 = b1;
+    beta2 = b2;
+  }
+  // construct complex block
+  DiagonalBlock(int jb, double *a1, double *a2)
+    : alpha(a1, a2)
+  {
+    jbar = jb;
+    real = false;
+    beta1 = a2 - 1;
+    beta2 = a1 + 1;
+  }
+  // construct real block
+  DiagonalBlock(int jb, double *a1)
+    : alpha(a1, a1)
+  {
+    jbar = jb;
+    real = true;
+    beta1 = 0;
+    beta2 = 0;
+  }
+  DiagonalBlock(const DiagonalBlock &b)
+  {
+    copy(b);
+  }
+  const DiagonalBlock &
+  operator=(const DiagonalBlock &b)
+  {
+    copy(b); return *this;
+  }
+  int
+  getIndex() const
+  {
+    return jbar;
+  }
+  bool
+  isReal() const
+  {
+    return real;
+  }
+  const DiagPair &
+  getAlpha() const
+  {
+    return alpha;
+  }
+  DiagPair &
+  getAlpha()
+  {
+    return alpha;
+  }
+  double &
+  getBeta1() const
+  {
+    return *beta1;
+  }
+  double &
+  getBeta2() const
+  {
+    return *beta2;
+  }
+  double getDeterminant() const;
+  double getSBeta() const;
+  double getSize() const;
+  void setReal();
+  // for debugging
+  void checkBlock(const double *d, int d_size);
+  friend class Diagonal;
 };
 
 template <class _Tdiag, class _Tblock, class _Titer>
-struct _diag_iter {
-	typedef _diag_iter<_Tdiag, _Tblock, _Titer> _Self;
-	_Tdiag diag;
-	_Titer it;
+struct _diag_iter
+{
+  typedef _diag_iter<_Tdiag, _Tblock, _Titer> _Self;
+  _Tdiag diag;
+  _Titer it;
 public:
-	_diag_iter(_Tdiag d, _Titer iter) : diag(d), it(iter) {}
-	_Tblock operator*() const {return *it;}
-	_Self& operator++() {++it; return *this;}
-	_Self& operator--() {--it; return *this;}
-	bool operator==(const _Self& x) const {return x.it == it;}
-	bool operator!=(const _Self& x) const {return x.it != it;}
-	const _Self& operator=(const _Self& x) {it = x.it; return *this;}
-	_Titer iter() const {return it;}
+  _diag_iter(_Tdiag d, _Titer iter) : diag(d), it(iter)
+  {
+  }
+  _Tblock
+  operator*() const
+  {
+    return *it;
+  }
+  _Self &
+  operator++()
+  {
+    ++it; return *this;
+  }
+  _Self &
+  operator--()
+  {
+    --it; return *this;
+  }
+  bool
+  operator==(const _Self &x) const
+  {
+    return x.it == it;
+  }
+  bool
+  operator!=(const _Self &x) const
+  {
+    return x.it != it;
+  }
+  const _Self &
+  operator=(const _Self &x)
+  {
+    it = x.it; return *this;
+  }
+  _Titer
+  iter() const
+  {
+    return it;
+  }
 };
 
-class Diagonal {
+class Diagonal
+{
 public:
-	typedef _diag_iter<const Diagonal&, const DiagonalBlock&, list<DiagonalBlock>::const_iterator> const_diag_iter;
-	typedef _diag_iter<Diagonal&, DiagonalBlock&, list<DiagonalBlock>::iterator> diag_iter;
+  typedef _diag_iter<const Diagonal &, const DiagonalBlock &, list<DiagonalBlock>::const_iterator> const_diag_iter;
+  typedef _diag_iter<Diagonal &, DiagonalBlock &, list<DiagonalBlock>::iterator> diag_iter;
 private:
-	int num_all;
-	list<DiagonalBlock> blocks;
-	int num_real;
-	void copy(const Diagonal&);
+  int num_all;
+  list<DiagonalBlock> blocks;
+  int num_real;
+  void copy(const Diagonal &);
 public:
-	Diagonal() : num_all(0), num_real(0) {}
-	Diagonal(double* data, int d_size);
-	Diagonal(double* data, const Diagonal& d);
-	Diagonal(const Diagonal& d) {copy(d);}
-	const Diagonal& operator =(const Diagonal& d) {copy(d); return *this;}
-	virtual ~Diagonal() {}
+  Diagonal() : num_all(0), num_real(0)
+  {
+  }
+  Diagonal(double *data, int d_size);
+  Diagonal(double *data, const Diagonal &d);
+  Diagonal(const Diagonal &d)
+  {
+    copy(d);
+  }
+  const Diagonal &
+  operator=(const Diagonal &d)
+  {
+    copy(d); return *this;
+  }
+  virtual ~Diagonal()
+  {
+  }
 
-	int getNumComplex() const {return num_all - num_real;}
-	int getNumReal() const {return num_real;}
-	int getSize() const {return getNumReal() + 2*getNumComplex();}
-	int getNumBlocks() const {return num_all;}
-	void getEigenValues(Vector& eig) const;
-	void swapLogically(diag_iter it);
-	void checkConsistency(diag_iter it);
-	double getAverageSize(diag_iter start, diag_iter end);
-	diag_iter findClosestBlock(diag_iter start, diag_iter end, double a);
-	diag_iter findNextLargerBlock(diag_iter start, diag_iter end, double a);
-	void print() const;
+  int
+  getNumComplex() const
+  {
+    return num_all - num_real;
+  }
+  int
+  getNumReal() const
+  {
+    return num_real;
+  }
+  int
+  getSize() const
+  {
+    return getNumReal() + 2*getNumComplex();
+  }
+  int
+  getNumBlocks() const
+  {
+    return num_all;
+  }
+  void getEigenValues(Vector &eig) const;
+  void swapLogically(diag_iter it);
+  void checkConsistency(diag_iter it);
+  double getAverageSize(diag_iter start, diag_iter end);
+  diag_iter findClosestBlock(diag_iter start, diag_iter end, double a);
+  diag_iter findNextLargerBlock(diag_iter start, diag_iter end, double a);
+  void print() const;
 
-	diag_iter begin()
-		{return diag_iter(*this, blocks.begin());}
-	const_diag_iter begin() const
-		{return const_diag_iter(*this, blocks.begin());}
-	diag_iter end()
-		{return diag_iter(*this, blocks.end());}
-	const_diag_iter end() const
-		{return const_diag_iter(*this, blocks.end());}
+  diag_iter
+  begin()
+  {
+    return diag_iter(*this, blocks.begin());
+  }
+  const_diag_iter
+  begin() const
+  {
+    return const_diag_iter(*this, blocks.begin());
+  }
+  diag_iter
+  end()
+  {
+    return diag_iter(*this, blocks.end());
+  }
+  const_diag_iter
+  end() const
+  {
+    return const_diag_iter(*this, blocks.end());
+  }
 
-	/* redefine pointers as data start at p */
-	void changeBase(double* p);
+  /* redefine pointers as data start at p */
+  void changeBase(double *p);
 private:
-	static double EPS;
-	static int getNumComplex(const double* data, int d_size);
-	static bool isZero(double p);
+  static double EPS;
+  static int getNumComplex(const double *data, int d_size);
+  static bool isZero(double p);
 };
 
 template <class _TRef, class _TPtr>
-struct _matrix_iter {
-	typedef _matrix_iter<_TRef, _TPtr> _Self;
-	int d_size;
-	bool real;
-	_TPtr ptr;
+struct _matrix_iter
+{
+  typedef _matrix_iter<_TRef, _TPtr> _Self;
+  int d_size;
+  bool real;
+  _TPtr ptr;
 public:
-	_matrix_iter(_TPtr base, int ds, bool r)
-		{ptr = base; d_size = ds; real = r;}
-	virtual ~_matrix_iter() {}
-	const _Self& operator=(const _Self& it)
-		{ptr = it.ptr; d_size = it.d_size; real = it.real; return *this;}
-	bool operator==(const _Self& it) const
-		{return ptr == it.ptr;}
-	bool operator!=(const _Self& it) const
-		{return ptr != it.ptr;}
-	_TRef operator*() const
-		{return *ptr;}
-	_TRef a() const
-		{return *ptr;}
-	virtual _Self& operator++() =0;
+  _matrix_iter(_TPtr base, int ds, bool r)
+  {
+    ptr = base; d_size = ds; real = r;
+  }
+  virtual ~_matrix_iter()
+  {
+  }
+  const _Self &
+  operator=(const _Self &it)
+  {
+    ptr = it.ptr; d_size = it.d_size; real = it.real; return *this;
+  }
+  bool
+  operator==(const _Self &it) const
+  {
+    return ptr == it.ptr;
+  }
+  bool
+  operator!=(const _Self &it) const
+  {
+    return ptr != it.ptr;
+  }
+  _TRef
+  operator*() const
+  {
+    return *ptr;
+  }
+  _TRef
+  a() const
+  {
+    return *ptr;
+  }
+  virtual _Self &operator++() = 0;
 };
 
 template <class _TRef, class _TPtr>
-class _column_iter : public _matrix_iter<_TRef, _TPtr> {
-	typedef _matrix_iter<_TRef, _TPtr> _Tparent; 
-	typedef _column_iter<_TRef, _TPtr> _Self;
-	int row;
+class _column_iter : public _matrix_iter<_TRef, _TPtr>
+{
+  typedef _matrix_iter<_TRef, _TPtr> _Tparent;
+  typedef _column_iter<_TRef, _TPtr> _Self;
+  int row;
 public:
-	_column_iter(_TPtr base, int ds, bool r, int rw)
-		: _matrix_iter<_TRef, _TPtr>(base, ds, r), row(rw) {};
-	_Self& operator++()
-		{_Tparent::ptr++; row++; return *this;}
-	_TRef b() const
-		{
-			if (_Tparent::real) {
-				return *(_Tparent::ptr);
-			} else {
-				return *(_Tparent::ptr+_Tparent::d_size);
-			}
-		}
-	int getRow() const {return row;}
+  _column_iter(_TPtr base, int ds, bool r, int rw)
+    : _matrix_iter<_TRef, _TPtr>(base, ds, r), row(rw)
+  {
+  };
+  _Self &
+  operator++()
+  {
+    _Tparent::ptr++; row++; return *this;
+  }
+  _TRef
+  b() const
+  {
+    if (_Tparent::real)
+      {
+        return *(_Tparent::ptr);
+      }
+    else
+      {
+        return *(_Tparent::ptr+_Tparent::d_size);
+      }
+  }
+  int
+  getRow() const
+  {
+    return row;
+  }
 };
 
 template <class _TRef, class _TPtr>
-class _row_iter : public _matrix_iter<_TRef, _TPtr> {
-	typedef _matrix_iter<_TRef, _TPtr> _Tparent; 
-	typedef _row_iter<_TRef, _TPtr> _Self;
-	int col;
+class _row_iter : public _matrix_iter<_TRef, _TPtr>
+{
+  typedef _matrix_iter<_TRef, _TPtr> _Tparent;
+  typedef _row_iter<_TRef, _TPtr> _Self;
+  int col;
 public:
-	_row_iter(_TPtr base, int ds, bool r, int cl)
-		: _matrix_iter<_TRef, _TPtr>(base, ds, r), col(cl) {};
-	_Self& operator++()
-		{_Tparent::ptr += _Tparent::d_size; col++; return *this;}
-	virtual _TRef b() const
-		{
-			if (_Tparent::real) {
-				return *(_Tparent::ptr);
-			}else {
-				return *(_Tparent::ptr+1);
-			}
-		}
-	int getCol() const {return col;}
+  _row_iter(_TPtr base, int ds, bool r, int cl)
+    : _matrix_iter<_TRef, _TPtr>(base, ds, r), col(cl)
+  {
+  };
+  _Self &
+  operator++()
+  {
+    _Tparent::ptr += _Tparent::d_size; col++; return *this;
+  }
+  virtual _TRef
+  b() const
+  {
+    if (_Tparent::real)
+      {
+        return *(_Tparent::ptr);
+      }
+    else
+      {
+        return *(_Tparent::ptr+1);
+      }
+  }
+  int
+  getCol() const
+  {
+    return col;
+  }
 };
 
 class SchurDecomp;
 class SchurDecompZero;
 
-class QuasiTriangular : public SqSylvMatrix {
+class QuasiTriangular : public SqSylvMatrix
+{
 public:
-	typedef _column_iter<const double&, const double*> const_col_iter;
-	typedef _column_iter<double&, double*> col_iter;
-	typedef _row_iter<const double&, const double*> const_row_iter;
-	typedef _row_iter<double&, double*> row_iter;	
-	typedef Diagonal::const_diag_iter const_diag_iter;
-	typedef Diagonal::diag_iter diag_iter;
+  typedef _column_iter<const double &, const double *> const_col_iter;
+  typedef _column_iter<double &, double *> col_iter;
+  typedef _row_iter<const double &, const double *> const_row_iter;
+  typedef _row_iter<double &, double *> row_iter;
+  typedef Diagonal::const_diag_iter const_diag_iter;
+  typedef Diagonal::diag_iter diag_iter;
 protected:
-	Diagonal diagonal;
+  Diagonal diagonal;
 public:
-	QuasiTriangular(const double* d, int d_size);
-	QuasiTriangular(double r, const QuasiTriangular& t);
-	QuasiTriangular(double r, const QuasiTriangular& t,
-					double rr, const QuasiTriangular& tt);
-	QuasiTriangular(int p, const QuasiTriangular& t);
-	QuasiTriangular(const SchurDecomp& decomp);
-	QuasiTriangular(const SchurDecompZero& decomp);
-	QuasiTriangular(const QuasiTriangular& t);
-	virtual ~QuasiTriangular();
-	const Diagonal& getDiagonal() const {return diagonal;}
-	int getNumOffdiagonal() const;
-	void swapDiagLogically(diag_iter it);
-	void checkDiagConsistency(diag_iter it);
-	double getAverageDiagSize(diag_iter start, diag_iter end);
-	diag_iter findClosestDiagBlock(diag_iter start, diag_iter end, double a);
-	diag_iter findNextLargerBlock(diag_iter start, diag_iter end, double a);
+  QuasiTriangular(const double *d, int d_size);
+  QuasiTriangular(double r, const QuasiTriangular &t);
+  QuasiTriangular(double r, const QuasiTriangular &t,
+                  double rr, const QuasiTriangular &tt);
+  QuasiTriangular(int p, const QuasiTriangular &t);
+  QuasiTriangular(const SchurDecomp &decomp);
+  QuasiTriangular(const SchurDecompZero &decomp);
+  QuasiTriangular(const QuasiTriangular &t);
+  virtual
+  ~QuasiTriangular();
+  const Diagonal &
+  getDiagonal() const
+  {
+    return diagonal;
+  }
+  int getNumOffdiagonal() const;
+  void swapDiagLogically(diag_iter it);
+  void checkDiagConsistency(diag_iter it);
+  double getAverageDiagSize(diag_iter start, diag_iter end);
+  diag_iter findClosestDiagBlock(diag_iter start, diag_iter end, double a);
+  diag_iter findNextLargerBlock(diag_iter start, diag_iter end, double a);
 
+  /* (I+T)y = x, y-->x  */
+  virtual void solvePre(Vector &x, double &eig_min);
+  /* (I+T')y = x, y-->x */
+  virtual void solvePreTrans(Vector &x, double &eig_min);
+  /* (I+T)x = b */
+  virtual void solve(Vector &x, const ConstVector &b, double &eig_min);
+  /* (I+T')x = b */
+  virtual void solveTrans(Vector &x, const ConstVector &b, double &eig_min);
+  /* x = Tb */
+  virtual void multVec(Vector &x, const ConstVector &b) const;
+  /* x = T'b */
+  virtual void multVecTrans(Vector &x, const ConstVector &b) const;
+  /* x = x + Tb */
+  virtual void multaVec(Vector &x, const ConstVector &b) const;
+  /* x = x + T'b */
+  virtual void multaVecTrans(Vector &x, const ConstVector &b) const;
+  /* x = (T\otimes I)x */
+  virtual void multKron(KronVector &x) const;
+  /* x = (T'\otimes I)x */
+  virtual void multKronTrans(KronVector &x) const;
+  /* A = T*A */
+  virtual void multLeftOther(GeneralMatrix &a) const;
+  /* A = T'*A */
+  virtual void multLeftOtherTrans(GeneralMatrix &a) const;
 
-	/* (I+T)y = x, y-->x  */
-	virtual void solvePre(Vector& x, double& eig_min);
-	/* (I+T')y = x, y-->x */
-	virtual void solvePreTrans(Vector& x, double& eig_min);
-	/* (I+T)x = b */
-	virtual void solve(Vector& x, const ConstVector& b, double& eig_min);
-	/* (I+T')x = b */
-	virtual void solveTrans(Vector& x, const ConstVector& b, double& eig_min);
-	/* x = Tb */
-	virtual void multVec(Vector& x, const ConstVector& b) const;
-	/* x = T'b */
-	virtual void multVecTrans(Vector& x, const ConstVector& b) const;
-	/* x = x + Tb */
-	virtual void multaVec(Vector& x, const ConstVector& b) const;
-	/* x = x + T'b */
-	virtual void multaVecTrans(Vector& x, const ConstVector& b) const;
-	/* x = (T\otimes I)x */
-	virtual void multKron(KronVector& x) const;
-	/* x = (T'\otimes I)x */
-	virtual void multKronTrans(KronVector& x) const;
-	/* A = T*A */
-	virtual void multLeftOther(GeneralMatrix& a) const;
-	/* A = T'*A */
-	virtual void multLeftOtherTrans(GeneralMatrix& a) const;
+  const_diag_iter
+  diag_begin() const
+  {
+    return diagonal.begin();
+  }
+  diag_iter
+  diag_begin()
+  {
+    return diagonal.begin();
+  }
+  const_diag_iter
+  diag_end() const
+  {
+    return diagonal.end();
+  }
+  diag_iter
+  diag_end()
+  {
+    return diagonal.end();
+  }
 
-	const_diag_iter diag_begin() const
-		{return diagonal.begin();}
-	diag_iter diag_begin()
-		{return diagonal.begin();}
-	const_diag_iter diag_end() const 
-		{return diagonal.end();}
-	diag_iter diag_end()
-		{return diagonal.end();}
+  /* iterators for off diagonal elements */
+  virtual const_col_iter col_begin(const DiagonalBlock &b) const;
+  virtual col_iter col_begin(const DiagonalBlock &b);
+  virtual const_row_iter row_begin(const DiagonalBlock &b) const;
+  virtual row_iter row_begin(const DiagonalBlock &b);
+  virtual const_col_iter col_end(const DiagonalBlock &b) const;
+  virtual col_iter col_end(const DiagonalBlock &b);
+  virtual const_row_iter row_end(const DiagonalBlock &b) const;
+  virtual row_iter row_end(const DiagonalBlock &b);
 
-	/* iterators for off diagonal elements */
-	virtual const_col_iter col_begin(const DiagonalBlock& b) const;
-	virtual col_iter col_begin(const DiagonalBlock& b);
-	virtual const_row_iter row_begin(const DiagonalBlock& b) const;
-	virtual row_iter row_begin(const DiagonalBlock& b);
-	virtual const_col_iter col_end(const DiagonalBlock& b) const;
-	virtual col_iter col_end(const DiagonalBlock& b);
-	virtual const_row_iter row_end(const DiagonalBlock& b) const;
-	virtual row_iter row_end(const DiagonalBlock& b);
-
-	/* clone */
-	virtual QuasiTriangular* clone() const
-		{return new QuasiTriangular(*this);}
-	virtual QuasiTriangular* clone(int p, const QuasiTriangular& t) const
-		{return new QuasiTriangular(p, t);}
-	virtual QuasiTriangular* clone(double r) const
-		{return new QuasiTriangular(r, *this);}
-	virtual QuasiTriangular* clone(double r, double rr, const QuasiTriangular& tt) const
-		{return new QuasiTriangular(r, *this, rr, tt);}
+  /* clone */
+  virtual QuasiTriangular *
+  clone() const
+  {
+    return new QuasiTriangular(*this);
+  }
+  virtual QuasiTriangular *
+  clone(int p, const QuasiTriangular &t) const
+  {
+    return new QuasiTriangular(p, t);
+  }
+  virtual QuasiTriangular *
+  clone(double r) const
+  {
+    return new QuasiTriangular(r, *this);
+  }
+  virtual QuasiTriangular *
+  clone(double r, double rr, const QuasiTriangular &tt) const
+  {
+    return new QuasiTriangular(r, *this, rr, tt);
+  }
 protected:
-	void setMatrix(double r, const QuasiTriangular& t);
-	void addMatrix(double r, const QuasiTriangular& t);
+  void setMatrix(double r, const QuasiTriangular &t);
+  void addMatrix(double r, const QuasiTriangular &t);
 private:
-	void addUnit();
-	/* x = x + (T\otimes I)b */
-	void multaKron(KronVector& x, const ConstKronVector& b) const;
-	/* x = x + (T'\otimes I)b */
-	void multaKronTrans(KronVector& x, const ConstKronVector& b) const;
-	/* implementation via iterators, useful for large matrices */
-	void setMatrixViaIter(double r, const QuasiTriangular& t);
-	void addMatrixViaIter(double r, const QuasiTriangular& t);	
-	/* hide noneffective implementations of parents */
-	void multsVec(Vector& x, const ConstVector& d) const;
-	void multsVecTrans(Vector& x, const ConstVector& d) const;
+  void addUnit();
+  /* x = x + (T\otimes I)b */
+  void multaKron(KronVector &x, const ConstKronVector &b) const;
+  /* x = x + (T'\otimes I)b */
+  void multaKronTrans(KronVector &x, const ConstKronVector &b) const;
+  /* implementation via iterators, useful for large matrices */
+  void setMatrixViaIter(double r, const QuasiTriangular &t);
+  void addMatrixViaIter(double r, const QuasiTriangular &t);
+  /* hide noneffective implementations of parents */
+  void multsVec(Vector &x, const ConstVector &d) const;
+  void multsVecTrans(Vector &x, const ConstVector &d) const;
 };
 
 #endif /* QUASI_TRIANGULAR_H */
 
-
 // Local Variables:
 // mode:C++
 // End:
diff --git a/dynare++/sylv/cc/QuasiTriangularZero.h b/dynare++/sylv/cc/QuasiTriangularZero.h
index 6396eed18e00d7582162336fcc9b85ab31d7505d..243c02123f5ee6fcf05c9d6dc106c6fbf77b8fc7 100644
--- a/dynare++/sylv/cc/QuasiTriangularZero.h
+++ b/dynare++/sylv/cc/QuasiTriangularZero.h
@@ -8,37 +8,50 @@
 #include "QuasiTriangular.h"
 #include "GeneralMatrix.h"
 
-class QuasiTriangularZero : public QuasiTriangular {
-	int nz; // number of zero columns
-	GeneralMatrix ru; // data in right upper part (nz,d_size)
+class QuasiTriangularZero : public QuasiTriangular
+{
+  int nz; // number of zero columns
+  GeneralMatrix ru; // data in right upper part (nz,d_size)
 public:
-	QuasiTriangularZero(int num_zeros, const double* d, int d_size);
-	QuasiTriangularZero(double r, const QuasiTriangularZero& t);
-	QuasiTriangularZero(double r, const QuasiTriangularZero& t,
-						double rr, const QuasiTriangularZero& tt);
-	QuasiTriangularZero(int p, const QuasiTriangularZero& t);
-	QuasiTriangularZero(const QuasiTriangular& t);
-	QuasiTriangularZero(const SchurDecompZero& decomp);
-	~QuasiTriangularZero();
-	void solvePre(Vector& x, double& eig_min);
-	void solvePreTrans(Vector& x, double& eig_min);
-	void multVec(Vector& x, const ConstVector& b) const;
-	void multVecTrans(Vector& x, const ConstVector& b) const;
-	void multaVec(Vector& x, const ConstVector& b) const;
-	void multaVecTrans(Vector& x, const ConstVector& b) const;
-	void multKron(KronVector& x) const;
-	void multKronTrans(KronVector& x) const;
-	void multLeftOther(GeneralMatrix& a) const;
-	/* clone */
-	virtual QuasiTriangular* clone() const
-		{return new QuasiTriangularZero(*this);}
-	virtual QuasiTriangular* clone(int p, const QuasiTriangular& t) const
-		{return new QuasiTriangularZero(p, (const QuasiTriangularZero&)t);}
-	virtual QuasiTriangular* clone(double r) const
-		{return new QuasiTriangularZero(r, *this);}
-	virtual QuasiTriangular* clone(double r, double rr, const QuasiTriangular& tt) const
-		{return new QuasiTriangularZero(r, *this, rr, (const QuasiTriangularZero&)tt);}
-	void print() const;
+  QuasiTriangularZero(int num_zeros, const double *d, int d_size);
+  QuasiTriangularZero(double r, const QuasiTriangularZero &t);
+  QuasiTriangularZero(double r, const QuasiTriangularZero &t,
+                      double rr, const QuasiTriangularZero &tt);
+  QuasiTriangularZero(int p, const QuasiTriangularZero &t);
+  QuasiTriangularZero(const QuasiTriangular &t);
+  QuasiTriangularZero(const SchurDecompZero &decomp);
+  ~QuasiTriangularZero();
+  void solvePre(Vector &x, double &eig_min);
+  void solvePreTrans(Vector &x, double &eig_min);
+  void multVec(Vector &x, const ConstVector &b) const;
+  void multVecTrans(Vector &x, const ConstVector &b) const;
+  void multaVec(Vector &x, const ConstVector &b) const;
+  void multaVecTrans(Vector &x, const ConstVector &b) const;
+  void multKron(KronVector &x) const;
+  void multKronTrans(KronVector &x) const;
+  void multLeftOther(GeneralMatrix &a) const;
+  /* clone */
+  virtual QuasiTriangular *
+  clone() const
+  {
+    return new QuasiTriangularZero(*this);
+  }
+  virtual QuasiTriangular *
+  clone(int p, const QuasiTriangular &t) const
+  {
+    return new QuasiTriangularZero(p, (const QuasiTriangularZero &) t);
+  }
+  virtual QuasiTriangular *
+  clone(double r) const
+  {
+    return new QuasiTriangularZero(r, *this);
+  }
+  virtual QuasiTriangular *
+  clone(double r, double rr, const QuasiTriangular &tt) const
+  {
+    return new QuasiTriangularZero(r, *this, rr, (const QuasiTriangularZero &) tt);
+  }
+  void print() const;
 };
 
 #endif /* QUASI_TRIANGULAR_ZERO_H */
diff --git a/dynare++/sylv/cc/SchurDecomp.h b/dynare++/sylv/cc/SchurDecomp.h
index 644e5d5c5c1233781c6a03404539dddebffd340f..9e83c92219269003bc6f552ec8d8bff0ebd1649e 100644
--- a/dynare++/sylv/cc/SchurDecomp.h
+++ b/dynare++/sylv/cc/SchurDecomp.h
@@ -9,35 +9,61 @@
 #include "QuasiTriangular.h"
 
 class QuasiTriangular;
-class SchurDecomp {
-	bool q_destroy;
-	SqSylvMatrix* q;
-	bool t_destroy;
-	QuasiTriangular* t;
+class SchurDecomp
+{
+  bool q_destroy;
+  SqSylvMatrix *q;
+  bool t_destroy;
+  QuasiTriangular *t;
 public:
-	SchurDecomp(const SqSylvMatrix& m);
-	SchurDecomp(const QuasiTriangular& tr);
-	SchurDecomp(QuasiTriangular& tr);
-	const SqSylvMatrix& getQ() const {return *q;}
-	const QuasiTriangular& getT() const {return *t;}
-	SqSylvMatrix& getQ() {return *q;}
-	QuasiTriangular& getT() {return *t;}
-	virtual int getDim() const;
-	virtual ~SchurDecomp();
+  SchurDecomp(const SqSylvMatrix &m);
+  SchurDecomp(const QuasiTriangular &tr);
+  SchurDecomp(QuasiTriangular &tr);
+  const SqSylvMatrix &
+  getQ() const
+  {
+    return *q;
+  }
+  const QuasiTriangular &
+  getT() const
+  {
+    return *t;
+  }
+  SqSylvMatrix &
+  getQ()
+  {
+    return *q;
+  }
+  QuasiTriangular &
+  getT()
+  {
+    return *t;
+  }
+  virtual int getDim() const;
+  virtual
+  ~SchurDecomp();
 };
 
-class SchurDecompZero : public SchurDecomp {
-	GeneralMatrix ru; /* right upper matrix */
+class SchurDecompZero : public SchurDecomp
+{
+  GeneralMatrix ru; /* right upper matrix */
 public:
-	SchurDecompZero(const GeneralMatrix& m);
-	const GeneralMatrix& getRU() const {return ru;}
-	int getDim() const;
-	int getZeroCols() const {return ru.numRows();}
+  SchurDecompZero(const GeneralMatrix &m);
+  const GeneralMatrix &
+  getRU() const
+  {
+    return ru;
+  }
+  int getDim() const;
+  int
+  getZeroCols() const
+  {
+    return ru.numRows();
+  }
 };
 
 #endif /* SCHUR_DECOMP_H */
 
-
 // Local Variables:
 // mode:C++
 // End:
diff --git a/dynare++/sylv/cc/SchurDecompEig.h b/dynare++/sylv/cc/SchurDecompEig.h
index 0e0da38d5c83ff2c455528ecb2258f9415f52aac..567f457831acd4a8f22fac71c9e575b89b675f37 100644
--- a/dynare++/sylv/cc/SchurDecompEig.h
+++ b/dynare++/sylv/cc/SchurDecompEig.h
@@ -10,22 +10,27 @@
 #include "SchurDecomp.h"
 #include "QuasiTriangular.h"
 
-class SchurDecompEig : public SchurDecomp {
+class SchurDecompEig : public SchurDecomp
+{
 public:
-	typedef QuasiTriangular::diag_iter diag_iter;
-	SchurDecompEig(const SqSylvMatrix& m) : SchurDecomp(m) {}
-	SchurDecompEig(const QuasiTriangular& tr) : SchurDecomp(tr) {};
-	SchurDecompEig(QuasiTriangular& tr) : SchurDecomp(tr) {}
-	diag_iter bubbleEigen(diag_iter from, diag_iter to);
-	void orderEigen();
+  typedef QuasiTriangular::diag_iter diag_iter;
+  SchurDecompEig(const SqSylvMatrix &m) : SchurDecomp(m)
+  {
+  }
+  SchurDecompEig(const QuasiTriangular &tr) : SchurDecomp(tr)
+  {
+  };
+  SchurDecompEig(QuasiTriangular &tr) : SchurDecomp(tr)
+  {
+  }
+  diag_iter bubbleEigen(diag_iter from, diag_iter to);
+  void orderEigen();
 protected:
-	bool tryToSwap(diag_iter& it, diag_iter& itadd);
+  bool tryToSwap(diag_iter &it, diag_iter &itadd);
 };
 
 #endif /* SCHUR_DECOMP_EIG_H */
 
-
 // Local Variables:
 // mode:C++
 // End:
-
diff --git a/dynare++/sylv/cc/SimilarityDecomp.h b/dynare++/sylv/cc/SimilarityDecomp.h
index 14f79297a21656827f7173b68fc92954bf4c1a2d..107da24e0cc2dfa43ea2b12d78a818e5938ab868 100644
--- a/dynare++/sylv/cc/SimilarityDecomp.h
+++ b/dynare++/sylv/cc/SimilarityDecomp.h
@@ -9,33 +9,43 @@
 #include "BlockDiagonal.h"
 #include "SylvParams.h"
 
-class SimilarityDecomp {
-	SqSylvMatrix* q;
-	BlockDiagonal* b;
-	SqSylvMatrix* invq;
-	typedef BlockDiagonal::diag_iter diag_iter;
+class SimilarityDecomp
+{
+  SqSylvMatrix *q;
+  BlockDiagonal *b;
+  SqSylvMatrix *invq;
+  typedef BlockDiagonal::diag_iter diag_iter;
 public:
-	SimilarityDecomp(const double* d, int d_size, double log10norm = 3.0);
-	virtual ~SimilarityDecomp();
-	const SqSylvMatrix& getQ() const
-		{return *q;}
-	const SqSylvMatrix& getInvQ() const
-		{return *invq;}
-	const BlockDiagonal& getB() const
-		{return *b;}
-	void check(SylvParams& pars, const GeneralMatrix& m) const;
-	void infoToPars(SylvParams& pars) const;
+  SimilarityDecomp(const double *d, int d_size, double log10norm = 3.0);
+  virtual
+  ~SimilarityDecomp();
+  const SqSylvMatrix &
+  getQ() const
+  {
+    return *q;
+  }
+  const SqSylvMatrix &
+  getInvQ() const
+  {
+    return *invq;
+  }
+  const BlockDiagonal &
+  getB() const
+  {
+    return *b;
+  }
+  void check(SylvParams &pars, const GeneralMatrix &m) const;
+  void infoToPars(SylvParams &pars) const;
 protected:
-	void getXDim(diag_iter start, diag_iter end, int& rows, int& cols) const;
-	bool solveX(diag_iter start, diag_iter end, GeneralMatrix& X, double norm) const;
-	void updateTransform(diag_iter start, diag_iter end, GeneralMatrix& X);
-	void bringGuiltyBlock(diag_iter start, diag_iter& end);
-	void diagonalize(double norm);
+  void getXDim(diag_iter start, diag_iter end, int &rows, int &cols) const;
+  bool solveX(diag_iter start, diag_iter end, GeneralMatrix &X, double norm) const;
+  void updateTransform(diag_iter start, diag_iter end, GeneralMatrix &X);
+  void bringGuiltyBlock(diag_iter start, diag_iter &end);
+  void diagonalize(double norm);
 };
 
 #endif /* SIMILARITY_DECOMP_H */
 
-
 // Local Variables:
 // mode:C++
 // End:
diff --git a/dynare++/sylv/cc/SylvException.h b/dynare++/sylv/cc/SylvException.h
index f3c22338a673772f3dfb531d6b369a45e8597671..5beb212a370a7d9f20b73f1f5c2b0c010eba6977 100644
--- a/dynare++/sylv/cc/SylvException.h
+++ b/dynare++/sylv/cc/SylvException.h
@@ -7,33 +7,34 @@
 
 #include "SylvMemory.h"
 
-
-class SylvException : public MallocAllocator {
+class SylvException : public MallocAllocator
+{
 protected:
-	char file[50];
-	int line;
-	const SylvException* source;
+  char file[50];
+  int line;
+  const SylvException *source;
 public:
-	SylvException(const char* f, int l, const SylvException* s);
-	virtual ~SylvException();
-	virtual int printMessage(char* str, int maxlen) const;
-	void printMessage() const;
+  SylvException(const char *f, int l, const SylvException *s);
+  virtual
+  ~SylvException();
+  virtual int printMessage(char *str, int maxlen) const;
+  void printMessage() const;
 };
 
-class SylvExceptionMessage : public SylvException {
-	char message[500];
+class SylvExceptionMessage : public SylvException
+{
+  char message[500];
 public:
-	SylvExceptionMessage(const char* f, int l, const char* mes);
-	virtual int printMessage(char* str, int maxlen) const;
+  SylvExceptionMessage(const char *f, int l, const char *mes);
+  virtual int printMessage(char *str, int maxlen) const;
 };
 
 // define macros:
 #define SYLV_EXCEPTION(exc) (SylvException(__FILE__, __LINE__, exc))
-#define SYLV_MES_EXCEPTION(mes) (SylvExceptionMessage(__FILE__, __LINE__, mes)) 
+#define SYLV_MES_EXCEPTION(mes) (SylvExceptionMessage(__FILE__, __LINE__, mes))
 
 #endif /* SYLV_EXCEPTION_H */
 
-
 // Local Variables:
 // mode:C++
 // End:
diff --git a/dynare++/sylv/cc/SylvMatrix.h b/dynare++/sylv/cc/SylvMatrix.h
index 99ab504ae0f62e3aa49122cb0bd4aa02594dfe51..063e6b30b75ba3e5a037a62bc5a895eb01162a57 100644
--- a/dynare++/sylv/cc/SylvMatrix.h
+++ b/dynare++/sylv/cc/SylvMatrix.h
@@ -10,72 +10,100 @@
 
 class SqSylvMatrix;
 
-class SylvMatrix : public GeneralMatrix {
+class SylvMatrix : public GeneralMatrix
+{
 public:
-	SylvMatrix(int m, int n)
-		: GeneralMatrix(m,n) {}
-	SylvMatrix(const double* d, int m, int n)
-		: GeneralMatrix(d, m, n) {}
-	SylvMatrix(double* d, int m, int n)
-		: GeneralMatrix(d, m, n) {}
-	SylvMatrix(const GeneralMatrix& m)
-		: GeneralMatrix(m) {}
-	SylvMatrix(const GeneralMatrix& m, int i, int j, int nrows, int ncols)
-		: GeneralMatrix(m, i, j, nrows, ncols) {}
-	SylvMatrix(GeneralMatrix& m, int i, int j, int nrows, int ncols)
-		: GeneralMatrix(m, i, j, nrows, ncols) {}
-	SylvMatrix(const GeneralMatrix& a, const GeneralMatrix& b)
-		: GeneralMatrix(a, b) {}
+  SylvMatrix(int m, int n)
+    : GeneralMatrix(m, n)
+  {
+  }
+  SylvMatrix(const double *d, int m, int n)
+    : GeneralMatrix(d, m, n)
+  {
+  }
+  SylvMatrix(double *d, int m, int n)
+    : GeneralMatrix(d, m, n)
+  {
+  }
+  SylvMatrix(const GeneralMatrix &m)
+    : GeneralMatrix(m)
+  {
+  }
+  SylvMatrix(const GeneralMatrix &m, int i, int j, int nrows, int ncols)
+    : GeneralMatrix(m, i, j, nrows, ncols)
+  {
+  }
+  SylvMatrix(GeneralMatrix &m, int i, int j, int nrows, int ncols)
+    : GeneralMatrix(m, i, j, nrows, ncols)
+  {
+  }
+  SylvMatrix(const GeneralMatrix &a, const GeneralMatrix &b)
+    : GeneralMatrix(a, b)
+  {
+  }
 
-	/* this = |I 0|* this
-	          |0 m|         */
-	void multLeftI(const SqSylvMatrix& m);
-	/* this = |I  0|* this
-	          |0 m'|         */
-	void multLeftITrans(const SqSylvMatrix& m);
-	/* this = |0 a|*b, so that |0 a| is square */
-	void multLeft(int zero_cols, const GeneralMatrix& a, const GeneralMatrix& b);
-	/* this = this * (m\otimes m..\otimes m) */
-	void multRightKron(const SqSylvMatrix& m, int order);
-	/* this = this * (m'\otimes m'..\otimes m') */
-	void multRightKronTrans(const SqSylvMatrix& m, int order);
-	/* this = P*this, x = P*x, where P is gauss transformation setting
-	 * a given element to zero */
-	void eliminateLeft(int row, int col, Vector& x);
-	/* this = this*P, x = P'*x, where P is gauss transformation setting
-	 * a given element to zero */
-	void eliminateRight(int row, int col, Vector& x);
+  /* this = |I 0|* this
+     |0 m|         */
+  void multLeftI(const SqSylvMatrix &m);
+  /* this = |I  0|* this
+     |0 m'|         */
+  void multLeftITrans(const SqSylvMatrix &m);
+  /* this = |0 a|*b, so that |0 a| is square */
+  void multLeft(int zero_cols, const GeneralMatrix &a, const GeneralMatrix &b);
+  /* this = this * (m\otimes m..\otimes m) */
+  void multRightKron(const SqSylvMatrix &m, int order);
+  /* this = this * (m'\otimes m'..\otimes m') */
+  void multRightKronTrans(const SqSylvMatrix &m, int order);
+  /* this = P*this, x = P*x, where P is gauss transformation setting
+   * a given element to zero */
+  void eliminateLeft(int row, int col, Vector &x);
+  /* this = this*P, x = P'*x, where P is gauss transformation setting
+   * a given element to zero */
+  void eliminateRight(int row, int col, Vector &x);
 };
 
-
-class SqSylvMatrix : public SylvMatrix {
+class SqSylvMatrix : public SylvMatrix
+{
 public:
-	SqSylvMatrix(int m) : SylvMatrix(m, m) {}
-	SqSylvMatrix(const double* d, int m) : SylvMatrix(d, m, m) {}
-	SqSylvMatrix(double* d, int m) : SylvMatrix(d, m, m) {}
-	SqSylvMatrix(const SqSylvMatrix& m) : SylvMatrix(m) {}
-	SqSylvMatrix(const GeneralMatrix& m, int i, int j, int nrows)
-		: SylvMatrix(m, i, j, nrows, nrows) {} 
-	SqSylvMatrix(GeneralMatrix& m, int i, int j, int nrows)
-		: SylvMatrix(m, i, j, nrows, nrows) {} 
-	SqSylvMatrix(const GeneralMatrix& a, const GeneralMatrix& b);
-	const SqSylvMatrix& operator=(const SqSylvMatrix& m)
-		{GeneralMatrix::operator=(m); return *this;}
-	/* x = (this \otimes this..\otimes this)*d */
-	void multVecKron(KronVector& x, const KronVector& d) const;
-	/* x = (this' \otimes this'..\otimes this')*d */
-	void multVecKronTrans(KronVector& x, const KronVector& d) const;
-	/* a = inv(this)*a, b=inv(this)*b */
-	void multInvLeft2(GeneralMatrix& a, GeneralMatrix& b,
-					  double& rcond1, double& rcondinf) const;
-	/* this = I */
-	void setUnit();
+  SqSylvMatrix(int m) : SylvMatrix(m, m)
+  {
+  }
+  SqSylvMatrix(const double *d, int m) : SylvMatrix(d, m, m)
+  {
+  }
+  SqSylvMatrix(double *d, int m) : SylvMatrix(d, m, m)
+  {
+  }
+  SqSylvMatrix(const SqSylvMatrix &m) : SylvMatrix(m)
+  {
+  }
+  SqSylvMatrix(const GeneralMatrix &m, int i, int j, int nrows)
+    : SylvMatrix(m, i, j, nrows, nrows)
+  {
+  }
+  SqSylvMatrix(GeneralMatrix &m, int i, int j, int nrows)
+    : SylvMatrix(m, i, j, nrows, nrows)
+  {
+  }
+  SqSylvMatrix(const GeneralMatrix &a, const GeneralMatrix &b);
+  const SqSylvMatrix &
+  operator=(const SqSylvMatrix &m)
+  {
+    GeneralMatrix::operator=(m); return *this;
+  }
+  /* x = (this \otimes this..\otimes this)*d */
+  void multVecKron(KronVector &x, const KronVector &d) const;
+  /* x = (this' \otimes this'..\otimes this')*d */
+  void multVecKronTrans(KronVector &x, const KronVector &d) const;
+  /* a = inv(this)*a, b=inv(this)*b */
+  void multInvLeft2(GeneralMatrix &a, GeneralMatrix &b,
+                    double &rcond1, double &rcondinf) const;
+  /* this = I */
+  void setUnit();
 };
 
-
 #endif /* SYLV_MATRIX_H */
 
-
 // Local Variables:
 // mode:C++
 // End:
diff --git a/dynare++/sylv/cc/SylvMemory.h b/dynare++/sylv/cc/SylvMemory.h
index 187aac0b508b54941593220388f12cd154a2c38d..48a0fcd3dc095779c70d69f230ec0ed6369fa9c9 100644
--- a/dynare++/sylv/cc/SylvMemory.h
+++ b/dynare++/sylv/cc/SylvMemory.h
@@ -9,55 +9,57 @@
 
 #include <new>
 
-class MallocAllocator {
+class MallocAllocator
+{
 #ifdef USE_MEMORY_POOL
 public:
-	void* operator new(size_t size);
-	void* operator new[](size_t size);
-	void operator delete(void* p);
-	void operator delete[](void* p);
+  void *operator new(size_t size);
+  void *operator new[](size_t size);
+  void operator delete(void *p);
+  void operator delete[](void *p);
 #endif
 };
 
 #ifdef USE_MEMORY_POOL
-void* operator new(size_t size);
-void* operator new[](size_t size);
-void operator delete(void* p);
-void operator delete[](void* p);
+void *operator new(size_t size);
+void *operator new[](size_t size);
+void operator delete(void *p);
+void operator delete[](void *p);
 #endif
 
-class SylvMemoryPool {
-	char* base;
-	size_t length;
-	size_t allocated;
-	bool stack_mode;
-	SylvMemoryPool(const SylvMemoryPool&);
-	const SylvMemoryPool& operator=(const SylvMemoryPool&);
+class SylvMemoryPool
+{
+  char *base;
+  size_t length;
+  size_t allocated;
+  bool stack_mode;
+  SylvMemoryPool(const SylvMemoryPool &);
+  const SylvMemoryPool &operator=(const SylvMemoryPool &);
 public:
-	SylvMemoryPool();
-	~SylvMemoryPool();
-	void init(size_t size);
-	void* allocate(size_t size);
-	void free(void* p);
-	void reset();
-	void setStackMode(bool);
+  SylvMemoryPool();
+  ~SylvMemoryPool();
+  void init(size_t size);
+  void *allocate(size_t size);
+  void free(void *p);
+  void reset();
+  void setStackMode(bool);
 };
 
-class SylvMemoryDriver {
-	SylvMemoryDriver(const SylvMemoryDriver&);
-	const SylvMemoryDriver& operator=(const SylvMemoryDriver&);
+class SylvMemoryDriver
+{
+  SylvMemoryDriver(const SylvMemoryDriver &);
+  const SylvMemoryDriver &operator=(const SylvMemoryDriver &);
 public:
-	SylvMemoryDriver(int num_d, int m, int n, int order);
-	SylvMemoryDriver(const SylvParams& pars, int num_d, int m, int n, int order);
-	static void setStackMode(bool);
-	~SylvMemoryDriver();
+  SylvMemoryDriver(int num_d, int m, int n, int order);
+  SylvMemoryDriver(const SylvParams &pars, int num_d, int m, int n, int order);
+  static void setStackMode(bool);
+  ~SylvMemoryDriver();
 protected:
-	void allocate(int num_d, int m, int n, int order);
+  void allocate(int num_d, int m, int n, int order);
 };
 
 #endif /* SYLV_MEMORY_H */
 
-
 // Local Variables:
 // mode:C++
 // End:
diff --git a/dynare++/sylv/cc/SylvParams.h b/dynare++/sylv/cc/SylvParams.h
index beb292670472a3bd07b16ab51d955668cb0962a2..9b58e92e58118e63bf777b94d16f0fb0ed0bebe7 100644
--- a/dynare++/sylv/cc/SylvParams.h
+++ b/dynare++/sylv/cc/SylvParams.h
@@ -15,148 +15,217 @@
 typedef enum {def, changed, undef} status;
 
 template <class _Type>
-struct ParamItem {
+struct ParamItem
+{
 protected:
-	typedef ParamItem<_Type> _Self;
-	status s;
-	_Type value;
+  typedef ParamItem<_Type> _Self;
+  status s;
+  _Type value;
 public:
-	ParamItem()
-		{s = undef;}
-	ParamItem(_Type val)
-		{value = val; s = def;}
-	ParamItem(const _Self& item)
-		{value = item.value; s = item.s;}
-	const _Self& operator=(const _Self& item)
-		{value = item.value; s = item.s; return *this;}
-	const _Self& operator=(const _Type& val)
-		{value = val; s = changed; return *this;}
-	_Type operator*() const
-		{return value;}
-	status getStatus() const
-		{return s;}
-	void print(FILE* f, const char* prefix, const char* str, const char* fmt) const
-		{
-			if (s == undef)
-				return;
-			char out[1000];
-			strcpy(out, prefix);
-			strcat(out, str);
-			strcat(out, "= ");
-			strcat(out, fmt);
-			if (s == def)
-				strcat(out, " <default>");
-			strcat(out,"\n");
-			fprintf(f, out, value);
-		} 
+  ParamItem()
+  {
+    s = undef;
+  }
+  ParamItem(_Type val)
+  {
+    value = val; s = def;
+  }
+  ParamItem(const _Self &item)
+  {
+    value = item.value; s = item.s;
+  }
+  const _Self &
+  operator=(const _Self &item)
+  {
+    value = item.value; s = item.s; return *this;
+  }
+  const _Self &
+  operator=(const _Type &val)
+  {
+    value = val; s = changed; return *this;
+  }
+  _Type
+  operator*() const
+  {
+    return value;
+  }
+  status
+  getStatus() const
+  {
+    return s;
+  }
+  void
+  print(FILE *f, const char *prefix, const char *str, const char *fmt) const
+  {
+    if (s == undef)
+      return;
+    char out[1000];
+    strcpy(out, prefix);
+    strcat(out, str);
+    strcat(out, "= ");
+    strcat(out, fmt);
+    if (s == def)
+      strcat(out, " <default>");
+    strcat(out, "\n");
+    fprintf(f, out, value);
+  }
 };
 
-class SylvParams {
+class SylvParams
+{
 public:
-	typedef enum {iter, recurse} solve_method;
+  typedef enum {iter, recurse} solve_method;
 
 protected:
-	class DoubleParamItem : public ParamItem<double> {
-	public:
-		DoubleParamItem() : ParamItem<double>() {}
-		DoubleParamItem(double val) : ParamItem<double>(val) {}
-		DoubleParamItem(const DoubleParamItem& item) : ParamItem<double>(item) {}
-		const DoubleParamItem& operator=(const double& val)
-			{ParamItem<double>::operator=(val); return *this;}
+  class DoubleParamItem : public ParamItem<double>
+  {
+  public:
+    DoubleParamItem() : ParamItem<double>()
+    {
+    }
+    DoubleParamItem(double val) : ParamItem<double>(val)
+    {
+    }
+    DoubleParamItem(const DoubleParamItem &item) : ParamItem<double>(item)
+    {
+    }
+    const DoubleParamItem &
+    operator=(const double &val)
+    {
+      ParamItem<double>::operator=(val); return *this;
+    }
 #if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE)
-		mxArray* createMatlabArray() const;
+    mxArray *createMatlabArray() const;
 #endif
-	};
-
-	class IntParamItem : public ParamItem<int> {
-	public:
-		IntParamItem() : ParamItem<int>() {}
-		IntParamItem(int val) : ParamItem<int>(val) {}
-		IntParamItem(const IntParamItem& item) : ParamItem<int>(item) {}
-		const IntParamItem& operator=(const int& val)
-			{ParamItem<int>::operator=(val); return *this;}
+  };
+
+  class IntParamItem : public ParamItem<int>
+  {
+  public:
+    IntParamItem() : ParamItem<int>()
+    {
+    }
+    IntParamItem(int val) : ParamItem<int>(val)
+    {
+    }
+    IntParamItem(const IntParamItem &item) : ParamItem<int>(item)
+    {
+    }
+    const IntParamItem &
+    operator=(const int &val)
+    {
+      ParamItem<int>::operator=(val); return *this;
+    }
 #if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE)
-		mxArray* createMatlabArray() const;
+    mxArray *createMatlabArray() const;
 #endif
-	};
-
-	class BoolParamItem : public ParamItem<bool> {
-	public:
-		BoolParamItem() : ParamItem<bool>() {}
-		BoolParamItem(bool val) : ParamItem<bool>(val) {}
-		BoolParamItem(const BoolParamItem& item) : ParamItem<bool>(item) {}
-		const BoolParamItem& operator=(const bool& val)
-			{ParamItem<bool>::operator=(val); return *this;}
+  };
+
+  class BoolParamItem : public ParamItem<bool>
+  {
+  public:
+    BoolParamItem() : ParamItem<bool>()
+    {
+    }
+    BoolParamItem(bool val) : ParamItem<bool>(val)
+    {
+    }
+    BoolParamItem(const BoolParamItem &item) : ParamItem<bool>(item)
+    {
+    }
+    const BoolParamItem &
+    operator=(const bool &val)
+    {
+      ParamItem<bool>::operator=(val); return *this;
+    }
 #if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE)
-		mxArray* createMatlabArray() const;
+    mxArray *createMatlabArray() const;
 #endif
-	};
-
-	class MethodParamItem : public ParamItem<solve_method> {
-	public:
-		MethodParamItem() : ParamItem<solve_method>() {}
-		MethodParamItem(solve_method val) : ParamItem<solve_method>(val) {}
-		MethodParamItem(const MethodParamItem& item) : ParamItem<solve_method>(item) {}
-		const MethodParamItem operator=(const solve_method& val)
-			{ParamItem<solve_method>::operator=(val); return *this;}
+  };
+
+  class MethodParamItem : public ParamItem<solve_method>
+  {
+  public:
+    MethodParamItem() : ParamItem<solve_method>()
+    {
+    }
+    MethodParamItem(solve_method val) : ParamItem<solve_method>(val)
+    {
+    }
+    MethodParamItem(const MethodParamItem &item) : ParamItem<solve_method>(item)
+    {
+    }
+    const MethodParamItem
+    operator=(const solve_method &val)
+    {
+      ParamItem<solve_method>::operator=(val); return *this;
+    }
 #if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE)
-		mxArray* createMatlabArray() const;
+    mxArray *createMatlabArray() const;
 #endif
-	};
+  };
 
 public:
-	// input parameters
-	MethodParamItem method; // method of solution: iter/recurse
-	DoubleParamItem convergence_tol; // norm for what we consider converged
-	IntParamItem max_num_iter; // max number of iterations
-	DoubleParamItem bs_norm; // Bavely Stewart log10 of norm for diagonalization
-	BoolParamItem want_check; // true => allocate extra space for checks
-	// output parameters
-	BoolParamItem converged; // true if converged
-	DoubleParamItem iter_last_norm; // norm of the last iteration
-	IntParamItem num_iter; // number of iterations
-	DoubleParamItem f_err1; // norm 1 of diagonalization abs. error C-V*F*inv(V)
-	DoubleParamItem f_errI; // norm Inf of diagonalization abs. error C-V*F*inv(V)
-	DoubleParamItem viv_err1; // norm 1 of error I-V*inv(V)
-	DoubleParamItem viv_errI; // norm Inf of error I-V*inv(V)
-	DoubleParamItem ivv_err1; // norm 1 of error I-inv(V)*V
-	DoubleParamItem ivv_errI; // norm Inf of error I-inv(V)*V
-	IntParamItem f_blocks; // number of diagonal blocks of F
-	IntParamItem f_largest; // size of largest diagonal block in F
-	IntParamItem f_zeros; // number of off diagonal zeros in F
-	IntParamItem f_offdiag; // number of all off diagonal elements in F
-	DoubleParamItem rcondA1; // reciprocal cond 1 number of A
-	DoubleParamItem rcondAI; // reciprocal cond Inf number of A
-	DoubleParamItem eig_min; // minimum eigenvalue of the solved system
-	DoubleParamItem mat_err1; // rel. matrix 1 norm of A*X-B*X*kron(C,..,C)-D
-	DoubleParamItem mat_errI; // rel. matrix Inf norm of A*X-B*X*kron(C,..,C)-D
-	DoubleParamItem mat_errF; // rel. matrix Frob. norm of A*X-B*X*kron(C,..,C)-D
-	DoubleParamItem vec_err1; // rel. vector 1 norm of A*X-B*X*kron(C,..,C)-D
-	DoubleParamItem vec_errI; // rel. vector Inf norm of A*X-B*X*kron(C,..,C)-D
-	DoubleParamItem cpu_time; // time of the job in CPU seconds
-	// note: remember to change copy() if adding/removing member
-
-	SylvParams(bool wc = false)
-		: method(recurse), convergence_tol(1.e-30), max_num_iter(15),
-		  bs_norm(1.3), want_check(wc) {}
-	SylvParams(const SylvParams& p)
-		{copy(p);}
-	const SylvParams& operator=(const SylvParams& p)
-		{copy(p); return *this;}
-	~SylvParams() {}
-	void print(const char* prefix) const;
-	void print(FILE* fdesc, const char* prefix) const;
-	void setArrayNames(int& num, const char** names) const;
+  // input parameters
+  MethodParamItem method; // method of solution: iter/recurse
+  DoubleParamItem convergence_tol; // norm for what we consider converged
+  IntParamItem max_num_iter; // max number of iterations
+  DoubleParamItem bs_norm; // Bavely Stewart log10 of norm for diagonalization
+  BoolParamItem want_check; // true => allocate extra space for checks
+  // output parameters
+  BoolParamItem converged; // true if converged
+  DoubleParamItem iter_last_norm; // norm of the last iteration
+  IntParamItem num_iter; // number of iterations
+  DoubleParamItem f_err1; // norm 1 of diagonalization abs. error C-V*F*inv(V)
+  DoubleParamItem f_errI; // norm Inf of diagonalization abs. error C-V*F*inv(V)
+  DoubleParamItem viv_err1; // norm 1 of error I-V*inv(V)
+  DoubleParamItem viv_errI; // norm Inf of error I-V*inv(V)
+  DoubleParamItem ivv_err1; // norm 1 of error I-inv(V)*V
+  DoubleParamItem ivv_errI; // norm Inf of error I-inv(V)*V
+  IntParamItem f_blocks; // number of diagonal blocks of F
+  IntParamItem f_largest; // size of largest diagonal block in F
+  IntParamItem f_zeros; // number of off diagonal zeros in F
+  IntParamItem f_offdiag; // number of all off diagonal elements in F
+  DoubleParamItem rcondA1; // reciprocal cond 1 number of A
+  DoubleParamItem rcondAI; // reciprocal cond Inf number of A
+  DoubleParamItem eig_min; // minimum eigenvalue of the solved system
+  DoubleParamItem mat_err1; // rel. matrix 1 norm of A*X-B*X*kron(C,..,C)-D
+  DoubleParamItem mat_errI; // rel. matrix Inf norm of A*X-B*X*kron(C,..,C)-D
+  DoubleParamItem mat_errF; // rel. matrix Frob. norm of A*X-B*X*kron(C,..,C)-D
+  DoubleParamItem vec_err1; // rel. vector 1 norm of A*X-B*X*kron(C,..,C)-D
+  DoubleParamItem vec_errI; // rel. vector Inf norm of A*X-B*X*kron(C,..,C)-D
+  DoubleParamItem cpu_time; // time of the job in CPU seconds
+  // note: remember to change copy() if adding/removing member
+
+  SylvParams(bool wc = false)
+    : method(recurse), convergence_tol(1.e-30), max_num_iter(15),
+      bs_norm(1.3), want_check(wc)
+  {
+  }
+  SylvParams(const SylvParams &p)
+  {
+    copy(p);
+  }
+  const SylvParams &
+  operator=(const SylvParams &p)
+  {
+    copy(p); return *this;
+  }
+  ~SylvParams()
+  {
+  }
+  void print(const char *prefix) const;
+  void print(FILE *fdesc, const char *prefix) const;
+  void setArrayNames(int &num, const char **names) const;
 #if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE)
-	mxArray* createStructArray() const;
+  mxArray *createStructArray() const;
 #endif
 private:
-	void copy(const SylvParams& p);
+  void copy(const SylvParams &p);
 };
 
 #endif /* SYLV_PARAMS_H */
 
-
 // Local Variables:
 // mode:C++
 // End:
diff --git a/dynare++/sylv/cc/SylvesterSolver.h b/dynare++/sylv/cc/SylvesterSolver.h
index df9bcce4520476fbb131628967a3f3f5cea2322c..344abd12740edc668aae6eb132191fe802677a0a 100644
--- a/dynare++/sylv/cc/SylvesterSolver.h
+++ b/dynare++/sylv/cc/SylvesterSolver.h
@@ -12,40 +12,47 @@
 #include "SylvParams.h"
 #include "SchurDecomp.h"
 
-class SylvesterSolver {
+class SylvesterSolver
+{
 protected:
-	const QuasiTriangular* const matrixK;
-	const QuasiTriangular* const matrixF;
+  const QuasiTriangular *const matrixK;
+  const QuasiTriangular *const matrixF;
 private:
-	/* return true when it is more efficient to use QuasiTriangular
-	 * than QuasiTriangularZero */
-	static bool zeroPad(const SchurDecompZero& kdecomp) {
-		return ((kdecomp.getZeroCols()*3 < kdecomp.getDim()*2) ||
-				(kdecomp.getZeroCols() < 10));
-	}
+  /* return true when it is more efficient to use QuasiTriangular
+   * than QuasiTriangularZero */
+  static bool
+  zeroPad(const SchurDecompZero &kdecomp)
+  {
+    return ((kdecomp.getZeroCols()*3 < kdecomp.getDim()*2)
+            || (kdecomp.getZeroCols() < 10));
+  }
 public:
-	SylvesterSolver(const QuasiTriangular& k, const QuasiTriangular& f)
-		: matrixK(new QuasiTriangular(k)),
-		  matrixF(new QuasiTriangular(f))
-		{}
-	SylvesterSolver(const SchurDecompZero& kdecomp, const SchurDecomp& fdecomp)
-		: matrixK((zeroPad(kdecomp)) ?
-				  new QuasiTriangular(kdecomp) : new QuasiTriangularZero(kdecomp)),
-		  matrixF(new QuasiTriangular(fdecomp))
-		{}
-	SylvesterSolver(const SchurDecompZero& kdecomp, const SimilarityDecomp& fdecomp)
-		: matrixK((zeroPad(kdecomp)) ?
-				  new QuasiTriangular(kdecomp) : new QuasiTriangularZero(kdecomp)),
-		  matrixF(new BlockDiagonal(fdecomp.getB()))
-		{}
-	virtual ~SylvesterSolver()
-		{delete matrixK; delete matrixF;}
-	virtual void solve(SylvParams& pars, KronVector& x) const = 0;
+  SylvesterSolver(const QuasiTriangular &k, const QuasiTriangular &f)
+    : matrixK(new QuasiTriangular(k)),
+      matrixF(new QuasiTriangular(f))
+  {
+  }
+  SylvesterSolver(const SchurDecompZero &kdecomp, const SchurDecomp &fdecomp)
+    : matrixK((zeroPad(kdecomp)) ?
+              new QuasiTriangular(kdecomp) : new QuasiTriangularZero(kdecomp)),
+      matrixF(new QuasiTriangular(fdecomp))
+  {
+  }
+  SylvesterSolver(const SchurDecompZero &kdecomp, const SimilarityDecomp &fdecomp)
+    : matrixK((zeroPad(kdecomp)) ?
+              new QuasiTriangular(kdecomp) : new QuasiTriangularZero(kdecomp)),
+      matrixF(new BlockDiagonal(fdecomp.getB()))
+  {
+  }
+  virtual ~SylvesterSolver()
+  {
+    delete matrixK; delete matrixF;
+  }
+  virtual void solve(SylvParams &pars, KronVector &x) const = 0;
 };
 
 #endif /* SYLVESTER_SOLVER_H */
 
-
 // Local Variables:
 // mode:C++
 // End:
diff --git a/dynare++/sylv/cc/SymSchurDecomp.h b/dynare++/sylv/cc/SymSchurDecomp.h
index 7840421118a55fdb68f6e196c2ef3cd391153d69..9b95f36bff767acc212f1a47d3cebd5e9d24488b 100644
--- a/dynare++/sylv/cc/SymSchurDecomp.h
+++ b/dynare++/sylv/cc/SymSchurDecomp.h
@@ -7,35 +7,45 @@
 
 #include "SylvMatrix.h"
 
-class SymSchurDecomp {
+class SymSchurDecomp
+{
 protected:
-	Vector lambda;
-	SqSylvMatrix q;
+  Vector lambda;
+  SqSylvMatrix q;
 public:
-	/** Calculates A = Q*Lambda*Q^T, where A is assummed to be
-	 * symmetric and Lambda real diagonal, hence a vector. */
-	SymSchurDecomp(const GeneralMatrix& a);
-	SymSchurDecomp(const SymSchurDecomp& ssd)
-		: lambda(ssd.lambda), q(ssd.q) {}
-	virtual ~SymSchurDecomp() {}
-	const Vector& getLambda() const
-		{return lambda;}
-	const SqSylvMatrix& getQ() const
-		{return q;}
-	/** Return factor F*F^T = A, raises and exception if A is not
-	 * positive semidefinite, F must be square. */
-	void getFactor(GeneralMatrix& f) const;
-	/** Returns true if A is positive semidefinite. */
-	bool isPositiveSemidefinite() const;
-	/** Correct definitness. This sets all eigenvalues between minus
-	 * tolerance and zero to zero. */
-	void correctDefinitness(double tol);
+  /** Calculates A = Q*Lambda*Q^T, where A is assummed to be
+   * symmetric and Lambda real diagonal, hence a vector. */
+  SymSchurDecomp(const GeneralMatrix &a);
+  SymSchurDecomp(const SymSchurDecomp &ssd)
+    : lambda(ssd.lambda), q(ssd.q)
+  {
+  }
+  virtual ~SymSchurDecomp()
+  {
+  }
+  const Vector &
+  getLambda() const
+  {
+    return lambda;
+  }
+  const SqSylvMatrix &
+  getQ() const
+  {
+    return q;
+  }
+  /** Return factor F*F^T = A, raises and exception if A is not
+   * positive semidefinite, F must be square. */
+  void getFactor(GeneralMatrix &f) const;
+  /** Returns true if A is positive semidefinite. */
+  bool isPositiveSemidefinite() const;
+  /** Correct definitness. This sets all eigenvalues between minus
+   * tolerance and zero to zero. */
+  void correctDefinitness(double tol);
 
 };
 
 #endif
 
-
 // Local Variables:
 // mode:C++
 // End:
diff --git a/dynare++/sylv/cc/TriangularSylvester.h b/dynare++/sylv/cc/TriangularSylvester.h
index b4908729e1044826ce43b72983c6f2246151e7fa..fa652bc12f70c676e15c68ceb02a0997ee998fc9 100644
--- a/dynare++/sylv/cc/TriangularSylvester.h
+++ b/dynare++/sylv/cc/TriangularSylvester.h
@@ -11,105 +11,112 @@
 #include "QuasiTriangularZero.h"
 #include "SimilarityDecomp.h"
 
-class TriangularSylvester : public SylvesterSolver {
-	const QuasiTriangular* const matrixKK;
-	const QuasiTriangular* const matrixFF;
+class TriangularSylvester : public SylvesterSolver
+{
+  const QuasiTriangular *const matrixKK;
+  const QuasiTriangular *const matrixFF;
 public:
-	TriangularSylvester(const QuasiTriangular& k, const QuasiTriangular& f);
-	TriangularSylvester(const SchurDecompZero& kdecomp, const SchurDecomp& fdecomp);
-	TriangularSylvester(const SchurDecompZero& kdecomp, const SimilarityDecomp& fdecomp);
-	virtual ~TriangularSylvester();
-	void print() const;
-	void solve(SylvParams& pars, KronVector& d) const;
+  TriangularSylvester(const QuasiTriangular &k, const QuasiTriangular &f);
+  TriangularSylvester(const SchurDecompZero &kdecomp, const SchurDecomp &fdecomp);
+  TriangularSylvester(const SchurDecompZero &kdecomp, const SimilarityDecomp &fdecomp);
+  virtual
+  ~TriangularSylvester();
+  void print() const;
+  void solve(SylvParams &pars, KronVector &d) const;
 
-	void solvi(double r, KronVector& d, double& eig_min) const;
-	void solvii(double alpha, double beta1, double beta2,
-				KronVector& d1, KronVector& d2,
-				double& eig_min) const;
-	void solviip(double alpha, double betas,
-				 KronVector& d, double& eig_min) const;
-	/* evaluates:
-	   |x1|   |d1| |alpha -beta1|                       |d1|
-	   |  | = |  |+|            |\otimes F'...\otimes K |  |
-	   |x2|   |d2| |beta2  alpha|                       |d2|
-	*/
-	void linEval(double alpha, double beta1, double beta2,
-				 KronVector& x1, KronVector& x2,
-				 const ConstKronVector& d1, const ConstKronVector& d2) const;
-	void linEval(double alpha, double beta1, double beta2,
-				 KronVector& x1, KronVector& x2,
-				 const KronVector& d1, const KronVector& d2) const
-		{linEval(alpha, beta1, beta2, x1, x2,
-				 ConstKronVector(d1), ConstKronVector(d2));}
+  void solvi(double r, KronVector &d, double &eig_min) const;
+  void solvii(double alpha, double beta1, double beta2,
+              KronVector &d1, KronVector &d2,
+              double &eig_min) const;
+  void solviip(double alpha, double betas,
+               KronVector &d, double &eig_min) const;
+  /* evaluates:
+     |x1|   |d1| |alpha -beta1|                       |d1|
+     |  | = |  |+|            |\otimes F'...\otimes K |  |
+     |x2|   |d2| |beta2  alpha|                       |d2|
+  */
+  void linEval(double alpha, double beta1, double beta2,
+               KronVector &x1, KronVector &x2,
+               const ConstKronVector &d1, const ConstKronVector &d2) const;
+  void
+  linEval(double alpha, double beta1, double beta2,
+          KronVector &x1, KronVector &x2,
+          const KronVector &d1, const KronVector &d2) const
+  {
+    linEval(alpha, beta1, beta2, x1, x2,
+            ConstKronVector(d1), ConstKronVector(d2));
+  }
 
-	/* evaluates:
-	   |x1|   |d1|          |gamma -delta1|                       |d1|
-	   |  | = |  | + 2alpha*|             |\otimes F'...\otimes K |  | +
-	   |x2|   |d2|          |delta2  gamma|                       |d2|
+  /* evaluates:
+     |x1|   |d1|          |gamma -delta1|                       |d1|
+     |  | = |  | + 2alpha*|             |\otimes F'...\otimes K |  | +
+     |x2|   |d2|          |delta2  gamma|                       |d2|
 
-                                     |gamma -delta1|^2                       |d1|
-                   + (alpha^2+betas)*|             |\otimes F'2...\otimes K2 |  |
-                                     |delta2  gamma|                         |d2|
-	*/
-	void quaEval(double alpha, double betas,
-				 double gamma, double delta1, double delta2,
-				 KronVector& x1, KronVector& x2,
-				 const ConstKronVector& d1, const ConstKronVector& d2) const;
-	void quaEval(double alpha, double betas,
-				 double gamma, double delta1, double delta2,
-				 KronVector& x1, KronVector& x2,
-				 const KronVector& d1, const KronVector& d2) const
-		{quaEval(alpha, betas, gamma, delta1, delta2, x1, x2,
-				 ConstKronVector(d1), ConstKronVector(d2));}
+     |gamma -delta1|^2                       |d1|
+     + (alpha^2+betas)*|             |\otimes F'2...\otimes K2 |  |
+     |delta2  gamma|                         |d2|
+  */
+  void quaEval(double alpha, double betas,
+               double gamma, double delta1, double delta2,
+               KronVector &x1, KronVector &x2,
+               const ConstKronVector &d1, const ConstKronVector &d2) const;
+  void
+  quaEval(double alpha, double betas,
+          double gamma, double delta1, double delta2,
+          KronVector &x1, KronVector &x2,
+          const KronVector &d1, const KronVector &d2) const
+  {
+    quaEval(alpha, betas, gamma, delta1, delta2, x1, x2,
+            ConstKronVector(d1), ConstKronVector(d2));
+  }
 private:
-	/* returns square of size of minimal eigenvalue of the system solved,
-	   now obsolete */ 
-	double getEigSep(int depth) const;
-	/* recursivelly calculates kronecker product of complex vectors (used in getEigSep) */
-	static void multEigVector(KronVector& eig, const Vector& feig, const Vector& keig);
-	/* auxiliary typedefs */
-	typedef QuasiTriangular::const_diag_iter const_diag_iter;
-	typedef QuasiTriangular::const_row_iter const_row_iter;
-	/* called from solvi */
-	void solviRealAndEliminate(double r, const_diag_iter di,
-							   KronVector& d, double& eig_min) const;
-	void solviComplexAndEliminate(double r, const_diag_iter di,
-								  KronVector& d, double& eig_min) const;
-	/* called from solviip */
-	void solviipRealAndEliminate(double alpha, double betas,
-								 const_diag_iter di, const_diag_iter dsi,
-								 KronVector& d, double& eig_min) const;
-	void solviipComplexAndEliminate(double alpha, double betas,
-									const_diag_iter di, const_diag_iter dsi,
-									KronVector& d, double& eig_min) const;
-	/* eliminations */
-	void solviEliminateReal(const_diag_iter di, KronVector& d,
-							const KronVector& y, double divisor) const;
-	void solviEliminateComplex(const_diag_iter di, KronVector& d,
-							   const KronVector& y1, const KronVector& y2,
-							   double divisor) const;
-	void solviipEliminateReal(const_diag_iter di, const_diag_iter dsi,
-							  KronVector& d,
-							  const KronVector& y1, const KronVector& y2,
-							  double divisor, double divisor2) const;
-	void solviipEliminateComplex(const_diag_iter di, const_diag_iter dsi,
-								 KronVector& d,
-								 const KronVector& y1, const KronVector& y11,
-								 const KronVector& y2, const KronVector& y22,
-								 double divisor) const;
-	/* Lemma 2 */
-	void solviipComplex(double alpha, double betas, double gamma,
-						double delta1, double delta2,
-						KronVector& d1, KronVector& d2,
-						double& eig_min) const;
-	/* norms for what we consider zero on diagonal of F */
-	static double diag_zero;
-	static double diag_zero_sq; // square of diag_zero
+  /* returns square of size of minimal eigenvalue of the system solved,
+     now obsolete */
+  double getEigSep(int depth) const;
+  /* recursivelly calculates kronecker product of complex vectors (used in getEigSep) */
+  static void multEigVector(KronVector &eig, const Vector &feig, const Vector &keig);
+  /* auxiliary typedefs */
+  typedef QuasiTriangular::const_diag_iter const_diag_iter;
+  typedef QuasiTriangular::const_row_iter const_row_iter;
+  /* called from solvi */
+  void solviRealAndEliminate(double r, const_diag_iter di,
+                             KronVector &d, double &eig_min) const;
+  void solviComplexAndEliminate(double r, const_diag_iter di,
+                                KronVector &d, double &eig_min) const;
+  /* called from solviip */
+  void solviipRealAndEliminate(double alpha, double betas,
+                               const_diag_iter di, const_diag_iter dsi,
+                               KronVector &d, double &eig_min) const;
+  void solviipComplexAndEliminate(double alpha, double betas,
+                                  const_diag_iter di, const_diag_iter dsi,
+                                  KronVector &d, double &eig_min) const;
+  /* eliminations */
+  void solviEliminateReal(const_diag_iter di, KronVector &d,
+                          const KronVector &y, double divisor) const;
+  void solviEliminateComplex(const_diag_iter di, KronVector &d,
+                             const KronVector &y1, const KronVector &y2,
+                             double divisor) const;
+  void solviipEliminateReal(const_diag_iter di, const_diag_iter dsi,
+                            KronVector &d,
+                            const KronVector &y1, const KronVector &y2,
+                            double divisor, double divisor2) const;
+  void solviipEliminateComplex(const_diag_iter di, const_diag_iter dsi,
+                               KronVector &d,
+                               const KronVector &y1, const KronVector &y11,
+                               const KronVector &y2, const KronVector &y22,
+                               double divisor) const;
+  /* Lemma 2 */
+  void solviipComplex(double alpha, double betas, double gamma,
+                      double delta1, double delta2,
+                      KronVector &d1, KronVector &d2,
+                      double &eig_min) const;
+  /* norms for what we consider zero on diagonal of F */
+  static double diag_zero;
+  static double diag_zero_sq; // square of diag_zero
 };
 
 #endif /* TRIANGULAR_SYLVESTER_H */
 
-
 // Local Variables:
 // mode:C++
 // End:
diff --git a/dynare++/sylv/cc/Vector.h b/dynare++/sylv/cc/Vector.h
index dc4acd532d5ad7026ee2e6dc33d1c1f6e772c6a7..3afd5d38948aa04a3e3d10d32ac746718e2e133a 100644
--- a/dynare++/sylv/cc/Vector.h
+++ b/dynare++/sylv/cc/Vector.h
@@ -7,169 +7,252 @@
 
 /* NOTE! Vector and ConstVector have not common super class in order
  * to avoid running virtual method invokation mechanism. Some
- * members, and methods are thus duplicated */ 
+ * members, and methods are thus duplicated */
 
 #include <cstdio>
 
 class GeneralMatrix;
 class ConstVector;
 
-class Vector {
+class Vector
+{
 protected:
-	int len;
-	int s;
-	double* data;
-	bool destroy;
+  int len;
+  int s;
+  double *data;
+  bool destroy;
 public:
-	Vector() : len(0), s(1), data(0), destroy(false) {}
-	Vector(int l) : len(l), s(1), data(new double[l]), destroy(true) {}
-	Vector(Vector& v) : len(v.length()), s(v.skip()), data(v.base()), destroy(false) {}
-	Vector(const Vector& v);
-	Vector(const ConstVector& v);
-	Vector(const double* d, int l)
-		: len(l), s(1), data(new double[len]), destroy(true)
-		{copy(d, 1);}
-	Vector(double* d, int l)
-		: len(l), s(1), data(d), destroy(false) {}
-	Vector(double* d, int skip, int l)
-		: len(l), s(skip), data(d), destroy(false) {}
-	Vector(Vector& v, int off, int l);
-	Vector(const Vector& v, int off, int l);
-	Vector(GeneralMatrix& m, int col);
-	Vector(int row, GeneralMatrix& m);
-	const Vector& operator=(const Vector& v);
-	const Vector& operator=(const ConstVector& v);
-	double& operator[](int i)
-		{return data[s*i];}
-	const double& operator[](int i) const
-		{return data[s*i];}
-	const double* base() const
-		{return data;}
-	double* base()
-		{return data;}
-	int length() const
-		{return len;}
-	int skip() const
-		{return s;}
-
-	/** Exact equality. */
-	bool operator==(const Vector& y) const;
-	bool operator!=(const Vector& y) const;
-	/** Lexicographic ordering. */
-	bool operator<(const Vector& y) const;
-	bool operator<=(const Vector& y) const;
-	bool operator>(const Vector& y) const;
-	bool operator>=(const Vector& y) const;
-
-	virtual ~Vector();
-	void zeros();
-	void nans();
-	void infs();
-	bool toBeDestroyed() const {return destroy;}
-	void rotatePair(double alpha, double beta1, double beta2, int i);
-	void add(double r, const Vector& v);
-	void add(double r, const ConstVector& v);
-	void add(const double* z, const Vector& v);
-	void add(const double* z, const ConstVector& v);
-	void mult(double r);
-	double getNorm() const;
-	double getMax() const;
-	double getNorm1() const;
-	double dot(const Vector& y) const;
-	bool isFinite() const;
-	void print() const;
-
-	/* multiplies | alpha -beta1|           |b1|   |x1|
-                  |             |\otimes I .|  | = |  |
-                  | -beta2 alpha|           |b2|   |x2|
-	*/
-	static void mult2(double alpha, double beta1, double beta2,
-					  Vector& x1, Vector& x2,
-					  const Vector& b1, const Vector& b2);
-	/* same, but adds instead of set */
-	static void mult2a(double alpha, double beta1, double beta2,
-					   Vector& x1, Vector& x2,
-					   const Vector& b1, const Vector& b2);
-	/* same, but subtracts instead of add */
-	static void mult2s(double alpha, double beta1, double beta2,
-					   Vector& x1, Vector& x2,
-					   const Vector& b1, const Vector& b2)
-		{mult2a(-alpha, -beta1, -beta2, x1, x2, b1, b2);}
+  Vector() : len(0), s(1), data(0), destroy(false)
+  {
+  }
+  Vector(int l) : len(l), s(1), data(new double[l]), destroy(true)
+  {
+  }
+  Vector(Vector &v) : len(v.length()), s(v.skip()), data(v.base()), destroy(false)
+  {
+  }
+  Vector(const Vector &v);
+  Vector(const ConstVector &v);
+  Vector(const double *d, int l)
+    : len(l), s(1), data(new double[len]), destroy(true)
+  {
+    copy(d, 1);
+  }
+  Vector(double *d, int l)
+    : len(l), s(1), data(d), destroy(false)
+  {
+  }
+  Vector(double *d, int skip, int l)
+    : len(l), s(skip), data(d), destroy(false)
+  {
+  }
+  Vector(Vector &v, int off, int l);
+  Vector(const Vector &v, int off, int l);
+  Vector(GeneralMatrix &m, int col);
+  Vector(int row, GeneralMatrix &m);
+  const Vector &operator=(const Vector &v);
+  const Vector &operator=(const ConstVector &v);
+  double &
+  operator[](int i)
+  {
+    return data[s*i];
+  }
+  const double &
+  operator[](int i) const
+  {
+    return data[s*i];
+  }
+  const double *
+  base() const
+  {
+    return data;
+  }
+  double *
+  base()
+  {
+    return data;
+  }
+  int
+  length() const
+  {
+    return len;
+  }
+  int
+  skip() const
+  {
+    return s;
+  }
+
+  /** Exact equality. */
+  bool operator==(const Vector &y) const;
+  bool operator!=(const Vector &y) const;
+  /** Lexicographic ordering. */
+  bool operator<(const Vector &y) const;
+  bool operator<=(const Vector &y) const;
+  bool operator>(const Vector &y) const;
+  bool operator>=(const Vector &y) const;
+
+  virtual
+  ~Vector();
+  void zeros();
+  void nans();
+  void infs();
+  bool
+  toBeDestroyed() const
+  {
+    return destroy;
+  }
+  void rotatePair(double alpha, double beta1, double beta2, int i);
+  void add(double r, const Vector &v);
+  void add(double r, const ConstVector &v);
+  void add(const double *z, const Vector &v);
+  void add(const double *z, const ConstVector &v);
+  void mult(double r);
+  double getNorm() const;
+  double getMax() const;
+  double getNorm1() const;
+  double dot(const Vector &y) const;
+  bool isFinite() const;
+  void print() const;
+
+  /* multiplies | alpha -beta1|           |b1|   |x1|
+     |             |\otimes I .|  | = |  |
+     | -beta2 alpha|           |b2|   |x2|
+  */
+  static void mult2(double alpha, double beta1, double beta2,
+                    Vector &x1, Vector &x2,
+                    const Vector &b1, const Vector &b2);
+  /* same, but adds instead of set */
+  static void mult2a(double alpha, double beta1, double beta2,
+                     Vector &x1, Vector &x2,
+                     const Vector &b1, const Vector &b2);
+  /* same, but subtracts instead of add */
+  static void
+  mult2s(double alpha, double beta1, double beta2,
+         Vector &x1, Vector &x2,
+         const Vector &b1, const Vector &b2)
+  {
+    mult2a(-alpha, -beta1, -beta2, x1, x2, b1, b2);
+  }
 private:
-	void copy(const double* d, int inc);
-	const Vector& operator=(int); // must not be used (not implemented)
-	const Vector& operator=(double); // must not be used (not implemented)
+  void copy(const double *d, int inc);
+  const Vector &operator=(int); // must not be used (not implemented)
+  const Vector &operator=(double); // must not be used (not implemented)
 };
 
-
-class BaseConstVector {
+class BaseConstVector
+{
 protected:
-	int len;
-	int s;
-	const double* data;
+  int len;
+  int s;
+  const double *data;
 public:
-	BaseConstVector(int l, int si, const double* d) : len(l), s(si), data(d) {}
-	BaseConstVector(const BaseConstVector& v) : len(v.len), s(v.s), data(v.data) {}
-	const BaseConstVector& operator=(const BaseConstVector& v)
-		{len = v.len; s = v.s; data = v.data; return *this;}
-	const double& operator[](int i) const
-		{return data[s*i];}
-	const double* base() const
-		{return data;}
-	int length() const
-		{return len;}
-	int skip() const
-		{return s;}
+  BaseConstVector(int l, int si, const double *d) : len(l), s(si), data(d)
+  {
+  }
+  BaseConstVector(const BaseConstVector &v) : len(v.len), s(v.s), data(v.data)
+  {
+  }
+  const BaseConstVector &
+  operator=(const BaseConstVector &v)
+  {
+    len = v.len; s = v.s; data = v.data; return *this;
+  }
+  const double &
+  operator[](int i) const
+  {
+    return data[s*i];
+  }
+  const double *
+  base() const
+  {
+    return data;
+  }
+  int
+  length() const
+  {
+    return len;
+  }
+  int
+  skip() const
+  {
+    return s;
+  }
 };
 
 class ConstGeneralMatrix;
 
-class ConstVector : public BaseConstVector {
+class ConstVector : public BaseConstVector
+{
 public:
-	ConstVector(const Vector& v) : BaseConstVector(v.length(), v.skip(), v.base()) {}
-	ConstVector(const ConstVector& v) : BaseConstVector(v) {}
-	ConstVector(const double* d, int l) : BaseConstVector(l, 1, d) {}
-	ConstVector(const Vector& v, int off, int l);
-	ConstVector(const ConstVector& v, int off, int l);
-	ConstVector(const double* d, int skip, int l);
-	ConstVector(const ConstGeneralMatrix& m, int col);
-	ConstVector(int row, const ConstGeneralMatrix& m);
-	
-	virtual ~ConstVector() {}
-	/** Exact equality. */
-	bool operator==(const ConstVector& y) const;
-	bool operator!=(const ConstVector& y) const
-		{return ! operator==(y);}
-	/** Lexicographic ordering. */
-	bool operator<(const ConstVector& y) const;
-	bool operator<=(const ConstVector& y) const
-		{return operator<(y) || operator==(y);}
-	bool operator>(const ConstVector& y) const
-		{return ! operator<=(y);}
-	bool operator>=(const ConstVector& y) const
-		{return ! operator<(y);}
-
-	double getNorm() const;
-	double getMax() const;
-	double getNorm1() const;
-	double dot(const ConstVector& y) const;
-	bool isFinite() const;
-	void print() const;
+  ConstVector(const Vector &v) : BaseConstVector(v.length(), v.skip(), v.base())
+  {
+  }
+  ConstVector(const ConstVector &v) : BaseConstVector(v)
+  {
+  }
+  ConstVector(const double *d, int l) : BaseConstVector(l, 1, d)
+  {
+  }
+  ConstVector(const Vector &v, int off, int l);
+  ConstVector(const ConstVector &v, int off, int l);
+  ConstVector(const double *d, int skip, int l);
+  ConstVector(const ConstGeneralMatrix &m, int col);
+  ConstVector(int row, const ConstGeneralMatrix &m);
+
+  virtual ~ConstVector()
+  {
+  }
+  /** Exact equality. */
+  bool operator==(const ConstVector &y) const;
+  bool
+  operator!=(const ConstVector &y) const
+  {
+    return !operator==(y);
+  }
+  /** Lexicographic ordering. */
+  bool operator<(const ConstVector &y) const;
+  bool
+  operator<=(const ConstVector &y) const
+  {
+    return operator<(y) || operator==(y);
+  }
+  bool
+  operator>(const ConstVector &y) const
+  {
+    return !operator<=(y);
+  }
+  bool
+  operator>=(const ConstVector &y) const
+  {
+    return !operator<(y);
+  }
+
+  double getNorm() const;
+  double getMax() const;
+  double getNorm1() const;
+  double dot(const ConstVector &y) const;
+  bool isFinite() const;
+  void print() const;
 };
 
-class ZeroPad {
+class ZeroPad
+{
 public:
-	static const int length = 16;
+  static const int length = 16;
 private:
-	double pad[16];
+  double pad[16];
 public:
-	ZeroPad();
-	const double* getBase() const {return pad;} 
+  ZeroPad();
+  const double *
+  getBase() const
+  {
+    return pad;
+  }
 };
 
 #endif /* VECTOR_H */
 
-
 // Local Variables:
 // mode:C++
 // End:
diff --git a/dynare++/sylv/testing/MMMatrix.h b/dynare++/sylv/testing/MMMatrix.h
index e30842caf544d40816ac9671f2e08a9196502075..f6afaa30dc2183d32908ea176cf786a8d6d341d8 100644
--- a/dynare++/sylv/testing/MMMatrix.h
+++ b/dynare++/sylv/testing/MMMatrix.h
@@ -12,31 +12,58 @@
 
 using namespace std;
 
-class MMException : public MallocAllocator {
-	string message;
+class MMException : public MallocAllocator
+{
+  string message;
 public:
-	MMException(string mes) : message(mes) {}
-	MMException(const char* mes) : message(mes) {}
-	const char* getMessage() const {return message.data();}
+  MMException(string mes) : message(mes)
+  {
+  }
+  MMException(const char *mes) : message(mes)
+  {
+  }
+  const char *
+  getMessage() const
+  {
+    return message.data();
+  }
 };
 
-class MMMatrixIn : public MallocAllocator {
-	double* data;
-	int rows;
-	int cols;
+class MMMatrixIn : public MallocAllocator
+{
+  double *data;
+  int rows;
+  int cols;
 public:
-	MMMatrixIn(const char* fname);
-	~MMMatrixIn();
-	const double* getData() const {return data;}
-	int size() const {return rows*cols;}
-	int row() const {return rows;}
-	int col() const {return cols;}
+  MMMatrixIn(const char *fname);
+  ~MMMatrixIn();
+  const double *
+  getData() const
+  {
+    return data;
+  }
+  int
+  size() const
+  {
+    return rows*cols;
+  }
+  int
+  row() const
+  {
+    return rows;
+  }
+  int
+  col() const
+  {
+    return cols;
+  }
 };
 
-class MMMatrixOut : public MallocAllocator {
+class MMMatrixOut : public MallocAllocator
+{
 public:
-	static void write(const char* fname, int rows, int cols, const double* data);
-	static void write(const char* fname, const GeneralMatrix& m);
+  static void write(const char *fname, int rows, int cols, const double *data);
+  static void write(const char *fname, const GeneralMatrix &m);
 };
 
 #endif /* MM_MATRIX_H */
diff --git a/dynare++/tl/testing/factory.h b/dynare++/tl/testing/factory.h
index fea2230110c80709aecdcd01d7484b410a6f7bee..89f0b6be825b394a250d17b65325d932051a3308 100644
--- a/dynare++/tl/testing/factory.h
+++ b/dynare++/tl/testing/factory.h
@@ -2,7 +2,7 @@
 /* Copyright 2004, Ondra Kamenik */
 
 #ifndef FACTORY_H
-#define FACTORY_H 
+#define FACTORY_H
 
 #include "symmetry.h"
 #include "int_sequence.h"
@@ -11,67 +11,78 @@
 #include "rfs_tensor.h"
 #include "t_container.h"
 
-class Factory {
-	void init(const Symmetry& s, const IntSequence& nvs);
-	void init(int dim, int nv);
-	void fillMatrix(TwoDMatrix& m) const;
+class Factory
+{
+  void init(const Symmetry &s, const IntSequence &nvs);
+  void init(int dim, int nv);
+  void fillMatrix(TwoDMatrix &m) const;
 public:
-	double get() const;
-	// this can be used with UGSTensor, FGSTensor
-	template <class _Ttype>
-	_Ttype* make(int r, const Symmetry& s, const IntSequence& nvs)
-		{
-			_Ttype* res = new _Ttype(r, TensorDimens(s, nvs));
-			init(s, nvs);
-			fillMatrix(*res);
-			return res;
-		}
+  double get() const;
+  // this can be used with UGSTensor, FGSTensor
+  template <class _Ttype>
+  _Ttype *
+  make(int r, const Symmetry &s, const IntSequence &nvs)
+  {
+    _Ttype *res = new _Ttype(r, TensorDimens(s, nvs));
+    init(s, nvs);
+    fillMatrix(*res);
+    return res;
+  }
 
-	// this can be used with FFSTensor, UFSTensor, FRTensor, URTensor
-	template <class _Ttype>
-	_Ttype* make(int r, int nv, int dim)
-		{
-			_Ttype* res = new _Ttype(r, nv, dim);
-			init(dim, nv);
-			fillMatrix(*res);
-			return res;
-		}
+  // this can be used with FFSTensor, UFSTensor, FRTensor, URTensor
+  template <class _Ttype>
+  _Ttype *
+  make(int r, int nv, int dim)
+  {
+    _Ttype *res = new _Ttype(r, nv, dim);
+    init(dim, nv);
+    fillMatrix(*res);
+    return res;
+  }
 
-	template <class _Ttype, class _Ctype>
-	_Ctype* makeCont(int r, const IntSequence& nvs, int maxdim)
-		{
-			int symnum = nvs.size();
-			_Ctype* res = new _Ctype(symnum);
-			for (int dim = 1; dim <= maxdim; dim++) {
-				if (symnum == 1) {
-					// full symmetry
-					Symmetry sym(dim);
-					_Ttype* t = make<_Ttype>(r, sym, nvs);
-					res->insert(t);
-				} else {
-					// general symmetry
-					for (int i = 0; i <= dim; i++) {
-						Symmetry sym(i, dim-i);
-						_Ttype* t = make<_Ttype>(r, sym, nvs);
-						res->insert(t);
-					}
-				}
-			}
-			return res;
-		}
+  template <class _Ttype, class _Ctype>
+  _Ctype *
+  makeCont(int r, const IntSequence &nvs, int maxdim)
+  {
+    int symnum = nvs.size();
+    _Ctype *res = new _Ctype(symnum);
+    for (int dim = 1; dim <= maxdim; dim++)
+      {
+        if (symnum == 1)
+          {
+            // full symmetry
+            Symmetry sym(dim);
+            _Ttype *t = make<_Ttype>(r, sym, nvs);
+            res->insert(t);
+          }
+        else
+          {
+            // general symmetry
+            for (int i = 0; i <= dim; i++)
+              {
+                Symmetry sym(i, dim-i);
+                _Ttype *t = make<_Ttype>(r, sym, nvs);
+                res->insert(t);
+              }
+          }
+      }
+    return res;
+  }
 
-	template <class _Ttype, class _Ptype>
-	_Ptype* makePoly(int r, int nv, int maxdim)
-		{
-			_Ptype* p = new _Ptype(r, nv);
-			for (int d = 1; d <= maxdim; d++) {
-				_Ttype* t = make<_Ttype>(r, nv, d);
-				p->insert(t);
-			}
-			return p;
-		}
+  template <class _Ttype, class _Ptype>
+  _Ptype *
+  makePoly(int r, int nv, int maxdim)
+  {
+    _Ptype *p = new _Ptype(r, nv);
+    for (int d = 1; d <= maxdim; d++)
+      {
+        _Ttype *t = make<_Ttype>(r, nv, d);
+        p->insert(t);
+      }
+    return p;
+  }
 
-	Vector* makeVector(int n);
+  Vector *makeVector(int n);
 };
 
 #endif
diff --git a/dynare++/tl/testing/monoms.h b/dynare++/tl/testing/monoms.h
index 94b34a3da002ae4ec786ecfa9e784bf5298989f8..76c56e2a7d391cc41a703973884acd9ca6fc6021 100644
--- a/dynare++/tl/testing/monoms.h
+++ b/dynare++/tl/testing/monoms.h
@@ -10,115 +10,121 @@
 #include "sparse_tensor.h"
 #include "Vector.h"
 
-class IntGenerator {
-	int maxim;
-	double probab;
+class IntGenerator
+{
+  int maxim;
+  double probab;
 public:
-	IntGenerator()
-		: maxim(5), probab(0.3) {}
-	void init(int nf, int ny, int nv, int nw, int nu, int mx, double prob);
-	int get() const;
+  IntGenerator()
+    : maxim(5), probab(0.3)
+  {
+  }
+  void init(int nf, int ny, int nv, int nw, int nu, int mx, double prob);
+  int get() const;
 };
 
 extern IntGenerator intgen;
 
-
-class Monom : public IntSequence {
+class Monom : public IntSequence
+{
 public:
-	Monom(int len); // generate a random monom
-	Monom(int len, int item); // generate monom whose items are the given item
-	double deriv(const IntSequence& vars) const;
-	// this = this*m^ex (in monomial sense)
-	void multiplyWith(int ex, const Monom& m);
-	void print() const;
+  Monom(int len); // generate a random monom
+  Monom(int len, int item); // generate monom whose items are the given item
+  double deriv(const IntSequence &vars) const;
+  // this = this*m^ex (in monomial sense)
+  void multiplyWith(int ex, const Monom &m);
+  void print() const;
 };
 
 class Monom2Vector;
-class Monom1Vector {
-	friend class Monom2Vector;
-	int nx;
-	int len;
-	Monom** const x;
+class Monom1Vector
+{
+  friend class Monom2Vector;
+  int nx;
+  int len;
+  Monom **const x;
 public:
-	Monom1Vector(int nxx, int l);
-	~Monom1Vector();
-	void deriv(const IntSequence& c, Vector& out) const;
-	FGSTensor* deriv(int dim) const;
-	void print() const;
+  Monom1Vector(int nxx, int l);
+  ~Monom1Vector();
+  void deriv(const IntSequence &c, Vector &out) const;
+  FGSTensor *deriv(int dim) const;
+  void print() const;
 };
 
 //class Monom3Vector;
-class Monom2Vector {
-	int ny;
-	int nu;
-	int len;
-	Monom** const y;
-	Monom** const u;
+class Monom2Vector
+{
+  int ny;
+  int nu;
+  int len;
+  Monom **const y;
+  Monom **const u;
 public:
-	// generate random vector of monom two vector
-	Monom2Vector(int nyy, int nuu, int l);
-	// calculate g(x(y,u))
-	Monom2Vector(const Monom1Vector& g, const Monom2Vector& xmon);
-	~Monom2Vector();
-	void deriv(const Symmetry& s, const IntSequence& c, Vector& out) const;
-	FGSTensor* deriv(const Symmetry& s) const;
-	FGSContainer* deriv(int maxdim) const;
-	void print() const;
+  // generate random vector of monom two vector
+  Monom2Vector(int nyy, int nuu, int l);
+  // calculate g(x(y,u))
+  Monom2Vector(const Monom1Vector &g, const Monom2Vector &xmon);
+  ~Monom2Vector();
+  void deriv(const Symmetry &s, const IntSequence &c, Vector &out) const;
+  FGSTensor *deriv(const Symmetry &s) const;
+  FGSContainer *deriv(int maxdim) const;
+  void print() const;
 };
 
-class Monom4Vector {
-	int len;
-	int nx1;
-	int nx2;
-	int nx3;
-	int nx4;
-	Monom** const x1;
-	Monom** const x2;
-	Monom** const x3;
-	Monom** const x4;
+class Monom4Vector
+{
+  int len;
+  int nx1;
+  int nx2;
+  int nx3;
+  int nx4;
+  Monom **const x1;
+  Monom **const x2;
+  Monom **const x3;
+  Monom **const x4;
 public:
-    /* random for g(y,u,sigma) */
-	Monom4Vector(int l, int ny, int nu);
-	/* random for G(y,u,u',sigma) */
-	Monom4Vector(int l, int ny, int nu, int nup);
-	/* random for f(y+,y,y-,u) */
-	Monom4Vector(int l, int nbigg, int ng, int ny, int nu);
-	/* substitution f(G(y,u,u',sigma),g(y,u,sigma),y,u) */
-	Monom4Vector(const Monom4Vector& f, const Monom4Vector& bigg,
-				 const Monom4Vector& g);
-	~Monom4Vector();
-	FSSparseTensor* deriv(int dim) const;
-	FGSTensor* deriv(const Symmetry& s) const;
-	void deriv(const Symmetry& s, const IntSequence& coor, Vector& out) const;
-	void print() const;
+  /* random for g(y,u,sigma) */
+  Monom4Vector(int l, int ny, int nu);
+  /* random for G(y,u,u',sigma) */
+  Monom4Vector(int l, int ny, int nu, int nup);
+  /* random for f(y+,y,y-,u) */
+  Monom4Vector(int l, int nbigg, int ng, int ny, int nu);
+  /* substitution f(G(y,u,u',sigma),g(y,u,sigma),y,u) */
+  Monom4Vector(const Monom4Vector &f, const Monom4Vector &bigg,
+               const Monom4Vector &g);
+  ~Monom4Vector();
+  FSSparseTensor *deriv(int dim) const;
+  FGSTensor *deriv(const Symmetry &s) const;
+  void deriv(const Symmetry &s, const IntSequence &coor, Vector &out) const;
+  void print() const;
 protected:
-	void init_random();
+  void init_random();
 };
 
-
-struct SparseDerivGenerator {
-	int maxdimen;
-	FGSContainer* bigg;
-	FGSContainer* g;
-	FGSContainer* rcont;
-	FSSparseTensor** const ts;
-	SparseDerivGenerator(int nf, int ny, int nu, int nup, int nbigg, int ng,
-						 int mx, double prob, int maxdim);
-	~SparseDerivGenerator();
+struct SparseDerivGenerator
+{
+  int maxdimen;
+  FGSContainer *bigg;
+  FGSContainer *g;
+  FGSContainer *rcont;
+  FSSparseTensor **const ts;
+  SparseDerivGenerator(int nf, int ny, int nu, int nup, int nbigg, int ng,
+                       int mx, double prob, int maxdim);
+  ~SparseDerivGenerator();
 };
 
-
-struct DenseDerivGenerator {
-	int maxdimen;
-	FGSContainer* xcont;
-	FGSContainer* rcont;
-	FGSTensor** const ts;
-	UGSContainer* uxcont;
-	UGSTensor** const uts;
-	DenseDerivGenerator(int ng, int nx, int ny, int nu,
-						int mx, double prob, int maxdim);
-	void unfold();
-	~DenseDerivGenerator();
+struct DenseDerivGenerator
+{
+  int maxdimen;
+  FGSContainer *xcont;
+  FGSContainer *rcont;
+  FGSTensor **const ts;
+  UGSContainer *uxcont;
+  UGSTensor **const uts;
+  DenseDerivGenerator(int ng, int nx, int ny, int nu,
+                      int mx, double prob, int maxdim);
+  void unfold();
+  ~DenseDerivGenerator();
 };
 
 #endif
diff --git a/dynare++/utils/cc/exception.h b/dynare++/utils/cc/exception.h
index 7f843b3ae78b86062262abe899f7fb7c4cf23c0f..97de4863e1b297791f2a0f3fda47d54b0e52e610 100644
--- a/dynare++/utils/cc/exception.h
+++ b/dynare++/utils/cc/exception.h
@@ -11,41 +11,54 @@
 #include <string>
 #include <algorithm>
 
-namespace ogu {
-
-	/** A primitive exception. */
-	class Exception {
-		static const int file_length = 100;
-		static const int mes_length = 500;
-	protected:
-		char file[file_length];
-		int line;
-		char mes[mes_length];
-	public:
-		Exception(const char* f, int l, const char* m)
-			{
-				strncpy(file, f, file_length-1);
-				file[file_length-1] = '\0';
-				line = l;
-				strncpy(mes, m, std::min(mes_length-1,(int)strlen(m)));
-				mes[mes_length-1] = '\0';
-			}
-		Exception(const char* f, int l, const std::string& m)
-			{
-				strncpy(file, f, file_length-1);
-				file[file_length-1] = '\0';
-				line = l;
-				strncpy(mes, m.c_str(), std::min(mes_length-1,(int)m.length()));
-				mes[mes_length-1] = '\0';
-			}
-		virtual ~Exception() {}
-		void print(FILE* fd) const
-			{ fprintf(fd, "%s:%d: %s\n", file, line, mes); }
-		void print() const
-			{ print(stdout); }
-		const char* message() const
-			{ return mes; }
-	};
+namespace ogu
+{
+
+  /** A primitive exception. */
+  class Exception
+  {
+    static const int file_length = 100;
+    static const int mes_length = 500;
+  protected:
+    char file[file_length];
+    int line;
+    char mes[mes_length];
+  public:
+    Exception(const char *f, int l, const char *m)
+    {
+      strncpy(file, f, file_length-1);
+      file[file_length-1] = '\0';
+      line = l;
+      strncpy(mes, m, std::min(mes_length-1, (int) strlen(m)));
+      mes[mes_length-1] = '\0';
+    }
+    Exception(const char *f, int l, const std::string &m)
+    {
+      strncpy(file, f, file_length-1);
+      file[file_length-1] = '\0';
+      line = l;
+      strncpy(mes, m.c_str(), std::min(mes_length-1, (int) m.length()));
+      mes[mes_length-1] = '\0';
+    }
+    virtual ~Exception()
+    {
+    }
+    void
+    print(FILE *fd) const
+    {
+      fprintf(fd, "%s:%d: %s\n", file, line, mes);
+    }
+    void
+    print() const
+    {
+      print(stdout);
+    }
+    const char *
+    message() const
+    {
+      return mes;
+    }
+  };
 };
 
 #endif
diff --git a/dynare++/utils/cc/memory_file.h b/dynare++/utils/cc/memory_file.h
index 79f08717ebc140c9b08a15ba5fe5fa055df04cb6..a4937d14a0a9d25925c6cdc998980c67d647482a 100644
--- a/dynare++/utils/cc/memory_file.h
+++ b/dynare++/utils/cc/memory_file.h
@@ -5,51 +5,69 @@
 #ifndef OGU_MEMORY_FILE
 #define OGU_MEMORY_FILE
 
-namespace ogu {
-	/** This function calculates an offset of a given position in a
-	 * given string. The position is given by the line number and by
-	 * the offset in the line (both starting from 1). */
-	int calc_pos_offset(int length, const char* str, int line, int col);
-	/** This function calculates a line number and column number of a
-	 * character given by the offset in the string. It is inverse to
-	 * calc_pos_offset. */
-	void calc_pos_line_and_col(int length, const char* str, int offset,
-							   int& line, int& col);
+namespace ogu
+{
+  /** This function calculates an offset of a given position in a
+   * given string. The position is given by the line number and by
+   * the offset in the line (both starting from 1). */
+  int calc_pos_offset(int length, const char *str, int line, int col);
+  /** This function calculates a line number and column number of a
+   * character given by the offset in the string. It is inverse to
+   * calc_pos_offset. */
+  void calc_pos_line_and_col(int length, const char *str, int offset,
+                             int &line, int &col);
 
-	/** This class opens a given file and makes its copy in memory and
-	 * appends it with the '\0' character. Since the type of length is
-	 * int, it can store files with size at most 4GB. If the file
-	 * could be opened for reading, data is NULL and length is -1. If
-	 * the file is empty but exists, len is zero and data points to a
-	 * newly allocated memory containing '\0' character at the end. */
-	class MemoryFile {
-	protected:
-		int len;
-		char* data;
-	public:
-		MemoryFile(const char* fname);
-		virtual ~MemoryFile()
-			{if (data) delete [] data;}
-		int length() const
-			{return len;}
-		const char* base() const
-			{return data;}
-		bool exists() const
-			{return len != -1;}
-		/** Return the offset of a character in the given line
-		 * (starting from 1) with the given offset in the line. */
-		int offset(int line, int lineoff) const
-			{return calc_pos_offset(len, data, line, lineoff);}
-		/** Return the line number and column number of the character
-		 * defined by the offset. */
-		void line_and_col(int offset, int& line, int& col) const
-			{calc_pos_line_and_col(len, data, offset, line, col);}
-	};
+  /** This class opens a given file and makes its copy in memory and
+   * appends it with the '\0' character. Since the type of length is
+   * int, it can store files with size at most 4GB. If the file
+   * could be opened for reading, data is NULL and length is -1. If
+   * the file is empty but exists, len is zero and data points to a
+   * newly allocated memory containing '\0' character at the end. */
+  class MemoryFile
+  {
+  protected:
+    int len;
+    char *data;
+  public:
+    MemoryFile(const char *fname);
+    virtual ~MemoryFile()
+    {
+      if (data)
+        delete [] data;
+    }
+    int
+    length() const
+    {
+      return len;
+    }
+    const char *
+    base() const
+    {
+      return data;
+    }
+    bool
+    exists() const
+    {
+      return len != -1;
+    }
+    /** Return the offset of a character in the given line
+     * (starting from 1) with the given offset in the line. */
+    int
+    offset(int line, int lineoff) const
+    {
+      return calc_pos_offset(len, data, line, lineoff);
+    }
+    /** Return the line number and column number of the character
+     * defined by the offset. */
+    void
+    line_and_col(int offset, int &line, int &col) const
+    {
+      calc_pos_line_and_col(len, data, offset, line, col);
+    }
+  };
 
-	
 };
 
-
 #endif
 
 // Local Variables:
diff --git a/dynare++/utils/cc/pascal_triangle.h b/dynare++/utils/cc/pascal_triangle.h
index 2e989aa5723cf21dd042f2bffc021884cf8ffb51..66b4bac6b2a03ade3f9867a1a3be7dab55d96500 100644
--- a/dynare++/utils/cc/pascal_triangle.h
+++ b/dynare++/utils/cc/pascal_triangle.h
@@ -7,43 +7,54 @@
 
 #include <vector>
 
-namespace ogu {
-
-	using std::vector;
-
-	class PascalRow : public vector<int> {
-		int k;
-	public:
-		PascalRow()
-			: vector<int>(), k(1)
-			{ push_back(2); }
-		void setFromPrevious(const PascalRow& prev);
-		void prolong(const PascalRow& prev);
-		void prolongFirst(int n);
-		void print() const;
-	};
-
-	class PascalTriangle {
-		vector<PascalRow> tr;
-	public:
-		PascalTriangle()
-			{tr.push_back(PascalRow());}
-		PascalTriangle(const PascalTriangle& triang)
-			: tr(triang.tr) {}
-		const PascalTriangle& operator=(const PascalTriangle& triang)
-			{ tr = triang.tr; return *this;}
-		int noverk(int n, int k);
-		void print() const;
-	protected:
-		void ensure(int n, int k);
-		int max_n() const;
-		int max_k() const;
-	};
+namespace ogu
+{
+
+  using std::vector;
+
+  class PascalRow : public vector<int>
+  {
+    int k;
+  public:
+    PascalRow()
+      : vector<int>(), k(1)
+    {
+      push_back(2);
+    }
+    void setFromPrevious(const PascalRow &prev);
+    void prolong(const PascalRow &prev);
+    void prolongFirst(int n);
+    void print() const;
+  };
+
+  class PascalTriangle
+  {
+    vector<PascalRow> tr;
+  public:
+    PascalTriangle()
+    {
+      tr.push_back(PascalRow());
+    }
+    PascalTriangle(const PascalTriangle &triang)
+      : tr(triang.tr)
+    {
+    }
+    const PascalTriangle &
+    operator=(const PascalTriangle &triang)
+    {
+      tr = triang.tr; return *this;
+    }
+    int noverk(int n, int k);
+    void print() const;
+  protected:
+    void ensure(int n, int k);
+    int max_n() const;
+    int max_k() const;
+  };
 };
 
 extern ogu::PascalTriangle ptriang;
 
-
 #endif
 
 // Local Variables:
diff --git a/examples/NK_baseline.mod b/examples/NK_baseline.mod
index 67afdec21f57dfce6ae4a4911f09a7f42b37d0b6..90954a4ed0ff6a960110066ea2429c6397f288db 100644
--- a/examples/NK_baseline.mod
+++ b/examples/NK_baseline.mod
@@ -155,18 +155,18 @@ sigma_m  =-5.85;
 Lambdamu=3.4e-3;
 LambdaA = 2.8e-3;
 
-LambdaYd= (LambdaA+alppha*Lambdamu)/(1-alppha);
 
 /*
 The following parameters are set in the steady state file as they depend on other 
-deep parameters that were estimated in the original study. Setting them in the
+deep parameters (some were estimated in the original study). Setting them in the
 steady state file means they are updated for every parameter draw in the MCMC
 algorithm, while the parameters initialized here are only set once for the initial
 values of the parameters they depend on:
 
-gammma1 as it depends on LambdaA, alppha, Lambdamu, betta, and delta
-Rbar =0 as it depends on PI, LambdaA, alppha, Lambdamu, and betta
-Lambdax
+gammma1=mu_z*mu_I/betta-(1-delta);
+R=1+(PIbar*mu_z/betta-1);
+Lambdax=exp(LambdaYd);
+LambdaYd= (LambdaA+alppha*Lambdamu)/(1-alppha);
 */
 
 
diff --git a/examples/NK_baseline_steadystate.m b/examples/NK_baseline_steadystate.m
index f7254b8fbb9b33f38029bdb2e7ec55dc2540f833..795c09979839c0cd277d1af4442cd5833ceb2b77 100644
--- a/examples/NK_baseline_steadystate.m
+++ b/examples/NK_baseline_steadystate.m
@@ -36,6 +36,7 @@ d=1;
 phi=1;
 m=0;
 zeta=1;
+LambdaYd= (LambdaA+alppha*Lambdamu)/(1-alppha);
 mu_z=exp(LambdaYd);
 mu_I=exp(Lambdamu);
 mu_A=exp(LambdaA);
diff --git a/examples/fs2000.mod b/examples/fs2000.mod
index 5b7ac75b8d27cab9cb3a1796404f27d6cbbd074a..3359370230c7a3f18cb3855393b0bc372520eb6d 100644
--- a/examples/fs2000.mod
+++ b/examples/fs2000.mod
@@ -6,22 +6,26 @@
  * 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 prior distribution follows the one originally specified in Schorfheide's paper.
- * Note that the beta prior for rho implies an asymptote and corresponding prior mode 
- * for rho at 0. It is generally recommended to avoid this extreme type of prior.  
+ * The prior distribution follows the one originally specified in Schorfheide's
+ * paper, except for parameter rho. In the paper, the elicited beta prior for rho
+ * implies an asymptote and corresponding prior mode at 0. It is generally
+ * recommended to avoid this extreme type of prior. Some optimizers, for instance
+ * mode_compute=12 (Mathworks' particleswarm algorithm) may find a posterior mode
+ * with rho equal to zero. We lowered the value of the prior standard deviation
+ * (changing .223 to .100) to remove the asymptote.
  *
  * 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
+ * This implementation was originally 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
+ * Copyright (C) 2004-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -109,7 +113,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.100;
 psi, beta_pdf, 0.65, 0.05;
 del, beta_pdf, 0.01, 0.005;
 stderr e_a, inv_gamma_pdf, 0.035449, inf;
diff --git a/license.txt b/license.txt
index 76243fd5eb2014a1f172de156e76217b69dd268b..2decd038dc3f0cbb616b3a30a24f4c9c72f8bbc1 100644
--- a/license.txt
+++ b/license.txt
@@ -1,16 +1,15 @@
-Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
+Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
 Upstream-Name: Dynare
-Upstream-Contact: Dynare Team, whose members in 2016 are:
+Upstream-Contact: Dynare Team, whose members in 2017 are:
                   Stéphane Adjemian <stephane.adjemian@univ-lemans.fr>
                   Houtan Bastani <houtan@dynare.org>
                   Michel Juillard <michel.juillard@mjui.fr>
                   Frédéric Karamé <frederic.karame@univ-lemans.fr>
                   Junior Maih <junior.maih@gmail.com>
                   Ferhat Mihoubi <fmihoubi@univ-evry.fr>
-                  George Perendia <george@perendia.orangehome.co.uk>
                   Johannes Pfeifer <jpfeifer@gmx.de>
-                  Marco Ratto <marco.ratto@jrc.ec.europa.eu>
-                  Sébastien Villemot <sebastien@dynare.org>
+                  Marco Ratto <marco.ratto@ec.europa.eu>
+                  Sébastien Villemot <sebastien.villemot@sciencespo.fr>
 Source: http://www.dynare.org
 
 Files: *
@@ -18,8 +17,8 @@ Copyright: 1996-2017 Dynare Team
 License: GPL-3+
 
 Files: matlab/AIM/SP*
-Copyright: public-domain
-License: public-domain
+Copyright: none
+License: public-domain-aim
  This code is in the public domain and may be used freely.
  However the authors would appreciate acknowledgement of the source by
  citation of any of the following papers:
@@ -86,6 +85,57 @@ Copyright: 2016 Benjamin Born and Johannes Pfeifer
            2016 Dynare Team
 License: GPL-3+
 
+Files: matlab/gsa/Morris_Measure_Groups.m
+       matlab/gsa/Sampling_Function_2.m
+Copyright: 2005 European Commission
+           2012 Dynare Team
+License: GPL-3+
+Comment: Written by Jessica Cariboni and Francesca Campolongo
+ Joint Research Centre, The European Commission,
+
+Files: matlab/gsa/cumplot.m
+       matlab/gsa/filt_mc_.m
+       matlab/gsa/gsa_plotmatrix.m
+       matlab/gsa/gsa_skewness.m
+       matlab/gsa/gsa_speed.m
+       matlab/gsa/log_trans_.m
+       matlab/gsa/map_calibration.m
+       matlab/gsa/map_ident_.m
+       matlab/gsa/mcf_analysis.m
+       matlab/gsa/myboxplot.m
+       matlab/gsa/myprctilecol.m
+       matlab/gsa/prior_draw_gsa.m
+       matlab/gsa/read_data.m
+       matlab/gsa/redform_map.m
+       matlab/gsa/redform_screen.m
+       matlab/gsa/scatter_mcf.m
+       matlab/gsa/smirnov.m
+       matlab/gsa/stab_map_.m
+       matlab/gsa/stab_map_1.m
+       matlab/gsa/stab_map_2.m
+       matlab/gsa/stand_.m
+       matlab/gsa/tcrit.m
+       matlab/gsa/teff.m
+       matlab/gsa/trank.m
+Copyright: 2011-2017 European Commission
+           2011-2017 Dynare Team
+License: GPL-3+
+
+Files: matlab/gsa/pick.m
+Copyright: none
+License: public-domain-jrc
+ This software has been developed at the Joint Research Centre of European Commission
+ by officers in the course of their official duties. This software is not subject to copyright
+ protection and is in the public domain. It is an experimental system. The Joint Research Centre
+ of European Commission assumes no responsibility whatsoever for its use by other parties
+ and makes no guarantees, expressed or implied, about its quality, reliability, or any other
+ characteristic. We would appreciate acknowledgement if the software is used.
+Comment: This file is part of GLUEWIN.
+ The program has been developed by M. Ratto, European Commission, Joint Research Centre,
+ Institute for the Protection and Security of The Citizen, Technological and Economic Risk Management,
+ Applied Statistics, as a deliverable of the IMPACT project
+ (EC Fifth Framework Programme, SCA Project, IST-1999-11313, DG-INFSO).
+
 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
@@ -127,37 +177,24 @@ Copyright: 2005 Jos van der Geest <jos@jasen.nl>
            2013 Christophe Gouel
            2016 Dynare Team
 License: BSD-2-clause
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are
- met:
- .
-     * Redistributions of source code must retain the above copyright
-       notice, this list of conditions and the following disclaimer.
-     * Redistributions in binary form must reproduce the above copyright
-       notice, this list of conditions and the following disclaimer in
-       the documentation and/or other materials provided with the distribution
- .
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
 
 Files: matlab/lmmcp/lmmcp.m
 Copyright: 2005 Christian Kanzow and Stefania Petra
            2013 Christophe Gouel
            2014 Dynare Team
-License: permissive
+License: permissive-lmmcp
  Unlimited permission is granted to everyone to use, copy, modify or
  distribute this software.
 
-Files: doc/dynare.texi doc/*.tex doc/*.svg doc/*.dia doc/*.pdf doc/*.bib
+Files: matlab/utilities/graphics/distinguishable_colors.m
+Copyright: 2010-2011 Timothy E. Holy
+License: BSD-2-clause
+
+Files: matlab/utilities/graphics/colorspace.m
+Copyright: 2005-2010 Pascal Getreuer
+License: BSD-2-clause
+
+Files: doc/dynare.texi doc/*.tex doc/*.svg doc/*.pdf doc/*.bib
 Copyright: 1996-2017 Dynare Team
 License: GFDL-NIV-1.3+
 
@@ -206,7 +243,7 @@ Files: m4/ax_compare_version.m4
 Copyright: 2008 Tim Toolan <toolan@ele.uri.edu>
 License: permissive-autoconf
 
-Files: m4/ax_latex_bibtex_test.m4 m4/ax_latex_class.m4 m4/ax_tex_test.m4
+Files: m4/ax_latex_class.m4 m4/ax_tex_test.m4
 Copyright: 2008 Boretti Mathieu <boretti@eig.unige.ch>
            2009 Dynare Team
 License: LGPL-2.1+
@@ -235,7 +272,7 @@ Copyright: 1996-2011 Daniel Waggoner and Tao Zha
 License: GPL-3+
 
 Files: contrib/ms-sbvar/switch_dw/state_space/sbvar/dw_csminwel.c
- state_space/sbvar/dw_csminwel.h
+       contrib/ms-sbvar/switch_dw/state_space/sbvar/dw_csminwel.h
 Copyright: 1996 Christopher Sims
            2003 Karibzhanov, Waggoner and Zha
 License: GPL-3+
@@ -316,7 +353,7 @@ License: GPL-3+
 
 Files: contrib/dmm/randlib/*
 Copyright: none
-License: public-domain
+License: public-domain-dmm
  We place the Randlib code that we have written in the public domain.  
  .
                                  NO WARRANTY
@@ -336,6 +373,29 @@ License: public-domain
      ITS ANALYSIS BEING  RENDERED INACCURATE OR  LOSSES SUSTAINED  BY THIRD
      PARTIES) THE PROGRAM.
 
+License: BSD-2-clause
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+ .
+     * Redistributions of source code must retain the above copyright
+       notice, this list of conditions and the following disclaimer.
+     * Redistributions in binary form must reproduce the above copyright
+       notice, this list of conditions and the following disclaimer in
+       the documentation and/or other materials provided with the distribution
+ .
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+
 License: GFDL-NIV-1.3+
  Permission is granted to copy, distribute and/or modify this document
  under the terms of the GNU Free Documentation License, Version 1.3 or
@@ -344,21 +404,6 @@ License: GFDL-NIV-1.3+
  .
  A copy of the license can be found at <http://www.gnu.org/licenses/fdl.txt>
 
-License: GPL-2+
- This program 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 2 of
- the License, or (at your option) any later version.
- .
- This program 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 this program.  If not, see
- <http://www.gnu.org/licenses/>.
-
 License: GPL-2+ with Autoconf exception
  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License as
diff --git a/m4/ax_latex_bibtex_test.m4 b/m4/ax_latex_bibtex_test.m4
deleted file mode 100644
index 17ab4d57b5ec320f98b008c626d9ad746ab4d6ac..0000000000000000000000000000000000000000
--- a/m4/ax_latex_bibtex_test.m4
+++ /dev/null
@@ -1,66 +0,0 @@
-# ===========================================================================
-#          http://www.nongnu.org/autoconf-archive/ax_latex_test.html
-# ===========================================================================
-#
-# OBSOLETE MACRO
-#
-#   Deprecated because of licensing issues. The Lesser GPL imposes licensing
-#   restrictions on the generated configure script unless it is augmented
-#   with an Autoconf Exception clause.
-#
-# SYNOPSIS
-#
-#   AX_LATEX_BIBTEX_TEST(FILEDATA,BIBDATA,VARIABLETOSET,[NOCLEAN])
-#
-# DESCRIPTION
-#
-#   This macros creates a bib file called contest.bib with BIBDATA,
-#   executes the latex application with FILEDATA as input, then runs
-#   bibtex on the resulting aux file, and finally sets VARIABLETOSET
-#   to yes or no depending on the result. If NOCLEAN is set, the folder
-#   used for the test is not deleted after testing.
-#
-#   The macro assumes that the variables PDFLATEX and BIBTEX are set.
-#
-#   Adapted from the macro AX_LATEX_TEST by Sébastien Villemot.
-#
-# LICENSE
-#
-#   Copyright (c) 2008 Boretti Mathieu <boretti@eig.unige.ch>
-#   Copyright (c) 2009 Dynare Team
-#
-#   This library is free software; you can redistribute it and/or modify it
-#   under the terms of the GNU Lesser General Public License as published by
-#   the Free Software Foundation; either version 2.1 of the License, or (at
-#   your option) any later version.
-#
-#   This library 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 Lesser
-#   General Public License for more details.
-#
-#   You should have received a copy of the GNU Lesser General Public License
-#   along with this library. If not, see <http://www.gnu.org/licenses/>.
-
-AC_DEFUN([AX_LATEX_BIBTEX_TEST],[
-rm -rf conftest.dir/.acltx
-AS_MKDIR_P([conftest.dir/.acltx])
-cd conftest.dir/.acltx
-m4_ifval([$3],[$3="no"; export $3;])
-cat > conftest.tex << ACLEOF
-$1
-ACLEOF
-cat > conftest.bib << ACLEOF
-$2
-ACLEOF
-$PDFLATEX conftest 2>&1 1>output
-$BIBTEX conftest 2>&1 1>output2 m4_ifval([$3],[&& $3=yes])
-cd ..
-cd ..
-sed 's/^/| /' conftest.dir/.acltx/conftest.tex >&5
-echo "$as_me:$LINENO: executing $PDFLATEX conftest" >&5
-sed 's/^/| /' conftest.dir/.acltx/output >&5
-echo "$as_me:$LINENO: executing $BIBTEX conftest" >&5
-sed 's/^/| /' conftest.dir/.acltx/output2 >&5
-m4_ifval([$4],,[rm -rf conftest.dir/.acltx])
-])
diff --git a/m4/ax_matlab_version.m4 b/m4/ax_matlab_version.m4
index 282d2ad547ecca6443c3f24a28cf757377433ea5..6f01df9f2b694ca8686a45b327d69734da00073a 100644
--- a/m4/ax_matlab_version.m4
+++ b/m4/ax_matlab_version.m4
@@ -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
+    *2017a | *2017A)
+      MATLAB_VERSION="9.2"
+      ;;
     *2016b | *2016B)
       MATLAB_VERSION="9.1"
       ;;
diff --git a/matlab/@dynTimeIndex/dynTimeIndex.m b/matlab/@dynTimeIndex/dynTimeIndex.m
deleted file mode 100644
index 323122c4b50d519c33acfe9784335c9636696cdd..0000000000000000000000000000000000000000
--- a/matlab/@dynTimeIndex/dynTimeIndex.m
+++ /dev/null
@@ -1,61 +0,0 @@
-function t = dynTimeIndex() % --*-- Unitary tests --*--
-
-% t = dynTimeIndex()
-%
-% Constructor for the dynTimeIndex class.
-%
-% INPUTS:
-%  None.
-%
-% OUTPUTS:
-%  * t, dynTimeIndex object.
-%
-% DESCRIPTION:
-%  The dynTimeIndex object is used to shift backward or forward dseries objects. For instance, if ts
-%  is a dseries object and t is a dynTimeIndex object then the following expressions are equivalent:
-%
-%      us = ts.lag()
-%      us = ts.lag(1)
-%      us = lag(ts,1)
-%      us = ts(t-1)
-%
-%  This class has only one member: t = int8(0) when instantiated.
-
-% 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/>.
-
-t = struct();
-
-t.index = int8(0);
-
-t = class(t,'dynTimeIndex');
-
-%@test:1
-%$ % Instantiate a dynTimeIndex object
-%$ try
-%$     u = dynTimeIndex();
-%$     t(1) = 1;
-%$ catch
-%$     t(1) = 0;
-%$ end
-%$
-%$ if t(1)
-%$   t(2) = isa(u,'dynTimeIndex');
-%$ end
-%$
-%$ T = all(t);
-%@eof:1
\ No newline at end of file
diff --git a/matlab/@dynTimeIndex/minus.m b/matlab/@dynTimeIndex/minus.m
deleted file mode 100644
index dff65f42df1f4c42397489c8f1f43201d94da8fc..0000000000000000000000000000000000000000
--- a/matlab/@dynTimeIndex/minus.m
+++ /dev/null
@@ -1,62 +0,0 @@
-function C = minus(A,B) % --*-- Unitary tests --*--
-
-% C = minus(A,B)
-%
-% Overloads binary minus operator.
-%
-% INPUTS:
-%  * A, dynTimeIndex object.
-%  * B, integer scalar.
-%
-% OUTPUTS:
-%  * C, dynTimeIndex object.
-%
-% EXAMPLE:
-%
-%  >> t = dynTimeIndex();
-%  >> t.index
-%
-%  ans =
-%
-%      0
-%
-%  >> s = t-1;
-%  >> s.index
-%
-%  ans =
-%
-%      -1
-%
-
-% 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 ~(isa(A,'dynTimeIndex') || isint(B))
-    error(['dynTimeIndex::plus: Input arguments ''' inputname(1) ''' and ''' inputname(2) ''' must be a dynTimeIndex object and an integer!'])
-end
-
-C = struct();
-C.index = A.index-B;
-C = class(C,'dynTimeIndex');
-
-%@test:1
-%$ a = dynTimeIndex();
-%$ b = a-1;
-%$ t(1) = isa(b,'dynTimeIndex');
-%$ t(2) = isequal(b.index,-int8(1));
-%$ T = all(t);
-%@eof:1
\ No newline at end of file
diff --git a/matlab/@dynTimeIndex/mpower.m b/matlab/@dynTimeIndex/mpower.m
deleted file mode 100644
index c4077caaa25059fe484f49b8b5fc8370705b3ddd..0000000000000000000000000000000000000000
--- a/matlab/@dynTimeIndex/mpower.m
+++ /dev/null
@@ -1,74 +0,0 @@
-function C = mpower(A,B) % --*-- Unitary tests --*--
-
-% C = mpower(A,B)
-%
-% Overloads binary mpower operator (^).
-%
-% INPUTS :
-%  * A, dynTimeIndex object.
-%  * B, integer scalar.
-%
-% OUTPUTS :
-%  * C, dynTimeIndex object.
-%
-% EXAMPLE 1 :
-%
-%  >> B = dynTimeIndex()-1;
-%  >> B
-%  B = <dynTimeIndex: -1>
-%  >> B^4
-%  ans = <dynTimeIndex: -4>
-%  >>
-%
-%  EXAMPLE 2 :
-%  This method can be used to apply the lead and lag methods an arbitrary number of times to a dseries object. For instance, if 
-%  ts is a dseries object, and if we define
-% 
-%  >> B = dynTimeIndex()-1;
-%  >> F = dynTimeIndex()+1;
-%
-%  B and F can be used as lag and lead operators and the following syntax:
-%
-%  >> us = ts(F^2);
-%
-%  is equivalent to
-%
-%  >> us = ts.lead(2)
-%
-%  or
-%
-%  >> us = ts.lead.lead
-%
-
-% 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 ~(isa(A,'dynTimeIndex') || isint(B))
-    error(['dynTimeIndex::mpower: Input arguments ''' inputname(1) ''' and ''' inputname(2) ''' must be a dynTimeIndex object and an integer!'])
-end
-
-C = struct();
-C.index = A.index*B;
-C = class(C,'dynTimeIndex');
-
-%@test:1
-%$ a = dynTimeIndex()+1;
-%$ b = a^2;
-%$ t(1) = isa(b,'dynTimeIndex');
-%$ t(2) = isequal(b.index,int8(2));
-%$ T = all(t);
-%@eof:1
\ No newline at end of file
diff --git a/matlab/@dynTimeIndex/plus.m b/matlab/@dynTimeIndex/plus.m
deleted file mode 100644
index 7b4752db922ad4d1017cdd67db6fbca61d113905..0000000000000000000000000000000000000000
--- a/matlab/@dynTimeIndex/plus.m
+++ /dev/null
@@ -1,62 +0,0 @@
-function C = plus(A,B) % --*-- Unitary tests --*--
-
-% C = plus(A,B)
-%
-% Overloads binary plus operator.
-%
-% INPUTS:
-%  * A, dynTimeIndex object.
-%  * B, integer scalar.
-%
-% OUTPUTS:
-%  * C, dynTimeIndex object.
-%
-% EXAMPLE:
-%
-%  >> t = dynTimeIndex();
-%  >> t.index
-%
-%  ans =
-%
-%      0
-%
-%  >> s = t+1;
-%  >> s.index
-%
-%  ans =
-%
-%      1
-%
-
-% 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 ~(isa(A,'dynTimeIndex') || isint(B))
-    error(['dynTimeIndex::plus: Input arguments ''' inputname(1) ''' and ''' inputname(2) ''' must be a dynTimeIndex object and an integer!'])
-end
-
-C = struct();
-C.index = A.index+B;
-C = class(C,'dynTimeIndex');
-
-%@test:1
-%$ a = dynTimeIndex();
-%$ b = a+1;
-%$ t(1) = isa(b,'dynTimeIndex');
-%$ t(2) = isequal(b.index,int8(1));
-%$ T = all(t);
-%@eof:1
\ No newline at end of file
diff --git a/matlab/@dynTimeIndex/subsref.m b/matlab/@dynTimeIndex/subsref.m
deleted file mode 100644
index 6c8aa79d4279dcbbb5610c729dcc6e0af7521d9d..0000000000000000000000000000000000000000
--- a/matlab/@dynTimeIndex/subsref.m
+++ /dev/null
@@ -1,54 +0,0 @@
-function B = subsref(A,S) % --*-- Unitary tests --*--
-
-% B = subsref(A,S)
-%
-% Overloads the subsref method for dynTimeIndex class. This method only allows to get
-% the value of the field `index`.
-    
-% 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 length(S)>1
-    error('dynTimeIndex::subsref: Something is wrong in your syntax!')
-end
-
-if isequal(S.type,'.')
-    if isequal(S.subs,'index')
-        B = builtin('subsref', A, S(1));
-    else
-        error(['dynTimeIndex::subsref: ' S.subs  ' is not a known member!'])
-    end
-else
-    error('dynTimeIndex::subsref: Something is wrong in your syntax!')
-end
-
-%@test:1
-%$ % Instantiate a dynTimeIndex object
-%$ u = dynTimeIndex();
-%$ try
-%$    v = u.index;
-%$    t(1) = 1;
-%$ catch
-%$    t(1) = 0;
-%$ end
-%$
-%$ if t(1)
-%$    t(2) = isequal(v,int8(0));
-%$ end
-%$
-%$ T = all(t);
-%@eof:1
\ No newline at end of file
diff --git a/matlab/AHessian.m b/matlab/AHessian.m
index 561c380a00da5f3872fb84227c0c73d6dcdc6762..f9d9db6e0ca667eb13c3da412dd412207f9aeb55 100644
--- a/matlab/AHessian.m
+++ b/matlab/AHessian.m
@@ -8,7 +8,7 @@ function [AHess, DLIK, LIK] = AHessian(T,R,Q,H,P,Y,DT,DYss,DOm,DH,DP,start,mf,ka
 % NOTE: the derivative matrices (DT,DR ...) are 3-dim. arrays with last
 % dimension equal to the number of structural parameters
 
-% Copyright (C) 2011-2016 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -26,123 +26,123 @@ function [AHess, DLIK, LIK] = AHessian(T,R,Q,H,P,Y,DT,DYss,DOm,DH,DP,start,mf,ka
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 
-    k = size(DT,3);                                 % number of structural parameters
-    smpl = size(Y,2);                               % Sample size.
-    pp   = size(Y,1);                               % Maximum number of observed variables.
-    mm   = size(T,2);                               % Number of state variables.
-    a    = zeros(mm,1);                             % State vector.
-    Om   = R*Q*transpose(R);                        % Variance of R times the vector of structural innovations.
-    t    = 0;                                       % Initialization of the time index.
-    oldK = 0;
-    notsteady   = 1;                                % Steady state flag.
-    F_singular  = 1;
+k = size(DT,3);                                 % number of structural parameters
+smpl = size(Y,2);                               % Sample size.
+pp   = size(Y,1);                               % Maximum number of observed variables.
+mm   = size(T,2);                               % Number of state variables.
+a    = zeros(mm,1);                             % State vector.
+Om   = R*Q*transpose(R);                        % Variance of R times the vector of structural innovations.
+t    = 0;                                       % Initialization of the time index.
+oldK = 0;
+notsteady   = 1;                                % Steady state flag.
+F_singular  = 1;
 
 lik  = zeros(smpl,1);                           % Initialization of the vector gathering the densities.
 LIK  = Inf;                                     % Default value of the log likelihood.
-if nargout > 1,
+if nargout > 1
     DLIK  = zeros(k,1);                             % Initialization of the score.
 end
-    AHess  = zeros(k,k);                             % Initialization of the Hessian
-    Da    = zeros(mm,k);                             % State vector.
-    Dv = zeros(length(mf),k);
-    
+AHess  = zeros(k,k);                             % Initialization of the Hessian
+Da    = zeros(mm,k);                             % State vector.
+Dv = zeros(length(mf),k);
+
 %     for ii = 1:k
-%         DOm = DR(:,:,ii)*Q*transpose(R) + R*DQ(:,:,ii)*transpose(R) + R*Q*transpose(DR(:,:,ii)); 
+%         DOm = DR(:,:,ii)*Q*transpose(R) + R*DQ(:,:,ii)*transpose(R) + R*Q*transpose(DR(:,:,ii));
 %     end
-    
-    while notsteady && t<smpl
-        t  = t+1;
-        v  = Y(:,t)-a(mf);
-        F  = P(mf,mf) + H;
-        if rcond(F) < kalman_tol
-            if ~all(abs(F(:))<kalman_tol)
-                return
-            else
-                a = T*a;
-                P = T*P*transpose(T)+Om;
-            end
+
+while notsteady && t<smpl
+    t  = t+1;
+    v  = Y(:,t)-a(mf);
+    F  = P(mf,mf) + H;
+    if rcond(F) < kalman_tol
+        if ~all(abs(F(:))<kalman_tol)
+            return
         else
-            F_singular = 0;
-            iF     = inv(F);
-            K      = P(:,mf)*iF;
-            lik(t) = log(det(F))+transpose(v)*iF*v;
-
-            [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K);
-            
-            		for ii = 1:k
-                        Dv(:,ii)   = -Da(mf,ii) - DYss(mf,ii);
-                        Da(:,ii)   = DT(:,:,ii)*(a+K*v) + T*(Da(:,ii)+DK(:,:,ii)*v + K*Dv(:,ii));
-                        if t>=start && nargout > 1
-                            DLIK(ii,1)  = DLIK(ii,1) + trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v;
-                        end
-                    end
-                    vecDPmf = reshape(DP(mf,mf,:),[],k);
-%                     iPmf = inv(P(mf,mf));
-                    if t>=start
-                        AHess = AHess + Dv'*iF*Dv + .5*(vecDPmf' * kron(iF,iF) * vecDPmf);
-                    end
-            a      = T*(a+K*v);                   
-            P      = T*(P-K*P(mf,:))*transpose(T)+Om;
-            DP     = DP1;
+            a = T*a;
+            P = T*P*transpose(T)+Om;
         end
-        notsteady = max(max(abs(K-oldK))) > riccati_tol;
-        oldK = K;
-    end
+    else
+        F_singular = 0;
+        iF     = inv(F);
+        K      = P(:,mf)*iF;
+        lik(t) = log(det(F))+transpose(v)*iF*v;
 
-    if F_singular
-        error('The variance of the forecast error remains singular until the end of the sample')
-    end
+        [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K);
 
-    
-    if t < smpl
-        t0 = t+1;
-        while t < smpl
-            t = t+1;
-            v = Y(:,t)-a(mf);
-                  	for ii = 1:k
-                        Dv(:,ii)   = -Da(mf,ii)-DYss(mf,ii);
-                        Da(:,ii)   = DT(:,:,ii)*(a+K*v) + T*(Da(:,ii)+DK(:,:,ii)*v + K*Dv(:,ii));
-                if t>=start && nargout >1
-                   DLIK(ii,1)  = DLIK(ii,1) + trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v;
-                end
-                    end
-             if t>=start
-                AHess = AHess + Dv'*iF*Dv; 
-             end   
-            a = T*(a+K*v);
-        lik(t) = transpose(v)*iF*v;
+        for ii = 1:k
+            Dv(:,ii)   = -Da(mf,ii) - DYss(mf,ii);
+            Da(:,ii)   = DT(:,:,ii)*(a+K*v) + T*(Da(:,ii)+DK(:,:,ii)*v + K*Dv(:,ii));
+            if t>=start && nargout > 1
+                DLIK(ii,1)  = DLIK(ii,1) + trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v;
+            end
+        end
+        vecDPmf = reshape(DP(mf,mf,:),[],k);
+        %                     iPmf = inv(P(mf,mf));
+        if t>=start
+            AHess = AHess + Dv'*iF*Dv + .5*(vecDPmf' * kron(iF,iF) * vecDPmf);
         end
-        AHess = AHess + .5*(smpl-t0+1)*(vecDPmf' * kron(iF,iF) * vecDPmf);
-        if nargout > 1
+        a      = T*(a+K*v);
+        P      = T*(P-K*P(mf,:))*transpose(T)+Om;
+        DP     = DP1;
+    end
+    notsteady = max(max(abs(K-oldK))) > riccati_tol;
+    oldK = K;
+end
+
+if F_singular
+    error('The variance of the forecast error remains singular until the end of the sample')
+end
+
+
+if t < smpl
+    t0 = t+1;
+    while t < smpl
+        t = t+1;
+        v = Y(:,t)-a(mf);
         for ii = 1:k
-%             DLIK(ii,1)  = DLIK(ii,1) + (smpl-t0+1)*trace( iF*DF(:,:,ii) );
+            Dv(:,ii)   = -Da(mf,ii)-DYss(mf,ii);
+            Da(:,ii)   = DT(:,:,ii)*(a+K*v) + T*(Da(:,ii)+DK(:,:,ii)*v + K*Dv(:,ii));
+            if t>=start && nargout >1
+                DLIK(ii,1)  = DLIK(ii,1) + trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v;
+            end
+        end
+        if t>=start
+            AHess = AHess + Dv'*iF*Dv;
         end
+        a = T*(a+K*v);
+        lik(t) = transpose(v)*iF*v;
+    end
+    AHess = AHess + .5*(smpl-t0+1)*(vecDPmf' * kron(iF,iF) * vecDPmf);
+    if nargout > 1
+        for ii = 1:k
+            %             DLIK(ii,1)  = DLIK(ii,1) + (smpl-t0+1)*trace( iF*DF(:,:,ii) );
         end
-        lik(t0:smpl) = lik(t0:smpl) + log(det(F));
-%         for ii = 1:k;
-%             for jj = 1:ii
-%              H(ii,jj) = trace(iPmf*(.5*DP(mf,mf,ii)*iPmf*DP(mf,mf,jj) + Dv(:,ii)*Dv(:,jj)'));
-%             end
-%         end
-    end    
-    
-AHess = -AHess;  
-if nargout > 1,
+    end
+    lik(t0:smpl) = lik(t0:smpl) + log(det(F));
+    %         for ii = 1:k;
+    %             for jj = 1:ii
+    %              H(ii,jj) = trace(iPmf*(.5*DP(mf,mf,ii)*iPmf*DP(mf,mf,jj) + Dv(:,ii)*Dv(:,jj)'));
+    %             end
+    %         end
+end
+
+AHess = -AHess;
+if nargout > 1
     DLIK = DLIK/2;
 end
 % adding log-likelihhod constants
 lik = (lik + pp*log(2*pi))/2;
 
 LIK = sum(lik(start:end)); % Minus the log-likelihood.
-% end of main function    
-    
+                           % end of main function
+
 function [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K)
 
-            k      = size(DT,3);
-            tmp    = P-K*P(mf,:);
+k      = size(DT,3);
+tmp    = P-K*P(mf,:);
 
 for ii = 1:k
-    DF(:,:,ii)  = DP(mf,mf,ii) + DH(:,:,ii); 
+    DF(:,:,ii)  = DP(mf,mf,ii) + DH(:,:,ii);
     DiF(:,:,ii) = -iF*DF(:,:,ii)*iF;
     DK(:,:,ii)  = DP(:,mf,ii)*iF + P(:,mf)*DiF(:,:,ii);
     Dtmp        = DP(:,:,ii) - DK(:,:,ii)*P(mf,:) - K*DP(mf,:,ii);
@@ -150,6 +150,3 @@ for ii = 1:k
 end
 
 % end of computeDKalman
-
-
-            
\ No newline at end of file
diff --git a/matlab/AIM/SPAimerr.m b/matlab/AIM/SPAimerr.m
index 2894a89a78e7cd9b54dec4a8e68193f8a7ca3418..6467479287eaab62df1caf12537c31d9ba4af85f 100644
--- a/matlab/AIM/SPAimerr.m
+++ b/matlab/AIM/SPAimerr.m
@@ -1,4 +1,4 @@
-function e = SPAimerr(c);
+function e = SPAimerr(c)
 % e = aimerr(c);
 %
 % Interpret the return codes generated by the aim routines.
@@ -29,7 +29,7 @@ function e = SPAimerr(c);
 % Journal of Economic Dynamics and Control, 2010, vol. 34, issue 3,
 % pages 472-489
 
-    if(c==1)  e='Aim: unique solution.';
+if(c==1)  e='Aim: unique solution.';
 elseif(c==2)  e='Aim: roots not correctly computed by real_schur.';
 elseif(c==3)  e='Aim: too many big roots.';
 elseif(c==35) e='Aim: too many big roots, and q(:,right) is singular.';
diff --git a/matlab/AIM/SPAmalg.m b/matlab/AIM/SPAmalg.m
index 41307b445e118ca8721e93952706d9be876bdc5e..c371a91b0f1b2cf11eb5f6541959fa7dcbc4b810 100644
--- a/matlab/AIM/SPAmalg.m
+++ b/matlab/AIM/SPAmalg.m
@@ -1,5 +1,5 @@
 function [b,rts,ia,nexact,nnumeric,lgroots,aimcode] = ...
-                        SPAmalg(h,neq,nlag,nlead,condn,uprbnd)
+    SPAmalg(h,neq,nlag,nlead,condn,uprbnd)
 %  [b,rts,ia,nexact,nnumeric,lgroots,aimcode] = ...
 %                       SPAmalg(h,neq,nlag,nlead,condn,uprbnd)
 %
@@ -8,9 +8,9 @@ function [b,rts,ia,nexact,nnumeric,lgroots,aimcode] = ...
 %  roots.  This procedure will fail if the companion matrix is
 %  defective and does not have a linearly independent set of
 %  eigenvectors associated with the big roots.
-% 
+%
 %  Input arguments:
-% 
+%
 %    h         Structural coefficient matrix (neq,neq*(nlag+1+nlead)).
 %    neq       Number of equations.
 %    nlag      Number of lags.
@@ -19,9 +19,9 @@ function [b,rts,ia,nexact,nnumeric,lgroots,aimcode] = ...
 %              by numeric_shift and reduced_form.
 %    uprbnd    Inclusive upper bound for the modulus of roots
 %              allowed in the reduced form.
-% 
+%
 %  Output arguments:
-% 
+%
 %    b         Reduced form coefficient matrix (neq,neq*nlag).
 %    rts       Roots returned by eig.
 %    ia        Dimension of companion matrix (number of non-trivial
@@ -57,7 +57,7 @@ function [b,rts,ia,nexact,nnumeric,lgroots,aimcode] = ...
 % pages 472-489
 
 b=[];rts=[];ia=[];nexact=[];nnumeric=[];lgroots=[];aimcode=[];
-if(nlag<1 || nlead<1) 
+if(nlag<1 || nlead<1)
     error('Aim_eig: model must have at least one lag and one lead');
 end
 % Initialization.
@@ -66,26 +66,26 @@ bcols=neq*nlag;q=zeros(qrows,qcols);rts=zeros(qcols,1);
 [h,q,iq,nexact]=SPExact_shift(h,q,iq,qrows,qcols,neq);
 if (iq>qrows)
     aimcode = 61;
-    return;
+    return
 end
 [h,q,iq,nnumeric]=SPNumeric_shift(h,q,iq,qrows,qcols,neq,condn);
 if (iq>qrows)
     aimcode = 62;
-    return;
+    return
 end
 [a,ia,js] = SPBuild_a(h,qcols,neq);
 if (ia ~= 0)
-    if any(any(isnan(a))) || any(any(isinf(a))) 
+    if any(any(isnan(a))) || any(any(isinf(a)))
         disp('A is NAN or INF')
-        aimcode=63; 
-        return 
-    end 
+        aimcode=63;
+        return
+    end
     [w,rts,lgroots,flag_trouble]=SPEigensystem(a,uprbnd,min(length(js),qrows-iq+1));
-    if flag_trouble==1; 
-        disp('Problem in SPEIG'); 
+    if flag_trouble==1
+        disp('Problem in SPEIG');
         aimcode=64;
         return
-    end 
+    end
     q = SPCopy_w(q,w,js,iq,qrows);
 end
 test=nexact+nnumeric+lgroots;
diff --git a/matlab/AIM/SPBuild_a.m b/matlab/AIM/SPBuild_a.m
index eb12473a8afef4a70b8088a7fc40233508253ed1..5701d3bf118856cadee3522ab5122fe910ceac3a 100644
--- a/matlab/AIM/SPBuild_a.m
+++ b/matlab/AIM/SPBuild_a.m
@@ -41,9 +41,9 @@ hs(:,left) = -hs(:,right)\hs(:,left);
 a = zeros(qcols,qcols);
 
 if(qcols > neq)
-  eyerows = 1:qcols-neq;
-  eyecols = neq+1:qcols;
-  a(eyerows,eyecols) = eye(qcols-neq);
+    eyerows = 1:qcols-neq;
+    eyecols = neq+1:qcols;
+    a(eyerows,eyecols) = eye(qcols-neq);
 end
 hrows      = qcols-neq+1:qcols;
 a(hrows,:) = hs(:,left);
@@ -51,14 +51,14 @@ a(hrows,:) = hs(:,left);
 %  Delete inessential lags and build index array js.  js indexes the
 %  columns in the big transition matrix that correspond to the
 %  essential lags in the model.  They are the columns of q that will
-%  get the unstable left eigenvectors. 
+%  get the unstable left eigenvectors.
 
 js       = 1:qcols;
 zerocols = sum(abs(a)) == 0;
 while( any(zerocols) )
-  a(:,zerocols) = [];
-  a(zerocols,:) = [];
-  js(zerocols)  = [];
-  zerocols = sum(abs(a)) == 0;
+    a(:,zerocols) = [];
+    a(zerocols,:) = [];
+    js(zerocols)  = [];
+    zerocols = sum(abs(a)) == 0;
 end
 ia = length(js);
diff --git a/matlab/AIM/SPCopy_w.m b/matlab/AIM/SPCopy_w.m
index 714a1e27466116e2d35df8838c535cbd8e519009..82dafe40ab50e044249b9db1fb00eb347103b704 100644
--- a/matlab/AIM/SPCopy_w.m
+++ b/matlab/AIM/SPCopy_w.m
@@ -2,7 +2,7 @@ function  q = SPCopy_w(q,w,js,iq,qrows)
 % q = SPCopy_w(q,w,js,iq,qrows)
 %
 %  Copy the eigenvectors corresponding to the largest roots into the
-%  remaining empty rows and columns js of q 
+%  remaining empty rows and columns js of q
 
 % Author: Gary Anderson
 % Original file downloaded from:
@@ -30,7 +30,7 @@ function  q = SPCopy_w(q,w,js,iq,qrows)
 
 
 if(iq < qrows)
-   lastrows = iq+1:qrows;
-   wrows    = 1:length(lastrows);
-   q(lastrows,js) = w(:,wrows)';
+    lastrows = iq+1:qrows;
+    wrows    = 1:length(lastrows);
+    q(lastrows,js) = w(:,wrows)';
 end
diff --git a/matlab/AIM/SPEigensystem.m b/matlab/AIM/SPEigensystem.m
index 16855401a521704a22778f62c1dce3edcaa39f99..61dd4606907159c34bb91442f9d9b7feb001aa5a 100644
--- a/matlab/AIM/SPEigensystem.m
+++ b/matlab/AIM/SPEigensystem.m
@@ -30,7 +30,7 @@ function [w,rts,lgroots,flag_trouble] = SPEigensystem(a,uprbnd,rowsLeft)
 % Journal of Economic Dynamics and Control, 2010, vol. 34, issue 3,
 % pages 472-489
 
-opts.disp=0; 
+opts.disp=0;
 % next block is commented out because eigs() intermitently returns different rts
 %try
 %    [w,d]   = eigs(a',rowsLeft,'LM',opts);
@@ -39,24 +39,24 @@ opts.disp=0;
 %    [mag,k] = sort(-mag);
 %    rts     = rts(k);
 %catch
-    %disp('Catch in SPE');
-    %pause(0.5);
-    %aStr=datestr(clock);
-    %eval(['save ' regexprep(aStr,' ','')  ' a']);
-    try
-        [w,d]=eig(a');
-    catch
-        lasterr
-        w=[];rts=[];lgroots=[];
-        flag_trouble=1;
-        return
-    end
-    rts     = diag(d);
-    mag     = abs(rts);
-    [mag,k] = sort(-mag);
-    rts     = rts(k);
+%disp('Catch in SPE');
+%pause(0.5);
+%aStr=datestr(clock);
+%eval(['save ' regexprep(aStr,' ','')  ' a']);
+try
+    [w,d]=eig(a');
+catch
+    lasterr
+    w=[];rts=[];lgroots=[];
+    flag_trouble=1;
+    return
+end
+rts     = diag(d);
+mag     = abs(rts);
+[mag,k] = sort(-mag);
+rts     = rts(k);
 %end
-flag_trouble=0; 
+flag_trouble=0;
 
 %ws=SPSparse(w);
 ws=sparse(w);
@@ -65,7 +65,7 @@ ws       = ws(:,k);
 %  Given a complex conjugate pair of vectors W = [w1,w2], there is a
 %  nonsingular matrix D such that W*D = real(W) + imag(W).  That is to
 %  say, W and real(W)+imag(W) span the same subspace, which is all
-%  that aim cares about. 
+%  that aim cares about.
 
 ws = real(ws) + imag(ws);
 
diff --git a/matlab/AIM/SPExact_shift.m b/matlab/AIM/SPExact_shift.m
index c9034e319bd3d309b4e49ebb53d6fa28a1e261d1..5ba49aa11430450905c99ff4d91cb73a1ffcf4e3 100644
--- a/matlab/AIM/SPExact_shift.m
+++ b/matlab/AIM/SPExact_shift.m
@@ -36,12 +36,11 @@ right  = qcols+1:qcols+neq;
 zerorows = find( sum(abs( hs(:,right)' ))==0 );
 
 while( any(zerorows) && iq <= qrows )
-   nz = length(zerorows);
-   q(iq+1:iq+nz,:) = hs(zerorows,left);
-   hs(zerorows,:)   = SPShiftright(hs(zerorows,:),neq);
-   iq     = iq + nz;
-   nexact = nexact + nz;
-   zerorows = find( sum(abs( hs(:,right)' ))==0 );
+    nz = length(zerorows);
+    q(iq+1:iq+nz,:) = hs(zerorows,left);
+    hs(zerorows,:)   = SPShiftright(hs(zerorows,:),neq);
+    iq     = iq + nz;
+    nexact = nexact + nz;
+    zerorows = find( sum(abs( hs(:,right)' ))==0 );
 end
 h=full(hs);
-
diff --git a/matlab/AIM/SPNumeric_shift.m b/matlab/AIM/SPNumeric_shift.m
index cc1e1825f7588a1481d6fabe986c86b8d1b60616..27049ca0cc41a629fe0a2d6c54fbe7e1044705a8 100644
--- a/matlab/AIM/SPNumeric_shift.m
+++ b/matlab/AIM/SPNumeric_shift.m
@@ -37,14 +37,14 @@ right    = qcols+1:qcols+neq;
 zerorows = find( abs(diag(R)) <= condn );
 
 while( any(zerorows) && iq <= qrows )
-   h=sparse(h);
-   Q=sparse(Q);
-   h = Q'*h;
-   nz = length(zerorows);
-   q(iq+1:iq+nz,:) = h(zerorows,left);
-   h(zerorows,:)   = SPShiftright( h(zerorows,:), neq );
-   iq       = iq + nz;
-   nnumeric = nnumeric + nz;
-   [Q,R,E] = qr( full(h(:,right)) );
-   zerorows = find( abs(diag(R)) <= condn );
+    h=sparse(h);
+    Q=sparse(Q);
+    h = Q'*h;
+    nz = length(zerorows);
+    q(iq+1:iq+nz,:) = h(zerorows,left);
+    h(zerorows,:)   = SPShiftright( h(zerorows,:), neq );
+    iq       = iq + nz;
+    nnumeric = nnumeric + nz;
+    [Q,R,E] = qr( full(h(:,right)) );
+    zerorows = find( abs(diag(R)) <= condn );
 end
diff --git a/matlab/AIM/SPObstruct.m b/matlab/AIM/SPObstruct.m
index 8620ca1b9b562ae859f342dfa093bc4337b29a68..9d9206501fd3cdea1401bff9e821be703a9e08fa 100644
--- a/matlab/AIM/SPObstruct.m
+++ b/matlab/AIM/SPObstruct.m
@@ -2,7 +2,7 @@ function scof = SPObstruct(cof,cofb,neq,nlag,nlead)
 % scof = SPObstruct(cof,cofb,neq,nlag,nlead)
 %
 % Construct the coefficients in the observable structure.
-%    
+%
 %   Input arguments:
 %
 %            cof    structural coefficients
@@ -51,17 +51,17 @@ qs=sparse(q);
 qs(1:rc,1:cc) = sparse(cofb);
 qcols = neq*(nlag+nlead);
 
-if( nlead > 1 ) 
-   for i = 1:nlead-1
-      rows = i*neq + (1:neq);
-      qs(rows,:) = SPShiftright( qs((rows-neq),:), neq );
-   end
+if( nlead > 1 )
+    for i = 1:nlead-1
+        rows = i*neq + (1:neq);
+        qs(rows,:) = SPShiftright( qs((rows-neq),:), neq );
+    end
 end
 
 l = (1: neq*nlag);
 r = (neq*nlag+1: neq*(nlag+nlead));
 
- qs(:,l) = - qs(:,r) \ qs(:,l);
+qs(:,l) = - qs(:,r) \ qs(:,l);
 
 minus =              1:       neq*(nlag+1);
 plus  = neq*(nlag+1)+1: neq*(nlag+1+nlead);
diff --git a/matlab/AIM/SPReduced_form.m b/matlab/AIM/SPReduced_form.m
index 3d5c8899078e52eb3f401904bad949351c48d73c..e7d60a1801c031dddc864cdeda845a1d435951dc 100644
--- a/matlab/AIM/SPReduced_form.m
+++ b/matlab/AIM/SPReduced_form.m
@@ -1,4 +1,4 @@
-function [nonsing,b] = SPReduced_form(q,qrows,qcols,bcols,neq,condn);
+function [nonsing,b] = SPReduced_form(q,qrows,qcols,bcols,neq,condn)
 % [nonsing,b] = SPReduced_form(q,qrows,qcols,bcols,neq,b,condn);
 %
 % Compute reduced-form coefficient matrix, b.
@@ -38,7 +38,7 @@ if(nonsing)
     b = qs(1:neq,1:bcols);
     b = full(b);
 else  %rescale by dividing row by maximal qr element
-    %'inverse condition number small, rescaling '
+      %'inverse condition number small, rescaling '
     themax=max(abs(qs(:,right)),[],2);
     oneover = diag(1 ./ themax);
     nonsing = rcond(full(oneover *qs(:,right))) > condn;
@@ -48,4 +48,3 @@ else  %rescale by dividing row by maximal qr element
         b = full(b);
     end
 end
-
diff --git a/matlab/AIM/SPShiftright.m b/matlab/AIM/SPShiftright.m
index 8299ce516b302d9b591e34eb1ed2afb33bb91363..70490848435230595ed56bfa00e24a81c7092a8c 100644
--- a/matlab/AIM/SPShiftright.m
+++ b/matlab/AIM/SPShiftright.m
@@ -3,7 +3,7 @@ function [y] = SPShiftright(x,n)
 % [y] = shiftright(x,n)
 %
 %  Shift the rows of x to the right by n columns, leaving zeros in the
-%  first n columns. 
+%  first n columns.
 
 % Original author: Gary Anderson
 % Original file downloaded from:
diff --git a/matlab/AIM/dynAIMsolver1.m b/matlab/AIM/dynAIMsolver1.m
index 2e23e0222004d70c4341fd48fbf81147f7f0719f..52a2ae6f92fd0abb75d290911908207da34db462 100644
--- a/matlab/AIM/dynAIMsolver1.m
+++ b/matlab/AIM/dynAIMsolver1.m
@@ -1,20 +1,20 @@
 function [dr,aimcode,rts]=dynAIMsolver1(jacobia_,M_,dr)
 % function [dr,aimcode]=dynAIMsolver1(jacobia_,M_,dr)
-% Maps Dynare jacobia to AIM 1st order model solver designed and developed by Gary ANderson 
+% Maps Dynare jacobia to AIM 1st order model solver designed and developed by Gary ANderson
 % and derives the solution for gy=dr.hgx and gu=dr.hgu from the AIM outputs
-% AIM System is given as a sum: 
-% i.e. for i=-$...+&   SUM(Hi*xt+i)= �*zt, t = 0, . . . ,?
+% AIM System is given as a sum:
+% i.e. for i=-$...+&   SUM(Hi*xt+i)= £*zt, t = 0, . . . ,?
 % and its input as single array of matrices: [H-$...  Hi ... H+&]
-% and its solution as xt=SUM( Bi*xt+i) + @*�*zt for i=-$...-1 
-% with the output in form bb=[B-$...  Bi ... B-1] and @=inv(Ho+H1*B-1) 
-% Dynare jacobian = [fy'-$...  fy'i ... fy'+&  fu'] 
-% where [fy'-$...  fy'i ... fy'+&]=[H-$...  Hi ... H+&] and fu'= �
+% and its solution as xt=SUM( Bi*xt+i) + @*£*zt for i=-$...-1
+% with the output in form bb=[B-$...  Bi ... B-1] and @=inv(Ho+H1*B-1)
+% Dynare jacobian = [fy'-$...  fy'i ... fy'+&  fu']
+% where [fy'-$...  fy'i ... fy'+&]=[H-$...  Hi ... H+&] and fu'= £
 %
 % INPUTS
-%   jacobia_   [matrix]           1st order derivative of the model 
+%   jacobia_   [matrix]           1st order derivative of the model
 %   dr         [matlab structure] Decision rules for stochastic simulations.
-%   M_         [matlab structure] Definition of the model.           
-%    
+%   M_         [matlab structure] Definition of the model.
+%
 % OUTPUTS
 %   dr         [matlab structure] Decision rules for stochastic simulations.
 %   aimcode    [integer]          1: the model defines variables uniquely
@@ -31,22 +31,22 @@ function [dr,aimcode,rts]=dynAIMsolver1(jacobia_,M_,dr)
 %      (c==63) e='Aim: A is NAN or INF.';
 %      (c==64) e='Aim: Problem in SPEIG.';
 %      else    e='Aimerr: return code not properly specified';
-%    
+%
 % SPECIAL REQUIREMENTS
-% Dynare use: 
+% Dynare use:
 %       1) the lognormal block in DR1 is being invoked for some models and changing
 %       values of ghx and ghy. We need to return the AIM output
 %       values before that block and run the block with the current returned values
-%       of gy (i.e. dr.ghx) and gu (dr.ghu) if it is needed even when the AIM is used  
+%       of gy (i.e. dr.ghx) and gu (dr.ghu) if it is needed even when the AIM is used
 %       (it does not depend on mjdgges output).
-%       
-%       2) passing in aa={Q'|1}*jacobia_ can produce ~ one order closer  
-%       results to the Dynare solutiion then when if plain jacobia_ is passed, 
-%       i.e. diff < e-14 for aa and diff < *e-13 for jacobia_ if Q' is used.  
 %
-% GP July 2008 
+%       2) passing in aa={Q'|1}*jacobia_ can produce ~ one order closer
+%       results to the Dynare solutiion then when if plain jacobia_ is passed,
+%       i.e. diff < e-14 for aa and diff < *e-13 for jacobia_ if Q' is used.
+%
+% GP July 2008
 
-% Copyright (C) 2008-2012 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -69,8 +69,8 @@ lags=M_.maximum_endo_lag; % no of lags and leads
 leads=M_.maximum_endo_lead;
 klen=(leads+lags+1);  % total lenght
 theAIM_H=zeros(neq, neq*klen); % alloc space
-lli=M_.lead_lag_incidence';  
-% "sparse" the compact jacobia into AIM H aray of matrices 
+lli=M_.lead_lag_incidence';
+% "sparse" the compact jacobia into AIM H aray of matrices
 % without exogenous shoc
 theAIM_H(:,find(lli(:)))=jacobia_(:,nonzeros(lli(:)));
 condn  = 1.e-10;%SPAmalg uses this in zero tests
@@ -102,7 +102,7 @@ if aimcode==1 %if OK
         col_order=[((i-1)*neq)+dr.order_var' col_order];
     end
     bb_ord= bb(dr.order_var,col_order); % derive ordered gy
-    
+
     % variables are present in the state space at the lag at which they
     % appear and at all smaller lags. The are ordered from smaller to
     % higher lag (reversed order of M_.lead_lag_incidence rows for lagged
@@ -117,7 +117,7 @@ if aimcode==1 %if OK
                   %theH0= theAIM_H (:,lags*neq+1: (lags+1)*neq);
                   %    theHP= theAIM_H (:,(M_.maximum_endo_lag+1)*neq+1: (M_.maximum_endo_lag+2)*neq);
                   %theHP= theAIM_H (:,(lags+1)*neq+1: (lags+2)*neq);
-        theAIM_Psi= - jacobia_(:, size(nonzeros(lli(:)))+1:end);% 
+        theAIM_Psi= - jacobia_(:, size(nonzeros(lli(:)))+1:end);%
                                                                 %? = inv(H0 + H1B1)
                                                                 %phi= (theH0+theHP*sparse(bb(:,(lags-1)*neq+1:end)))\eye( neq);
                                                                 %AIM_ghu=phi*theAIM_Psi;
@@ -137,8 +137,8 @@ else
     if aimcode < 1 || aimcode > 5  % too big exception, use mjdgges
         error('Error in AIM: aimcode=%d ; %s', aimcode, err);
     end
-    %    if aimcode > 5 
+    %    if aimcode > 5
     %        disp(['Error in AIM: aimcode=' sprintf('%d : %s',aimcode, err)]);
     %        aimcode=5;
-    %    end  
+    %    end
 end
diff --git a/matlab/AIM_first_order_solver.m b/matlab/AIM_first_order_solver.m
index fb3a99dc6a499affeb56d82eff1498d78365f98a..893deefb0c43ce611bb9553fbec8851b7f628edc 100644
--- a/matlab/AIM_first_order_solver.m
+++ b/matlab/AIM_first_order_solver.m
@@ -51,7 +51,7 @@ function [dr,info]=AIM_first_order_solver(jacobia,M,dr,qz_criterium)
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2001-2016 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -67,35 +67,34 @@ function [dr,info]=AIM_first_order_solver(jacobia,M,dr,qz_criterium)
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
-    
-    info = 0;
-    
-    [dr,aimcode]=dynAIMsolver1(jacobia,M,dr);
 
-    if aimcode ~=1
-        info(1) = convertAimCodeToInfo(aimCode); %convert to be in the 100 range
-        info(2) = 1.0e+8;
-        return
-    end
-    A = kalman_transition_matrix(dr,M.nstatic+(1:M.nspred), 1:M.nspred,...
-                                 M.exo_nbr);
-    dr.eigval = eig(A);
-    disp(dr.eigval)
-    nd = size(dr.kstate,1);
-    nba = nd-sum( abs(dr.eigval) < qz_criterium );
+info = 0;
 
-    nsfwrd = M.nsfwrd;
+[dr,aimcode]=dynAIMsolver1(jacobia,M,dr);
 
-    if nba ~= nsfwrd
-        temp = sort(abs(dr.eigval));
-        if nba > nsfwrd
-            temp = temp(nd-nba+1:nd-nsfwrd)-1-qz_criterium;
-            info(1) = 3;
-        elseif nba < nsfwrd;
-            temp = temp(nd-nsfwrd+1:nd-nba)-1-qz_criterium;
-            info(1) = 4;
-        end
-        info(2) = temp'*temp;
-        return
-    end
+if aimcode ~=1
+    info(1) = convertAimCodeToInfo(aimCode); %convert to be in the 100 range
+    info(2) = 1.0e+8;
+    return
+end
+A = kalman_transition_matrix(dr,M.nstatic+(1:M.nspred), 1:M.nspred,...
+                             M.exo_nbr);
+dr.eigval = eig(A);
+disp(dr.eigval)
+nd = size(dr.kstate,1);
+nba = nd-sum( abs(dr.eigval) < qz_criterium );
 
+nsfwrd = M.nsfwrd;
+
+if nba ~= nsfwrd
+    temp = sort(abs(dr.eigval));
+    if nba > nsfwrd
+        temp = temp(nd-nba+1:nd-nsfwrd)-1-qz_criterium;
+        info(1) = 3;
+    elseif nba < nsfwrd
+        temp = temp(nd-nsfwrd+1:nd-nba)-1-qz_criterium;
+        info(1) = 4;
+    end
+    info(2) = temp'*temp;
+    return
+end
diff --git a/matlab/CheckPath.m b/matlab/CheckPath.m
index c8300551307d7887bc118e9657bf2de7cde86ec8..002c9bd17d47167dae7636f03650ec14c0cc35a4 100644
--- a/matlab/CheckPath.m
+++ b/matlab/CheckPath.m
@@ -2,7 +2,7 @@ function [DirectoryName, info] = CheckPath(type,dname)
 % Creates the subfolder "./M_.dname/type" if it does not exist yet.
 %
 % INPUTS
-%    type   [string]    Name of the subfolder. 
+%    type   [string]    Name of the subfolder.
 %    dname  [string]    Name of the directory
 %
 % OUTPUTS
@@ -12,7 +12,7 @@ function [DirectoryName, info] = CheckPath(type,dname)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2005-2013 Dynare Team
+% Copyright (C) 2005-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/CutSample.m b/matlab/CutSample.m
index 5ec0881a8677eda180b302911d4f6a6a35c701aa..1582ec8836fbb88577cda54da12a66afb567fe9b 100644
--- a/matlab/CutSample.m
+++ b/matlab/CutSample.m
@@ -16,7 +16,7 @@ function CutSample(M_, options_, estim_params_)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2005-2015 Dynare Team
+% Copyright (C) 2005-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -66,7 +66,7 @@ if (TotalNumberOfMhFiles-1)-(FirstMhFile+1)+1 > 0
 elseif TotalNumberOfMhFiles == 1
     record.KeepedDraws.Distribution = [];
 elseif TotalNumberOfMhFiles == 2 && FirstMhFile > 1
-    record.KeepedDraws.Distribution = [MAX_nruns-FirstLine+1 ; record.MhDraws(end,3)];  
+    record.KeepedDraws.Distribution = [MAX_nruns-FirstLine+1 ; record.MhDraws(end,3)];
 end
 
 % Save updated mh-history file.
diff --git a/matlab/DsgeSmoother.m b/matlab/DsgeSmoother.m
index f9e459e004d0d6794c8be35c8601b197201310e4..997904afcf14acf81b3612aebb3fc18ee2c9950e 100644
--- a/matlab/DsgeSmoother.m
+++ b/matlab/DsgeSmoother.m
@@ -1,8 +1,8 @@
 function [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T,R,P,PK,decomp,trend_addition,state_uncertainty,M_,oo_,options_,bayestopt_] = DsgeSmoother(xparam1,gend,Y,data_index,missing_value,M_,oo_,options_,bayestopt_,estim_params_)
-% Estimation of the smoothed variables and innovations. 
-% 
-% INPUTS 
-%   o xparam1       [double]   (p*1) vector of (estimated) parameters. 
+% Estimation of the smoothed variables and innovations.
+%
+% INPUTS
+%   o xparam1       [double]   (p*1) vector of (estimated) parameters.
 %   o gend          [integer]  scalar specifying the number of observations ==> varargin{1}.
 %   o data          [double]   (n*T) matrix of data.
 %   o data_index    [cell]      1*smpl cell of column vectors of indices.
@@ -12,7 +12,7 @@ function [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T,R,P,PK,de
 %   o options_      [structure] describing the options
 %   o bayestopt_    [structure] describing the priors
 %   o estim_params_ [structure] characterizing parameters to be estimated
-%  
+%
 % OUTPUTS
 %   o alphahat      [double]  (m*T) matrix, smoothed endogenous variables (a_{t|T})  (decision-rule order)
 %   o etahat        [double]  (r*T) matrix, smoothed structural shocks (r>=n is the number of shocks).
@@ -29,36 +29,36 @@ function [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T,R,P,PK,de
 %                       matrices (meaningless for periods 1:d) (decision-rule order)
 %   o decomp        (K*m*r*(T+K)) 4D array of shock decomposition of k-step ahead
 %                       filtered variables (decision-rule order)
-%   o trend_addition [double] (n*T) pure trend component; stored in options_.varobs order         
+%   o trend_addition [double] (n*T) pure trend component; stored in options_.varobs order
 %   o state_uncertainty [double] (K,K,T) array, storing the uncertainty
 %                                   about the smoothed state (decision-rule order)
 %   o M_            [structure] decribing the model
 %   o oo_           [structure] storing the results
 %   o options_      [structure] describing the options
 %   o bayestopt_    [structure] describing the priors
-%  
+%
 % Notes:
 %   m:  number of endogenous variables (M_.endo_nbr)
 %   T:  number of Time periods (options_.nobs)
 %   r:  number of strucural shocks (M_.exo_nbr)
 %   n:  number of observables (length(options_.varobs))
 %   K:  maximum forecast horizon (max(options_.nk))
-% 
+%
 %   To get variables that are stored in decision rule order in order of declaration
 %   as in M_.endo_names, ones needs code along the lines of:
 %   variables_declaration_order(dr.order_var,:) = alphahat
-% 
-%   Defines bayestopt_.mf = bayestopt_.smoother_mf (positions of observed variables 
-%   and requested smoothed variables in decision rules (decision rule order)) and 
+%
+%   Defines bayestopt_.mf = bayestopt_.smoother_mf (positions of observed variables
+%   and requested smoothed variables in decision rules (decision rule order)) and
 %   passes it back via global variable
-% 
-% ALGORITHM 
-%   Diffuse Kalman filter (Durbin and Koopman)       
+%
+% ALGORITHM
+%   Diffuse Kalman filter (Durbin and Koopman)
 %
 % SPECIAL REQUIREMENTS
 %   None
 
-% Copyright (C) 2006-2016 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -97,7 +97,7 @@ end
 %------------------------------------------------------------------------------
 % 2. call model setup & reduction program
 %------------------------------------------------------------------------------
-oldoo.restrict_var_list = oo_.dr.restrict_var_list; 
+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;
@@ -133,8 +133,8 @@ mf    = bayestopt_.mf;
 % ------------------------------------------------------------------------------
 %  3. Initial condition of the Kalman filter
 % ------------------------------------------------------------------------------
-% 
-%  Here, Pinf and Pstar are determined. If the model is stationary, determine 
+%
+%  Here, Pinf and Pstar are determined. If the model is stationary, determine
 %  Pstar as the solution of the Lyapunov equation and set Pinf=[] (Notation follows
 %  Koopman/Durbin (2003), Journal of Time Series Analysis 24(1))
 %
@@ -169,7 +169,7 @@ elseif options_.lik_init == 3           % Diffuse Kalman filter
         kalman_algo = 3;
     else
         if ~all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
-            %Augment state vector (follows Section 6.4.3 of DK (2012))
+                                                %Augment state vector (follows Section 6.4.3 of DK (2012))
             expanded_state_vector_for_univariate_filter=1;
             T  = blkdiag(T,zeros(vobs));
             np    = size(T,1);
@@ -240,30 +240,32 @@ if kalman_algo == 1 || kalman_algo == 3
 end
 
 if kalman_algo == 2 || kalman_algo == 4
-        if ~all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
-            if ~expanded_state_vector_for_univariate_filter
-                %Augment state vector (follows Section 6.4.3 of DK (2012))
-                expanded_state_vector_for_univariate_filter=1;
-                Z   = [Z, eye(vobs)];
-                ST  = blkdiag(ST,zeros(vobs));
-                np  = size(ST,1);
-                Q   = blkdiag(Q,H);
-                R1  = blkdiag(R,eye(vobs));
-                if kalman_algo == 4
-                    %recompute Schur state space transformation with
-                    %expanded state space
-                    [Pstar,Pinf] = compute_Pinf_Pstar(mf,ST,R1,Q,options_.qz_criterium);
-                else
-                    Pstar = blkdiag(Pstar,H);
-                    Pinf  = blkdiag(Pinf,zeros(vobs));                    
-                end
-                %now reset H to 0
-                H   = zeros(vobs,vobs);
+    if ~all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
+        if ~expanded_state_vector_for_univariate_filter
+            %Augment state vector (follows Section 6.4.3 of DK (2012))
+            expanded_state_vector_for_univariate_filter=1;
+            Z   = [Z, eye(vobs)];
+            ST  = blkdiag(ST,zeros(vobs));
+            np  = size(ST,1);
+            Q   = blkdiag(Q,H);
+            R1  = blkdiag(R,eye(vobs));
+            if kalman_algo == 4
+                %recompute Schur state space transformation with
+                %expanded state space
+                [Pstar,Pinf] = compute_Pinf_Pstar(mf,ST,R1,Q,options_.qz_criterium);
             else
-                %do nothing, state vector was already expanded
+                Pstar = blkdiag(Pstar,H);
+                if ~isempty(Pinf)
+                    Pinf  = blkdiag(Pinf,zeros(vobs));
+                end
             end
+            %now reset H to 0
+            H   = zeros(vobs,vobs);
+        else
+            %do nothing, state vector was already expanded
         end
-        
+    end
+
     [alphahat,epsilonhat,etahat,ahat,P,aK,PK,decomp,state_uncertainty] = missing_DiffuseKalmanSmootherH3_Z(ST, ...
                                                       Z,R1,Q,diag(H), ...
                                                       Pinf,Pstar,data1,vobs,np,smpl,data_index, ...
@@ -280,7 +282,7 @@ if expanded_state_vector_for_univariate_filter && (kalman_algo == 2 || kalman_al
     ahat = ahat(k,:);
     aK = aK(:,k,:,:);
     epsilonhat=etahat(end-vobs+1:end,:);
-    etahat=etahat(1:end-vobs,:);    
+    etahat=etahat(1:end-vobs,:);
     if ~isempty(PK)
         PK = PK(:,k,k,:);
     end
diff --git a/matlab/GetAllPosteriorDraws.m b/matlab/GetAllPosteriorDraws.m
index 88e80f9182121cfe739d460349c2fe93b3151738..0408da5095c3cd567c0fa2dae83adffa27fe95f8 100644
--- a/matlab/GetAllPosteriorDraws.m
+++ b/matlab/GetAllPosteriorDraws.m
@@ -5,18 +5,18 @@ function Draws = GetAllPosteriorDraws(column, FirstMhFile, FirstLine, TotalNumbe
 %
 % INPUTS
 %    column:               column
-%    FirstMhFile:          first mh file 
+%    FirstMhFile:          first mh file
 %    FirstLine:            first line
-%    TotalNumberOfMhFile:  total number of mh file 
+%    TotalNumberOfMhFile:  total number of mh file
 %    NumberOfDraws:        number of draws
 
 % OUTPUTS
 %    Draws:                draws from posterior distribution
-%        
+%
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2005-2011 Dynare Team
+% Copyright (C) 2005-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -55,7 +55,7 @@ if nblck>1 && nargin<6
                 iline = 1;
             end
         end
-    else 
+    else
         for blck = 1:nblck
             iline=iline0;
             for file = FirstMhFile:TotalNumberOfMhFile
diff --git a/matlab/GetOneDraw.m b/matlab/GetOneDraw.m
index 82d4c088fa04f0b195c98f5aa89c389a096b7d13..f8e2a0d63b96c9264e2cd35e4a110d16fe409373 100644
--- a/matlab/GetOneDraw.m
+++ b/matlab/GetOneDraw.m
@@ -5,15 +5,15 @@ function [xparams, logpost] = GetOneDraw(type)
 % INPUTS
 %    type:      [string]       'posterior': draw from MCMC draws
 %                              'prior': draw from prior
-%        
+%
 % OUTPUTS
 %    xparams:   vector of estimated parameters (drawn from posterior or prior distribution)
 %    logpost:   log of the posterior density of this parameter vector
-%        
+%
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2005-2015 Dynare Team
+% Copyright (C) 2005-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/GetPosteriorMeanVariance.m b/matlab/GetPosteriorMeanVariance.m
index d1e2935873b0e5a969446e4c2572c31756469140..22d9e60045efd834db265168a73d3e10c63a3789 100644
--- a/matlab/GetPosteriorMeanVariance.m
+++ b/matlab/GetPosteriorMeanVariance.m
@@ -1,6 +1,6 @@
 function [mean,variance] = GetPosteriorMeanVariance(M,drop)
 
-% Copyright (C) 2012-2016 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -16,38 +16,38 @@ function [mean,variance] = GetPosteriorMeanVariance(M,drop)
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
-    
-    MetropolisFolder = CheckPath('metropolis',M.dname);
-    FileName = M.fname;
-    BaseName = [MetropolisFolder filesep FileName];
-    load_last_mh_history_file(MetropolisFolder, FileName);
-    NbrDraws = sum(record.MhDraws(:,1));
-    NbrFiles = sum(record.MhDraws(:,2));
-    NbrBlocks = record.Nblck;
-    mean = 0;
-    variance = 0;
-    
-    NbrKeptDraws = 0;
-    for i=1:NbrBlocks
-        NbrDrawsCurrentBlock = 0;
-        for j=1:NbrFiles
-            o = load([BaseName '_mh' int2str(j) '_blck' int2str(i),'.mat']);
-            NbrDrawsCurrentFile = size(o.x2,1);
-            if NbrDrawsCurrentBlock + NbrDrawsCurrentFile <= drop*NbrDraws
-                NbrDrawsCurrentBlock = NbrDrawsCurrentBlock + NbrDrawsCurrentFile;
-                continue
-            elseif NbrDrawsCurrentBlock < drop*NbrDraws
-                FirstDraw = ceil(drop*NbrDraws - NbrDrawsCurrentBlock + 1);
-                x2 = o.x2(FirstDraw:end,:);
-            else
-                x2 = o.x2;
-            end
-            NbrKeptDrawsCurrentFile = size(x2,1);
-            %recursively compute mean and variance
-            mean = (NbrKeptDraws*mean + sum(x2)')/(NbrKeptDraws+NbrKeptDrawsCurrentFile);
-            x2Demeaned = bsxfun(@minus,x2,mean');
-            variance = (NbrKeptDraws*variance + x2Demeaned'*x2Demeaned)/(NbrKeptDraws+NbrKeptDrawsCurrentFile);
+
+MetropolisFolder = CheckPath('metropolis',M.dname);
+FileName = M.fname;
+BaseName = [MetropolisFolder filesep FileName];
+load_last_mh_history_file(MetropolisFolder, FileName);
+NbrDraws = sum(record.MhDraws(:,1));
+NbrFiles = sum(record.MhDraws(:,2));
+NbrBlocks = record.Nblck;
+mean = 0;
+variance = 0;
+
+NbrKeptDraws = 0;
+for i=1:NbrBlocks
+    NbrDrawsCurrentBlock = 0;
+    for j=1:NbrFiles
+        o = load([BaseName '_mh' int2str(j) '_blck' int2str(i),'.mat']);
+        NbrDrawsCurrentFile = size(o.x2,1);
+        if NbrDrawsCurrentBlock + NbrDrawsCurrentFile <= drop*NbrDraws
             NbrDrawsCurrentBlock = NbrDrawsCurrentBlock + NbrDrawsCurrentFile;
-            NbrKeptDraws = NbrKeptDraws + NbrKeptDrawsCurrentFile;
+            continue
+        elseif NbrDrawsCurrentBlock < drop*NbrDraws
+            FirstDraw = ceil(drop*NbrDraws - NbrDrawsCurrentBlock + 1);
+            x2 = o.x2(FirstDraw:end,:);
+        else
+            x2 = o.x2;
         end
+        NbrKeptDrawsCurrentFile = size(x2,1);
+        %recursively compute mean and variance
+        mean = (NbrKeptDraws*mean + sum(x2)')/(NbrKeptDraws+NbrKeptDrawsCurrentFile);
+        x2Demeaned = bsxfun(@minus,x2,mean');
+        variance = (NbrKeptDraws*variance + x2Demeaned'*x2Demeaned)/(NbrKeptDraws+NbrKeptDrawsCurrentFile);
+        NbrDrawsCurrentBlock = NbrDrawsCurrentBlock + NbrDrawsCurrentFile;
+        NbrKeptDraws = NbrKeptDraws + NbrKeptDrawsCurrentFile;
     end
+end
diff --git a/matlab/GetPosteriorParametersStatistics.m b/matlab/GetPosteriorParametersStatistics.m
index a7c91062167ee4660d7893bd1b822f95bea36669..6bea8d66a11b72c82eca2172f504e0435015fb79 100644
--- a/matlab/GetPosteriorParametersStatistics.m
+++ b/matlab/GetPosteriorParametersStatistics.m
@@ -1,22 +1,22 @@
 function oo_ = GetPosteriorParametersStatistics(estim_params_, M_, options_, bayestopt_, oo_, pnames)
 % This function prints and saves posterior estimates after the mcmc
-% (+updates of oo_ & TeX output). 
-% 
-% INPUTS 
-%   estim_params_    [structure] 
+% (+updates of oo_ & TeX output).
+%
+% INPUTS
+%   estim_params_    [structure]
 %   M_               [structure]
 %   options_         [structure]
 %   bayestopt_       [structure]
 %   oo_              [structure]
 %   pnames           [char]        Array of char, names of the prior shapes available
-%  
-% OUTPUTS 
-%   oo_              [structure]  
+%
+% OUTPUTS
+%   oo_              [structure]
 %
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2006-2016 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -34,7 +34,7 @@ function oo_ = GetPosteriorParametersStatistics(estim_params_, M_, options_, bay
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 %if ~options_.mh_replic && options_.load_mh_file
-%   load([M_.fname '_results.mat'],'oo_'); 
+%   load([M_.fname '_results.mat'],'oo_');
 %end
 
 TeX     = options_.TeX;
@@ -48,7 +48,7 @@ nx      = nvx+nvn+ncx+ncn+np;
 
 MetropolisFolder = CheckPath('metropolis',M_.dname);
 OutputFolder = CheckPath('Output',M_.dname);
-FileName = M_.fname;  
+FileName = M_.fname;
 
 load_last_mh_history_file(MetropolisFolder,FileName);
 
@@ -108,14 +108,14 @@ if np
                 [post_mean, post_median, post_var, hpd_interval, post_deciles, ...
                  density] = posterior_moments(Draws,1,options_.mh_conf_sig);
                 name = bayestopt_.name{ip};
-                oo_ = Filloo(oo_,name,type,post_mean,hpd_interval,post_median,post_var,post_deciles,density);                
+                oo_ = Filloo(oo_,name,type,post_mean,hpd_interval,post_median,post_var,post_deciles,density);
             end
         end
         disp(sprintf(pformat,header_width,name,bayestopt_.p1(ip),...
                      post_mean, ...
                      hpd_interval, ...
                      pnames(bayestopt_.pshape(ip)+1,:), ...
-                     bayestopt_.p2(ip)));    
+                     bayestopt_.p2(ip)));
         if TeX
             k = estim_params_.param_vals(i,1);
             name = deblank(M_.param_names_tex(k,:));
@@ -163,7 +163,7 @@ if nvx
         end
         disp(sprintf(pformat,header_width,name,bayestopt_.p1(ip),post_mean,hpd_interval,...
                      pnames(bayestopt_.pshape(ip)+1,:),bayestopt_.p2(ip)));
-        if TeX,
+        if TeX
             name = deblank(M_.exo_names_tex(k,:));
             TeXCore(fid,name,deblank(pnames(bayestopt_.pshape(ip)+1,:)),bayestopt_.p1(ip),...
                     bayestopt_.p2(ip),post_mean,sqrt(post_var),hpd_interval);
@@ -171,7 +171,7 @@ if nvx
         ip = ip+1;
     end
     if TeX
-        TeXEnd(fid,2,'standard deviation of structural shocks');        
+        TeXEnd(fid,2,'standard deviation of structural shocks');
     end
 end
 if nvn
@@ -213,7 +213,7 @@ if nvn
         ip = ip+1;
     end
     if TeX
-        TeXEnd(fid,3,'standard deviation of measurement errors');        
+        TeXEnd(fid,3,'standard deviation of measurement errors');
     end
 end
 if ncx
@@ -311,15 +311,15 @@ if ncn
         end
         disp(sprintf(pformat, header_width,name,bayestopt_.p1(ip),post_mean,hpd_interval, ...
                      pnames(bayestopt_.pshape(ip)+1,:),bayestopt_.p2(ip)));
-        if TeX,
+        if TeX
             name = ['(',deblank(M_.endo_names_tex(k1,:)) ',' deblank(M_.endo_names_tex(k2,:)),')'];
             TeXCore(fid,name,deblank(pnames(bayestopt_.pshape(ip)+1,:)),bayestopt_.p1(ip),...
-                    bayestopt_.p2(ip),post_mean,sqrt(post_var),hpd_interval);            
+                    bayestopt_.p2(ip),post_mean,sqrt(post_var),hpd_interval);
         end
         ip = ip+1;
     end
     if TeX
-        TeXEnd(fid,5,'correlation of measurement errors');        
+        TeXEnd(fid,5,'correlation of measurement errors');
     end
 end
 
@@ -359,7 +359,7 @@ fid = fidTeX;
 
 
 function TeXCore(fid,name,shape,priormean,priorstd,postmean,poststd,hpd)
-fprintf(fid,['$%s$ & %s & %7.3f & %6.4f & %7.3f& %6.4f & %7.4f & %7.4f \\\\ \n'],... 
+fprintf(fid,['$%s$ & %s & %7.3f & %6.4f & %7.3f& %6.4f & %7.4f & %7.4f \\\\ \n'],...
         name,...
         shape,...
         priormean,...
@@ -371,7 +371,7 @@ fprintf(fid,['$%s$ & %s & %7.3f & %6.4f & %7.3f& %6.4f & %7.4f & %7.4f \\\\ \n']
 
 
 function TeXEnd(fid,fnum,title)
-fprintf(fid,'\\end{longtable}\n ');    
+fprintf(fid,'\\end{longtable}\n ');
 fprintf(fid,'\\end{center}\n');
 fprintf(fid,'%% End of TeX file.\n');
 fclose(fid);
diff --git a/matlab/MakeAllFigures.m b/matlab/MakeAllFigures.m
index 89f35dac6095ee8c9240381815fbc4138b76f696..6c3de53abd749cb5a32a79bc8691b1868639dc78 100644
--- a/matlab/MakeAllFigures.m
+++ b/matlab/MakeAllFigures.m
@@ -1,6 +1,6 @@
 function MakeAllFigures(NumberOfPlots,Caption,FigureProperties,Info)
 
-% Copyright (C) 2005-2009 Dynare Team
+% Copyright (C) 2005-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -19,11 +19,11 @@ function MakeAllFigures(NumberOfPlots,Caption,FigureProperties,Info)
 
 global M_ options_
 
-FigHandle = figure('Name',FigureProperties.Name);  
+FigHandle = figure('Name',FigureProperties.Name);
 
 NAMES = cell(NumberOfPlots,1);
 if options_.TeX
-    TeXNAMES = cell(NumberOfPlots,1); 
+    TeXNAMES = cell(NumberOfPlots,1);
 end
 
 if NumberOfPlots == 9
@@ -53,7 +53,7 @@ elseif NumberOfPlots == 2
 elseif NumberOfPlots == 1
     nr = 1;
     nc = 1;
-end  
+end
 
 for plt = 1:NumberOfPlots
     eval(['NumberOfCurves = Info.Box' int2str(plt) '.Number;'])
@@ -138,7 +138,7 @@ for plt = 1:NumberOfPlots
             set(hh,'Color','r','LineStyle','-','LineWidth',2)
             %
             %
-        end  
+        end
     end
     axis([xmin xmax ymin ymax])
     title(NAMES{plt})
@@ -150,14 +150,14 @@ if Info.SaveFormat.Eps
     if isempty(Info.SaveFormat.Name)
         eval(['print -depsc2 ' M_.fname Info.SaveFormat.GenericName int2str(Info.SaveFormat.Number) '.eps']);
     else
-        eval(['print -depsc2 ' M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name '.eps']);  
+        eval(['print -depsc2 ' M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name '.eps']);
     end
 end
 if Info.SaveFormat.Pdf && ~isoctave
     if isempty(Info.SaveFormat.Name)
         eval(['print -dpdf ' M_.fname Info.SaveFormat.GenericName int2str(Info.SaveFormat.Number)]);
     else
-        eval(['print -dpdf ' M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name]);  
+        eval(['print -dpdf ' M_.fname Info.SaveFormat.GenericName Info.SaveFormat.Name]);
     end
 end
 if Info.SaveFormat.Fig && ~isoctave
diff --git a/matlab/PlotPosteriorDistributions.m b/matlab/PlotPosteriorDistributions.m
index 2ae1837931c318e5fb766be59abb3d0b7bf3e5c5..84ff775ea3612180655b6da05cd4b8c662c5563a 100644
--- a/matlab/PlotPosteriorDistributions.m
+++ b/matlab/PlotPosteriorDistributions.m
@@ -4,19 +4,19 @@ function oo_ = PlotPosteriorDistributions(estim_params_, M_, options_, bayestopt
 % plots posterior distributions
 %
 % INPUTS
-%    estim_params_   [structure] 
+%    estim_params_   [structure]
 %    M_              [structure]
-%    options_        [structure] 
+%    options_        [structure]
 %    bayestopt_      [structure]
 %    oo_             [structure]
-%    
+%
 % OUTPUTS
-%    oo_             [structure]  
-%    
+%    oo_             [structure]
+%
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2005-2016 Dynare Team
+% Copyright (C) 2005-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -49,7 +49,7 @@ nn = sqrt(MaxNumberOfPlotPerFigure);
 
 figurename = 'Priors and posteriors';
 
-if TeX && any(strcmp('eps',cellstr(options_.graph_format)))    
+if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
     fidTeX = fopen([OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors.tex'],'w');
     fprintf(fidTeX,'%% TeX eps-loader file generated by PlotPosteriorDistributions.m (Dynare).\n');
     fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
@@ -63,7 +63,7 @@ for i=1:npar
     subplotnum = subplotnum+1;
     if subplotnum == 1
         figunumber = figunumber+1;
-        hfig=dyn_figure(options_,'Name',figurename);
+        hfig=dyn_figure(options_.nodisplay,'Name',figurename);
     end
     [nam,texnam] = get_the_name(i,TeX,M_,estim_params_,options_);
     if subplotnum == 1
@@ -78,9 +78,9 @@ for i=1:npar
         end
     end
     [x2,f2,abscissa,dens,binf2,bsup2] = draw_prior_density(i,bayestopt_);
-    top2 = max(f2); 
+    top2 = max(f2);
     if i <= nvx
-        name = deblank(M_.exo_names(estim_params_.var_exo(i,1),:));  
+        name = deblank(M_.exo_names(estim_params_.var_exo(i,1),:));
         x1 = oo_.posterior_density.shocks_std.(name)(:,1);
         f1 = oo_.posterior_density.shocks_std.(name)(:,2);
         oo_.prior_density.shocks_std.(name)(:,1) = x2;
@@ -96,18 +96,18 @@ for i=1:npar
         oo_.prior_density.measurement_errors_std.(name)(:,2) = f2;
         if ~options_.mh_posterior_mode_estimation
             pmod = oo_.posterior_mode.measurement_errors_std.(name);
-        end     
+        end
     elseif i <= nvx+nvn+ncx
         j = i - (nvx+nvn);
         k1 = estim_params_.corrx(j,1);
         k2 = estim_params_.corrx(j,2);
-        name = [deblank(M_.exo_names(k1,:)) '_' deblank(M_.exo_names(k2,:))];  
+        name = [deblank(M_.exo_names(k1,:)) '_' deblank(M_.exo_names(k2,:))];
         x1 = oo_.posterior_density.shocks_corr.(name)(:,1);
         f1 = oo_.posterior_density.shocks_corr.(name)(:,2);
         oo_.prior_density.shocks_corr.(name)(:,1) = x2;
         oo_.prior_density.shocks_corr.(name)(:,2) = f2;
         if ~options_.mh_posterior_mode_estimation
-            pmod = oo_.posterior_mode.shocks_corr.(name);  
+            pmod = oo_.posterior_mode.shocks_corr.(name);
         end
     elseif i <= nvx+nvn+ncx+ncn
         j = i - (nvx+nvn+ncx);
@@ -151,13 +151,13 @@ for i=1:npar
     title(nam,'Interpreter','none');
     hold off;
     drawnow
-    if subplotnum == MaxNumberOfPlotPerFigure || i == npar;
-        dyn_saveas(hfig,[OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber)],options_);
+    if subplotnum == MaxNumberOfPlotPerFigure || i == npar
+        dyn_saveas(hfig,[OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber)],options_.nodisplay,options_.graph_format);
         if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
             fprintf(fidTeX,'\\begin{figure}[H]\n');
             for j = 1:size(NAMES,1)
                 fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(j,:)),deblank(TeXNAMES(j,:)));
-            end    
+            end
             fprintf(fidTeX,'\\centering\n');
             fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s/%s_PriorsAndPosteriors%s}\n',options_.figures.textwidth*min(subplotnum/nn,1),OutputDirectoryName,M_.fname,int2str(figunumber));
             fprintf(fidTeX,'\\caption{Priors and posteriors.}');
diff --git a/matlab/PosteriorIRF.m b/matlab/PosteriorIRF.m
index 8b086c5b96daf8269893c53628351b6114aa4211..157a5e3a13a22be663ff72f1db6d11716bf05562 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 posterior_sampler.m funtion.
 
-% Copyright (C) 2006-2016 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -178,7 +178,7 @@ if strcmpi(type,'posterior')
     end
 end
 
-if ~strcmpi(type,'prior'),
+if ~strcmpi(type,'prior')
     localVars.x=x;
 end
 
@@ -202,16 +202,16 @@ localVars.ifil2=ifil2;
 localVars.MhDirectoryName=MhDirectoryName;
 
 % Like sequential execution!
-if isnumeric(options_.parallel),
+if isnumeric(options_.parallel)
     [fout] = PosteriorIRF_core1(localVars,1,B,0);
     nosaddle = fout.nosaddle;
 else
     % Parallel execution!
     [nCPU, totCPU, nBlockPerCPU] = distributeJobs(options_.parallel, 1, B);
-    for j=1:totCPU-1,
+    for j=1:totCPU-1
         nfiles = ceil(nBlockPerCPU(j)/MAX_nirfs_dsge);
         NumberOfIRFfiles_dsge(j+1) =NumberOfIRFfiles_dsge(j)+nfiles;
-        if MAX_nirfs_dsgevar,
+        if MAX_nirfs_dsgevar
             nfiles = ceil(nBlockPerCPU(j)/MAX_nirfs_dsgevar);
         else
             nfiles=0;
@@ -235,12 +235,17 @@ else
     % which files have to be copied to run remotely
     NamFileInput(1,:) = {'',[M_.fname '_static.m']};
     NamFileInput(2,:) = {'',[M_.fname '_dynamic.m']};
-    if options_.steadystate_flag,
-        NamFileInput(length(NamFileInput)+1,:)={'',[M_.fname '_steadystate.m']};
+    NamFileInput(3,:) = {'',[M_.fname '_set_auxiliary_variables.m']};
+    if options_.steadystate_flag
+        if options_.steadystate_flag == 1
+            NamFileInput(length(NamFileInput)+1,:)={'',[M_.fname '_steadystate.m']};
+        else
+            NamFileInput(length(NamFileInput)+1,:)={'',[M_.fname '_steadystate2.m']};
+        end
     end
     [fout] = masterParallel(options_.parallel, 1, B,NamFileInput,'PosteriorIRF_core1', localVars, globalVars, options_.parallel_info);
     nosaddle=0;
-    for j=1:length(fout),
+    for j=1:length(fout)
         nosaddle = nosaddle + fout(j).nosaddle;
     end
 
@@ -363,101 +368,101 @@ end
 % PosteriorIRF_core2.m function.
 
 if ~options_.nograph && ~options_.no_graph.posterior
-% Save the local variables.
-localVars=[];
+    % Save the local variables.
+    localVars=[];
 
-Check=options_.TeX;
-if (Check)
-    localVars.varlist_TeX=varlist_TeX;
-end
+    Check=options_.TeX;
+    if (Check)
+        localVars.varlist_TeX=varlist_TeX;
+    end
 
 
-localVars.nvar=nvar;
-localVars.MeanIRF=MeanIRF;
-localVars.tit=tit;
-localVars.nn=nn;
-localVars.MAX_nirfs_dsgevar=MAX_nirfs_dsgevar;
-localVars.HPDIRF=HPDIRF;
-localVars.varlist=varlist;
-localVars.MaxNumberOfPlotPerFigure=MaxNumberOfPlotPerFigure;
-if options_.dsge_var
-    localVars.HPDIRFdsgevar=HPDIRFdsgevar;
-    localVars.MeanIRFdsgevar = MeanIRFdsgevar;
-end
+    localVars.nvar=nvar;
+    localVars.MeanIRF=MeanIRF;
+    localVars.tit=tit;
+    localVars.nn=nn;
+    localVars.MAX_nirfs_dsgevar=MAX_nirfs_dsgevar;
+    localVars.HPDIRF=HPDIRF;
+    localVars.varlist=varlist;
+    localVars.MaxNumberOfPlotPerFigure=MaxNumberOfPlotPerFigure;
+    if options_.dsge_var
+        localVars.HPDIRFdsgevar=HPDIRFdsgevar;
+        localVars.MeanIRFdsgevar = MeanIRFdsgevar;
+    end
 
-% The files .TeX are genereted in sequential way always!
-
-% The files .TeX are generated in sequential way always!
-subplotnum = 0;
-tit_TeX(M_.exo_names_orig_ord,:) = M_.exo_names_tex;
-if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
-    fidTeX = fopen([DirectoryName filesep M_.fname '_BayesianIRF.tex'],'w');
-    fprintf(fidTeX,'%% TeX eps-loader file generated by PosteriorIRF.m (Dynare).\n');
-    fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
-    fprintf(fidTeX,' \n');
-    titTeX(M_.exo_names_orig_ord,:) = M_.exo_names_tex;
-
-    for ii=irf_shocks_indx
-        figunumber = 0;
-
-        for jj=1:nvar
-            if max(abs(MeanIRF(:,jj,ii))) >= options_.impulse_responses.plot_threshold
-                subplotnum = subplotnum+1;
-                
-                if subplotnum == 1 
-                    fprintf(fidTeX,'\\begin{figure}[H]\n');    
+    % The files .TeX are genereted in sequential way always!
+
+    % The files .TeX are generated in sequential way always!
+    subplotnum = 0;
+    tit_TeX(M_.exo_names_orig_ord,:) = M_.exo_names_tex;
+    if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
+        fidTeX = fopen([DirectoryName filesep M_.fname '_BayesianIRF.tex'],'w');
+        fprintf(fidTeX,'%% TeX eps-loader file generated by PosteriorIRF.m (Dynare).\n');
+        fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
+        fprintf(fidTeX,' \n');
+        titTeX(M_.exo_names_orig_ord,:) = M_.exo_names_tex;
+
+        for ii=irf_shocks_indx
+            figunumber = 0;
+
+            for jj=1:nvar
+                if max(abs(MeanIRF(:,jj,ii))) >= options_.impulse_responses.plot_threshold
+                    subplotnum = subplotnum+1;
+
+                    if subplotnum == 1
+                        fprintf(fidTeX,'\\begin{figure}[H]\n');
+                    end
+                    name = deblank(varlist(jj,:));
+                    texname = deblank(varlist_TeX(jj,:));
+                    fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{%s}\n'],name,['$' texname '$']);
                 end
-                name = deblank(varlist(jj,:));
-                texname = deblank(varlist_TeX(jj,:));
-                fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{%s}\n'],name,['$' texname '$']);
-            end
-            if subplotnum == MaxNumberOfPlotPerFigure || (jj == nvar  && subplotnum> 0)
-                figunumber = figunumber+1;
-                
-                fprintf(fidTeX,'\\centering \n');
-                fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s/%s_Bayesian_IRF_%s_%d}\n',options_.figures.textwidth*min(subplotnum/nn,1),DirectoryName,M_.fname,deblank(tit(ii,:)),figunumber);
-                if options_.relative_irf
-                    fprintf(fidTeX,['\\caption{Bayesian relative IRF.}']);
-                else
-                    fprintf(fidTeX,'\\caption{Bayesian IRF: Orthogonalized shock to $%s$.}\n',deblank(tit_TeX(ii,:)));
+                if subplotnum == MaxNumberOfPlotPerFigure || (jj == nvar  && subplotnum> 0)
+                    figunumber = figunumber+1;
+
+                    fprintf(fidTeX,'\\centering \n');
+                    fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s/%s_Bayesian_IRF_%s_%d}\n',options_.figures.textwidth*min(subplotnum/nn,1),DirectoryName,M_.fname,deblank(tit(ii,:)),figunumber);
+                    if options_.relative_irf
+                        fprintf(fidTeX,['\\caption{Bayesian relative IRF.}']);
+                    else
+                        fprintf(fidTeX,'\\caption{Bayesian IRF: Orthogonalized shock to $%s$.}\n',deblank(tit_TeX(ii,:)));
+                    end
+                    fprintf(fidTeX,'\\label{Fig:BayesianIRF:%s:%d}\n',deblank(tit(ii,:)),figunumber);
+                    fprintf(fidTeX,'\\end{figure}\n');
+                    fprintf(fidTeX,' \n');
+
+                    subplotnum = 0;
                 end
-                fprintf(fidTeX,'\\label{Fig:BayesianIRF:%s:%d}\n',deblank(tit(ii,:)),figunumber);
-                fprintf(fidTeX,'\\end{figure}\n');
-                fprintf(fidTeX,' \n');
-                
-                subplotnum = 0;
-            end        
+            end
         end
+        fprintf(fidTeX,'%% End of TeX file.\n');
+        fclose(fidTeX);
     end
-    fprintf(fidTeX,'%% End of TeX file.\n');
-    fclose(fidTeX);
-end
 
-% The others file format are generated in parallel by PosteriorIRF_core2!
+    % The others file format are generated in parallel by PosteriorIRF_core2!
 
 
-% Comment for testing!
-if ~isoctave
-    if isnumeric(options_.parallel)  || (M_.exo_nbr*ceil(size(varlist,1)/MaxNumberOfPlotPerFigure))<8,
-        [fout] = PosteriorIRF_core2(localVars,1,M_.exo_nbr,0);
-    else
-        isRemoteOctave = 0;
-        for indPC=1:length(options_.parallel),
-            isRemoteOctave = isRemoteOctave + (findstr(options_.parallel(indPC).MatlabOctavePath, 'octave'));
-        end
-        if isRemoteOctave
+    % Comment for testing!
+    if ~isoctave
+        if isnumeric(options_.parallel)  || (M_.exo_nbr*ceil(size(varlist,1)/MaxNumberOfPlotPerFigure))<8
             [fout] = PosteriorIRF_core2(localVars,1,M_.exo_nbr,0);
         else
-            globalVars = struct('M_',M_, ...
-                'options_', options_);
+            isRemoteOctave = 0;
+            for indPC=1:length(options_.parallel)
+                isRemoteOctave = isRemoteOctave + (findstr(options_.parallel(indPC).MatlabOctavePath, 'octave'));
+            end
+            if isRemoteOctave
+                [fout] = PosteriorIRF_core2(localVars,1,M_.exo_nbr,0);
+            else
+                globalVars = struct('M_',M_, ...
+                                    'options_', options_);
 
-            [fout] = masterParallel(options_.parallel, 1, M_.exo_nbr,NamFileInput,'PosteriorIRF_core2', localVars, globalVars, options_.parallel_info);
+                [fout] = masterParallel(options_.parallel, 1, M_.exo_nbr,NamFileInput,'PosteriorIRF_core2', localVars, globalVars, options_.parallel_info);
+            end
         end
+    else
+        [fout] = PosteriorIRF_core2(localVars,1,M_.exo_nbr,0);
     end
-else
-    [fout] = PosteriorIRF_core2(localVars,1,M_.exo_nbr,0);
-end
-% END parallel code!
+    % END parallel code!
 
 end
 
diff --git a/matlab/PosteriorIRF_core1.m b/matlab/PosteriorIRF_core1.m
index 37f98209bad6c628fb3cb78d73a00fbb789639b9..561104f673c8c0921c84f9c345d58a5183ac6093 100644
--- a/matlab/PosteriorIRF_core1.m
+++ b/matlab/PosteriorIRF_core1.m
@@ -23,7 +23,7 @@ function myoutput=PosteriorIRF_core1(myinputs,fpar,B,whoiam, ThisMatlab)
 % SPECIAL REQUIREMENTS.
 %   None.
 %
-% Copyright (C) 2006-2016 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -43,7 +43,7 @@ function myoutput=PosteriorIRF_core1(myinputs,fpar,B,whoiam, ThisMatlab)
 
 global options_ estim_params_ oo_ M_ bayestopt_ dataset_ dataset_info
 
-if nargin<4,
+if nargin<4
     whoiam=0;
 end
 
@@ -55,7 +55,7 @@ irun =myinputs.irun;
 irun2=myinputs.irun2;
 npar=myinputs.npar;
 type=myinputs.type;
-if ~strcmpi(type,'prior'),
+if ~strcmpi(type,'prior')
     x=myinputs.x;
 end
 
@@ -102,7 +102,7 @@ end
 RemoteFlag = 0;
 
 if whoiam
-    if Parallel(ThisMatlab).Local==0,
+    if Parallel(ThisMatlab).Local==0
         RemoteFlag =1;
     end
     prct0={0,whoiam,Parallel(ThisMatlab)};
@@ -165,7 +165,7 @@ while fpar<B
         elseif info(1) == 5
             errordef = 'Rank condition  is not satisfied';
         end
-        if strcmpi(type,'prior'),
+        if strcmpi(type,'prior')
             disp(['PosteriorIRF :: Dynare is unable to solve the model (' errordef ')'])
             continue
         else
@@ -240,9 +240,9 @@ while fpar<B
         else
             stock_irf_bvardsge(:,:,:,IRUN) = reshape(tmp_dsgevar,options_.irf,dataset_.vobs,M_.exo_nbr);
             instr = [MhDirectoryName '/' M_.fname '_irf_bvardsge' ...
-                     int2str(NumberOfIRFfiles_dsgevar) '.mat stock_irf_bvardsge;'];,
+                     int2str(NumberOfIRFfiles_dsgevar) '.mat stock_irf_bvardsge;'];
             eval(['save ' instr]);
-            if RemoteFlag==1,
+            if RemoteFlag==1
                 OutputFileName_bvardsge = [OutputFileName_bvardsge; {[MhDirectoryName filesep], [M_.fname '_irf_bvardsge' int2str(NumberOfIRFfiles_dsgevar) '.mat']}];
             end
             NumberOfIRFfiles_dsgevar = NumberOfIRFfiles_dsgevar+1;
@@ -259,14 +259,14 @@ while fpar<B
                          int2str(NumberOfIRFfiles_dsgevar) '.mat stock_irf_bvardsge;'];
                 eval(['save ' instr]);
                 NumberOfIRFfiles_dsgevar = NumberOfIRFfiles_dsgevar+1;
-                if RemoteFlag==1,
+                if RemoteFlag==1
                     OutputFileName_bvardsge = [OutputFileName_bvardsge; {[MhDirectoryName filesep], [M_.fname '_irf_bvardsge' int2str(NumberOfIRFfiles_dsgevar) '.mat']}];
                 end
                 irun = 0;
             end
         end
         save([MhDirectoryName '/' M_.fname '_irf_dsge' int2str(NumberOfIRFfiles_dsge) '.mat'],'stock_irf_dsge');
-        if RemoteFlag==1,
+        if RemoteFlag==1
             OutputFileName_dsge = [OutputFileName_dsge; {[MhDirectoryName filesep], [M_.fname '_irf_dsge' int2str(NumberOfIRFfiles_dsge) '.mat']}];
         end
         NumberOfIRFfiles_dsge = NumberOfIRFfiles_dsge+1;
@@ -278,7 +278,7 @@ while fpar<B
         end
         stock = stock_param;
         save([MhDirectoryName '/' M_.fname '_param_irf' int2str(ifil2) '.mat'],'stock');
-        if RemoteFlag==1,
+        if RemoteFlag==1
             OutputFileName_param = [OutputFileName_param; {[MhDirectoryName filesep], [M_.fname '_param_irf' int2str(ifil2) '.mat']}];
         end
         ifil2 = ifil2 + 1;
diff --git a/matlab/PosteriorIRF_core2.m b/matlab/PosteriorIRF_core2.m
index 295f6d5eb9c17e80d6406632a08b1ddce4de7298..09e003c430cabca00cf8cae7edb9c7ec222baea2 100644
--- a/matlab/PosteriorIRF_core2.m
+++ b/matlab/PosteriorIRF_core2.m
@@ -2,10 +2,10 @@ 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
 % Performs in parallel execution a portion of the PosteriorIRF.m code.
-% For more information, see the comment in posterior_sampler_core.m 
+% For more information, see the comment in posterior_sampler_core.m
 % function.
 %
 % INPUTS
@@ -30,7 +30,7 @@ function myoutput=PosteriorIRF_core2(myinputs,fpar,npar,whoiam,ThisMatlab)
 % SPECIAL REQUIREMENTS.
 %   None.
 %
-% Copyright (C) 2006-2016 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -49,7 +49,7 @@ function myoutput=PosteriorIRF_core2(myinputs,fpar,npar,whoiam,ThisMatlab)
 
 global options_  M_
 
-if nargin<4,
+if nargin<4
     whoiam=0;
 end
 
@@ -85,8 +85,8 @@ end
 DirectoryName = CheckPath('Output',M_.dname);
 
 RemoteFlag = 0;
-if whoiam,
-    if Parallel(ThisMatlab).Local==0,
+if whoiam
+    if Parallel(ThisMatlab).Local==0
         RemoteFlag =1;
     end
     prct0={0,whoiam,Parallel(ThisMatlab)};
@@ -96,16 +96,16 @@ end
 OutputFileName={};
 
 subplotnum = 0;
-for i=fpar:npar,
+for i=fpar:npar
     figunumber = 0;
 
     for j=1:nvar
         if max(abs(MeanIRF(:,j,i))) >= options_.impulse_responses.plot_threshold
             subplotnum = subplotnum+1;
             if subplotnum == 1 && options_.relative_irf
-                hh = dyn_figure(options_,'Name',['Relative response to orthogonalized shock to ' tit(i,:)]);
+                hh = dyn_figure(options_.nodisplay,'Name',['Relative response to orthogonalized shock to ' tit(i,:)]);
             elseif subplotnum == 1 && ~options_.relative_irf
-                hh = dyn_figure(options_,'Name',['Orthogonalized shock to ' tit(i,:)]);
+                hh = dyn_figure(options_.nodisplay,'Name',['Orthogonalized shock to ' tit(i,:)]);
             end
 
             set(0,'CurrentFigure',hh)
@@ -135,7 +135,7 @@ for i=fpar:npar,
                     plot(1:options_.irf,HPDIRFdsgevar(:,1,j,i),'--k','linewidth',1)
                     plot(1:options_.irf,HPDIRFdsgevar(:,2,j,i),'--k','linewidth',1)
                 end
-                 % plot([1 options_.irf],[0 0],'-r','linewidth',0.5);
+                % plot([1 options_.irf],[0 0],'-r','linewidth',0.5);
                 box on
                 axis tight
                 xlim([1 options_.irf]);
@@ -152,17 +152,17 @@ for i=fpar:npar,
 
         if subplotnum == MaxNumberOfPlotPerFigure || (j == nvar  && subplotnum> 0)
             figunumber = figunumber+1;
-            dyn_saveas(hh,[DirectoryName '/'  M_.fname '_Bayesian_IRF_' deblank(tit(i,:)) '_' int2str(figunumber)],options_);
-            if RemoteFlag==1,
+            dyn_saveas(hh,[DirectoryName '/'  M_.fname '_Bayesian_IRF_' deblank(tit(i,:)) '_' int2str(figunumber)],options_.nodisplay,options_.graph_format);
+            if RemoteFlag==1
                 OutputFileName = [OutputFileName; {[DirectoryName,filesep], [M_.fname '_Bayesian_IRF_' deblank(tit(i,:)) '_' int2str(figunumber) '.*']}];
             end
             subplotnum = 0;
         end
     end% loop over selected endo_var
-    if whoiam,
+    if whoiam
         fprintf('Done! \n');
         waitbarString = [ 'Exog. shocks ' int2str(i) '/' int2str(npar) ' done.'];
-%         fMessageStatus((i-fpar+1)/(npar-fpar+1),whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab));
+        %         fMessageStatus((i-fpar+1)/(npar-fpar+1),whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab));
         dyn_waitbar((i-fpar+1)/(npar-fpar+1),[],waitbarString);
     end
 end% loop over exo_var
diff --git a/matlab/ReshapeMatFiles.m b/matlab/ReshapeMatFiles.m
index 1ad90fce11f9d7fa0bd6d3f0a1b66ea094c115ff..1d127a67bacdc9c2a20611e7d701f0b5b64c488c 100644
--- a/matlab/ReshapeMatFiles.m
+++ b/matlab/ReshapeMatFiles.m
@@ -18,14 +18,14 @@ function ReshapeMatFiles(type, type2)
 %                      posterior
 %                      gsa
 %                      prior
-%    
+%
 % OUTPUTS:
-%    none              
+%    none
 %
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2011 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -44,15 +44,15 @@ function ReshapeMatFiles(type, type2)
 
 global M_ options_
 
-if nargin==1, 
+if nargin==1
     MhDirectoryName = [ CheckPath('metropolis',M_.dname) filesep ];
 else
     if strcmpi(type2,'posterior')
         MhDirectoryName = [CheckPath('metropolis',M_.dname) filesep ];
     elseif strcmpi(type2,'gsa')
-        if options_.opt_gsa.morris==1,
+        if options_.opt_gsa.morris==1
             MhDirectoryName = [CheckPath('gsa/screen',M_.dname) filesep ];
-        elseif options_.opt_gsa.morris==2,
+        elseif options_.opt_gsa.morris==2
             MhDirectoryName = [CheckPath('gsa/identif',M_.dname) filesep ];
         elseif options_.opt_gsa.pprior
             MhDirectoryName = [CheckPath(['gsa' filesep 'prior'],M_.dname) filesep ];
@@ -61,17 +61,17 @@ else
         end
     else
         MhDirectoryName = [CheckPath('prior',M_.dname) filesep ];
-    end  
+    end
 end
 switch type
   case 'irf_dsge'
     CAPtype  = 'IRF_DSGE';
     TYPEsize = [ options_.irf , size(options_.varlist,1) , M_.exo_nbr ];
-    TYPEarray = 4;    
+    TYPEarray = 4;
   case 'irf_bvardsge'
     CAPtype  = 'IRF_BVARDSGE';
     TYPEsize = [ options_.irf , length(options_.varobs) , M_.exo_nbr ];
-    TYPEarray = 4;      
+    TYPEarray = 4;
   case 'smooth'
     CAPtype  = 'SMOOTH';
     TYPEsize = [ M_.endo_nbr , options_.nobs ];
@@ -134,7 +134,7 @@ switch TYPEarray
                 eval(['idx = idx + size(stock_' type ',4);'])
             end
             %eval(['STOCK_' CAPtype ' = sort(STOCK_' CAPtype ',4);'])
-            save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(NumberOfTYPEfiles-foffset+1) '.mat'],['STOCK_' CAPtype]);  
+            save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(NumberOfTYPEfiles-foffset+1) '.mat'],['STOCK_' CAPtype]);
         end
     else
         load([MhDirectoryName M_.fname '_' type '1.mat']);
@@ -176,7 +176,7 @@ switch TYPEarray
         load([MhDirectoryName M_.fname '_' type '1.mat']);
         %eval(['STOCK_' CAPtype ' = sort(stock_' type ',3);'])
         eval(['STOCK_' CAPtype ' = stock_' type ';'])
-        save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(1) '.mat'],['STOCK_' CAPtype ]);      
+        save([MhDirectoryName M_.fname '_' CAPtype 's' int2str(1) '.mat'],['STOCK_' CAPtype ]);
     end
     % Original file format may be useful in some cases...
     % for file = 1:NumberOfTYPEfiles
diff --git a/matlab/TaRB_optimizer_wrapper.m b/matlab/TaRB_optimizer_wrapper.m
index 4d29add34a3c4777b98097124e03bfa62d2ea32a..948266a23c65c0ad7f6d8b7eec6d6be685ed9cab 100644
--- a/matlab/TaRB_optimizer_wrapper.m
+++ b/matlab/TaRB_optimizer_wrapper.m
@@ -3,15 +3,15 @@ function [fval,info,exit_flag,DLIK,Hess,SteadyState,trend_coeff]  = TaRB_optimiz
 % Wrapper function for target function used in TaRB algorithm; reassembles
 % full parameter vector before calling target function
 %
-% INPUTS 
-%   o optpar            [double]   (p_opt*1) vector of subset of parameters to be considered 
-%   o par_vector        [double]   (p*1) full vector of parameters 
+% INPUTS
+%   o optpar            [double]   (p_opt*1) vector of subset of parameters to be considered
+%   o par_vector        [double]   (p*1) full vector of parameters
 %   o parameterindices  [double]   (p_opt*1) index of optpar entries in
 %                                   par_vector
 %   o TargetFun         [char]      string specifying the name of the objective
 %                                   function (posterior kernel).
 %   o varargin          [structure] other inputs of target function
-% 
+%
 % OUTPUTS
 %   o fval       [scalar]   value of (minus) the likelihood.
 %   o info       [double]  (p*2) error code vector
@@ -20,8 +20,9 @@ function [fval,info,exit_flag,DLIK,Hess,SteadyState,trend_coeff]  = TaRB_optimiz
 %   o Hess       [double]  (p*p) asymptotic Hessian matrix.
 %   o SteadyState [double]  Vector of doubles, steady state level for the endogenous variables.
 %   o trend_coeff [double]  Matrix of doubles, coefficients of the deterministic trend in the measurement equation
-% 
-% Copyright (C) 2015-16 Dynare Team
+%
+
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -40,4 +41,3 @@ function [fval,info,exit_flag,DLIK,Hess,SteadyState,trend_coeff]  = TaRB_optimiz
 
 par_vector(parameterindices,:)=optpar; %reassemble parameter
 [fval,info,exit_flag,DLIK,Hess,SteadyState,trend_coeff] = feval(TargetFun,par_vector,varargin{:}); %call target function
-
diff --git a/matlab/Tracing.m b/matlab/Tracing.m
index 7d0e947c9772fe09098cd1d1fc3ce86a224ae7d5..d3ba8c0be9832a4eaf2459debe10593524d65e08 100644
--- a/matlab/Tracing.m
+++ b/matlab/Tracing.m
@@ -2,19 +2,19 @@ function [] = Tracing()
 % DESCRIPTION
 % This function is used to test the correct execution of a matlab section
 % on remote machine.
-% 
+%
 % If no error happen the function simply create a file.
 %
 % INPUTS
 % ...
-% 
+%
 % OUTPUTS
 % ...
-%        
+%
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2010 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/UnivariateSpectralDensity.m b/matlab/UnivariateSpectralDensity.m
index fa0a9e22c4aa1e939f9a28f3ec02b9bc90e973b2..41b67c4031c87a4197e8c7d21c6ff52f193d6385 100644
--- a/matlab/UnivariateSpectralDensity.m
+++ b/matlab/UnivariateSpectralDensity.m
@@ -1,15 +1,15 @@
 function [oo_] = UnivariateSpectralDensity(M_,oo_,options_,var_list)
 % This function computes the theoretical spectral density of each
-% endogenous variable declared in var_list. Results are stored in 
-% oo_.SpectralDensity and may be plotted. Plots are saved into the 
-% graphs-folder. 
-% 
+% endogenous variable declared in var_list. Results are stored in
+% oo_.SpectralDensity and may be plotted. Plots are saved into the
+% graphs-folder.
+%
 % INPUTS
 %   M_                  [structure]    Dynare's model structure
 %   oo_                 [structure]    Dynare's results structure
 %   options_            [structure]    Dynare's options structure
 %   var_list            [integer]      Vector of indices for a subset of variables.
-%    
+%
 % OUTPUTS
 %   oo_                 [structure]    Dynare's results structure,
 %                                       containing the subfield
@@ -17,9 +17,9 @@ function [oo_] = UnivariateSpectralDensity(M_,oo_,options_,var_list)
 %                                       and density, which are of size nvar*ngrid.
 %
 
-% Adapted from th_autocovariances.m.  
+% Adapted from th_autocovariances.m.
 
-% Copyright (C) 2006-2015 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -38,7 +38,7 @@ function [oo_] = UnivariateSpectralDensity(M_,oo_,options_,var_list)
 
 
 if options_.order > 1
-    disp('UnivariateSpectralDensity :: I Cannot compute the theoretical spectral density') 
+    disp('UnivariateSpectralDensity :: I Cannot compute the theoretical spectral density')
     disp('with a second order approximation of the DSGE model!')
     disp('Please set order = 1. I abort')
     return
@@ -102,7 +102,7 @@ if ~isempty(u)
     ivar = oo_.dr.order_var(iky);
 end
 
-iky = iv(ivar);  
+iky = iv(ivar);
 aa = ghx(iky,:);
 bb = ghu(iky,:);
 ngrid = options_.hp_ngrid; %number of grid points
@@ -112,7 +112,7 @@ tneg  = exp(-sqrt(-1)*freqs); %negative frequencies
 if options_.one_sided_hp_filter
     error('UnivariateSpectralDensity:: spectral density estimate not available with one-sided HP filter')
 elseif options_.hp_filter == 0 && ~options_.bandpass.indicator %do not filter
-   filter_gain=ones(ngrid,1);
+    filter_gain=ones(ngrid,1);
 elseif ~(options_.hp_filter == 0 && ~options_.bandpass.indicator) && options_.bandpass.indicator %filter with bandpass
     filter_gain = zeros(1,ngrid);
     lowest_periodicity=options_.bandpass.passband(2);
@@ -122,7 +122,7 @@ elseif ~(options_.hp_filter == 0 && ~options_.bandpass.indicator) && options_.ba
     filter_gain(freqs<=-2*pi/lowest_periodicity+2*pi & freqs>=-2*pi/highest_periodicity+2*pi)=1;
 elseif ~(options_.hp_filter == 0 && ~options_.bandpass.indicator) && ~options_.bandpass.indicator %filter with HP-filter
     lambda = options_.hp_filter;
-    filter_gain = 4*lambda*(1 - cos(freqs)).^2 ./ (1 + 4*lambda*(1 - cos(freqs)).^2);    
+    filter_gain = 4*lambda*(1 - cos(freqs)).^2 ./ (1 + 4*lambda*(1 - cos(freqs)).^2);
 end
 
 mathp_col = NaN(ngrid,length(ivar)^2);
@@ -134,12 +134,12 @@ for ig = 1:ngrid
     g_omega = [aa*tneg(ig) bb]*f_omega*[aa'*tpos(ig); bb']; % selected variables
     f_hp = filter_gain(ig)^2*g_omega; % spectral density of selected filtered series
     mathp_col(ig,:) = (f_hp(:))';    % store as matrix row
-end;
+end
 
 f = zeros(nvar,ngrid);
 for i=1:nvar
     f(i,:) = real(mathp_col(:,(i-1)*nvar+i)); %read out spectral density
-end  
+end
 
 oo_.SpectralDensity.freqs=freqs;
 oo_.SpectralDensity.density=f;
@@ -159,12 +159,12 @@ if options_.nograph == 0
     end
 
     for i= 1:nvar
-        hh = dyn_figure(options_,'Name',['Spectral Density of ' deblank(M_.endo_names(ivar(i),:)) '.']);
+        hh = dyn_figure(options_.nodisplay,'Name',['Spectral Density of ' deblank(M_.endo_names(ivar(i),:)) '.']);
         plot(freqs,f(i,:),'-k','linewidth',2)
         xlabel('0 \leq \omega \leq \pi')
         ylabel('f(\omega)')
         box on
-        axis tight        
-        dyn_saveas(hh,[M_.fname ,filesep,'graphs', filesep, 'SpectralDensity_' deblank(M_.endo_names(ivar(i),:))],options_)
+        axis tight
+        dyn_saveas(hh,[M_.fname ,filesep,'graphs', filesep, 'SpectralDensity_' deblank(M_.endo_names(ivar(i),:))],options_.nodisplay,options_.graph_format)
     end
 end
diff --git a/matlab/WriteShockDecomp2Excel.m b/matlab/WriteShockDecomp2Excel.m
new file mode 100644
index 0000000000000000000000000000000000000000..5417e5250b0a42001b54d77c277d4a5b65965fa3
--- /dev/null
+++ b/matlab/WriteShockDecomp2Excel.m
@@ -0,0 +1,126 @@
+function WriteShockDecomp2Excel(z,shock_names,endo_names,i_var,initial_date,DynareModel,DynareOptions,opts_decomp)
+%function WriteShockDecomp2Excel(z,shock_names,endo_names,i_var,initial_date,DynareModel,DynareOptions)
+% Saves the results from the shock_decomposition command to xls
+%
+% Inputs
+%   z               [n_var*(nshock+2)*nperiods]     shock decomposition array, see shock_decomposition.m for details
+%   shock_names     [endo_nbr*string length]        shock names from M_.exo_names
+%   endo_names      [exo_nbr*string length]         variable names from M_.endo_names
+%   i_var           [n_var*1]                       vector indices of requested variables in M_.endo_names and z
+%   initial_date    [dseries object]                first period of decomposition to plot
+%   DynareModel     [structure]                     Dynare model structure
+%   DynareOptions   [structure]                     Dynare options structure
+
+% Copyright (C) 2016-2017 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/>.
+
+SteadyState=[];
+fig_mode='';
+fig_mode1='';
+fig_name='';
+screen_shocks=0;
+use_shock_groups = DynareOptions.plot_shock_decomp.use_shock_groups;
+if use_shock_groups
+    shock_groups = DynareModel.shock_groups.(use_shock_groups);
+    shock_ind = fieldnames(shock_groups);
+end
+
+% number of components equals number of shocks + 1 (initial conditions)
+comp_nbr = size(z,2)-1;
+
+if nargin==8
+    if isfield(opts_decomp,'steady_state')
+        SteadyState = opts_decomp.steady_state;
+    end
+    if isfield(opts_decomp,'fig_mode') && ~isempty(opts_decomp.fig_mode)
+        fig_mode = opts_decomp.fig_mode;
+        fig_mode1 = ['_' fig_mode];
+        fig_mode = [fig_mode '_'];
+    end
+    if isfield(opts_decomp,'screen_shocks')
+        if use_shock_groups
+            screen_shocks=0;
+        elseif comp_nbr>18
+            screen_shocks = opts_decomp.screen_shocks;
+        end
+    end
+    if isfield(opts_decomp,'fig_name')
+        fig_name = opts_decomp.fig_name;
+        %         fig_name = ['_' fig_name];
+        fig_name1 = [fig_name];
+        fig_name = [fig_name '_'];
+    end
+    if screen_shocks
+        fig_name1 = [fig_name1 '_screen'];
+        fig_name = [fig_name 'screen_'];
+    end
+end
+
+
+gend = size(z,3);
+if isempty(initial_date)
+    x = 1:gend;
+else
+    freq = initial_date.freq;
+    initial_period = initial_date.time(1) + (initial_date.time(2)-1)/freq;
+    x = initial_period:(1/freq):initial_period+(gend-1)/freq;
+end
+
+
+nvar = length(i_var);
+
+labels = char(char(shock_names),'Initial values');
+if ~(screen_shocks && comp_nbr>18)
+    screen_shocks=0;
+end
+comp_nbr0=comp_nbr;
+%%plot decomposition
+for j=1:nvar
+    d0={};
+    z1 = squeeze(z(i_var(j),:,:));
+    if screen_shocks
+        [junk, isort] = sort(mean(abs(z1(1:end-2,:)')), 'descend');
+        labels = char(char(shock_names(isort(1:16),:)),'Others', 'Initial values');
+        zres = sum(z1(isort(17:end),:),1);
+        z1 = [z1(isort(1:16),:); zres; z1(comp_nbr0:end,:)];
+        comp_nbr=18;
+    end
+
+    d0(1,:)=[{'Decomposition'} cellstr(labels(1:comp_nbr,:))' {'Smoot Var'}];
+    d0=[d0; num2cell([x' z1'])];
+    LastRow=size(d0,1);
+    if use_shock_groups
+        d0(LastRow+2,1)={'Legend.'};
+        d0(LastRow+2,2)={'Shocks include:'};
+        d0(LastRow+3:LastRow+3+comp_nbr-1,1)=cellstr(labels(1:comp_nbr,:));
+        for ic=1:comp_nbr
+            group_members = shock_groups.(shock_ind{ic}).shocks;
+            d0(LastRow+2+ic,2:1+length(group_members))=group_members;
+        end
+    end
+
+    warning off
+    if ~ismac
+        [STATUS,MESSAGE] = xlswrite([DynareModel.fname,'_shock_decomposition',fig_mode,fig_name1],d0,deblank(endo_names(i_var(j),:)));
+    else
+        [STATUS] = xlwrite([DynareModel.fname,'_shock_decomposition',fig_mode,fig_name1],d0,deblank(endo_names(i_var(j),:)));
+    end
+    warning on
+
+    clear d0
+
+end
diff --git a/matlab/add_filter_subtitle.m b/matlab/add_filter_subtitle.m
index 65258751793cc66945e27c822291c9589dd16e05..4b0a63ede8d006eeff541d0ba4127e5795067940 100644
--- a/matlab/add_filter_subtitle.m
+++ b/matlab/add_filter_subtitle.m
@@ -1,7 +1,24 @@
 function title=add_filter_subtitle(title,options_)
 
+% Copyright (C) 2015-2017 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_.hp_filter && ~options_.one_sided_hp_filter  && ~options_.bandpass.indicator %do not filter
-    %nothing to add here
+                                                                                         %nothing to add here
 elseif ~options_.hp_filter && ~options_.one_sided_hp_filter && options_.bandpass.indicator
     title = [title ' (Bandpass filter, (' ...
              num2str(options_.bandpass.passband(1)),' ',num2str(options_.bandpass.passband(2)), '))'];
@@ -10,6 +27,6 @@ elseif options_.hp_filter && ~options_.one_sided_hp_filter  && ~options_.bandpas
              num2str(options_.hp_filter) ')'];
 elseif ~options_.hp_filter && options_.one_sided_hp_filter && ~options_.bandpass.indicator
     title = [title ' (One-sided HP filter, lambda = ' ...
-             num2str(options_.one_sided_hp_filter) ')'];    
+             num2str(options_.one_sided_hp_filter) ')'];
 end
 end
\ No newline at end of file
diff --git a/matlab/add_path_to_mex_files.m b/matlab/add_path_to_mex_files.m
index 38da0d345a95a6f2cad33604511009aeedf9fbe4..13140bba5b03243ea71ca3e4f5fd9044665c4c34 100644
--- a/matlab/add_path_to_mex_files.m
+++ b/matlab/add_path_to_mex_files.m
@@ -1,6 +1,6 @@
 function mexpath = add_path_to_mex_files(dynareroot, modifypath)
-    
-% Copyright (C) 2015-2016 Dynare Team
+
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -20,9 +20,13 @@ function mexpath = add_path_to_mex_files(dynareroot, modifypath)
 if nargin<2
     modifypath = true;
 end
-    
+
 if exist('OCTAVE_VERSION')
-    mexpath = {[dynareroot '../mex/octave/']};
+    if ispc() && strcmpi(computer(), 'i686-w64-mingw32')
+        mexpath = {[dynareroot '../mex/octave32/']};
+    else
+        mexpath = {[dynareroot '../mex/octave/']};
+    end
     if modifypath
         addpath(mexpath{1});
     end
@@ -48,7 +52,7 @@ else
                 end
             end
         else
-            tmp = [dynareroot '../mex/matlab/win64-7.8-9.1/'];
+            tmp = [dynareroot '../mex/matlab/win64-7.8-9.2/'];
             if exist(tmp, 'dir')
                 mexpath = tmp;
                 if modifypath
diff --git a/matlab/annualized_shock_decomposition.m b/matlab/annualized_shock_decomposition.m
new file mode 100644
index 0000000000000000000000000000000000000000..4972edb3078a218f64b8117fd1387174d0fe51d6
--- /dev/null
+++ b/matlab/annualized_shock_decomposition.m
@@ -0,0 +1,333 @@
+function [z, endo_names, endo_names_tex, steady_state, i_var, oo_] = annualized_shock_decomposition(oo_, M_, options_, i_var, t0, t1, realtime_, vintage_, steady_state, q2a, cumfix)
+% function oo_ = annualized_shock_decomposition(oo_,t0,options_.nobs);
+% Computes annualized shocks contribution to a simulated trajectory. The fields set are
+% oo_.annualized_shock_decomposition, oo_.annualized_realtime_shock_decomposition,
+% oo_.annualized_realtime_conditional_shock_decomposition and oo_.annualized_realtime_forecast_shock_decomposition.
+% Subfields are arrays n_var by nshock+2 by nperiods. The
+% first nshock columns store the respective shock contributions, column n+1
+% stores the role of the initial conditions, while column n+2 stores the
+% value of the smoothed variables.  Both the variables and shocks are stored
+% in the order of endo_names and M_.exo_names, respectively.
+%
+% INPUTS
+%    oo_:          [structure] Storage of results
+%    M_:           [structure] Storage of model
+%    opts:         [structure] options for shock decomp
+%    i_var:        [array] index of vars
+%    t0:           [integer]  first period
+%    t1:           [integer] last period
+%    realtime_:    [integer]
+%    vintage_:     [integer]
+%    steady_state: [array] steady state value of quarterly (log-) level vars
+%    q2a:          [structure] info on q2a
+%
+% OUTPUTS
+%    z:              [matrix] shock decomp to plot
+%    endo_names:     [char] updated var names
+%    endo_names_tex: [char] updated TeX var names
+%    steady_state:   [array] updated stady state of vars
+%    i_var:          [integer array] updated var indices to plot
+%    oo_:            [structure]  Storage of results
+%
+% SPECIAL REQUIREMENTS
+%    none
+
+% Copyright (C) 2017 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 = options_.plot_shock_decomp;
+nvar = length(i_var);
+GYTREND0 = q2a.GYTREND0;
+var_type = q2a.type;
+islog    = q2a.islog;
+aux      = q2a.aux;
+aux0 = aux;
+cumfix      = q2a.cumfix;
+% usual shock decomp
+if isstruct(oo_)
+    %     z = oo_.shock_decomposition;
+    myopts=options_;
+    myopts.plot_shock_decomp.type='qoq';
+    myopts.plot_shock_decomp.realtime=0;
+    [z, junk] = plot_shock_decomposition(M_,oo_,myopts,[]);
+else
+    z = oo_;
+end
+z = z(i_var,:,:);
+mytype=var_type;
+if isfield(q2a,'name')
+    mytxt = q2a.name;
+    mytex = q2a.name;
+    if isfield(q2a,'tex_name')
+        mytex = q2a.tex_name;
+    end
+    if mytype==2
+        gtxt = ['PHI' mytxt]; % inflation rate
+        gtex = ['{\pi(' mytex ')}'];
+    elseif mytype
+        gtxt = ['G' mytxt]; % inflation rate
+        gtex = ['{g(' mytex ')}'];
+    end
+    if isfield(q2a,'gname')
+        gtxt = q2a.gname;
+    end
+    if isfield(q2a,'tex_gname')
+        gtex = q2a.tex_gname;
+    end
+    mytype=0;
+end
+if isstruct(aux)
+    if ischar(aux.y)
+        myopts=options_;
+        myopts.plot_shock_decomp.type='qoq';
+        myopts.plot_shock_decomp.realtime=0;
+        [y_aux, steady_state_aux] = plot_shock_decomposition(M_,oo_,myopts,aux.y);
+        aux.y=y_aux;
+        aux.yss=steady_state_aux;
+    end
+    yaux=aux.y;
+end
+if mytype==2
+    gtxt = 'PHI'; % inflation rate
+    gtex = '\pi';
+elseif mytype
+    gtxt = 'G'; % growth rate
+    gtex = 'g';
+end
+steady_state=steady_state(i_var);
+% endo_names = M_.endo_names(i_var,:);
+% endo_names_tex = M_.endo_names_tex(i_var,:);
+nterms = size(z,2);
+nfrcst = opts.forecast/4;
+
+for j=1:nvar
+    if j>1
+        endo_names = char(endo_names,[deblank(M_.endo_names(i_var(j),:)) '_A']);
+        endo_names_tex = char(endo_names_tex,['{' deblank(M_.endo_names_tex(i_var(j),:)) '}^A']);
+        gendo_names = char(gendo_names,[gtxt endo_names(j,:)]);
+        gendo_names_tex = char(gendo_names_tex,[gtex '(' deblank(endo_names_tex(j,:)) ')']);
+    else
+        if nvar==1 && ~mytype
+            endo_names = mytxt;
+            endo_names_tex = mytex;
+            gendo_names = gtxt;
+            gendo_names_tex = gtex;
+        else
+            endo_names = [deblank(M_.endo_names(i_var(j),:)) '_A'];
+            endo_names_tex = ['{' deblank(M_.endo_names_tex(i_var(j),:)) '}^A'];
+            gendo_names = [gtxt endo_names(j,:)];
+            gendo_names_tex = [gtex '(' deblank(endo_names_tex(j,:)) ')'];
+        end
+    end
+    for k =1:nterms
+        if isstruct(aux)
+            aux.y = squeeze(yaux(j,k,min((t0-3):-4:1):end));
+        end
+        [za(j,k,:), steady_state_a(j,1), gza(j,k,:), steady_state_ga(j,1)] = ...
+            quarterly2annual(squeeze(z(j,k,min((t0-3):-4:1):end)),steady_state(j),GYTREND0,var_type,islog,aux);
+    end
+    ztmp=squeeze(za(j,:,:));
+    if cumfix==0
+        zscale = sum(ztmp(1:end-1,:))./ztmp(end,:);
+        ztmp(1:end-1,:) = ztmp(1:end-1,:)./repmat(zscale,[nterms-1,1]);
+    else
+        zres = ztmp(end,:)-sum(ztmp(1:end-1,:));
+        ztmp(end-1,:) = ztmp(end-1,:) + zres;
+    end
+    gztmp=squeeze(gza(j,:,:));
+    if cumfix==0
+        gscale = sum(gztmp(1:end-1,:))./ gztmp(end,:);
+        gztmp(1:end-1,:) = gztmp(1:end-1,:)./repmat(gscale,[nterms-1,1]);
+    else
+        gres = gztmp(end,:) - sum(gztmp(1:end-1,:));
+        gztmp(end-1,:) = gztmp(end-1,:)+gres;
+    end
+    za(j,:,:) = ztmp;
+    gza(j,:,:) = gztmp;
+end
+
+if q2a.plot ==1
+    z=gza;
+    endo_names = gendo_names;
+    endo_names_tex = gendo_names_tex;
+elseif q2a.plot == 2
+    z=za;
+else
+    z=cat(1,za,gza);
+    endo_names = char(endo_names,gendo_names);
+    endo_names_tex = char(endo_names_tex,gendo_names_tex);
+end
+% if isstruct(oo_)
+%     oo_.annualized_shock_decomposition=z;
+% end
+
+% realtime
+if realtime_ && isstruct(oo_) && isfield(oo_, 'realtime_shock_decomposition')
+    init=1;
+    for i=t0:4:t1
+        yr=floor(i/4);
+        za=[];
+        gza=[];
+        myopts=options_;
+        myopts.plot_shock_decomp.type='qoq';
+        myopts.plot_shock_decomp.realtime=1;
+        myopts.plot_shock_decomp.vintage=i;
+        [z, steady_state_aux] = plot_shock_decomposition(M_,oo_,myopts,[]);
+        z = z(i_var,:,:);
+        if isstruct(aux)
+            if ischar(aux0.y)
+                [y_aux, steady_state_aux] = plot_shock_decomposition(M_,oo_,myopts,aux0.y);
+                aux.y=y_aux;
+                aux.yss=steady_state_aux;
+            end
+            yaux=aux.y;
+        end
+        nterms = size(z,2);
+
+        %     z = oo_.realtime_shock_decomposition.(['time_' int2str(i)]);
+        %     z = z(i_var,:,:);
+
+        for j=1:nvar
+            for k =nterms:-1:1
+                %             if k<nterms
+                %                 ztmp = squeeze(sum(z(j,[1:k-1,k+1:end-1],t0-4:end)));
+                %             else
+                ztmp = squeeze(z(j,k,min((t0-3):-4:1):end));
+                %             end
+                if isstruct(aux)
+                    aux.y = squeeze(yaux(j,k,min((t0-3):-4:1):end));
+                end
+                [za(j,k,:), steady_state_a(j,1), gza(j,k,:), steady_state_ga(j,1)] = ...
+                    quarterly2annual(ztmp,steady_state(j),GYTREND0,var_type,islog,aux);
+                %             if k<nterms
+                %                 za(j,k,:) = za(j,end,:) - za(j,k,:);
+                %                 gza(j,k,:) = gza(j,end,:) - gza(j,k,:);
+                %             end
+
+            end
+
+            ztmp=squeeze(za(j,:,:));
+
+            if cumfix==0
+                zscale = sum(ztmp(1:end-1,:))./ztmp(end,:);
+                ztmp(1:end-1,:) = ztmp(1:end-1,:)./repmat(zscale,[nterms-1,1]);
+            else
+                zres = ztmp(end,:)-sum(ztmp(1:end-1,:));
+                ztmp(end-1,:) = ztmp(end-1,:) + zres;
+            end
+
+            gztmp=squeeze(gza(j,:,:));
+            if cumfix==0
+                gscale = sum(gztmp(1:end-1,:))./ gztmp(end,:);
+                gztmp(1:end-1,:) = gztmp(1:end-1,:)./repmat(gscale,[nterms-1,1]);
+            else
+                gres = gztmp(end,:) - sum(gztmp(1:end-1,:));
+                gztmp(end-1,:) = gztmp(end-1,:)+gres;
+            end
+
+            za(j,:,:) = ztmp;
+            gza(j,:,:) = gztmp;
+        end
+
+        if q2a.plot ==1
+            z=gza;
+        elseif q2a.plot == 2
+            z=za;
+        else
+            z=cat(1,za,gza);
+        end
+
+        if init==1
+            oo_.annualized_realtime_shock_decomposition.pool = z;
+        else
+            oo_.annualized_realtime_shock_decomposition.pool(:,:,yr) = z(:,:,end-nfrcst);
+        end
+        oo_.annualized_realtime_shock_decomposition.(['yr_' int2str(yr)]) = z;
+
+        if opts.forecast
+            oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr)]) = z(:,:,end-nfrcst:end);
+            if init>nfrcst
+                oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-nfrcst)]) = ...
+                    oo_.annualized_realtime_shock_decomposition.pool(:,:,yr-nfrcst:end) - ...
+                    oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr-nfrcst)]);
+                % fix others
+                oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-nfrcst)])(:,end-1,:) = ...
+                    oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-nfrcst)])(:,end-1,:) + ...
+                    oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr-nfrcst)])(:,end,:);
+                % fix total
+                oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-nfrcst)])(:,end,:) = ...
+                    oo_.annualized_realtime_shock_decomposition.pool(:,end,yr-nfrcst:end);
+                if i==t1
+                    for my_forecast_=(nfrcst-1):-1:1
+                        oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-my_forecast_)]) = ...
+                            oo_.annualized_realtime_shock_decomposition.pool(:,:,yr-my_forecast_:yr) - ...
+                            oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr-my_forecast_)])(:,:,1:my_forecast_+1);
+                        oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-my_forecast_)])(:,end-1,:) = ...
+                            oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(yr-my_forecast_)])(:,end,1:my_forecast_+1);
+                        oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(yr-my_forecast_)])(:,end,:) = ...
+                            oo_.annualized_realtime_shock_decomposition.pool(:,end,yr-my_forecast_:yr);
+                    end
+                end
+            end
+        end
+        % ztmp=oo_.realtime_shock_decomposition.pool(:,:,21:29)-oo_.realtime_forecast_shock_decomposition.time_21;
+
+
+
+        init=init+1;
+    end
+
+
+    switch realtime_
+
+      case 0
+        z = oo_.annualized_shock_decomposition;
+
+      case 1 % realtime
+        if vintage_
+            z = oo_.annualized_realtime_shock_decomposition.(['yr_' int2str(floor(vintage_/4))]);
+        else
+            z = oo_.annualized_realtime_shock_decomposition.pool;
+        end
+
+      case 2 % conditional
+        if vintage_
+            z = oo_.annualized_realtime_conditional_shock_decomposition.(['yr_' int2str(floor(vintage_/4))]);
+        else
+            error();
+        end
+
+      case 3 % forecast
+        if vintage_
+            z = oo_.annualized_realtime_forecast_shock_decomposition.(['yr_' int2str(floor(vintage_/4))]);
+        else
+            error()
+        end
+    end
+end
+
+if q2a.plot ==0
+    i_var=1:2*nvar;
+    steady_state = [steady_state_a;steady_state_ga];
+else
+    i_var=1:nvar;
+    if q2a.plot ==1
+        steady_state = steady_state_ga;
+    else
+        steady_state = steady_state_a;
+    end
+end
diff --git a/matlab/autoregressive_process_specification.m b/matlab/autoregressive_process_specification.m
index 7cc34db27db46895e6780c6e2a54d927953a6fe4..6f73b7e0545fab9873b7289f3f1f5e117dff3323 100644
--- a/matlab/autoregressive_process_specification.m
+++ b/matlab/autoregressive_process_specification.m
@@ -2,48 +2,48 @@ function [InnovationVariance,AutoregressiveParameters] = autoregressive_process_
 % This function computes the parameters of an AR(p) process from the variance and the autocorrelation function
 % (the first p terms) of this process.
 %
-% INPUTS 
+% INPUTS
 %  [1] Variance                 [double]  scalar, variance of the variable.
 %  [2] Rho                      [double]  p*1 vector, the autocorelation function: \rho(1), \rho(2), ..., \rho(p).
 %  [3] p                        [double]  scalar, the number of lags in the AR process.
 %
-% OUTPUTS 
+% OUTPUTS
 %  [1] InnovationVariance       [double]  scalar, the variance of the innovation.
 %  [2] AutoregressiveParameters [double]  p*1 vector of autoregressive parameters.
 %
-% NOTES 
+% NOTES
 %
 % The AR(p) model for {y_t} is:
-%   
-%           y_t = \phi_1 * y_{t-1} +  \phi_2 * y_{t-2} + ... +  \phi_p * y_{t-p} + e_t    
+%
+%           y_t = \phi_1 * y_{t-1} +  \phi_2 * y_{t-2} + ... +  \phi_p * y_{t-p} + e_t
 %
 % Let \gamma(0) and \rho(1), ..., \rho(2) be the variance and the autocorrelation function of {y_t}. This function
-% compute the variance of {e_t} and the \phi_i (i=1,...,p) from the variance and the autocorrelation function of {y_t}. 
+% compute the variance of {e_t} and the \phi_i (i=1,...,p) from the variance and the autocorrelation function of {y_t}.
 % We know that:
-%    
+%
 %    \gamma(0) = \phi_1 \gamma(1) + ... + \phi_p \gamma(p) + \sigma^2
 %
 % where \sigma^2 is the variance of {e_t}. Equivalently we have:
 %
-%    \sigma^2 = \gamma(0) (1-\rho(1)\phi_1 - ... - \rho(p)\phi_p)     
+%    \sigma^2 = \gamma(0) (1-\rho(1)\phi_1 - ... - \rho(p)\phi_p)
 %
 % We also have for any integer  h>0:
-% 
+%
 %    \rho(h) = \phi_1 \rho(h-1) + ... + \phi_p \rho(h-p)
 %
 % We can write the equations for \rho(1), ..., \rho(p) using matrices. Let R be the p*p autocorelation
-% matrix and v be the p*1 vector gathering the first p terms of the autocorrelation function. We have: 
+% matrix and v be the p*1 vector gathering the first p terms of the autocorrelation function. We have:
 %
 %           v = R*PHI
-%    
+%
 % where PHI is a p*1 vector with the autoregressive parameters of the AR(p) process. We can recover the autoregressive
 % parameters by inverting the autocorrelation matrix: PHI = inv(R)*v.
-% 
+%
 % This function first computes the vector PHI by inverting R and computes the variance of the innovation by evaluating
 %
 %           \sigma^2 = \gamma(0)*(1-PHI'*v)
 
-% Copyright (C) 2009 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/backward/backward_model_forecast.m b/matlab/backward/backward_model_forecast.m
new file mode 100644
index 0000000000000000000000000000000000000000..0c23abaefc3f6b441235649f8605af4fa98f62eb
--- /dev/null
+++ b/matlab/backward/backward_model_forecast.m
@@ -0,0 +1,122 @@
+function forecasts = backward_model_forecast(initialcondition, listofvariables, periods, withuncertainty)
+
+% Returns unconditional forecasts.
+%
+% INPUTS 
+% - initialcondition    [dseries]             Initial conditions for the endogenous variables.
+% - periods             [integer]             scalar, the number of (forecast) periods.
+% - withuncertainty     [logical]             scalar, returns confidence bands if true.
+%
+% OUTPUTS 
+% - forecast            [dseries]   
+
+% Copyright (C) 2017 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 that the model is actually backward
+if M_.maximum_lead
+    error(['backward_model_irf:: The specified model is not backward looking!'])
+end
+
+% Initialize returned argument.
+forecasts = struct();
+
+% Set defaults.
+if nargin<2
+    listofvariables = cellstr(M_.endo_names);
+    periods = 8;
+    withuncertainty = false;
+end
+
+if nargin<3
+    periods = 8;
+    withuncertainty = false;
+end
+
+if nargin<4
+    withuncertainty = false;
+end
+
+% Get full list of endogenous variables
+endo_names = cellstr(M_.endo_names);
+
+% Get vector of indices for the selected endogenous variables.
+n = length(listofvariables);
+idy = zeros(n,1);
+for i=1:n
+    j = strmatch(listofvariables{i}, endo_names, 'exact');
+    if isempty(j)
+        error('backward_model_forecast:: Variable %s is unknown!', listofvariables{i})
+    else
+        idy(i) = j;
+    end
+end
+
+% Set the number of simulations (if required).
+if withuncertainty
+    B = 1000;
+end
+
+% Get the covariance matrix of the shocks.
+if withuncertainty
+    Sigma = M_.Sigma_e + 1e-14*eye(M_.exo_nbr);
+    sigma = transpose(chol(Sigma));
+end
+
+% Set initial condition.
+if isdates(initialcondition)
+    if isempty(M_.endo_histval)
+        error('backward_model_irf: histval block for setting initial condition is missing!')
+    end
+    initialcondition = dseries(transpose(M_.endo_histval), initialcondition, endo_names, cellstr(M_.endo_names_tex));
+end
+
+% Put initial conditions in a vector of doubles
+initialconditions = transpose(initialcondition{endo_names{:}}.data);
+
+% Compute forecast without shock 
+innovations = zeros(periods+max(M_.maximum_exo_lag, 1), M_.exo_nbr);
+if M_.maximum_exo_lag
+    if isempty(M_.exo_histval)
+        error('You need to set the past values for the exogenous variables!')
+    else
+        innovations(1:M_.maximum_exo_lag, :) = M_.exo_histval;
+    end
+end
+
+oo__0 = simul_backward_model(initialconditions, periods, options_, M_, oo_, innovations);
+forecasts.pointforecast = dseries(transpose(oo__0.endo_simul(idy,:)), initialcondition.init, listofvariables);
+
+if withuncertainty
+    % Preallocate an array gathering the simulations.
+    ArrayOfForectasts = zeros(n, periods+1, B);
+    for i=1:B
+        innovations(max(M_.maximum_exo_lag, 1)+1:end,:) = transpose(sigma*randn(M_.exo_nbr, periods));
+        oo__ = simul_backward_model(initialconditions, periods, options_, M_, oo_, innovations);     
+        ArrayOfForecasts(:,:,i) = oo__.endo_simul(idy,:); 
+    end
+    % Compute mean (over future uncertainty) forecast.
+    forecasts.meanforecast = dseries(transpose(mean(ArrayOfForecasts, 3)), initialcondition.init, listofvariables);
+    forecasts.medianforecast = dseries(transpose(median(ArrayOfForecasts, 3)), initialcondition.init, listofvariables);
+    forecasts.stdforecast = dseries(transpose(std(ArrayOfForecasts, 1,3)), initialcondition.init, listofvariables);
+    % Compute lower and upper 95% confidence bands
+    ArrayOfForecasts = sort(ArrayOfForecasts, 3);
+    forecasts.lb = dseries(transpose(ArrayOfForecasts(:,:,round(0.025*B))), initialcondition.init, listofvariables);
+    forecasts.ub = dseries(transpose(ArrayOfForecasts(:,:,round(0.975*B))), initialcondition.init, listofvariables);
+end
\ No newline at end of file
diff --git a/matlab/backward/backward_model_inversion.m b/matlab/backward/backward_model_inversion.m
new file mode 100644
index 0000000000000000000000000000000000000000..6acbcc606c367d1017d11292ac99ecd3a86452d4
--- /dev/null
+++ b/matlab/backward/backward_model_inversion.m
@@ -0,0 +1,121 @@
+function [endogenousvariables, exogenousvariables] = backward_model_inversion(constraints, exogenousvariables, initialconditions, endo_names, exo_names, freeinnovations, DynareModel, DynareOptions, DynareOutput)
+
+% INPUTS
+% - constraints         [dseries]        with N constrained endogenous variables from t1 to t2.
+% - exogenousvariables  [dseries]        with Q exogenous variables.
+% - initialconditions   [dseries]        with M endogenous variables starting before t1 (M initialcond must contain at least the state variables).
+% - endo_names          [cell]           list of endogenous variable names.
+% - exo_names           [cell]           list of exogenous variable names.
+% - freeinstruments     [cell]           list of exogenous variable names used to control the constrained endogenous variables.
+%
+% OUTPUTS
+% - endogenous          [dseries]
+% - exogenous           [dseries]
+%
+% REMARKS
+
+% Copyright (C) 2017 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/>.
+
+% Get indices for the calibrated and free innovations.
+freeinnovations_id = zeros(length(freeinnovations), 1);
+if length(freeinnovations)<DynareModel.exo_nbr
+    for i=1:length(freeinnovations)
+        freeinnovations_id(i) = strmatch(freeinnovations{i}, exo_names, 'exact');
+    end
+    calibratedinnovations_id = setdiff(transpose(1:length(exo_names)), freeinnovations_id);
+else
+    freeinnovations_id = transpose(1:length(exo_names));
+    calibratedinnovations_id = [];
+end
+
+nxfree = length(freeinnovations_id);
+nxcalb = length(calibratedinnovations_id);
+
+% Get indices for the the controlled and free endogenous variables.
+controlledendogenousvariables_id = zeros(length(freeinnovations), 1);
+if length(freeinnovations)<DynareModel.endo_nbr
+    for i=1:length(freeinnovations)
+        controlledendogenousvariables_id(i) = strmatch(constraints.name{i}, endo_names, 'exact');
+    end
+    freeendogenousvariables_id = setdiff(transpose(1:length(endo_names)), controlledendogenousvariables_id);
+else
+    controlledendogenousvariables_id = transpose(1:length(endo_names));
+    freeendogenousvariables_id = [];
+end
+
+nyfree = length(freeendogenousvariables_id);
+nyctrl = length(controlledendogenousvariables_id);
+
+% Get indices of variables appearing at time t-1.
+iy1 = find(DynareModel.lead_lag_incidence(1,:)>0);
+
+% Get indices of variables appearing at time t.
+iy0 = find(DynareModel.lead_lag_incidence(2,:)>0);
+
+% Set indices for trust_region algorithm.
+idx = 1:DynareModel.endo_nbr;
+jdx = 1:(nyfree+nxfree);
+
+% Build structure to be passed to the objective function.
+ModelInversion.nyfree = nyfree;
+ModelInversion.nyctrl = nyctrl;
+ModelInversion.nxfree = nxfree;
+ModelInversion.nxcalb = nxcalb;
+ModelInversion.y_constrained_id = vec(DynareModel.lead_lag_incidence(2,controlledendogenousvariables_id));
+ModelInversion.y_free_id = vec(DynareModel.lead_lag_incidence(2,freeendogenousvariables_id));
+ModelInversion.x_free_id = freeinnovations_id;
+ModelInversion.J_id = [ModelInversion.y_free_id ; sum(DynareModel.lead_lag_incidence(:)>0)+ModelInversion.x_free_id];
+
+% Get the name of the dynamic model routines.
+model_dynamic = str2func([DynareModel.fname,'_dynamic']);
+model_dtransf = str2func('dynamic_backward_model_for_inversion');
+
+% Initialization of vector y (free endogenous variables and free innovations).
+y = NaN(nyfree+nxfree);
+
+% Initialization of the returned simulations (endogenous variables).
+Y = NaN(DynareModel.endo_nbr, nobs(constraints)+1);
+initialconditions
+constraints.dates(1)
+Y(:,1) = initialconditions(constraints.dates(1)-1).data(1:DynareModel.endo_nbr);
+for i=1:nyctrl
+    Y(controlledendogenousvariables_id(i),2:end) = transpose(constraints.data(:,i));
+end
+
+% Initialization of the returned simulations (exogenous variables).
+X = exogenousvariables{exo_names{:}}(constraints.dates(1)-max(1,DynareModel.maximum_exo_lag):constraints.dates(end)).data;
+
+% Inversion of the model, solvers for the free endogenous and exogenous variables (call a Newton-like algorithm in each period).
+for it = 2:nobs(constraints)+1
+    % Set the lagged values of the endogenous variables.
+    ylag = Y(iy1,it-1);
+    % Set the current values of the constrained endogenous variables.
+    ycur = Y(controlledendogenousvariables_id,it);
+    % Vector z gather the free endogenous variables (initialized with lagged
+    % values) and the free exogenous variables (initialized with 0).
+    z = [Y(freeendogenousvariables_id,it-1); zeros(nxfree, 1)];
+    % Solves for z.
+    z = dynare_solve(model_dtransf, z, DynareOptions, model_dynamic, ylag, ycur, X, DynareModel.params, DynareOutput.steady_state, it+DynareModel.maximum_exo_lag, ModelInversion);
+    % Update the matrix of exogenous variables.
+    X(it,freeinnovations_id) = z(nyfree+1:end);
+    % Update the matrix of endogenous variables.
+    Y(freeendogenousvariables_id,it) = z(1:nyfree);
+end
+
+endogenousvariables = dseries(Y', constraints.dates(1)-1, endo_names);
+exogenousvariables = dseries(X(max(DynareModel.maximum_exo_lag,1)+1:end,:), constraints.dates(1), exo_names);
\ No newline at end of file
diff --git a/matlab/backward/backward_model_irf.m b/matlab/backward/backward_model_irf.m
new file mode 100644
index 0000000000000000000000000000000000000000..043568351aec00a28c5c7227ba0aa2c57189c037
--- /dev/null
+++ b/matlab/backward/backward_model_irf.m
@@ -0,0 +1,119 @@
+function irfs = backward_model_irf(initialcondition, listofshocks, listofvariables, varargin)
+
+% Returns impulse response functions.
+%
+% INPUTS 
+% - initialcondition    [dseries,dates]       Initial conditions for the endogenous variables, or period 0.
+% - listofshocks        [cell of strings]     The innovations for which the IRFs need to be computed.  
+% - listofvariables     [cell of strings]     The endogenous variables which will be returned.  
+% - periods             [integer]             scalar, the number of periods.
+%
+% OUTPUTS 
+% - irfs                [struct of dseries]   
+%
+% REMARKS 
+% The names of the fields in the returned structure are given by the name
+% of the innovations listed in the second input argument. Each field gather
+% the associated paths for endogenous variables listed in the third input 
+% argument. 
+
+
+% Copyright (C) 2017 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 that the model is actually backward
+if M_.maximum_lead
+    error(['simul_model_irf:: The specified model is not backward looking!'])
+end
+
+% Set default value for the fourth input argument.
+if nargin<4
+    periods = 40;
+    notransform = true;
+else
+    periods = varargin{1};
+end
+
+% Set default value for the last input argument (no transformation).
+if nargin<5
+    notransform = true;
+else
+    notransform = false;
+    transform = varargin{2};
+end
+
+% Get list of all exogenous variables in a cell of strings
+exo_names = cellstr(M_.exo_names);
+
+% Get the list of all exogenous variables in a cell of strings
+endo_names = cellstr(M_.endo_names);
+
+% Set initial condition.
+if isdates(initialcondition)
+    if isempty(M_.endo_histval)
+        error('backward_model_irf: histval block for setting initial condition is missing!')
+    end
+    initialcondition = dseries(transpose(M_.endo_histval), initialcondition, endo_names, cellstr(M_.endo_names_tex));
+end
+
+% Get the covariance matrix of the shocks.
+Sigma = M_.Sigma_e + 1e-14*eye(M_.exo_nbr);
+sigma = transpose(chol(Sigma));
+
+% Put initial conditions in a vector of doubles
+initialconditions = transpose(initialcondition{endo_names{:}}.data);
+
+% Initialization of the returned argument. Each will be a dseries object containing the IRFS for the endogenous variables listed in the third input argument.
+irfs = struct();
+
+% Get the covariance matrix of the shocks.
+Sigma = M_.Sigma_e + 1e-14*eye(M_.exo_nbr);
+sigma = transpose(chol(Sigma));
+
+% Put initial conditions in a vector of doubles
+initialconditions = transpose(initialcondition{endo_names{:}}.data);
+
+% Compute the IRFs (loop over innovations).
+for i=1:length(listofshocks)
+    % Get transition paths induced by the initial condition.
+    innovations = zeros(periods+M_.maximum_exo_lag, M_.exo_nbr);
+    if ~isempty(M_.exo_histval)
+        innovations(1:M_.maximum_exo_lag,:) = M_.exo_histval;
+    end
+    oo__0 = simul_backward_model(initialconditions, periods, options_, M_, oo_, innovations);
+    % Add the shock.
+    j = strmatch(listofshocks{i}, exo_names);
+    if isempty(j)
+        error('backward_model_irf: Exogenous variable %s is unknown!', listofshocks{i})
+    end
+    innovations(1+M_.maximum_exo_lag,:) = transpose(sigma(:,j));
+    oo__1 = simul_backward_model(initialconditions, periods, options_, M_, oo_, innovations);
+    % Transform the endogenous variables
+    if notransform
+        endo_simul__0 = oo__0.endo_simul;
+        endo_simul__1 = oo__1.endo_simul;
+    else
+        endo_simul__0 = feval(transform, oo__0.endo_simul);
+        endo_simul__1 = feval(transform, oo__1.endo_simul);
+    end
+    % Instantiate a dseries object (with all the endogenous variables)
+    allirfs = dseries(transpose(endo_simul__1-endo_simul__0), initialcondition.init, cellstr(M_.endo_names), cellstr(M_.endo_names_tex));
+    % Extract a sub-dseries object
+    irfs.(listofshocks{i}) = allirfs{listofvariables{:}};
+end
\ No newline at end of file
diff --git a/matlab/backward/dynamic_backward_model_for_inversion.m b/matlab/backward/dynamic_backward_model_for_inversion.m
new file mode 100644
index 0000000000000000000000000000000000000000..540e2f732999cd25d4c82882dac2259d619180d4
--- /dev/null
+++ b/matlab/backward/dynamic_backward_model_for_inversion.m
@@ -0,0 +1,39 @@
+function [r, J] = dynamic_backward_model_for_inversion(z, dynamicmodel, ylag, ycur, x, params, steady_state, it_, ModelInversion)
+
+% Copyright (C) 2017 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 up y
+y = zeros(length(ylag)+ModelInversion.nyfree+ModelInversion.nyctrl,1);
+y(1:length(ylag)) = ylag;
+
+y(ModelInversion.y_constrained_id) = ycur;
+if ModelInversion.nyfree
+    y(ModelInversion.y_free_id) = z(1:ModelInversion.nyfree);
+end
+
+% Update x
+x(it_, ModelInversion.x_free_id) = transpose(z(ModelInversion.nyfree+(1:ModelInversion.nxfree)));
+
+if nargout>1
+    [r, Jacobian] = feval(dynamicmodel, y, x, params, steady_state, it_);
+else
+    r = feval(dynamicmodel, y, x, params, steady_state, it_);
+    return
+end
+
+J = Jacobian(:,ModelInversion.J_id);
\ No newline at end of file
diff --git a/matlab/backward/dynamic_backward_model_for_simulation.m b/matlab/backward/dynamic_backward_model_for_simulation.m
new file mode 100644
index 0000000000000000000000000000000000000000..4947aa6695ac6e245bb592c74cf89d4753f5a47f
--- /dev/null
+++ b/matlab/backward/dynamic_backward_model_for_simulation.m
@@ -0,0 +1,40 @@
+function [r, J] = dynamic_backward_model_for_simulation(z, dynamicmodel, ylag, x, params, steady_state, it_)
+
+% Copyright (C) 2017 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/>.
+
+% Get indices of the variables appearing at time t.
+% NOTE: It is assumed that all variables appear at time t in the model.
+idy = length(ylag)+(1:length(z));
+
+% Build y vector to be passed to the dynamic model.
+y = zeros(length(ylag)+length(z), 1);
+y(1:length(ylag)) = ylag;
+y(idy) = z;
+
+if nargout>1
+    % Compute residuals and jacobian of the full dynamic model.
+    [r, Jacobian] = feval(dynamicmodel, y, x, params, steady_state, it_);
+else
+    % Compute residuals and return.
+    r = feval(dynamicmodel, y, x, params, steady_state, it_);
+    return
+end
+
+% If the jacobian is computed, remove the columns related to the innovations
+% and the variables appearing at time t-1.
+J = Jacobian(:,idy);
\ No newline at end of file
diff --git a/matlab/simul_backward_linear_model.m b/matlab/backward/simul_backward_linear_model.m
similarity index 97%
rename from matlab/simul_backward_linear_model.m
rename to matlab/backward/simul_backward_linear_model.m
index c4ed4fe2645c84ffa1615c8a5fbe673c606c74bd..44555449f179251fa11b8d34ced468bd45c10528 100644
--- a/matlab/simul_backward_linear_model.m
+++ b/matlab/backward/simul_backward_linear_model.m
@@ -34,7 +34,7 @@ function DynareOutput = simul_backward_linear_model(initial_conditions, sample_s
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2012-2016 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -84,9 +84,9 @@ A0inv = inv(jacob(:,jdx));
 A1 = jacob(:,nonzeros(DynareModel.lead_lag_incidence(1,:)));
 B = jacob(:,end-number_of_shocks+1:end);
 
-% Simulations 
+% Simulations
 for it = 2:sample_size+1
-    Y(:,it) = -A0inv*(cst + A1*Y(iy1,it-1) + B*DynareOutput.exo_simul(it,:)'); 
+    Y(:,it) = -A0inv*(cst + A1*Y(iy1,it-1) + B*DynareOutput.exo_simul(it,:)');
 end
 
 DynareOutput.endo_simul = Y;
\ No newline at end of file
diff --git a/matlab/simul_backward_model.m b/matlab/backward/simul_backward_model.m
similarity index 82%
rename from matlab/simul_backward_model.m
rename to matlab/backward/simul_backward_model.m
index 90c0f5c746861090ae2b542fd5e7df91f0b4ac6e..32486e651e1c234757acb7f5fbe7a361a158d98d 100644
--- a/matlab/simul_backward_model.m
+++ b/matlab/backward/simul_backward_model.m
@@ -1,4 +1,4 @@
-function DynareOutput = simul_backward_linear_model(initial_conditions, sample_size, DynareOptions, DynareModel, DynareOutput, innovations)
+function DynareOutput = simul_backward_model(initial_conditions, sample_size, DynareOptions, DynareModel, DynareOutput, innovations)
 
 %@info:
 %! @deftypefn {Function File} {@var{DynareOutput} =} simul_backward_nonlinear_model (@var{sample_size},@var{DynareOptions}, @var{DynareModel}, @var{DynareOutput})
@@ -34,7 +34,7 @@ function DynareOutput = simul_backward_linear_model(initial_conditions, sample_s
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2012-2016 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -76,10 +76,14 @@ if nargin<6
       otherwise
         error(['simul_backward_nonlinear_model:: ' DynareOption.bnlms.innovation_distribution ' distribution for the structural innovations is not (yet) implemented!'])
     end
-
     % Put the simulated innovations in DynareOutput.exo_simul.
-    DynareOutput.exo_simul = zeros(sample_size+1,number_of_shocks);
+    DynareOutput.exo_simul = zeros(sample_size, number_of_shocks);
     DynareOutput.exo_simul(2:end,positive_var_indx) = DynareOutput.bnlms.shocks;
+    if isfield(DynareModel,'exo_histval') && ~isempty(DynareModel.exo_histval)
+        DynareOutput.exo_simul = [M_.exo_histval; DynareOutput.exo_simul];
+    else
+        DynareOutput.exo_simul = [zeros(1,number_of_shocks); DynareOutput.exo_simul];
+    end
 else
     number_of_shocks = size(innovations,2);
     DynareOutput.exo_simul = innovations;
@@ -87,9 +91,8 @@ end
 
 if DynareOptions.linear
     DynareOutput = simul_backward_linear_model(initial_conditions, sample_size, DynareOptions, ...
-                                DynareModel, DynareOutput, innovations);
+                                               DynareModel, DynareOutput, innovations);
 else
     DynareOutput = simul_backward_nonlinear_model(initial_conditions, sample_size, DynareOptions, ...
-                                DynareModel, DynareOutput, innovations);
-end    
-    
\ No newline at end of file
+                                                  DynareModel, DynareOutput, innovations);
+end
diff --git a/matlab/simul_backward_nonlinear_model.m b/matlab/backward/simul_backward_nonlinear_model.m
similarity index 60%
rename from matlab/simul_backward_nonlinear_model.m
rename to matlab/backward/simul_backward_nonlinear_model.m
index 99dd3932bea61fc96fdd5b678af9cbc870d6c571..fadf6ee3ffb628d1cd0f637688b131f42cdd6eca 100644
--- a/matlab/simul_backward_nonlinear_model.m
+++ b/matlab/backward/simul_backward_nonlinear_model.m
@@ -1,40 +1,27 @@
 function DynareOutput = simul_backward_nonlinear_model(initial_conditions, sample_size, DynareOptions, DynareModel, DynareOutput, innovations)
 
-%@info:
-%! @deftypefn {Function File} {@var{DynareOutput} =} simul_backward_nonlinear_model (@var{sample_size},@var{DynareOptions}, @var{DynareModel}, @var{DynareOutput})
-%! @anchor{@simul_backward_nonlinear_model}
-%! @sp 1
-%! Simulates a stochastic non linear backward looking model with arbitrary precision (a deterministic solver is used).
-%! @sp 2
-%! @strong{Inputs}
-%! @sp 1
-%! @table @ @var
-%! @item sample_size
-%! Scalar integer, size of the sample to be generated.
-%! @item DynareOptions
-%! Matlab/Octave structure (Options used by Dynare).
-%! @item DynareDynareModel
-%! Matlab/Octave structure (Description of the model).
-%! @item DynareOutput
-%! Matlab/Octave structure (Results reported by Dynare).
-%! @end table
-%! @sp 1
-%! @strong{Outputs}
-%! @sp 1
-%! @table @ @var
-%! @item DynareOutput
-%! Matlab/Octave structure (Results reported by Dynare).
-%! @end table
-%! @sp 2
-%! @strong{This function is called by:}
-%! @sp 2
-%! @strong{This function calls:}
-%! @ref{dynTime}
-%!
-%! @end deftypefn
-%@eod:
+% Simulates a stochastic non linear backward looking model with arbitrary precision (a deterministic solver is used).
+%
+% INPUTS
+% - initial_conditions  [double]      n*1 vector, initial conditions for the endogenous variables.
+% - sample_size         [integer]     scalar, number of periods for the simulation.
+% - DynareOptions       [struct]      Dynare's options_ global structure.
+% - DynareModel         [struct]      Dynare's M_ global structure.
+% - DynareOutput        [struct]      Dynare's oo_ global structure.
+% - innovations         [double]      T*q matrix, innovations to be used for the simulation.
+%
+% OUTPUTS
+% - DynareOutput        [struct]      Dynare's oo_ global structure.
+%
+% REMARKS
+% [1] The innovations used for the simulation are saved in DynareOutput.exo_simul, and the resulting paths for the endogenous
+%     variables are saved in DynareOutput.endo_simul.
+% [2] The last input argument is not mandatory. If absent we use random draws and rescale them with the informations provided
+%     through the shocks block.
+% [3] If the first input argument is empty, the endogenous variables are initialized with 0, or if available with the informations
+%     provided thrtough the histval block.
 
-% Copyright (C) 2012-2016 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -77,13 +64,16 @@ if nargin<6
     % Put the simulated innovations in DynareOutput.exo_simul.
     DynareOutput.exo_simul = zeros(sample_size,number_of_shocks);
     DynareOutput.exo_simul(:,positive_var_indx) = DynareOutput.bnlms.shocks;
-    DynareOutput.exo_simul = [zeros(1,number_of_shocks); DynareOutput.exo_simul];
+    if isfield(DynareModel,'exo_histval') && ~ isempty(DynareModel.exo_histval)
+        DynareOutput.exo_simul = [M_.exo_histval; DynareOutput.exo_simul];
+    else
+        DynareOutput.exo_simul = [zeros(1,number_of_shocks); DynareOutput.exo_simul];
+    end
 else
     DynareOutput.exo_simul = innovations;
 end
 
 % Get usefull vector of indices.
-ny0 = nnz(DynareModel.lead_lag_incidence(2,:));
 ny1 = nnz(DynareModel.lead_lag_incidence(1,:));
 iy1 = find(DynareModel.lead_lag_incidence(1,:)>0);
 idx = 1:DynareModel.endo_nbr;
@@ -92,6 +82,7 @@ hdx = 1:ny1;
 
 % Get the name of the dynamic model routine.
 model_dynamic = str2func([DynareModel.fname,'_dynamic']);
+model_dynamic_s = str2func('dynamic_backward_model_for_simulation');
 
 % initialization of vector y.
 y = NaN(length(idx)+ny1,1);
@@ -99,7 +90,7 @@ y = NaN(length(idx)+ny1,1);
 % initialization of the returned simulations.
 DynareOutput.endo_simul = NaN(DynareModel.endo_nbr,sample_size+1);
 if isempty(initial_conditions)
-    if isfield(DynareModel,'endo_histval')
+    if isfield(DynareModel,'endo_histval') && ~isempty(DynareModel.endo_histval)
         DynareOutput.endo_simul(:,1:DynareModel.maximum_lag) = DynareModel.endo_histval;
     else
         warning('simul_backward_nonlinear_model:: Initial condition is zero for all variables! If the model is nonlinear, the model simulation may fail with the default initialization')
@@ -110,16 +101,12 @@ else
 end
 Y = DynareOutput.endo_simul;
 
+
 % Simulations (call a Newton-like algorithm for each period).
 for it = 2:sample_size+1
-    y(jdx) = Y(:,it-1);                       % A good guess for the initial conditions is the previous values for the endogenous variables.
-    y(hdx) = y(jdx(iy1));                     % Set lagged variables.
-    z = trust_region(model_dynamic, y, idx, jdx, 1, DynareOptions.gstep, ...
-                    DynareOptions.solve_tolf,DynareOptions.solve_tolx, ...
-                    DynareOptions.simul.maxit,DynareOptions.debug, ...
-                    DynareOutput.exo_simul, DynareModel.params, ...
-                    DynareOutput.steady_state, it);
-    Y(:,it) = z(jdx);
+    ylag = Y(iy1,it-1);                   % Set lagged variables.
+    y = Y(:,it-1);                        % A good guess for the initial conditions is the previous values for the endogenous variables.
+    Y(:,it) = dynare_solve(model_dynamic_s, y, DynareOptions, model_dynamic, ylag, DynareOutput.exo_simul, DynareModel.params, DynareOutput.steady_state, it+(DynareModel.maximum_exo_lag-1));
 end
 
 DynareOutput.endo_simul = Y;
\ No newline at end of file
diff --git a/matlab/basic_plan.m b/matlab/basic_plan.m
index c7b4cb360330ab126ae612deb0595570381f26c8..ae7d6bcbf6a5f2dab454d187c825993e83d18ec5 100644
--- a/matlab/basic_plan.m
+++ b/matlab/basic_plan.m
@@ -14,7 +14,7 @@ function plan = basic_plan(plan, exogenous, expectation_type, date, value)
 %  plan                   [structure]        Returns a structure containing the updated forecast scenario.
 %
 %
-% Copyright (C) 2013-2014 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -31,60 +31,60 @@ function plan = basic_plan(plan, exogenous, expectation_type, date, value)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-  if ~ischar(expectation_type) || size(expectation_type,1) ~= 1
-      error(['in basic_plan the third argument should be a string containing the simulation type (''perfect_foresight'' or ''surprise'')']);
-  end
-  exogenous = strtrim(exogenous);
-  ix = find(strcmp(exogenous, plan.exo_names));
-  if  isempty(ix)
-      error(['in basic_plan the second argument ' exogenous ' is not an exogenous variable']);
-  end;
-  sdate = length(date);
-  if sdate > 1
-      if date(1) < plan.date(1) || date(end) > plan.date(end)
-          error(['in basic_plan the fourth argument (date='  date ') must lay inside the plan.date ' plan.date]);
-      end
-  else
-      if date < plan.date(1) || date > plan.date(end)
-          error(['in basic_plan the fourth argument (date='  date ') must lay iside the plan.date ' plan.date]);
-      end
-  end
-  if length(date) ~= length(value)
-      error(['in basic_plan the number of dates (' int2str(length(date)) ') is not equal to the numbers of shock (' int2str(length(value)) ') for exogenous variable ' exogenous]);
-  end
-  if ~isempty(plan.options_cond_fcst_.controlled_varexo)
-      common_var = find(ix == plan.options_cond_fcst_.controlled_varexo);
-      if ~isempty(common_var)
-          common_date = intersect(date, plan.constrained_date_{common_var});
-          if ~isempty(common_date)
-              [date_, i_date] = setdiff(date, common_date);
-              value = value(i_date);
-              if common_date.length > 1
-                  the_dates = [cell2mat(strings(common_date(1))) ':' cell2mat(strings(common_date(end)))];
-              else
-                  the_dates = cell2mat(strings(common_date));
-              end
-              warning(['Impossible case: ' plan.exo_names{plan.options_cond_fcst_.controlled_varexo(common_var)} ' is used both as a shock and as an endogenous variable to control the path of ' plan.endo_names{plan.constrained_vars_(common_var)} ' at the dates ' the_dates]);
-              warning('This shock will not be considered');
-          end
-      end
-  end
-  if isempty(plan.shock_vars_)
-      plan.shock_vars_ = ix;
-      if strcmp(expectation_type, 'perfect_foresight')
-          plan.shock_perfect_foresight_ = 1;
-      else
-          plan.shock_perfect_foresight_ = 0;
-      end
-  else
-      plan.shock_vars_ = [plan.shock_vars_ ; ix];
-      if strcmp(expectation_type, 'perfect_foresight')
-          plan.shock_perfect_foresight_ = [plan.shock_perfect_foresight_ ; 1];
-      else
-          plan.shock_perfect_foresight_ = [plan.shock_perfect_foresight_ ; 0];
-      end
-  end
-  plan.shock_date_{length(plan.shock_date_) + 1} = date;
-  plan.shock_str_date_{length(plan.shock_str_date_) + 1} = strings(date);
-  plan.shock_int_date_{length(plan.shock_int_date_) + 1} = date - plan.date(1) + 1;
-  plan.shock_paths_{length(plan.shock_paths_) + 1} = value;
+if ~ischar(expectation_type) || size(expectation_type,1) ~= 1
+    error(['in basic_plan the third argument should be a string containing the simulation type (''perfect_foresight'' or ''surprise'')']);
+end
+exogenous = strtrim(exogenous);
+ix = find(strcmp(exogenous, plan.exo_names));
+if  isempty(ix)
+    error(['in basic_plan the second argument ' exogenous ' is not an exogenous variable']);
+end
+sdate = length(date);
+if sdate > 1
+    if date(1) < plan.date(1) || date(end) > plan.date(end)
+        error(['in basic_plan the fourth argument (date='  date ') must lay inside the plan.date ' plan.date]);
+    end
+else
+    if date < plan.date(1) || date > plan.date(end)
+        error(['in basic_plan the fourth argument (date='  date ') must lay iside the plan.date ' plan.date]);
+    end
+end
+if length(date) ~= length(value)
+    error(['in basic_plan the number of dates (' int2str(length(date)) ') is not equal to the numbers of shock (' int2str(length(value)) ') for exogenous variable ' exogenous]);
+end
+if ~isempty(plan.options_cond_fcst_.controlled_varexo)
+    common_var = find(ix == plan.options_cond_fcst_.controlled_varexo);
+    if ~isempty(common_var)
+        common_date = intersect(date, plan.constrained_date_{common_var});
+        if ~isempty(common_date)
+            [date_, i_date] = setdiff(date, common_date);
+            value = value(i_date);
+            if common_date.length > 1
+                the_dates = [cell2mat(strings(common_date(1))) ':' cell2mat(strings(common_date(end)))];
+            else
+                the_dates = cell2mat(strings(common_date));
+            end
+            warning(['Impossible case: ' plan.exo_names{plan.options_cond_fcst_.controlled_varexo(common_var)} ' is used both as a shock and as an endogenous variable to control the path of ' plan.endo_names{plan.constrained_vars_(common_var)} ' at the dates ' the_dates]);
+            warning('This shock will not be considered');
+        end
+    end
+end
+if isempty(plan.shock_vars_)
+    plan.shock_vars_ = ix;
+    if strcmp(expectation_type, 'perfect_foresight')
+        plan.shock_perfect_foresight_ = 1;
+    else
+        plan.shock_perfect_foresight_ = 0;
+    end
+else
+    plan.shock_vars_ = [plan.shock_vars_ ; ix];
+    if strcmp(expectation_type, 'perfect_foresight')
+        plan.shock_perfect_foresight_ = [plan.shock_perfect_foresight_ ; 1];
+    else
+        plan.shock_perfect_foresight_ = [plan.shock_perfect_foresight_ ; 0];
+    end
+end
+plan.shock_date_{length(plan.shock_date_) + 1} = date;
+plan.shock_str_date_{length(plan.shock_str_date_) + 1} = strings(date);
+plan.shock_int_date_{length(plan.shock_int_date_) + 1} = date - plan.date(1) + 1;
+plan.shock_paths_{length(plan.shock_paths_) + 1} = value;
diff --git a/matlab/bksup0.m b/matlab/bksup0.m
index c304b42a48b1013b45b5d69a3a51a31bd582aa8b..b801e40e245c1cbd9e99dba40f1dc8b059042443 100644
--- a/matlab/bksup0.m
+++ b/matlab/bksup0.m
@@ -4,14 +4,14 @@ function d = bksup0(c,ny,jcf,iyf,icf,periods)
 % INPUTS
 %    ny:             number of endogenous variables
 %    jcf:            variables index forward
-%    
+%
 % OUTPUTS
 %    d:              vector of backsubstitution results
 %
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2009 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/bksup1.m b/matlab/bksup1.m
index a6bcb3b9f3070afc3ea780925e3611417f75ea66..4e6fb733c70646cfbc352d662b4427fc82f71993 100644
--- a/matlab/bksup1.m
+++ b/matlab/bksup1.m
@@ -5,14 +5,14 @@ function d = bksup1(c,ny,jcf,iyf,periods)
 % INPUTS
 %    ny:             number of endogenous variables
 %    jcf:            variables index forward
-%    
+%
 % OUTPUTS
 %    d:              vector of backsubstitution results
 %
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2010 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -40,4 +40,3 @@ for i = 2:periods
 end
 
 d = c(:,jcf) ;
-
diff --git a/matlab/bksupk.m b/matlab/bksupk.m
index 33f9c18b0008cfc1254f9b8a7847ec61a3807e4c..64de63b8b6e37c5c239dad2d0fcc6b278202b696 100644
--- a/matlab/bksupk.m
+++ b/matlab/bksupk.m
@@ -15,7 +15,7 @@ function d1 = bksupk(ny,fid,jcf,icc1)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2011 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -68,7 +68,7 @@ while i <= options_.periods
     c = fread(fid,[jcf,ny],'float64')' ;
 
     d1(ir) = c(:,jcf)-c(:,icf)*d1(irf) ;
-    ir = ir-ny ;                        
+    ir = ir-ny ;
     irf = irf-ny ;
     i = i+1;
 end
diff --git a/matlab/bseastr.m b/matlab/bseastr.m
index 2ab688e0b81c0560c6659f3ab8e9f5c03cf47008..c8b2de0fc77ef4bda2dfa5904443672630bee09b 100644
--- a/matlab/bseastr.m
+++ b/matlab/bseastr.m
@@ -1,6 +1,6 @@
 function x = bseastr(s1,s2)
 
-% Copyright (C) 2001-2009 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -33,16 +33,15 @@ for im = 1:m
             for i = 1:min(length(key),length(temp))
                 if temp(i) > key(i)
                     h = mid - 1 ;
-                    break 
+                    break
                 else
                     l = mid + 1 ;
-                    break 
+                    break
                 end
             end
         else
             x(im) = mid ;
-            break 
+            break
         end
     end
 end
-
diff --git a/matlab/bvar_density.m b/matlab/bvar_density.m
index b147834ed6b37701508de8d416289ddeb53b1318..5c75f18f81354adefea7ddbf5294f2c56c88f336 100644
--- a/matlab/bvar_density.m
+++ b/matlab/bvar_density.m
@@ -12,7 +12,7 @@ function bvar_density(maxnlags)
 %    none
 
 % Copyright (C) 2003-2007 Christopher Sims
-% Copyright (C) 2007-2016 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -37,16 +37,16 @@ for nlags = 1:maxnlags
     [ny, nx, posterior, prior] = bvar_toolbox(nlags);
     oo_.bvar.posterior{nlags}=posterior;
     oo_.bvar.prior{nlags}=prior;
-    
+
     posterior_int = matrictint(posterior.S, posterior.df, posterior.XXi);
     prior_int = matrictint(prior.S, prior.df, prior.XXi);
-    
+
     lik_nobs = posterior.df - prior.df;
-    
+
     log_dnsty = posterior_int - prior_int - 0.5*ny*lik_nobs*log(2*pi);
-    
+
     oo_.bvar.log_marginal_data_density(nlags)=log_dnsty;
-    
+
     skipline()
     fprintf('The marginal log density of the BVAR(%g) model is equal to %10.4f\n', ...
             nlags, log_dnsty);
@@ -61,7 +61,7 @@ function w = matrictint(S, df, XXi)
 % S:   parameter of inverse-Wishart distribution
 % df:  number of degrees of freedom of inverse-Wishart distribution
 % XXi: first component of VCV matrix of matrix-normal distribution
-% 
+%
 % Computes the integral over (Phi, Sigma) of:
 %
 % det(Sigma)^(-k/2)*exp(-0.5*Tr((Phi-PhiHat)'*(XXi)^(-1)*(Phi-PhiHat)*Sigma^(-1)))*
diff --git a/matlab/bvar_forecast.m b/matlab/bvar_forecast.m
index 9b22ff679ee60333320245cbb4a327ea6cc082ac..55fdf9ce9503b5985ab0438af82d6edebd0882b0 100644
--- a/matlab/bvar_forecast.m
+++ b/matlab/bvar_forecast.m
@@ -11,7 +11,7 @@ function bvar_forecast(nlags)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2007-2013 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -54,7 +54,7 @@ p = 0;
 % Loop counter initialization
 d = 0;
 while d <= options_.bvar_replic
-    
+
     Sigma = rand_inverse_wishart(ny, posterior.df, S_inv_upper_chol);
 
     % Option 'lower' of chol() not available in old versions of
@@ -62,15 +62,15 @@ while d <= options_.bvar_replic
     Sigma_lower_chol = chol(Sigma)';
 
     Phi = rand_matrix_normal(k, ny, posterior.PhiHat, Sigma_lower_chol, XXi_lower_chol);
-    
+
     % All the eigenvalues of the companion matrix have to be on or inside the unit circle
-    Companion_matrix(1:ny,:) = Phi(1:ny*nlags,:)'; 
+    Companion_matrix(1:ny,:) = Phi(1:ny*nlags,:)';
     test = (abs(eig(Companion_matrix)));
     if any(test>1.0000000000001)
         p = p+1;
     end
     d = d+1;
-    
+
     % Without shocks
     lags_data = forecast_data.initval;
     for t = 1:options_.forecast
@@ -80,7 +80,7 @@ while d <= options_.bvar_replic
         lags_data(end,:) = y;
         sims_no_shock(t, :, d) = y;
     end
-    
+
     % With shocks
     lags_data = forecast_data.initval;
     for t = 1:options_.forecast
@@ -120,19 +120,19 @@ dyn_graph=dynare_graph_init(sprintf('BVAR forecasts (nlags = %d)', nlags), ny, {
 
 for i = 1:ny
     dyn_graph=dynare_graph(dyn_graph,[ sims_no_shock_median(:, i) ...
-                   sims_no_shock_up_conf(:, i) sims_no_shock_down_conf(:, i) ...
-                   sims_with_shocks_up_conf(:, i) sims_with_shocks_down_conf(:, i) ], ...
-                 options_.varobs{i});
+                        sims_no_shock_up_conf(:, i) sims_no_shock_down_conf(:, i) ...
+                        sims_with_shocks_up_conf(:, i) sims_with_shocks_down_conf(:, i) ], ...
+                           options_.varobs{i});
 end
 
-dyn_saveas(dyn_graph.fh,[OutputDirectoryName '/' M_.fname '_BVAR_forecast_',num2str(nlags)],options_)
+dyn_saveas(dyn_graph.fh,[OutputDirectoryName '/' M_.fname '_BVAR_forecast_',num2str(nlags)],options_.nodisplay,options_.graph_format)
 
 % Compute RMSE
 
 if ~isempty(forecast_data.realized_val)
-    
+
     sq_err_cumul = zeros(1, ny);
-    
+
     lags_data = forecast_data.initval;
     for t = 1:size(forecast_data.realized_val, 1)
         X = [ reshape(flipdim(lags_data, 1)', 1, ny*nlags) forecast_data.realized_xdata(t, :) ];
@@ -141,14 +141,14 @@ if ~isempty(forecast_data.realized_val)
         lags_data(end,:) = y;
         sq_err_cumul = sq_err_cumul + (y - forecast_data.realized_val(t, :)) .^ 2;
     end
-    
+
     rmse = sqrt(sq_err_cumul / size(forecast_data.realized_val, 1));
-    
+
     fprintf('RMSE of BVAR(%d):\n', nlags);
-    
+
     for i = 1:length(options_.varobs)
         fprintf('%s: %10.4f\n', options_.varobs{i}, rmse(i));
-    end 
+    end
 end
 
 % Store results
diff --git a/matlab/bvar_irf.m b/matlab/bvar_irf.m
index 17228b5c433b3298e4dea1b9b8fdee825bfb86b9..5f017aa7d40be6a4c7d487799d7f6cbd8bb55b3e 100644
--- a/matlab/bvar_irf.m
+++ b/matlab/bvar_irf.m
@@ -11,7 +11,7 @@ function bvar_irf(nlags,identification)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2007-2012 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -54,7 +54,7 @@ p = 0;
 sampled_irfs = NaN(ny, ny, options_.irf, options_.bvar_replic);
 
 for draw=1:options_.bvar_replic
-    
+
     % Get a covariance matrix from an inverted Wishart distribution.
     Sigma = rand_inverse_wishart(ny, posterior.df, S_inv_upper_chol);
     Sigma_upper_chol = chol(Sigma);
@@ -62,10 +62,10 @@ for draw=1:options_.bvar_replic
 
     % Get the Autoregressive matrices from a matrix variate distribution.
     Phi = rand_matrix_normal(k, ny, posterior.PhiHat, Sigma_lower_chol, XXi_lower_chol);
-    
+
     % Form the companion matrix.
-    Companion_matrix(1:ny,:) = transpose(Phi(1:ny*nlags,:)); 
-    
+    Companion_matrix(1:ny,:) = transpose(Phi(1:ny*nlags,:));
+
     % All the eigenvalues of the companion matrix have to be on or
     % inside the unit circle to rule out explosive time series.
     test = (abs(eig(Companion_matrix)));
@@ -78,7 +78,7 @@ for draw=1:options_.bvar_replic
     elseif strcmpi(identification,'SquareRoot')
         StructuralMat = sqrtm(Sigma);
     end
-    
+
     % Build the IRFs...
     lags_data = zeros(ny,ny*nlags) ;
     sampled_irfs(:,:,1,draw) = Sigma_lower_chol ;
@@ -88,7 +88,7 @@ for draw=1:options_.bvar_replic
         lags_data(:,ny+1:end) = lags_data(:,1:end-ny) ;
         lags_data(:,1:ny) = sampled_irfs(:,:,t,draw) ;
     end
-    
+
 end
 
 if p > 0
@@ -106,7 +106,7 @@ sort_idx = round((0.5 + [-options_.bvar.conf_sig, options_.bvar.conf_sig, .0]/2)
 
 posterior_down_conf_irfs = sorted_irfs(:,:,:,sort_idx(1));
 posterior_up_conf_irfs = sorted_irfs(:,:,:,sort_idx(2));
-posterior_median_irfs = sorted_irfs(:,:,:,sort_idx(3));   
+posterior_median_irfs = sorted_irfs(:,:,:,sort_idx(3));
 
 number_of_columns = fix(sqrt(ny));
 number_of_rows = ceil(ny / number_of_columns) ;
diff --git a/matlab/bvar_toolbox.m b/matlab/bvar_toolbox.m
index 76c95ef9de6964105a31c5db690a849022fcac04..4393e21aca7e977a09ffb5bf6537b42d222908cf 100644
--- a/matlab/bvar_toolbox.m
+++ b/matlab/bvar_toolbox.m
@@ -29,7 +29,7 @@ function [ny, nx, posterior, prior, forecast_data] = bvar_toolbox(nlags)
 %                     forecasting, of size options_.forecast*nx (actually only
 %                     contains "1" values for the constant term if nx ~= 0)
 %                   - realized_val: only non-empty if options_.nobs doesn't point
-%                     to the end of sample    
+%                     to the end of sample
 %                     In that case, contains values of endogenous variables after
 %                     options_.nobs and up to the end of the sample
 %                   - realized_xdata: contains values of exogenous variables after
@@ -42,7 +42,7 @@ function [ny, nx, posterior, prior, forecast_data] = bvar_toolbox(nlags)
 %    - bvar_prior_{tau,decay,lambda,mu,omega,flat,train}
 
 % Copyright (C) 2003-2007 Christopher Sims
-% Copyright (C) 2007-2012 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -67,7 +67,7 @@ options_ = set_default_option(options_, 'nobs', size(dataset,1)-options_.first_o
 
 if (options_.first_obs+options_.nobs-1)> size(dataset,1)
     fprintf('Incorrect or missing specification of the number of observations. nobs can be at most %4u\n',size(dataset,1)-options_.first_obs+1);
-    error('Inconsistent number of observations.') 
+    error('Inconsistent number of observations.')
 end
 
 % Parameters for prior
@@ -160,7 +160,7 @@ function [ydum,xdum,breaks]=varprior(nv,nx,lags,mnprior,vprior)
 %function [ydum,xdum,breaks]=varprior(nv,nx,lags,mnprior,vprior)
 % ydum, xdum:   dummy observation data that implement the prior
 % breaks:       vector of points in the dummy data after which new dummy obs's start
-%                   Set breaks=T+[0;breaks], ydata=[ydata;ydum], xdum=[xdata;xdum], where 
+%                   Set breaks=T+[0;breaks], ydata=[ydata;ydum], xdum=[xdata;xdum], where
 %                   actual data matrix has T rows, in preparing input for rfvar3
 % nv,nx,lags: VAR dimensions
 % mnprior.tight:Overall tightness of Minnesota prior
@@ -175,8 +175,8 @@ function [ydum,xdum,breaks]=varprior(nv,nx,lags,mnprior,vprior)
 %                   taken to include the sum-of-coefficients and co-persistence components
 %                   that are implemented directly in rfvar3.m.  The diagonal prior on v, combined
 %                   with sum-of-coefficients and co-persistence components and with the unit own-first-lag
-%                   prior mean generates larger prior variances for own than for cross-effects even in 
-%                   this formulation, but here there is no way to shrink toward a set of unconstrained 
+%                   prior mean generates larger prior variances for own than for cross-effects even in
+%                   this formulation, but here there is no way to shrink toward a set of unconstrained
 %                   univariate AR's.
 
 % Original file downloaded from:
@@ -228,9 +228,9 @@ function var=rfvar3(ydata,lags,xdata,breaks,lambda,mu)
 %          discontinuities in the data (e.g. war years) and for the possibility of
 %          adding dummy observations to implement a prior.  This must be a column vector.
 %          Note that a single dummy observation becomes lags+1 rows of the data matrix,
-%          with a break separating it from the rest of the data.  The function treats the 
+%          with a break separating it from the rest of the data.  The function treats the
 %          first lags observations at the top and after each "break" in ydata and xdata as
-%          initial conditions. 
+%          initial conditions.
 % lambda:  weight on "co-persistence" prior dummy observations.  This expresses
 %          belief that when data on *all* y's are stable at their initial levels, they will
 %          tend to persist at that level.  lambda=5 is a reasonable first try.  With lambda<0,
@@ -243,7 +243,7 @@ function var=rfvar3(ydata,lags,xdata,breaks,lambda,mu)
 %          one of these for each variable.  A reasonable first guess is mu=2.
 %      The program assumes that the first lags rows of ydata and xdata are real data, not dummies.
 %      Dummy observations should go at the end, if any.  If pre-sample x's are not available,
-%      repeating the initial xdata(lags+1,:) row or copying xdata(lags+1:2*lags,:) into 
+%      repeating the initial xdata(lags+1,:) row or copying xdata(lags+1:2*lags,:) into
 %      xdata(1:lags,:) are reasonable subsititutes.  These values are used in forming the
 %      persistence priors.
 
@@ -280,7 +280,7 @@ for is = 1:length(smpl)
 end
 X = [X(:,:) xdata(smpl,:)];
 y = ydata(smpl,:);
-% Everything now set up with input data for y=Xb+e 
+% Everything now set up with input data for y=Xb+e
 
 % Add persistence dummies
 if lambda ~= 0 || mu > 0
diff --git a/matlab/cartesian_product_of_sets.m b/matlab/cartesian_product_of_sets.m
index 8901886ff40a59a2ebde75fd29cabcc10ad0c810..9fbe37c0773fdd1e7ae8d12917354142f94032a1 100644
--- a/matlab/cartesian_product_of_sets.m
+++ b/matlab/cartesian_product_of_sets.m
@@ -5,7 +5,7 @@ function cprod = cartesian_product_of_sets(varargin)
 %! @deftypefn {Function File} {@var{cprod} =} cartesian_product_of_sets (@var{a},@var{b}, ...)
 %! @anchor{cartesian_product_of_sets}
 %! @sp 1
-%! Computes A_1 * A_2 * .... * A_n with a generic set A_i = {e_1,e_2,e_3,...} where e_i is a string 
+%! Computes A_1 * A_2 * .... * A_n with a generic set A_i = {e_1,e_2,e_3,...} where e_i is a string
 %! or a number. It is assumed that each element e_i is unique in set A_i.
 %! @sp 2
 %! @strong{Inputs}
@@ -31,7 +31,7 @@ function cprod = cartesian_product_of_sets(varargin)
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/cellofchar2mfile.m b/matlab/cellofchar2mfile.m
index 6cfce7c5fc563f5e5543a6bcc9c7517526b4f705..6160f5a471c5e76ab9501bf4f52324f12116b750 100644
--- a/matlab/cellofchar2mfile.m
+++ b/matlab/cellofchar2mfile.m
@@ -2,14 +2,14 @@ function cellofchar2mfile(fname, c, cname)
 
 % Write a cell of char in a matlab script.
 %
-% INPUTS 
+% INPUTS
 % - fname [string] name of the file where c is to be saved.
 % - c     [cell]   a two dimensional cell of char.
 %
-% OUTPUTS 
+% OUTPUTS
 % None.
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/check.m b/matlab/check.m
index a0e7aa1bb4d584e86f976d43794155abb79bdfca..f97a758f49ccd8fa355b5e78982faa6171a0148c 100644
--- a/matlab/check.m
+++ b/matlab/check.m
@@ -40,7 +40,7 @@ function [eigenvalues_,result,info] = check(M, options, oo)
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2001-2013 Dynare Team
+% Copyright (C) 2001-2014 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/check_dsge_var_model.m b/matlab/check_dsge_var_model.m
index 8b16ec09dac452bf45e97317d15742224db77e49..fb06d42eeced3663284f34924ba46ec49b5aa6e7 100644
--- a/matlab/check_dsge_var_model.m
+++ b/matlab/check_dsge_var_model.m
@@ -2,7 +2,7 @@ function check_dsge_var_model(Model, EstimatedParameters, BayesInfo)
 
 % Check if the dsge model can be estimated with the DSGE-VAR approach.
 
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2014 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/check_for_calibrated_covariances.m b/matlab/check_for_calibrated_covariances.m
index b6d960c2b6f66532c848de620f35a6fec201f6fc..7bf00e6a4f5df2aa47cc7cc9e1a5dc96aae6cb84 100644
--- a/matlab/check_for_calibrated_covariances.m
+++ b/matlab/check_for_calibrated_covariances.m
@@ -12,7 +12,7 @@ function estim_params=check_for_calibrated_covariances(xparam1,estim_params,M)
 % Notes: M is local to this function and not updated when calling
 % set_all_parameters
 
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -42,7 +42,7 @@ calibrated_covariance_pos=covariance_pos(~ismember(covariance_pos,correlation_po
 if any(calibrated_covariance_pos)
     [rows, columns]=ind2sub(size(M.Sigma_e),calibrated_covariance_pos); %find linear indices of lower triangular covariance entries
     estim_params.calibrated_covariances.position=[calibrated_covariance_pos;sub2ind(size(M.Sigma_e),columns,rows)]; %get linear entries of upper triangular parts
-    estim_params.calibrated_covariances.cov_value=Sigma_e_calibrated(estim_params.calibrated_covariances.position);  
+    estim_params.calibrated_covariances.cov_value=Sigma_e_calibrated(estim_params.calibrated_covariances.position);
 end
 
 correlation_pos_ME=find(tril(M.Correlation_matrix_ME,-1)); %off-diagonal elements set by correlations after accounting for estimation
@@ -50,6 +50,5 @@ calibrated_covariance_pos_ME=covariance_pos_ME(~ismember(covariance_pos_ME,corre
 if any(calibrated_covariance_pos_ME)
     [rows, columns]=ind2sub(size(M.H),calibrated_covariance_pos_ME); %find linear indices of lower triangular covariance entries
     estim_params.calibrated_covariances_ME.position=[calibrated_covariance_pos_ME;sub2ind(size(M.H),columns,rows)]; %get linear entries of upper triangular parts
-    estim_params.calibrated_covariances_ME.cov_value=H_calibrated(estim_params.calibrated_covariances_ME.position);  
+    estim_params.calibrated_covariances_ME.cov_value=H_calibrated(estim_params.calibrated_covariances_ME.position);
 end
-
diff --git a/matlab/check_list_of_variables.m b/matlab/check_list_of_variables.m
index e9fb3be3b03ec3dfb2868dd0efa8e6eb1dc29770..7bf05e4783fdaf6c6f3719bfba4b744fdeb7d1b3 100644
--- a/matlab/check_list_of_variables.m
+++ b/matlab/check_list_of_variables.m
@@ -1,20 +1,20 @@
 function varlist = check_list_of_variables(options_, M_, varlist)
 % This function defines, if necessary, the list of endogenous variables
-% for which the posterior statistics have to be computed. 
-% 
+% for which the posterior statistics have to be computed.
 %
-% INPUTS 
+%
+% INPUTS
 %
 %   options_        [structure]    Dynare structure.
 %   M_              [structure]    Dynare structure (related to model definition).
 %   varlist         [string]       Array of strings with name of the endogenous variables.
-%    
-% OUTPUTS 
-%   varlist         [string] 
-%        
+%
+% OUTPUTS
+%   varlist         [string]
+%
 % SPECIAL REQUIREMENTS
 
-% Copyright (C) 2003-2014 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -33,8 +33,8 @@ function varlist = check_list_of_variables(options_, M_, varlist)
 
 %get uniques
 
-[junk1,junk2,index_uniqes] = varlist_indices(varlist,M_.endo_names);
-varlist=varlist(index_uniqes,:);
+[junk1,junk2,index_uniques] = varlist_indices(varlist,M_.endo_names);
+varlist=varlist(index_uniques,:);
 
 msg = 0;
 if options_.dsge_var && options_.bayesian_irf
@@ -63,7 +63,7 @@ if ~isempty(varlist) && ~isempty(options_.endo_vars_for_moment_computations_in_e
     error('You cannot use the consider_all_endogenous or consider_all_observed options when listing variables after the estimation command')
 elseif isempty(varlist) && ~isempty(options_.endo_vars_for_moment_computations_in_estimation)
     if strcmp(options_.endo_vars_for_moment_computations_in_estimation,'all_endogenous_variables')
-        varlist = M_.endo_names(1:M_.orig_endo_nbr, :);    
+        varlist = M_.endo_names(1:M_.orig_endo_nbr, :);
     elseif strcmp(options_.endo_vars_for_moment_computations_in_estimation,'only_observed_variables')
         varlist = char(options_.varobs');
     else
@@ -106,7 +106,7 @@ elseif isempty(varlist) && isempty(options_.endo_vars_for_moment_computations_in
     end
     if ~isempty(cas)
         string = [ cas , ' will be computed for the ' num2str(M_.endo_nbr)  ' endogenous variables'];
-        string = [ string ' of your model, this can be very long....']; 
+        string = [ string ' of your model, this can be very long....'];
         format_text(string, 10)
         if options_.nointeractive
             % Default behaviour is to consider all the endogenous variables.
diff --git a/matlab/check_matlab_path.m b/matlab/check_matlab_path.m
index 3817def6be90e02781b2a85254c74ca36fcfa03d..8f0d187c35e48d7cd38835a9ebb036ce40d4350b 100644
--- a/matlab/check_matlab_path.m
+++ b/matlab/check_matlab_path.m
@@ -1,6 +1,6 @@
 function check_matlab_path(change_path_flag)
-    
-% Copyright (C) 2015-2016 Dynare Team
+
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -82,7 +82,7 @@ else
                     warning(msg);
                     skipline()
                     rmpath(DYNARE_PATH)
-                    addpath(DYNARE_PATH)    
+                    addpath(DYNARE_PATH)
                 end
                 warning on backtrace
             end
@@ -90,7 +90,7 @@ else
     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 
+        % 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);
@@ -107,40 +107,40 @@ else
 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
-    
+% 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
-    flist={};
-    %get m-files in this directory
-    dd = dir([p,filesep '*.m']);
-    temp=struct2cell(dd);
-    flist=[flist temp(1,:)];
-    %deal with subdirectories
-    dlist=getalldirectories(p,excludedsubfolders); %first call with excluded directories
-    for ii=1:length(dlist)
-        flist=[flist getallroutinenames([ p filesep dlist{ii}])]; %recursive calls without subfolders
-    end
-    
+if nargin<2
+    excludedsubfolders = {};
+end
+flist={};
+%get m-files in this directory
+dd = dir([p,filesep '*.m']);
+temp=struct2cell(dd);
+flist=[flist temp(1,:)];
+%deal with subdirectories
+dlist=getalldirectories(p,excludedsubfolders); %first call with excluded directories
+for ii=1:length(dlist)
+    flist=[flist getallroutinenames([ p filesep dlist{ii}])]; %recursive calls without subfolders
+end
+
 
 function dlist = getalldirectories(p,excluded_directories)
-    if nargin<2
-        excluded_directories = {};
-    end
-    dd = dir(p);
-    dir_result=struct2cell(dd);
-    directory_indicator=cell2mat(dir_result(4,:));
-    dlist = dir_result(1,directory_indicator==1 & ~strcmp('.',dir_result(1,:)) & ~strcmp('..',dir_result(1,:)) & ~ismember(dir_result(1,:),excluded_directories));
+if nargin<2
+    excluded_directories = {};
+end
+dd = dir(p);
+dir_result=struct2cell(dd);
+directory_indicator=cell2mat(dir_result(4,:));
+dlist = dir_result(1,directory_indicator==1 & ~strcmp('.',dir_result(1,:)) & ~strcmp('..',dir_result(1,:)) & ~ismember(dir_result(1,:),excluded_directories));
 
 function n = position(i, currentpath)
-    n = length(strfind(currentpath(1:i), pathsep));
\ No newline at end of file
+n = length(strfind(currentpath(1:i), pathsep));
\ No newline at end of file
diff --git a/matlab/check_model.m b/matlab/check_model.m
index 60cf7cba1e5472ce1a0a40d03665f076ec66c267..1abc89db10fc36ea014159f34df1ae59c00cd02c 100644
--- a/matlab/check_model.m
+++ b/matlab/check_model.m
@@ -1,6 +1,6 @@
 function check_model(DynareModel)
 
-% Copyright (C) 2005-2012 Dynare Team
+% Copyright (C) 2005-2013 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/check_posterior_analysis_data.m b/matlab/check_posterior_analysis_data.m
index b1d25b3d131dd2b35f0665098a2ddacaf4c92218..75aa78a7ffa87a4315d76ecca89b47ea173419c1 100644
--- a/matlab/check_posterior_analysis_data.m
+++ b/matlab/check_posterior_analysis_data.m
@@ -1,13 +1,13 @@
 function [info,description] = check_posterior_analysis_data(type,M_)
 % function [info,description] = check_posterior_analysis_data(type,M_)
-% Checks the status of posterior analysis and in particular if files need to be 
+% Checks the status of posterior analysis and in particular if files need to be
 % created or updated; called by posterior_analysis.m
-% 
+%
 % Inputs:
 %   type        [string]        name of the posterior moment considered
 %   M_          [structure]     Dynare model structure
-% 
-% Outputs: 
+%
+% Outputs:
 %   info        [scalar]        return code
 %                                   info = 1; % select_posterior_draws has to be called first.
 %                                   info = 2; % _posterior_draws files have to be updated.
@@ -17,7 +17,7 @@ function [info,description] = check_posterior_analysis_data(type,M_)
 %                                   info = 6; % Ok (nothing to do ;-)
 %   description [string]        Message corresponding to info
 
-% Copyright (C) 2008-2015 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -99,7 +99,7 @@ else
     number_of_the_last_post_data_file = length(pdfinfo);
     name_of_the_last_post_data_file = ...
         [ pwd filesep MetropolisFolder filesep ...
-          M_.fname '_' ... 
+          M_.fname '_' ...
           generic_post_data_file_name ...
           int2str(number_of_the_last_post_data_file) ...
           '.mat' ];
@@ -108,7 +108,7 @@ else
         info = 5; % posterior data files have to be updated.
         if nargout>1
             description = 'posterior data files have to be updated.';
-        end            
+        end
     else
         info = 6; % Ok (nothing to do ;-)
         if nargout>1
diff --git a/matlab/check_posterior_sampler_options.m b/matlab/check_posterior_sampler_options.m
index 299b4b3f6bab2c99089706e7d0c3847837bf18ce..4683639f3af1418b084e16d42ad58e0f3645093c 100644
--- a/matlab/check_posterior_sampler_options.m
+++ b/matlab/check_posterior_sampler_options.m
@@ -13,7 +13,7 @@ function [posterior_sampler_options, options_] = check_posterior_sampler_options
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -32,347 +32,347 @@ function [posterior_sampler_options, options_] = check_posterior_sampler_options
 
 
 init=0;
-if isempty(posterior_sampler_options),
+if isempty(posterior_sampler_options)
     init=1;
 end
 
-if init,
+if init
     % set default options and user defined options
     posterior_sampler_options.posterior_sampling_method = options_.posterior_sampler_options.posterior_sampling_method;
     posterior_sampler_options.bounds = bounds;
-    
+
     switch posterior_sampler_options.posterior_sampling_method
-        
-        case 'random_walk_metropolis_hastings'
-            posterior_sampler_options.parallel_bar_refresh_rate=50;
-            posterior_sampler_options.serial_bar_refresh_rate=3;
-            posterior_sampler_options.parallel_bar_title='RWMH';
-            posterior_sampler_options.serial_bar_title='RW Metropolis-Hastings';
-            
-            % default options
-            posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.rwmh);
-            
-            % user defined options
-            if ~isempty(options_.posterior_sampler_options.sampling_opt)
-                options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt);
-                for i=1:rows(options_list)
-                    switch options_list{i,1}
-                        
-                        case 'proposal_distribution'
-                            if ~(strcmpi(options_list{i,2}, 'rand_multivariate_student') || ...
-                                    strcmpi(options_list{i,2}, 'rand_multivariate_normal'))
-                                error(['initial_estimation_checks:: the proposal_distribution option to estimation takes either ' ...
-                                    'rand_multivariate_student or rand_multivariate_normal as options']);
-                            else
-                                posterior_sampler_options.proposal_distribution=options_list{i,2};
-                            end
-                            
-                            
-                        case 'student_degrees_of_freedom'
-                            if options_list{i,2} <= 0
-                                error('initial_estimation_checks:: the student_degrees_of_freedom takes a positive integer argument');
-                            else
-                                posterior_sampler_options.student_degrees_of_freedom=options_list{i,2};
-                            end
-                            
-                        case 'use_mh_covariance_matrix'
-                            % indicates to use the covariance matrix from previous iterations to
-                            % define the covariance of the proposal distribution
-                            % default = 0
-                            posterior_sampler_options.use_mh_covariance_matrix = options_list{i,2};
-                            options_.use_mh_covariance_matrix = options_list{i,2};
-                        case 'scale_file'
-                            % load optimal_mh_scale parameter if previous run was with mode_compute=6
-                            % will overwrite jscale from set_prior.m
-                            if exist(options_list{i,2},'file') || exist([options_list{i,2},'.mat'],'file')
-                                tmp = load(options_list{i,2},'Scale');
-                                global bayestopt_
-                                bayestopt_.mh_jscale = tmp.Scale;
-                                options_.mh_jscale = tmp.Scale;
-                                bayestopt_.jscale = ones(size(bounds.lb,1),1)*tmp.Scale;
-%                                 options_.mh_init_scale = 2*options_.mh_jscale;
-                            else
-                                error('initial_estimation_checks:: The specified mh_scale_file does not exist.')
-                            end
-                        case 'save_tmp_file'
-                            posterior_sampler_options.save_tmp_file = options_list{i,2};
-                        otherwise
-                            warning(['rwmh_sampler: Unknown option (' options_list{i,1} ')!'])
+
+      case 'random_walk_metropolis_hastings'
+        posterior_sampler_options.parallel_bar_refresh_rate=50;
+        posterior_sampler_options.serial_bar_refresh_rate=3;
+        posterior_sampler_options.parallel_bar_title='RWMH';
+        posterior_sampler_options.serial_bar_title='RW Metropolis-Hastings';
+
+        % default options
+        posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.rwmh);
+
+        % user defined options
+        if ~isempty(options_.posterior_sampler_options.sampling_opt)
+            options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt);
+            for i=1:rows(options_list)
+                switch options_list{i,1}
+
+                  case 'proposal_distribution'
+                    if ~(strcmpi(options_list{i,2}, 'rand_multivariate_student') || ...
+                         strcmpi(options_list{i,2}, 'rand_multivariate_normal'))
+                        error(['initial_estimation_checks:: the proposal_distribution option to estimation takes either ' ...
+                               'rand_multivariate_student or rand_multivariate_normal as options']);
+                    else
+                        posterior_sampler_options.proposal_distribution=options_list{i,2};
+                    end
+
+
+                  case 'student_degrees_of_freedom'
+                    if options_list{i,2} <= 0
+                        error('initial_estimation_checks:: the student_degrees_of_freedom takes a positive integer argument');
+                    else
+                        posterior_sampler_options.student_degrees_of_freedom=options_list{i,2};
+                    end
+
+                  case 'use_mh_covariance_matrix'
+                    % indicates to use the covariance matrix from previous iterations to
+                    % define the covariance of the proposal distribution
+                    % default = 0
+                    posterior_sampler_options.use_mh_covariance_matrix = options_list{i,2};
+                    options_.use_mh_covariance_matrix = options_list{i,2};
+                  case 'scale_file'
+                    % load optimal_mh_scale parameter if previous run was with mode_compute=6
+                    % will overwrite jscale from set_prior.m
+                    if exist(options_list{i,2},'file') || exist([options_list{i,2},'.mat'],'file')
+                        tmp = load(options_list{i,2},'Scale');
+                        global bayestopt_
+                        bayestopt_.mh_jscale = tmp.Scale;
+                        options_.mh_jscale = tmp.Scale;
+                        bayestopt_.jscale = ones(size(bounds.lb,1),1)*tmp.Scale;
+                        %                                 options_.mh_init_scale = 2*options_.mh_jscale;
+                    else
+                        error('initial_estimation_checks:: The specified mh_scale_file does not exist.')
                     end
+                  case 'save_tmp_file'
+                    posterior_sampler_options.save_tmp_file = options_list{i,2};
+                  otherwise
+                    warning(['rwmh_sampler: Unknown option (' options_list{i,1} ')!'])
                 end
             end
-            
-        case 'tailored_random_block_metropolis_hastings'
-            posterior_sampler_options.parallel_bar_refresh_rate=5;
-            posterior_sampler_options.serial_bar_refresh_rate=1;
-            posterior_sampler_options.parallel_bar_title='TaRB-MH';
-            posterior_sampler_options.serial_bar_title='TaRB Metropolis-Hastings';
-            
-            % default options
-            posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.tarb);
-            
-            % user defined options
-            if ~isempty(options_.posterior_sampler_options.sampling_opt)
-                options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt);
-                for i=1:rows(options_list)
-                    
-                    switch options_list{i,1}
-                        
-                        case 'proposal_distribution'
-                            if ~(strcmpi(options_list{i,2}, 'rand_multivariate_student') || ...
-                                    strcmpi(options_list{i,2}, 'rand_multivariate_normal'))
-                                error(['initial_estimation_checks:: the proposal_distribution option to estimation takes either ' ...
-                                    'rand_multivariate_student or rand_multivariate_normal as options']);
-                            else
-                                posterior_sampler_options.proposal_distribution=options_list{i,2};
-                            end
-                            
-                            
-                        case 'student_degrees_of_freedom'
-                            if options_list{i,2} <= 0
-                                error('initial_estimation_checks:: the student_degrees_of_freedom takes a positive integer argument');
-                            else
-                                posterior_sampler_options.student_degrees_of_freedom=options_list{i,2};
-                            end
-                            
-                        case 'mode_compute'
-                            posterior_sampler_options.mode_compute=options_list{i,2};
-                            
-                        case 'optim'
-                            posterior_sampler_options.optim_opt=options_list{i,2};
-
-                        case 'new_block_probability'
-                            if options_list{i,2}<0 || options_list{i,2}>1
-                                error('check_posterior_sampler_options:: The tarb new_block_probability must be between 0 and 1!')
-                            else
-                                posterior_sampler_options.new_block_probability=options_list{i,2};
-                            end
-                        case 'scale_file'
-                            % load optimal_mh_scale parameter if previous run was with mode_compute=6
-                            % will overwrite jscale from set_prior.m
-                            if exist(options_list{i,2},'file') || exist([options_list{i,2},'.mat'],'file')
-                                tmp = load(options_list{i,2},'Scale');
-                                global bayestopt_
-                                bayestopt_.mh_jscale = tmp.Scale;
-                                options_.mh_jscale = tmp.Scale;
-                                bayestopt_.jscale = ones(size(bounds.lb,1),1)*tmp.Scale;
-%                                 options_.mh_init_scale = 2*options_.mh_jscale;
-                            else
-                                error('initial_estimation_checks:: The specified scale_file does not exist.')
-                            end
-                        case 'save_tmp_file'
-                            posterior_sampler_options.save_tmp_file = options_list{i,2};
-    
-                        otherwise
-                            warning(['tarb_sampler: Unknown option (' options_list{i,1} ')!'])
-                            
+        end
+
+      case 'tailored_random_block_metropolis_hastings'
+        posterior_sampler_options.parallel_bar_refresh_rate=5;
+        posterior_sampler_options.serial_bar_refresh_rate=1;
+        posterior_sampler_options.parallel_bar_title='TaRB-MH';
+        posterior_sampler_options.serial_bar_title='TaRB Metropolis-Hastings';
+
+        % default options
+        posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.tarb);
+
+        % user defined options
+        if ~isempty(options_.posterior_sampler_options.sampling_opt)
+            options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt);
+            for i=1:rows(options_list)
+
+                switch options_list{i,1}
+
+                  case 'proposal_distribution'
+                    if ~(strcmpi(options_list{i,2}, 'rand_multivariate_student') || ...
+                         strcmpi(options_list{i,2}, 'rand_multivariate_normal'))
+                        error(['initial_estimation_checks:: the proposal_distribution option to estimation takes either ' ...
+                               'rand_multivariate_student or rand_multivariate_normal as options']);
+                    else
+                        posterior_sampler_options.proposal_distribution=options_list{i,2};
+                    end
+
+
+                  case 'student_degrees_of_freedom'
+                    if options_list{i,2} <= 0
+                        error('initial_estimation_checks:: the student_degrees_of_freedom takes a positive integer argument');
+                    else
+                        posterior_sampler_options.student_degrees_of_freedom=options_list{i,2};
+                    end
+
+                  case 'mode_compute'
+                    posterior_sampler_options.mode_compute=options_list{i,2};
+
+                  case 'optim'
+                    posterior_sampler_options.optim_opt=options_list{i,2};
+
+                  case 'new_block_probability'
+                    if options_list{i,2}<0 || options_list{i,2}>1
+                        error('check_posterior_sampler_options:: The tarb new_block_probability must be between 0 and 1!')
+                    else
+                        posterior_sampler_options.new_block_probability=options_list{i,2};
                     end
-                    
+                  case 'scale_file'
+                    % load optimal_mh_scale parameter if previous run was with mode_compute=6
+                    % will overwrite jscale from set_prior.m
+                    if exist(options_list{i,2},'file') || exist([options_list{i,2},'.mat'],'file')
+                        tmp = load(options_list{i,2},'Scale');
+                        global bayestopt_
+                        bayestopt_.mh_jscale = tmp.Scale;
+                        options_.mh_jscale = tmp.Scale;
+                        bayestopt_.jscale = ones(size(bounds.lb,1),1)*tmp.Scale;
+                        %                                 options_.mh_init_scale = 2*options_.mh_jscale;
+                    else
+                        error('initial_estimation_checks:: The specified scale_file does not exist.')
+                    end
+                  case 'save_tmp_file'
+                    posterior_sampler_options.save_tmp_file = options_list{i,2};
+
+                  otherwise
+                    warning(['tarb_sampler: Unknown option (' options_list{i,1} ')!'])
+
                 end
-                
+
             end
-            
-        case 'independent_metropolis_hastings'
-            posterior_sampler_options.parallel_bar_refresh_rate=50;
-            posterior_sampler_options.serial_bar_refresh_rate=3;
-            posterior_sampler_options.parallel_bar_title='IMH';
-            posterior_sampler_options.serial_bar_title='Ind. Metropolis-Hastings';
-            
-            % default options
-            posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.imh);
-            
-            % user defined options
-            if ~isempty(options_.posterior_sampler_options.sampling_opt)
-                options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt);
-                for i=1:rows(options_list)
-                    switch options_list{i,1}
-                        
-                        case 'proposal_distribution'
-                            if ~(strcmpi(options_list{i,2}, 'rand_multivariate_student') || ...
-                                    strcmpi(options_list{i,2}, 'rand_multivariate_normal'))
-                                error(['initial_estimation_checks:: the proposal_distribution option to estimation takes either ' ...
-                                    'rand_multivariate_student or rand_multivariate_normal as options']);
-                            else
-                                posterior_sampler_options.proposal_distribution=options_list{i,2};
-                            end
-                            
-                            
-                        case 'student_degrees_of_freedom'
-                            if options_list{i,2} <= 0
-                                error('initial_estimation_checks:: the student_degrees_of_freedom takes a positive integer argument');
-                            else
-                                posterior_sampler_options.student_degrees_of_freedom=options_list{i,2};
-                            end
-                            
-                        case 'use_mh_covariance_matrix'
-                            % indicates to use the covariance matrix from previous iterations to
-                            % define the covariance of the proposal distribution
-                            % default = 0
-                            posterior_sampler_options.use_mh_covariance_matrix = options_list{i,2};
-                            options_.use_mh_covariance_matrix = options_list{i,2};
-                            
-                        case 'save_tmp_file'
-                            posterior_sampler_options.save_tmp_file = options_list{i,2};
-
-                        otherwise
-                            warning(['imh_sampler: Unknown option (' options_list{i,1} ')!'])
+
+        end
+
+      case 'independent_metropolis_hastings'
+        posterior_sampler_options.parallel_bar_refresh_rate=50;
+        posterior_sampler_options.serial_bar_refresh_rate=3;
+        posterior_sampler_options.parallel_bar_title='IMH';
+        posterior_sampler_options.serial_bar_title='Ind. Metropolis-Hastings';
+
+        % default options
+        posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.imh);
+
+        % user defined options
+        if ~isempty(options_.posterior_sampler_options.sampling_opt)
+            options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt);
+            for i=1:rows(options_list)
+                switch options_list{i,1}
+
+                  case 'proposal_distribution'
+                    if ~(strcmpi(options_list{i,2}, 'rand_multivariate_student') || ...
+                         strcmpi(options_list{i,2}, 'rand_multivariate_normal'))
+                        error(['initial_estimation_checks:: the proposal_distribution option to estimation takes either ' ...
+                               'rand_multivariate_student or rand_multivariate_normal as options']);
+                    else
+                        posterior_sampler_options.proposal_distribution=options_list{i,2};
+                    end
+
+
+                  case 'student_degrees_of_freedom'
+                    if options_list{i,2} <= 0
+                        error('initial_estimation_checks:: the student_degrees_of_freedom takes a positive integer argument');
+                    else
+                        posterior_sampler_options.student_degrees_of_freedom=options_list{i,2};
                     end
+
+                  case 'use_mh_covariance_matrix'
+                    % indicates to use the covariance matrix from previous iterations to
+                    % define the covariance of the proposal distribution
+                    % default = 0
+                    posterior_sampler_options.use_mh_covariance_matrix = options_list{i,2};
+                    options_.use_mh_covariance_matrix = options_list{i,2};
+
+                  case 'save_tmp_file'
+                    posterior_sampler_options.save_tmp_file = options_list{i,2};
+
+                  otherwise
+                    warning(['imh_sampler: Unknown option (' options_list{i,1} ')!'])
                 end
             end
-            
-            
-        case 'slice'
-            posterior_sampler_options.parallel_bar_refresh_rate=1;
-            posterior_sampler_options.serial_bar_refresh_rate=1;
-            posterior_sampler_options.parallel_bar_title='SLICE';
-            posterior_sampler_options.serial_bar_title='SLICE';
-            
-            % default options
-            posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.slice);
-            
-            % user defined options
-            if ~isempty(options_.posterior_sampler_options.sampling_opt)
-                options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt);
-                for i=1:rows(options_list)
-                    switch options_list{i,1}
-                        case 'rotated'
-                            % triggers rotated slice iterations using a covariance
-                            % matrix from initial burn-in iterations
-                            % must be associated with:
-                            % <use_mh_covariance_matrix> or <slice_initialize_with_mode>
-                            % default  = 0
-                            posterior_sampler_options.rotated = options_list{i,2};
-                            
-                        case 'mode'
-                            % for multimodal posteriors, provide the list of modes as a
-                            % matrix, ordered by column, i.e. [x1 x2 x3] for three
-                            % modes x1 x2 x3
-                            % MR note: not sure this is possible with the
-                            % read_key_value_string ???
-                            % if this is not possible <mode_files> does to job in any case
-                            % This will automatically trigger <rotated>
-                            % default = []
-                            tmp_mode = options_list{i,2};
-                            for j=1:size(tmp_mode,2),
-                                posterior_sampler_options.mode(j).m = tmp_mode(:,j);
-                            end
-                            
-                        case 'mode_files'
-                            % for multimodal posteriors provide the name of
-                            % a file containing a variable array xparams = [nparam * nmodes]
-                            % one column per mode. With this info, the code will automatically
-                            % set the <mode> option. 
-                            % This will automatically trigger <rotated>
-                            % default = []
-                            posterior_sampler_options.mode_files = options_list{i,2};
-                            
-                        case 'slice_initialize_with_mode'
-                            % the default for slice is to set mode_compute = 0 in the
-                            % preprocessor and start the chain(s) from a random location in the prior.
-                            % This option first runs the optimizer and then starts the
-                            % chain from the mode. Associated with optios <rotated>, it will
-                            % use invhess from the mode to perform rotated slice
-                            % iterations.
-                            % default = 0
-                            posterior_sampler_options.slice_initialize_with_mode = options_list{i,2};
-                            
-                        case 'initial_step_size'
-                            % sets the initial size of the interval in the STEPPING-OUT PROCEDURE
-                            % the initial_step_size must be a real number in [0, 1],
-                            % and it sets the size as a proportion of the prior bounds,
-                            % i.e. the size will be initial_step_size*(UB-LB)
-                            % slice sampler requires prior_truncation > 0!
-                            % default = 0.8
-                            if options_list{i,2}<=0 || options_list{i,2}>=1
-                                error('check_posterior_sampler_options:: slice initial_step_size must be between 0 and 1')
-                            else
-                                posterior_sampler_options.initial_step_size=options_list{i,2};
-                            end
-                        case 'use_mh_covariance_matrix'
-                            % in association with <rotated> indicates to use the
-                            % covariance matrix from previous iterations to define the
-                            % rotated slice
-                            % default = 0
-                            posterior_sampler_options.use_mh_covariance_matrix = options_list{i,2};
-                            options_.use_mh_covariance_matrix = options_list{i,2};
-
-                        case 'save_tmp_file'
-                            posterior_sampler_options.save_tmp_file = options_list{i,2};
-                            
-                        otherwise
-                            warning(['slice_sampler: Unknown option (' options_list{i,1} ')!'])
+        end
+
+
+      case 'slice'
+        posterior_sampler_options.parallel_bar_refresh_rate=1;
+        posterior_sampler_options.serial_bar_refresh_rate=1;
+        posterior_sampler_options.parallel_bar_title='SLICE';
+        posterior_sampler_options.serial_bar_title='SLICE';
+
+        % default options
+        posterior_sampler_options = add_fields_(posterior_sampler_options,options_.posterior_sampler_options.slice);
+
+        % user defined options
+        if ~isempty(options_.posterior_sampler_options.sampling_opt)
+            options_list = read_key_value_string(options_.posterior_sampler_options.sampling_opt);
+            for i=1:rows(options_list)
+                switch options_list{i,1}
+                  case 'rotated'
+                    % triggers rotated slice iterations using a covariance
+                    % matrix from initial burn-in iterations
+                    % must be associated with:
+                    % <use_mh_covariance_matrix> or <slice_initialize_with_mode>
+                    % default  = 0
+                    posterior_sampler_options.rotated = options_list{i,2};
+
+                  case 'mode'
+                    % for multimodal posteriors, provide the list of modes as a
+                    % matrix, ordered by column, i.e. [x1 x2 x3] for three
+                    % modes x1 x2 x3
+                    % MR note: not sure this is possible with the
+                    % read_key_value_string ???
+                    % if this is not possible <mode_files> does to job in any case
+                    % This will automatically trigger <rotated>
+                    % default = []
+                    tmp_mode = options_list{i,2};
+                    for j=1:size(tmp_mode,2)
+                        posterior_sampler_options.mode(j).m = tmp_mode(:,j);
                     end
+
+                  case 'mode_files'
+                    % for multimodal posteriors provide the name of
+                    % a file containing a variable array xparams = [nparam * nmodes]
+                    % one column per mode. With this info, the code will automatically
+                    % set the <mode> option.
+                    % This will automatically trigger <rotated>
+                    % default = []
+                    posterior_sampler_options.mode_files = options_list{i,2};
+
+                  case 'slice_initialize_with_mode'
+                    % the default for slice is to set mode_compute = 0 in the
+                    % preprocessor and start the chain(s) from a random location in the prior.
+                    % This option first runs the optimizer and then starts the
+                    % chain from the mode. Associated with optios <rotated>, it will
+                    % use invhess from the mode to perform rotated slice
+                    % iterations.
+                    % default = 0
+                    posterior_sampler_options.slice_initialize_with_mode = options_list{i,2};
+
+                  case 'initial_step_size'
+                    % sets the initial size of the interval in the STEPPING-OUT PROCEDURE
+                    % the initial_step_size must be a real number in [0, 1],
+                    % and it sets the size as a proportion of the prior bounds,
+                    % i.e. the size will be initial_step_size*(UB-LB)
+                    % slice sampler requires prior_truncation > 0!
+                    % default = 0.8
+                    if options_list{i,2}<=0 || options_list{i,2}>=1
+                        error('check_posterior_sampler_options:: slice initial_step_size must be between 0 and 1')
+                    else
+                        posterior_sampler_options.initial_step_size=options_list{i,2};
+                    end
+                  case 'use_mh_covariance_matrix'
+                    % in association with <rotated> indicates to use the
+                    % covariance matrix from previous iterations to define the
+                    % rotated slice
+                    % default = 0
+                    posterior_sampler_options.use_mh_covariance_matrix = options_list{i,2};
+                    options_.use_mh_covariance_matrix = options_list{i,2};
+
+                  case 'save_tmp_file'
+                    posterior_sampler_options.save_tmp_file = options_list{i,2};
+
+                  otherwise
+                    warning(['slice_sampler: Unknown option (' options_list{i,1} ')!'])
                 end
             end
-            
-            % slice posterior sampler does not require mode or hessian to run
-            % needs to be set to 1 to skip parts in dynare_estimation_1.m
-            % requiring posterior maximization/calibrated smoother before MCMC
-            options_.mh_posterior_mode_estimation=1;
-            
-            if ~ posterior_sampler_options.slice_initialize_with_mode
+        end
+
+        % slice posterior sampler does not require mode or hessian to run
+        % needs to be set to 1 to skip parts in dynare_estimation_1.m
+        % requiring posterior maximization/calibrated smoother before MCMC
+        options_.mh_posterior_mode_estimation=1;
+
+        if ~ posterior_sampler_options.slice_initialize_with_mode
             % by default, slice sampler should trigger
             % mode_compute=0 and
             % mh_replic=100 (much smaller than the default mh_replic=20000 of RWMH)
-                options_.mode_compute = 0;
-                options_.cova_compute = 0;
-            else
-                if (isequal(options_.mode_compute,0) && isempty(options_.mode_file) )
-                    skipline()
-                    disp('check_posterior_sampler_options:: You have specified the option "slice_initialize_with_mode"')
-                    disp('check_posterior_sampler_options:: to initialize the slice sampler using mode information')
-                    disp('check_posterior_sampler_options:: but no mode file nor posterior maximization is selected,')
-                    error('check_posterior_sampler_options:: The option "slice_initialize_with_mode" is inconsistent with mode_compute=0 or empty mode_file.')
-                else
-                    options_.mh_posterior_mode_estimation=0;
-                end
-            end
-            
-            if any(isinf(bounds.lb)) || any(isinf(bounds.ub)),
+            options_.mode_compute = 0;
+            options_.cova_compute = 0;
+        else
+            if (isequal(options_.mode_compute,0) && isempty(options_.mode_file) )
                 skipline()
-                disp('some priors are unbounded and prior_trunc is set to zero')
-                error('The option "slice" is inconsistent with prior_trunc=0.')
+                disp('check_posterior_sampler_options:: You have specified the option "slice_initialize_with_mode"')
+                disp('check_posterior_sampler_options:: to initialize the slice sampler using mode information')
+                disp('check_posterior_sampler_options:: but no mode file nor posterior maximization is selected,')
+                error('check_posterior_sampler_options:: The option "slice_initialize_with_mode" is inconsistent with mode_compute=0 or empty mode_file.')
+            else
+                options_.mh_posterior_mode_estimation=0;
             end
-            
-            % moreover slice must be associated to:
-            %     options_.mh_posterior_mode_estimation = 0;
-            % this is done below, but perhaps preprocessing should do this?
-            
-            if ~isempty(posterior_sampler_options.mode)
-                % multimodal case
-                posterior_sampler_options.rotated = 1;
-                posterior_sampler_options.WR=[];
+        end
+
+        if any(isinf(bounds.lb)) || any(isinf(bounds.ub))
+            skipline()
+            disp('some priors are unbounded and prior_trunc is set to zero')
+            error('The option "slice" is inconsistent with prior_trunc=0.')
+        end
+
+        % moreover slice must be associated to:
+        %     options_.mh_posterior_mode_estimation = 0;
+        % this is done below, but perhaps preprocessing should do this?
+
+        if ~isempty(posterior_sampler_options.mode)
+            % multimodal case
+            posterior_sampler_options.rotated = 1;
+            posterior_sampler_options.WR=[];
+        end
+        %     posterior_sampler_options = set_default_option(posterior_sampler_options,'mode_files',[]);
+
+
+        posterior_sampler_options.W1=posterior_sampler_options.initial_step_size*(bounds.ub-bounds.lb);
+        if options_.load_mh_file
+            posterior_sampler_options.slice_initialize_with_mode = 0;
+        else
+            if ~posterior_sampler_options.slice_initialize_with_mode
+                posterior_sampler_options.invhess=[];
             end
-            %     posterior_sampler_options = set_default_option(posterior_sampler_options,'mode_files',[]);
-            
-            
-            posterior_sampler_options.W1=posterior_sampler_options.initial_step_size*(bounds.ub-bounds.lb);
-            if options_.load_mh_file,
-                posterior_sampler_options.slice_initialize_with_mode = 0;
-            else
-                if ~posterior_sampler_options.slice_initialize_with_mode,
-                    posterior_sampler_options.invhess=[];
-                end
+        end
+
+        if ~isempty(posterior_sampler_options.mode_files) % multimodal case
+            modes = posterior_sampler_options.mode_files; % these can be also mean files from previous parallel slice chains
+            load(modes, 'xparams')
+            if size(xparams,2)<2
+                error(['check_posterior_sampler_options:: Variable xparams loaded in file <' modes '> has size [' int2str(size(xparams,1)) 'x' int2str(size(xparams,2)) ']: it must contain at least two columns, to allow multi-modal sampling.'])
             end
-            
-            if ~isempty(posterior_sampler_options.mode_files), % multimodal case
-                modes = posterior_sampler_options.mode_files; % these can be also mean files from previous parallel slice chains
-                load(modes, 'xparams')
-                if size(xparams,2)<2,
-                    error(['check_posterior_sampler_options:: Variable xparams loaded in file <' modes '> has size [' int2str(size(xparams,1)) 'x' int2str(size(xparams,2)) ']: it must contain at least two columns, to allow multi-modal sampling.'])
-                end
-                for j=1:size(xparams,2),
-                    mode(j).m=xparams(:,j);
-                end
-                posterior_sampler_options.mode = mode;
-                posterior_sampler_options.rotated = 1;
-                posterior_sampler_options.WR=[];
+            for j=1:size(xparams,2)
+                mode(j).m=xparams(:,j);
             end
-            
-        otherwise
-            error('check_posterior_sampler_options:: Unknown posterior_sampling_method option %s ',posterior_sampler_options.posterior_sampling_method);
+            posterior_sampler_options.mode = mode;
+            posterior_sampler_options.rotated = 1;
+            posterior_sampler_options.WR=[];
+        end
+
+      otherwise
+        error('check_posterior_sampler_options:: Unknown posterior_sampling_method option %s ',posterior_sampler_options.posterior_sampling_method);
     end
-    
+
     return
 end
 
@@ -386,7 +386,7 @@ if ~strcmp(posterior_sampler_options.posterior_sampling_method,'slice')
     end
 end
 
-if options_.load_mh_file && posterior_sampler_options.use_mh_covariance_matrix,
+if options_.load_mh_file && posterior_sampler_options.use_mh_covariance_matrix
     [junk, invhess] = compute_mh_covariance_matrix;
     posterior_sampler_options.invhess = invhess;
 end
@@ -396,10 +396,8 @@ end
 % check specific options for slice sampler
 if strcmp(posterior_sampler_options.posterior_sampling_method,'slice')
     invhess = posterior_sampler_options.invhess;
-    
-    if posterior_sampler_options.rotated,
-        if isempty(posterior_sampler_options.mode_files) && isempty(posterior_sampler_options.mode), % rotated unimodal
-            
+    if posterior_sampler_options.rotated
+        if isempty(posterior_sampler_options.mode_files) && isempty(posterior_sampler_options.mode) % rotated unimodal
             if ~options_.cova_compute && ~(options_.load_mh_file && posterior_sampler_options.use_mh_covariance_matrix)
                 skipline()
                 disp('check_posterior_sampler_options:: I cannot start rotated slice sampler because')
@@ -418,16 +416,14 @@ if strcmp(posterior_sampler_options.posterior_sampling_method,'slice')
             posterior_sampler_options.V1=V1;
             posterior_sampler_options.WR=sqrt(diag(D))*3;
         end
+    else
+        if ~options_.load_mh_file && ~posterior_sampler_options.slice_initialize_with_mode
+            posterior_sampler_options.invhess=[];
+        end
     end
-    
     % needs to be re-set to zero otherwise posterior analysis is filtered
     % out in dynare_estimation_1.m
     options_.mh_posterior_mode_estimation = 0;
-    
-    
-else
-    
-    
 end
 
 return
@@ -438,6 +434,3 @@ fnam = fieldnames(sampler_options);
 for j=1:length(fnam)
     posterior_sampler_options.(fnam{j}) = sampler_options.(fnam{j});
 end
-
-
-
diff --git a/matlab/check_prior_analysis_data.m b/matlab/check_prior_analysis_data.m
index 8d74ba943c655625901c879d3e3d0d3c3472993e..e0570cc682b7624f471f7ca0ea3a4f4440a38039 100644
--- a/matlab/check_prior_analysis_data.m
+++ b/matlab/check_prior_analysis_data.m
@@ -1,13 +1,13 @@
 function [info,description] = check_prior_analysis_data(type,M_)
 % function [info,description] = check_prior_analysis_data(type,M_)
-% Checks the status of prior analysis and in particular if files need to be 
+% Checks the status of prior analysis and in particular if files need to be
 % created or updated; called by prior_analysis.m
-% 
+%
 % Inputs:
 %   type        [string]        name of the posterior moment considered
 %   M_          [structure]     Dynare model structure
-% 
-% Outputs: 
+%
+% Outputs:
 %   info        [scalar]        return code
 %                                   info = 1; % prior_sampler has to be called first.
 %                                   info = 2; % _prior_draws files have to be updated.
@@ -18,7 +18,7 @@ function [info,description] = check_prior_analysis_data(type,M_)
 %   description [string]        Message corresponding to info
 
 
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -40,7 +40,7 @@ if nargout>1
     description = '';
 end
 
-%% Get informations about prior draws files. 
+%% Get informations about prior draws files.
 if ~exist([ M_.dname '/prior/draws'],'dir')
     disp('check_prior_analysis_data:: Can''t find any prior draws file!')
     return
@@ -65,7 +65,7 @@ else
         end
         return
     else
-        info = 3; % Nothing to do!  
+        info = 3; % Nothing to do!
         if nargout>1
             description = 'prior draws files are up to date.';
         end
@@ -98,9 +98,9 @@ else
     name_of_the_last_prior_data_file = pdinfo(end).name;
     pdfdate = pdinfo(end).datenum;
     % /!\ REMARK /!\
-    % The user can change the model or the value of a calibrated 
-    % parameter without changing the prior. In this case the (prior) 
-    % moments should be computed. But this case cannot be detected!!! 
+    % The user can change the model or the value of a calibrated
+    % parameter without changing the prior. In this case the (prior)
+    % moments should be computed. But this case cannot be detected!!!
     if pdfdate<date_of_the_last_prior_draw_file
         info = 5; % prior data files have to be updated.
         if nargout>1
diff --git a/matlab/check_prior_bounds.m b/matlab/check_prior_bounds.m
index 5214ce010c0a02f2891eec0763ef3ca284bc736c..9c982ff4d2322faed5bcaeff806c26b257a6271e 100644
--- a/matlab/check_prior_bounds.m
+++ b/matlab/check_prior_bounds.m
@@ -5,12 +5,12 @@ function check_prior_bounds(xparam1,bounds,M_,estim_params_,options_,bayestopt_)
 %   -xparam1        [double]    vector of parameters to be estimated (initial values)
 %   -bounds         [vector]    vector containing the lower and upper
 %   bounds
-%   -M_             [structure] characterizing the model. 
+%   -M_             [structure] characterizing the model.
 %   -estim_params_  [structure] characterizing parameters to be estimated
 %   -options_       [structure] characterizing the options
 %   -bayestopt_     [structure] characterizing priors
 
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/chol_SE.m b/matlab/chol_SE.m
index 0ec5a900bf4a23fb44f5f20a852b1d8220f8ede2..48b70edf4ff7ddad0f9a9d2807d48cb5211e12aa 100644
--- a/matlab/chol_SE.m
+++ b/matlab/chol_SE.m
@@ -1,17 +1,17 @@
 function [R,indef, E, P]=chol_SE(A,pivoting)
 % [R,indef, E, P]=chol_SE(A,pivoting)
-% Performs a (modified) Cholesky factorization of the form 
-% 
+% Performs a (modified) Cholesky factorization of the form
+%
 %     P'*A*P  + E = R'*R
-% 
+%
 % As detailed in Schnabel/Eskow (1990), the factorization has 2 phases:
 %   Phase 1: While A can still be positive definite, pivot on the maximum diagonal element.
 %            Check that the standard Cholesky update would result in a positive diagonal
-%            at the current iteration. If so, continue with the normal Cholesky update. 
-%            Otherwise switch to phase 2. 
-%            If A is safely positive definite, stage 1 is never left, resulting in 
-%            the standard Cholesky decomposition. 
-%            
+%            at the current iteration. If so, continue with the normal Cholesky update.
+%            Otherwise switch to phase 2.
+%            If A is safely positive definite, stage 1 is never left, resulting in
+%            the standard Cholesky decomposition.
+%
 %    Phase 2: Pivot on the minimum of the negatives of the lower Gershgorin bound
 %            estimates. To prevent negative diagonals, compute the amount to add to the
 %            pivot element and add this. Then, do the Cholesky update and update the estimates of the
@@ -21,39 +21,40 @@ function [R,indef, E, P]=chol_SE(A,pivoting)
 %   -   During factorization, L=R' is stored in the lower triangle of the original matrix A,
 %       miminizing the memory requirements
 %   -   Conforming with the original Schnabel/Eskow (1990) algorithm:
-%            - at each iteration the updated Gershgorin bounds are estimated instead of recomputed, 
+%            - at each iteration the updated Gershgorin bounds are estimated instead of recomputed,
 %              reducing the computational requirements from o(n^3) to o (n^2)
 %           -  For the last 2 by 2 submatrix, an eigenvalue-based decomposition is used
-%   -   While pivoting is not necessary, it improves the size of E, the add-on on to the diagonal. But this comes at 
+%   -   While pivoting is not necessary, it improves the size of E, the add-on on to the diagonal. But this comes at
 %       the cost of introduding a permutation.
-% 
 %
-% Inputs  
-%   A           [n*n]     Matrix to be factorized
-%   pivoting    [scalar]  dummy whether pivoting is used
-% 
-% Outputs  
-%   R           [n*n]     originally stored in lower triangular portion of A, including the main diagonal
 %
-%   E           [n*1]     Elements added to the diagonal of A
-%   P           [n*1]     record of how the rows and columns of the matrix were permuted while
-%                         performing the decomposition
+% INPUTS
+%  - A           [n*n]     Matrix to be factorized
+%  - pivoting    [scalar]  dummy whether pivoting is used
+%
+% OUTPUTS
+%  - R           [n*n]     originally stored in lower triangular portion of A, including the main diagonal
+%
+%  - E           [n*1]     Elements added to the diagonal of A
+%  - P           [n*1]     record of how the rows and columns of the matrix were permuted while
+%                          performing the decomposition
 %
 % REFERENCES:
-%   This implementation is based on 
+%   This implementation is based on
 %
 %       Robert B. Schnabel and Elizabeth Eskow. 1990. "A New Modified Cholesky
 %       Factorization," SIAM Journal of Scientific Statistical Computating,
 %       11, 6: 1136-58.
-% 
+%
 %       Elizabeth Eskow and Robert B. Schnabel 1991. "Algorithm 695 - Software for a New Modified Cholesky
 %       Factorization," ACM Transactions on Mathematical Software, Vol 17, No 3: 306-312
-% 
-% 
+%
+%
 % Author: Johannes Pfeifer based on Eskow/Schnabel (1991)
-% 
+
 % Copyright (C) 2015 Johannes Pfeifer
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
+%
 % This file is part of Dynare.
 %
 % Dynare is free software: you can redistribute it and/or modify
@@ -148,7 +149,7 @@ for j = 1:n-1
                 % Swap elements of the permutation vector
                 itemp = P(j);
                 P(j) = P(imaxd);
-                P(imaxd) = itemp;          
+                P(imaxd) = itemp;
             end
         end
         % check to see whether the normal Cholesky update for this
@@ -183,13 +184,13 @@ for j = 1:n-1
             g=gersh_nested(A,j,n);
         end
     end
-    
+
     % PHASE 2
     if ~phase1
         if j ~= n-1
             if pivoting
                 % Find the minimum negative Gershgorin bound
-                [tmp,iming] = min(g(j:n)); 
+                [tmp,iming] = min(g(j:n));
                 iming=iming+j-1;
                 % Pivot to the top the row and column with the
                 % minimum negative Gershgorin bound
@@ -229,9 +230,9 @@ for j = 1:n-1
             end
             % Calculate delta and add to the diagonal. delta=max{0,-A(j,j) + max{normj,taugam},delta_previous}
             % where normj=sum of |A(i,j)|,for i=1,n, delta_previous is the delta computed at the previous iter and taugam is tau1*gamma.
-                       
+
             normj=sum(abs(A(j+1:n,j)));
-            
+
             delta = max([0;delta;-A(j,j)+normj;-A(j,j)+taugam]); % get adjustment based on formula on bottom of p. 309 of Eskow/Schnabel (1991)
 
             E(j) =  delta;
@@ -259,9 +260,9 @@ for j = 1:n-1
             % Find eigenvalues of final 2 by 2 submatrix
             % Find delta such that:
             % 1.  the l2 condition number of the final 2X2 submatrix + delta*I <= tau2
-            % 2. delta >= previous delta, 
+            % 2. delta >= previous delta,
             % 3. min(eigvals) + delta >= tau2 * gamma, where min(eigvals) is the smallest eigenvalue of the final 2X2 submatrix
-            
+
             A(n-1,n)=A(n,n-1); %set value above diagonal for computation of eigenvalues
             eigvals  = eig(A(n-1:n,n-1:n));
             delta    = max([ 0 ; delta ; -min(eigvals)+tau2*max((max(eigvals)-min(eigvals))/(1-tau1),gammma) ]); %Formula 5.3.2 of Schnabel/Eskow (1990)
@@ -272,7 +273,7 @@ for j = 1:n-1
                 E(n-1) = delta;
                 E(n) = delta;
             end
-            
+
             % Final update
             A(n-1,n-1) = sqrt(A(n-1,n-1));
             A(n,n-1) = A(n,n-1)/A(n-1,n-1);
@@ -293,17 +294,16 @@ function  g=gersh_nested(A,j,n)
 
 g=zeros(n,1);
 for ii = j:n
-    if ii == 1;
+    if ii == 1
         sum_up_to_i = 0;
     else
         sum_up_to_i = sum(abs(A(ii,j:(ii-1))));
-    end;
-    if ii == n;
+    end
+    if ii == n
         sum_after_i = 0;
     else
         sum_after_i = sum(abs(A((ii+1):n,ii)));
-    end;
+    end
     g(ii) = sum_up_to_i + sum_after_i- A(ii,ii);
 end
 end
-
diff --git a/matlab/clear_persistent_variables.m b/matlab/clear_persistent_variables.m
index e2fe5666f6c2dc45f22a73a7b91cce2761319540..c3250fb4dc7e19cb5146698fd90a432e95a524ee 100644
--- a/matlab/clear_persistent_variables.m
+++ b/matlab/clear_persistent_variables.m
@@ -2,7 +2,7 @@ function clear_persistent_variables(folder, writelistofroutinestobecleared)
 
 % Clear all the functions with persistent variables in directory folder (and subdirectories).
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -58,5 +58,5 @@ if writelistofroutinestobecleared
     return
 end
 
-list_of_functions_to_be_cleared;    
+list_of_functions_to_be_cleared;
 clear(list_of_functions{:});
\ No newline at end of file
diff --git a/matlab/cli/prior.m b/matlab/cli/prior.m
index 9e044506646b29224efcada72ef6969ce8af48c1..703297d73dda4ca91c5aa60c9d961441dd231a50 100644
--- a/matlab/cli/prior.m
+++ b/matlab/cli/prior.m
@@ -11,7 +11,7 @@ function varargout = prior(varargin)
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2015-2016 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -42,7 +42,7 @@ if isempty(varargin) || ( isequal(length(varargin), 1) && isequal(varargin{1},'h
     return
 end
 
-global options_ M_ estim_params_ bayestopt_ oo_ 
+global options_ M_ estim_params_ bayestopt_ oo_
 
 donesomething = false;
 
@@ -53,11 +53,11 @@ end
 
 if (size(estim_params_.var_endo,1) || size(estim_params_.corrn,1))
     % Prior over measurement errors are defined...
-   if ((isfield(options_,'varobs') && isempty(options_.varobs)) || ~isfield(options_,'varobs'))
-       % ... But the list of observed variabled is not yet defined.
-       warning('Prior detected on measurement erros, but no list of observed variables (varobs is missing)!')
-       return
-   end
+    if ((isfield(options_,'varobs') && isempty(options_.varobs)) || ~isfield(options_,'varobs'))
+        % ... But the list of observed variabled is not yet defined.
+        warning('Prior detected on measurement erros, but no list of observed variables (varobs is missing)!')
+        return
+    end
 end
 
 % Fill or update bayestopt_ structure
@@ -103,6 +103,9 @@ if ismember('simulate', varargin) % Prior simulations (BK).
     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)])
+    if options_.loglinear
+        disp(['Nonpositive steady state share        = ' num2str(results.ss.nonpositive_share)])
+    end
     disp(['Analytical steady state problem share = ' num2str(results.ass.problem_share)])
     skipline(2)
     donesomething = true;
@@ -114,7 +117,7 @@ if ismember('optimize', varargin) % Prior optimization.
 end
 
 if ismember('moments', varargin) % Prior simulations (2nd order moments).
-    % Set estimated parameters to the prior mode...
+                                 % Set estimated parameters to the prior mode...
     xparam1 = BayesOptions.p5;
     % ... Except for uniform priors (use the prior mean)!
     k = find(isnan(xparam1));
diff --git a/matlab/collect_latex_files.m b/matlab/collect_latex_files.m
index 5c4f2b7d643d419c558053edbcde65783be13ca7..45902f1bac500205707c781ef37967a7b2551733 100644
--- a/matlab/collect_latex_files.m
+++ b/matlab/collect_latex_files.m
@@ -1,14 +1,14 @@
 function collect_latex_files
 % function collect_LaTeX_Files;
 % Creates TeX-File embedding all eps-loaders created for current mod-file
-% 
+%
 % Inputs: none
-% 
-% Notes: 
+%
+% Notes:
 %   - The packages loaded enable pdflatex to run
 %   - The _dynamic and _static TeX-model files are not included as they are standalone TeX-files
 
-% Copyright (C) 2015-16 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -45,11 +45,11 @@ TeX_Files=dir([M_.fname,'*.tex']);
 for ii=1:length(TeX_Files)
     [pathstr,f_name,ext] = fileparts(TeX_Files(ii).name);
     if ~strcmp(TeX_Files(ii).name,f_name_binder) && ...
-        ~strcmp(TeX_Files(ii).name,[M_.fname,'_dynamic.tex']) && ...
-        ~strcmp(TeX_Files(ii).name,[M_.fname,'_static.tex']) && ...
-        ~strcmp(TeX_Files(ii).name,[M_.fname,'_original.tex']) && ...
-        ~strcmp(TeX_Files(ii).name,[M_.fname,'_TeX_binder.tex'])
-        fprintf(fid,'%s \n',['\include{',f_name,'}']);    
+            ~strcmp(TeX_Files(ii).name,[M_.fname,'_dynamic.tex']) && ...
+            ~strcmp(TeX_Files(ii).name,[M_.fname,'_static.tex']) && ...
+            ~strcmp(TeX_Files(ii).name,[M_.fname,'_original.tex']) && ...
+            ~strcmp(TeX_Files(ii).name,[M_.fname,'_TeX_binder.tex'])
+        fprintf(fid,'%s \n',['\include{',f_name,'}']);
     end
 end
 
@@ -58,7 +58,7 @@ TeX_Files=dir([M_.dname filesep 'Output' filesep  M_.fname '*.tex']);
 for ii=1:length(TeX_Files)
     [pathstr,f_name,ext] = fileparts(TeX_Files(ii).name);
     if ~strcmp(TeX_Files(ii).name,f_name_binder)
-        fprintf(fid,'%s \n',['\include{', M_.dname '/Output' '/',f_name,'}']);    
+        fprintf(fid,'%s \n',['\include{', M_.dname '/Output' '/',f_name,'}']);
     end
 end
 
@@ -67,7 +67,7 @@ TeX_Files=dir([M_.dname filesep 'graphs' filesep  M_.fname '*.tex']);
 for ii=1:length(TeX_Files)
     [pathstr,f_name,ext] = fileparts(TeX_Files(ii).name);
     if ~strcmp(TeX_Files(ii).name,f_name_binder)
-        fprintf(fid,'%s \n',['\include{', M_.dname '/graphs' '/',f_name,'}']);    
+        fprintf(fid,'%s \n',['\include{', M_.dname '/graphs' '/',f_name,'}']);
     end
 end
 
@@ -76,7 +76,7 @@ TeX_Files=dir([M_.dname filesep 'identification' filesep  M_.fname '*.tex']);
 for ii=1:length(TeX_Files)
     [pathstr,f_name,ext] = fileparts(TeX_Files(ii).name);
     if ~strcmp(TeX_Files(ii).name,f_name_binder)
-        fprintf(fid,'%s \n',['\include{', M_.dname '/identification' '/',f_name,'}']);    
+        fprintf(fid,'%s \n',['\include{', M_.dname '/identification' '/',f_name,'}']);
     end
 end
 
@@ -86,7 +86,7 @@ TeX_Files=dir([M_.dname filesep 'identification' filesep 'Output' filesep M_.fna
 for ii=1:length(TeX_Files)
     [pathstr,f_name,ext] = fileparts(TeX_Files(ii).name);
     if ~strcmp(TeX_Files(ii).name,f_name_binder)
-        fprintf(fid,'%s \n',['\include{', M_.dname '/identification/Output' '/',f_name,'}']);    
+        fprintf(fid,'%s \n',['\include{', M_.dname '/identification/Output' '/',f_name,'}']);
     end
 end
 
@@ -95,7 +95,7 @@ TeX_Files=dir([M_.dname filesep 'gsa' filesep  M_.fname '*.tex']);
 for ii=1:length(TeX_Files)
     [pathstr,f_name,ext] = fileparts(TeX_Files(ii).name);
     if ~strcmp(TeX_Files(ii).name,f_name_binder)
-        fprintf(fid,'%s \n',['\include{', M_.dname '/gsa' '/',f_name,'}']);    
+        fprintf(fid,'%s \n',['\include{', M_.dname '/gsa' '/',f_name,'}']);
     end
 end
 
@@ -104,7 +104,7 @@ TeX_Files=dir([M_.dname filesep 'gsa' filesep 'Output' filesep  M_.fname '*.tex'
 for ii=1:length(TeX_Files)
     [pathstr,f_name,ext] = fileparts(TeX_Files(ii).name);
     if ~strcmp(TeX_Files(ii).name,f_name_binder)
-        fprintf(fid,'%s \n',['\include{', M_.dname '/gsa/Output' '/',f_name,'}']);    
+        fprintf(fid,'%s \n',['\include{', M_.dname '/gsa/Output' '/',f_name,'}']);
     end
 end
 
diff --git a/matlab/compute_Pinf_Pstar.m b/matlab/compute_Pinf_Pstar.m
index 2fbae5b330d552ccf43b2f38ce318d83b46d7beb..d847ffacc28b98ca806c817401085bedd758502b 100644
--- a/matlab/compute_Pinf_Pstar.m
+++ b/matlab/compute_Pinf_Pstar.m
@@ -1,36 +1,36 @@
 function [Pstar,Pinf] = compute_Pinf_Pstar(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, but excluding zero columns of the transition matrix. 
+% 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 
+% 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 
+%
+% INPUTS
 %   mf           [integer]    vector of indices of observed variables in
 %                             state vector
 %   T            [double]     matrix of transition
 %   R            [double]     matrix of structural shock effects
 %   Q            [double]     matrix of covariance of structural shocks
-%   qz_criterium [double]     numerical criterium for unit roots   
-%  
-% OUTPUTS 
+%   qz_criterium [double]     numerical criterium for unit roots
+%
+% OUTPUTS
 %   Pstar        [double]     matrix of covariance of stationary part
 %   Pinf         [double]     matrix of covariance initialization for
-%                             nonstationary part    
-%    
-% ALGORITHM 
+%                             nonstationary part
+%
+% ALGORITHM
 %   Real Schur transformation of transition equation
 %
 % SPECIAL REQUIREMENTS
 %   None
 
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -49,7 +49,7 @@ function [Pstar,Pinf] = compute_Pinf_Pstar(mf,T,R,Q,qz_criterium, restrict_colum
 
 np = size(T,1);
 
-% perform Kitagawa transformation 
+% perform Kitagawa transformation
 [QT,ST] = schur(T);
 e1 = abs(ordeig(ST)) > 2-qz_criterium;
 [QT,ST] = ordschur(QT,ST,e1);
@@ -105,11 +105,10 @@ end
 Pinf = zeros(np,np);
 Pinf(1:nk,1:nk) = eye(nk);
 for k = 1:nk
-    if norm(QT(mf,k)) < 1e-8
+    if norm(QT(mf,:)*ST(:,k)) < 1e-8
         Pinf(k,k) = 0;
     end
 end
 
 Pinf = QT*Pinf*QT';
 Pstar = QT*Pstar*QT';
-
diff --git a/matlab/compute_mh_covariance_matrix.m b/matlab/compute_mh_covariance_matrix.m
index 8b62a2afe269b7080d5e600110ea0eba5f00d417..d7885c7f99ad3e5c0fd26855986185384ca292ba 100644
--- a/matlab/compute_mh_covariance_matrix.m
+++ b/matlab/compute_mh_covariance_matrix.m
@@ -1,21 +1,21 @@
 function [posterior_mean,posterior_covariance,posterior_mode,posterior_kernel_at_the_mode] = compute_mh_covariance_matrix()
 % Estimation of the posterior covariance matrix, posterior mean, posterior mode and evaluation of the posterior kernel at the
 % estimated mode, using the draws from a metropolis-hastings. The estimated posterior mode and covariance matrix are saved in
-% a file <M_.fname>_mh_mode.mat. 
-% 
-% INPUTS 
+% a file <M_.fname>_mh_mode.mat.
+%
+% INPUTS
 %   None.
-%  
+%
 % OUTPUTS
 %   o  posterior_mean                [double]  (n*1) vector, posterior expectation of the parameters.
 %   o  posterior_covariance          [double]  (n*n) matrix, posterior covariance of the parameters (computed from previous metropolis hastings).
-%   o  posterior_mode                [double]  (n*1) vector, posterior mode of the parameters. 
+%   o  posterior_mode                [double]  (n*1) vector, posterior mode of the parameters.
 %   o  posterior_kernel_at_the_mode  [double]  scalar.
 %
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -62,7 +62,7 @@ offset = 0;
 for b=1:nblck
     first_line = FirstLine;
     for n = FirstMhFile:TotalNumberOfMhFiles
-        load([ BaseName '_mh' int2str(n) '_blck' int2str(b) '.mat'],'x2','logpo2'); 
+        load([ BaseName '_mh' int2str(n) '_blck' int2str(b) '.mat'],'x2','logpo2');
         [tmp,idx] = max(logpo2);
         if tmp>posterior_kernel_at_the_mode
             posterior_kernel_at_the_mode = tmp;
diff --git a/matlab/compute_model_moments.m b/matlab/compute_model_moments.m
index 1c89a5e07dfee184832b99247aff6ce7f5d892af..50c1d00727d16cf5b0ffe1dea0c8ce989c177fed 100644
--- a/matlab/compute_model_moments.m
+++ b/matlab/compute_model_moments.m
@@ -4,14 +4,14 @@ function moments=compute_model_moments(dr,M_,options_)
 %    dr:        structure describing model solution
 %    M_:   structure of Dynare options
 %     options_
-%    
+%
 % OUTPUTS
 %    moments: a cell array containing requested moments
-%        
+%
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2008-2009 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/compute_moments_varendo.m b/matlab/compute_moments_varendo.m
index f2e26744016d9f2a0fa571df2b8eb8960e173fb9..c072f9c10c06967ed476cfac56cf2e6be239b2eb 100644
--- a/matlab/compute_moments_varendo.m
+++ b/matlab/compute_moments_varendo.m
@@ -2,21 +2,21 @@ function oo_ = compute_moments_varendo(type,options_,M_,oo_,var_list_)
 % Computes the second order moments (autocorrelation function, covariance
 % matrix and variance decomposition) distributions for all the endogenous variables selected in
 % var_list_. The results are saved in oo_
-%  
+%
 % INPUTS:
 %   type            [string]       'posterior' or 'prior'
 %   options_        [structure]    Dynare structure.
 %   M_              [structure]    Dynare structure (related to model definition).
 %   oo_             [structure]    Dynare structure (results).
 %   var_list_       [string]       Array of string with endogenous variable names.
-%    
+%
 % OUTPUTS
 %   oo_             [structure]    Dynare structure (results).
 %
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2008-2010 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -31,7 +31,7 @@ function oo_ = compute_moments_varendo(type,options_,M_,oo_,var_list_)
 % 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/>.
 
 
 fprintf('Estimation::compute_moments_varendo: I''m computing endogenous moments (this may take a while)... ');
@@ -129,7 +129,7 @@ if M_.exo_nbr > 1
         headers = char(' ',headers);
         lh = size(deblank(var_list_),2)+2;
         dyntable(options_,title,headers,deblank(var_list_),100* ...
-            temp,lh,8,2);
+                 temp,lh,8,2);
         if options_.TeX
             headers=M_.exo_names_tex;
             headers = char(' ',headers);
@@ -166,7 +166,7 @@ if M_.exo_nbr > 1
             headers = char(' ',headers);
             lh = size(deblank(var_list_),2)+2;
             dyntable(options_,title_print,headers,deblank(var_list_),100* ...
-                temp(:,:,step_iter),lh,8,2);
+                     temp(:,:,step_iter),lh,8,2);
             if options_.TeX
                 headers=M_.exo_names_tex;
                 headers = char(' ',headers);
diff --git a/matlab/compute_overall_acceptance_ratio.m b/matlab/compute_overall_acceptance_ratio.m
index d3b323eb309659191033067caf984802170a5bf5..90db1d37445ba91a5991d75438879e6142de7c76 100644
--- a/matlab/compute_overall_acceptance_ratio.m
+++ b/matlab/compute_overall_acceptance_ratio.m
@@ -1,6 +1,6 @@
 function overallacceptanceratio = compute_overall_acceptance_ratio(MetropolisFolder, ModelName)
 
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -16,7 +16,7 @@ function overallacceptanceratio = compute_overall_acceptance_ratio(MetropolisFol
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
-    
+
 BaseName = [MetropolisFolder filesep ModelName];
 mh_history_files = dir([BaseName '_mh_history_*.mat']);
 
@@ -24,12 +24,12 @@ n = length(mh_history_files);
 
 load([BaseName '_mh_history_' num2str(0)]);
 TotalNumberOfDraws = record.MhDraws(end,1);
-TotalNumberOfAcceptedProposals = record.AcceptanceRatio*record.MhDraws(end,1);  
+TotalNumberOfAcceptedProposals = record.AcceptanceRatio*record.MhDraws(end,1);
 
 for i=2:n
     load([BaseName '_mh_history_' num2str(i-1)]);
     TotalNumberOfDraws = TotalNumberOfDraws + record.MhDraws(end,1);
-    TotalNumberOfAcceptedProposals = TotalNumberOfAcceptedProposals + record.AcceptanceRatio*record.MhDraws(end,1);  
+    TotalNumberOfAcceptedProposals = TotalNumberOfAcceptedProposals + record.AcceptanceRatio*record.MhDraws(end,1);
 end
 
 overallacceptanceratio = TotalNumberOfAcceptedProposals/TotalNumberOfDraws;
\ No newline at end of file
diff --git a/matlab/compute_trend_coefficients.m b/matlab/compute_trend_coefficients.m
index 9686867e29c45822149facded5249ac32964eade..d9bd3441a80a87e5294ccf172a2fa6e36454b220 100644
--- a/matlab/compute_trend_coefficients.m
+++ b/matlab/compute_trend_coefficients.m
@@ -18,7 +18,7 @@ function [trend_addition, trend_coeff]=compute_trend_coefficients(M_,DynareOptio
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2014 Dynare Team
+% Copyright (C) 2014-2016 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/conditional_variance_decomposition.m b/matlab/conditional_variance_decomposition.m
index 3ecf7441039d3f1ef60b8c729d45f0b3b1f00d06..177684ce6566af57191b48ae7f0112e31d94ee89 100644
--- a/matlab/conditional_variance_decomposition.m
+++ b/matlab/conditional_variance_decomposition.m
@@ -1,14 +1,14 @@
 function ConditionalVarianceDecomposition = conditional_variance_decomposition(StateSpaceModel, Steps, SubsetOfVariables,sigma_e_is_diagonal)
 % This function computes the conditional variance decomposition of a given state space model
 % for a subset of endogenous variables.
-% 
-% INPUTS 
+%
+% INPUTS
 %   StateSpaceModel     [structure]   Specification of the state space model.
 %   Steps               [integer]     1*h vector of dates.
 %   SubsetOfVariables   [integer]     1*q vector of indices.
-%    
-% OUTPUTS 
-%   ConditionalVarianceDecomposition  [double] [n h p] array, where 
+%
+% OUTPUTS
+%   ConditionalVarianceDecomposition  [double] [n h p] array, where
 %                                                    n is equal to length(SubsetOfVariables)
 %                                                    h is the number of Steps
 %                                                    p is the number of state innovations and
@@ -16,7 +16,7 @@ function ConditionalVarianceDecomposition = conditional_variance_decomposition(S
 %
 % [1] In this version, absence of measurement errors is assumed...
 
-% Copyright (C) 2010-2011 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -77,7 +77,7 @@ for h = 1:length(Steps)
     SumOfVariances(:,h) = sum(ConditionalVariance(:,h,:),3);
 end
 
-ConditionalVarianceDecomposition = zeros(NumberOfVariables,length(Steps),number_of_state_innovations); 
+ConditionalVarianceDecomposition = zeros(NumberOfVariables,length(Steps),number_of_state_innovations);
 for i=1:number_of_state_innovations
     for h = 1:length(Steps)
         ConditionalVarianceDecomposition(:,h,i) = squeeze(ConditionalVariance(:,h,i))./SumOfVariances(:,h);
diff --git a/matlab/conditional_variance_decomposition_mc_analysis.m b/matlab/conditional_variance_decomposition_mc_analysis.m
index 67b42d0b0c4e6225fbf88f16d6fc58d22d03ab9f..c320554ebdcfc1f10bb06020946c60180dc13cbf 100644
--- a/matlab/conditional_variance_decomposition_mc_analysis.m
+++ b/matlab/conditional_variance_decomposition_mc_analysis.m
@@ -9,7 +9,7 @@ function oo_ = ...
 %   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        
+%   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
@@ -23,7 +23,7 @@ function oo_ = ...
 % OUTPUTS
 %   oo_          [structure]        Dynare structure where the results are saved.
 
-% Copyright (C) 2009-2015 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -106,7 +106,7 @@ for i=1:length(Steps)
         p_density(:,:,i) = pp_density;
     else
         [pp_mean, pp_median, pp_var, hpd_interval, pp_deciles] = ...
-            posterior_moments(tmp(:,i),0,mh_conf_sig);        
+            posterior_moments(tmp(:,i),0,mh_conf_sig);
     end
     p_mean(i) = pp_mean;
     p_median(i) = pp_median;
diff --git a/matlab/convergence_diagnostics/McMCDiagnostics.m b/matlab/convergence_diagnostics/McMCDiagnostics.m
index fb4f4126281e8ef2d3d804a149a0a7b8172da67a..a3fa70fd90b6b8b808b402511619d2fdbc2c8b8e 100644
--- a/matlab/convergence_diagnostics/McMCDiagnostics.m
+++ b/matlab/convergence_diagnostics/McMCDiagnostics.m
@@ -1,14 +1,14 @@
 function oo_ = McMCDiagnostics(options_, estim_params_, M_, oo_)
 % function McMCDiagnostics
-% Computes convergence tests 
-% 
-% INPUTS 
+% Computes convergence tests
+%
+% INPUTS
 %   options_         [structure]
 %   estim_params_    [structure]
 %   M_               [structure]
 %
-% OUTPUTS 
-%   oo_              [structure] 
+% OUTPUTS
+%   oo_              [structure]
 %
 % SPECIAL REQUIREMENTS
 %   none
@@ -16,7 +16,7 @@ function oo_ = McMCDiagnostics(options_, estim_params_, M_, oo_)
 % PARALLEL CONTEXT
 % See the comment in posterior_sampler.m funtion.
 
-% Copyright (C) 2005-2016 Dynare Team
+% Copyright (C) 2005-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -82,12 +82,12 @@ param_name_tex=[];
 for jj=1:npar
     if options_.TeX
         [par_name_temp,par_name_tex_temp]=get_the_name(jj,options_.TeX,M_,estim_params_,options_);
-        param_name = strvcat(param_name,par_name_temp);        
+        param_name = strvcat(param_name,par_name_temp);
         par_name_tex_temp = strrep(par_name_tex_temp,'$','');
         param_name_tex = strvcat(param_name_tex,par_name_tex_temp);
     else
         [par_name_temp]=get_the_name(jj,options_.TeX,M_,estim_params_,options_);
-        param_name = strvcat(param_name,par_name_temp);            
+        param_name = strvcat(param_name,par_name_temp);
     end
     Draws = GetAllPosteriorDraws(jj,FirstMhFile,FirstLine,TotalNumberOfMhFiles,NumberOfDraws);
     Draws = reshape(Draws,[NumberOfDraws nblck]);
@@ -101,7 +101,7 @@ end
 my_title='MCMC Inefficiency factors per block';
 IFAC_header='Parameter';
 IFAC_header_tex='Parameter';
-for j=1:nblck,
+for j=1:nblck
     IFAC_header = char(IFAC_header,['Block ' int2str(j)]);
     IFAC_header_tex = char(IFAC_header_tex,['Block~' int2str(j)]);
 end
@@ -130,7 +130,7 @@ end
 if nblck == 1 % Brooks and Gelman tests need more than one block
     convergence_diagnostics_geweke=zeros(npar,4+2*length(options_.convergence.geweke.taper_steps));
     if any(options_.convergence.geweke.geweke_interval<0) || any(options_.convergence.geweke.geweke_interval>1) || length(options_.convergence.geweke.geweke_interval)~=2 ...
-        || (options_.convergence.geweke.geweke_interval(2)-options_.convergence.geweke.geweke_interval(1)<0)
+            || (options_.convergence.geweke.geweke_interval(2)-options_.convergence.geweke.geweke_interval(1)<0)
         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
@@ -139,9 +139,9 @@ if nblck == 1 % Brooks and Gelman tests need more than one block
     first_obs_end_sample = first_obs_begin_sample+round(options_.convergence.geweke.geweke_interval(2)*NumberOfDraws*(1-options_.mh_drop));
     param_name=[];
     if options_.TeX
-        param_name_tex=[];    
+        param_name_tex=[];
     end
-    for jj=1:npar        
+    for jj=1:npar
         if options_.TeX
             [param_name_temp, param_name_tex_temp]= get_the_name(jj,options_.TeX,M_,estim_params_,options_);
             param_name_tex = strvcat(param_name_tex,strrep(param_name_tex_temp,'$',''));
@@ -152,7 +152,7 @@ if nblck == 1 % Brooks and Gelman tests need more than one block
         end
     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,NumberOfDraws);
-    fprintf('p-values are for Chi2-test for equality of means.\n');    
+    fprintf('p-values are for Chi2-test for equality of means.\n');
     Geweke_header=char('Parameter', 'Post. Mean', 'Post. Std', 'p-val No Taper');
     for ii=1:length(options_.convergence.geweke.taper_steps)
         Geweke_header=char(Geweke_header,['p-val ' num2str(options_.convergence.geweke.taper_steps(ii)),'% Taper']);
@@ -168,12 +168,12 @@ if nblck == 1 % Brooks and Gelman tests need more than one block
         end
         [results_vec, results_struct] = geweke_moments(param_draws,options_);
         convergence_diagnostics_geweke(jj,:)=results_vec;
-    
+
         param_draws1 = param_draws(first_obs_begin_sample:last_obs_begin_sample,:);
         param_draws2 = param_draws(first_obs_end_sample:end,:);
         [results_vec1] = geweke_moments(param_draws1,options_);
         [results_vec2] = geweke_moments(param_draws2,options_);
-        
+
         results_struct = geweke_chi2_test(results_vec1,results_vec2,results_struct,options_);
         eval(['oo_.convergence.geweke.',param_name(jj,:),'=results_struct;'])
         datamat(jj,:)=[results_struct.posteriormean,results_struct.posteriorstd,results_struct.prob_chi2_test];
@@ -183,29 +183,29 @@ if nblck == 1 % Brooks and Gelman tests need more than one block
     if options_.TeX
         Geweke_tex_header=char('Parameter', 'Mean', 'Std', 'No\ Taper');
         additional_header={[' & \multicolumn{2}{c}{Posterior} & \multicolumn{',num2str(1+length(options_.convergence.geweke.taper_steps)),'}{c}{p-values} \\'],
-            ['\cmidrule(r{.75em}){2-3} \cmidrule(r{.75em}){4-',num2str(4+length(options_.convergence.geweke.taper_steps)),'}']};
+                           ['\cmidrule(r{.75em}){2-3} \cmidrule(r{.75em}){4-',num2str(4+length(options_.convergence.geweke.taper_steps)),'}']};
         for ii=1:length(options_.convergence.geweke.taper_steps)
             Geweke_tex_header=char(Geweke_tex_header,[num2str(options_.convergence.geweke.taper_steps(ii)),'\%%\ Taper']);
         end
         headers = char(Geweke_tex_header);
         lh = size(param_name_tex,2)+2;
         my_title=sprintf('Geweke (1992) Convergence Tests, based on means of draws %d to %d vs %d to %d. p-values are for $\\\\chi^2$-test for equality of means.',first_obs_begin_sample,last_obs_begin_sample,first_obs_end_sample,NumberOfDraws);
-        dyn_latex_table(M_,options_,my_title,'geweke',headers,param_name_tex,datamat,lh,12,4,additional_header);    
+        dyn_latex_table(M_,options_,my_title,'geweke',headers,param_name_tex,datamat,lh,12,4,additional_header);
     end
     skipline(2);
-    
+
     if options_.convergence.rafterylewis.indicator
         if any(options_.convergence.rafterylewis.qrs<0) || any(options_.convergence.rafterylewis.qrs>1) || length(options_.convergence.rafterylewis.qrs)~=3 ...
-            || (options_.convergence.rafterylewis.qrs(1)-options_.convergence.rafterylewis.qrs(2)<=0)
+                || (options_.convergence.rafterylewis.qrs(1)-options_.convergence.rafterylewis.qrs(2)<=0)
             fprintf('\nCONVERGENCE DIAGNOSTICS: Invalid option for raftery_lewis_qrs. Using the default of [0.025 0.005 0.95].\n')
             options_.convergence.rafterylewis.qrs=[0.025 0.005 0.95];
-        end        
+        end
         Raftery_Lewis_q=options_.convergence.rafterylewis.qrs(1);
         Raftery_Lewis_r=options_.convergence.rafterylewis.qrs(2);
         Raftery_Lewis_s=options_.convergence.rafterylewis.qrs(3);
         oo_.Raftery_Lewis = raftery_lewis(x2,Raftery_Lewis_q,Raftery_Lewis_r,Raftery_Lewis_s);
         oo_.Raftery_Lewis.parameter_names=param_name;
-        my_title=sprintf('Raftery/Lewis (1992) Convergence Diagnostics, based on quantile q=%4.3f with precision r=%4.3f with probability s=%4.3f.',Raftery_Lewis_q,Raftery_Lewis_r,Raftery_Lewis_s);     
+        my_title=sprintf('Raftery/Lewis (1992) Convergence Diagnostics, based on quantile q=%4.3f with precision r=%4.3f with probability s=%4.3f.',Raftery_Lewis_q,Raftery_Lewis_r,Raftery_Lewis_s);
         headers = char('Variables','M (burn-in)','N (req. draws)','N+M (total draws)','k (thinning)');
 
         raftery_data_mat=[oo_.Raftery_Lewis.M_burn,oo_.Raftery_Lewis.N_prec,oo_.Raftery_Lewis.N_total,oo_.Raftery_Lewis.k_thin];
@@ -217,15 +217,15 @@ if nblck == 1 % Brooks and Gelman tests need more than one block
             labels_Raftery_Lewis_tex=char(param_name_tex,'Maximum');
             lh = size(labels_Raftery_Lewis_tex,2)+2;
             dyn_latex_table(M_,options_,my_title,'raftery_lewis',headers,labels_Raftery_Lewis_tex,raftery_data_mat,lh,10,0);
-        end      
+        end
     end
-       
-    return;
+
+    return
 end
 
 Origin = 1000;
-StepSize = ceil((NumberOfDraws-Origin)/100);% So that the computational time does not 
-ALPHA = 0.2;                                % increase too much with the number of simulations. 
+StepSize = ceil((NumberOfDraws-Origin)/100);% So that the computational time does not
+ALPHA = 0.2;                                % increase too much with the number of simulations.
 time = 1:NumberOfDraws;
 xx = Origin:StepSize:NumberOfDraws;
 NumberOfLines = length(xx);
@@ -262,7 +262,7 @@ localVars.M_ = M_;
 
 
 % Like sequential execution!
-if isnumeric(options_.parallel),
+if isnumeric(options_.parallel)
     fout = McMCDiagnostics_core(localVars,1,npar,0);
     UDIAG = fout.UDIAG;
     clear fout
@@ -273,21 +273,21 @@ else
         ModelName = [ModelName '_bvar'];
     end
     NamFileInput={[M_.dname '/metropolis/'],[ModelName '_mh*_blck*.mat']};
-    
+
     [fout, nBlockPerCPU, totCPU] = masterParallel(options_.parallel, 1, npar,NamFileInput,'McMCDiagnostics_core', localVars, [], options_.parallel_info);
     UDIAG = fout(1).UDIAG;
-    for j=2:totCPU,
+    for j=2:totCPU
         UDIAG = cat(3,UDIAG ,fout(j).UDIAG);
     end
 end
 
 UDIAG(:,[2 4 6],:) = UDIAG(:,[2 4 6],:)/nblck;
 skipline()
-clear pmet temp moyenne CSUP CINF csup cinf n linea iter tmp;    
+clear pmet temp moyenne CSUP CINF csup cinf n linea iter tmp;
 pages = floor(npar/3);
-k = 0;  
+k = 0;
 for i = 1:pages
-    h=dyn_figure(options_,'Name','MCMC univariate convergence diagnostic (Brooks and Gelman,1998)');
+    h=dyn_figure(options_.nodisplay,'Name','MCMC univariate convergence diagnostic (Brooks and Gelman,1998)');
     boxplot = 1;
     for j = 1:3 % Loop over parameters
         k = k+1;
@@ -296,12 +296,12 @@ for i = 1:pages
             if crit == 1
                 plt1 = UDIAG(:,1,k);
                 plt2 = UDIAG(:,2,k);
-                namnam  = [nam , ' (Interval)']; 
+                namnam  = [nam , ' (Interval)'];
             elseif crit == 2
                 plt1 = UDIAG(:,3,k);
                 plt2 = UDIAG(:,4,k);
                 namnam  = [nam , ' (m2)'];
-            elseif crit == 3    
+            elseif crit == 3
                 plt1 = UDIAG(:,5,k);
                 plt2 = UDIAG(:,6,k);
                 namnam  = [nam , ' (m3)'];
@@ -325,12 +325,12 @@ for i = 1:pages
             boxplot = boxplot + 1;
         end
     end
-    dyn_saveas(h,[OutputFolder '/' ModelName '_udiag' int2str(i)],options_);
+    dyn_saveas(h,[OutputFolder '/' ModelName '_udiag' int2str(i)],options_.nodisplay,options_.graph_format);
     if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
         fprintf(fidTeX,'\\begin{figure}[H]\n');
         for jj = 1:size(NAMES,1)
             fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TEXNAMES(jj,:)));
-        end    
+        end
         fprintf(fidTeX,'\\centering \n');
         fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_udiag%s}\n',options_.figures.textwidth*min((boxplot-1)/3,1),[OutputFolder '/' ModelName],int2str(i));
         fprintf(fidTeX,'\\caption{Univariate convergence diagnostics for the Metropolis-Hastings.\n');
@@ -346,11 +346,11 @@ if reste
     if reste == 1
         nr = 3;
         nc = 1;
-    elseif reste == 2;
+    elseif reste == 2
         nr = 2;
         nc = 3;
     end
-    h = dyn_figure(options_,'Name','MCMC univariate convergence diagnostic (Brooks and Gelman, 1998)');
+    h = dyn_figure(options_.nodisplay,'Name','MCMC univariate convergence diagnostic (Brooks and Gelman, 1998)');
     boxplot = 1;
     for j = 1:reste
         k = k+1;
@@ -359,12 +359,12 @@ if reste
             if crit == 1
                 plt1 = UDIAG(:,1,k);
                 plt2 = UDIAG(:,2,k);
-                namnam  = [nam , ' (Interval)']; 
+                namnam  = [nam , ' (Interval)'];
             elseif crit == 2
                 plt1 = UDIAG(:,3,k);
                 plt2 = UDIAG(:,4,k);
                 namnam  = [nam , ' (m2)'];
-            elseif crit == 3    
+            elseif crit == 3
                 plt1 = UDIAG(:,5,k);
                 plt2 = UDIAG(:,6,k);
                 namnam  = [nam , ' (m3)'];
@@ -388,12 +388,12 @@ if reste
             boxplot = boxplot + 1;
         end
     end
-    dyn_saveas(h,[ OutputFolder '/' ModelName '_udiag' int2str(pages+1)],options_);
+    dyn_saveas(h,[ OutputFolder '/' ModelName '_udiag' int2str(pages+1)],options_.nodisplay,options_.graph_format);
     if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
         fprintf(fidTeX,'\\begin{figure}[H]\n');
-        for jj = 1:size(NAMES,1);
+        for jj = 1:size(NAMES,1)
             fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TEXNAMES(jj,:)));
-        end    
+        end
         fprintf(fidTeX,'\\centering \n');
         fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_udiag%s}\n',options_.figures.textwidth*min((boxplot-1)/nc,1),[OutputFolder '/' ModelName],int2str(pages+1));
         if reste == 2
@@ -435,7 +435,7 @@ for b = 1:nblck
 end
 clear logpo2;
 tmp(:,2) = kron(transpose(1:nblck),ones(NumberOfDraws,1));
-tmp(:,3) = kron(ones(nblck,1),time'); 
+tmp(:,3) = kron(ones(nblck,1),time');
 tmp = sortrows(tmp,1);
 ligne   = 0;
 for iter  = Origin:StepSize:NumberOfDraws
@@ -454,25 +454,25 @@ for iter  = Origin:StepSize:NumberOfDraws
     for i=1:nblck
         pmet = temp(find(temp(:,2)==i));
         MDIAG(ligne,2) = MDIAG(ligne,2) + pmet(csup,1)-pmet(cinf,1);
-        moyenne = mean(pmet,1); %% Within mean. 
+        moyenne = mean(pmet,1); %% Within mean.
         MDIAG(ligne,4) = MDIAG(ligne,4) + sum((pmet(:,1)-moyenne).^2)/(n-1);
         MDIAG(ligne,6) = MDIAG(ligne,6) + sum(abs(pmet(:,1)-moyenne).^3)/(n-1);
     end
 end
-MDIAG(:,[2 4 6],:) = MDIAG(:,[2 4 6],:)/nblck;  
+MDIAG(:,[2 4 6],:) = MDIAG(:,[2 4 6],:)/nblck;
 
-h = dyn_figure(options_,'Name','Multivariate convergence diagnostic');
+h = dyn_figure(options_.nodisplay,'Name','Multivariate convergence diagnostic');
 boxplot = 1;
 for crit = 1:3
     if crit == 1
         plt1 = MDIAG(:,1);
         plt2 = MDIAG(:,2);
-        namnam  = 'Interval'; 
+        namnam  = 'Interval';
     elseif crit == 2
         plt1 = MDIAG(:,3);
         plt2 = MDIAG(:,4);
         namnam  = 'm2';
-    elseif crit == 3    
+    elseif crit == 3
         plt1 = MDIAG(:,5);
         plt2 = MDIAG(:,6);
         namnam  = 'm3';
@@ -493,13 +493,13 @@ for crit = 1:3
     title(namnam,'Interpreter','none');
     boxplot = boxplot + 1;
 end
-dyn_saveas(h,[ OutputFolder '/' ModelName '_mdiag'],options_);
+dyn_saveas(h,[ OutputFolder '/' ModelName '_mdiag'],options_.nodisplay,options_.graph_format);
 
 if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
     fprintf(fidTeX,'\\begin{figure}[H]\n');
     for jj = 1:3
         fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),' ');
-    end    
+    end
     fprintf(fidTeX,'\\centering \n');
     fprintf(fidTeX,'\\includegraphics[width=0.8\\textwidth]{%s_mdiag}\n',[OutputFolder '/' ModelName]);
     fprintf(fidTeX,'\\caption{Multivariate convergence diagnostics for the Metropolis-Hastings.\n');
@@ -512,4 +512,3 @@ if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
     fprintf(fidTeX,'%% End Of TeX file.');
     fclose(fidTeX);
 end
-
diff --git a/matlab/convergence_diagnostics/McMCDiagnostics_core.m b/matlab/convergence_diagnostics/McMCDiagnostics_core.m
index af41566c94a5d15264f2815a93ae530e713733e9..283e6ada1079a3f86f86d11ad9c5338bc336fd43 100644
--- a/matlab/convergence_diagnostics/McMCDiagnostics_core.m
+++ b/matlab/convergence_diagnostics/McMCDiagnostics_core.m
@@ -2,12 +2,12 @@ function myoutput = McMCDiagnostics_core(myinputs,fpar,npar,whoiam, ThisMatlab)
 % function myoutput = McMCDiagnostics_core(myinputs,fpar,npar,whoiam, ThisMatlab)
 % Computes the Brooks/Gelman (1998) convergence diagnostics, both the
 % parameteric and the non-parameteric versions
-% 
+%
 % PARALLEL CONTEXT
 % Core functionality for MCMC Diagnostics, which can be parallelized.
 % See also the comment in posterior_sampler_core.m funtion.
-% 
-% 
+%
+%
 % INPUTS
 %   See See the comment in posterior_sampler_core.m funtion.
 
@@ -25,15 +25,15 @@ function myoutput = McMCDiagnostics_core(myinputs,fpar,npar,whoiam, ThisMatlab)
 %
 % ALGORITHM
 %   Computes part of the convergence diagnostics, the rest is computed in McMCDiagnostics.m .
-%   The methodology and terminology is based on: Brooks/Gelman (1998): General 
-%   Methods for Monitoring Convergence of Iterative Simulations, Journal of Computational 
+%   The methodology and terminology is based on: Brooks/Gelman (1998): General
+%   Methods for Monitoring Convergence of Iterative Simulations, Journal of Computational
 %   and Graphical Statistics, Volume 7, Number 4, Pages 434-455
-% 
+%
 %
 % SPECIAL REQUIREMENTS.
 %   None.
 
-% Copyright (C) 2006-2016 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -50,7 +50,7 @@ function myoutput = McMCDiagnostics_core(myinputs,fpar,npar,whoiam, ThisMatlab)
 % 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,
+if nargin<4
     whoiam=0;
 end
 
@@ -71,7 +71,7 @@ M_=myinputs.M_;
 if whoiam
     Parallel=myinputs.Parallel;
 end
-if ~exist('MetropolisFolder'),
+if ~exist('MetropolisFolder')
     MetropolisFolder = CheckPath('metropolis',M_.dname);
 end
 
@@ -81,16 +81,16 @@ UDIAG = zeros(NumberOfLines,6,npar-fpar+1);
 
 if whoiam
     waitbarString = ['Please wait... McMCDiagnostics (' int2str(fpar) 'of' int2str(npar) ')...'];
-    if Parallel(ThisMatlab).Local,
+    if Parallel(ThisMatlab).Local
         waitbarTitle=['Local '];
     else
         waitbarTitle=[Parallel(ThisMatlab).ComputerName];
     end
     fMessageStatus(0,whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab));
 end
-for j=fpar:npar,
+for j=fpar:npar
     if isoctave
-        if (whoiam==0),
+        if (whoiam==0)
             printf('    Parameter %d...  ',j);
         end
     else
@@ -131,13 +131,13 @@ for j=fpar:npar,
         end
     end
     if isoctave
-        if (whoiam==0),
+        if (whoiam==0)
             printf('Done! \n');
         end
     else
         fprintf('Done! \n');
     end
-    if whoiam,
+    if whoiam
         waitbarString = [ 'Parameter ' int2str(j) '/' int2str(npar) ' done.'];
         fMessageStatus((j-fpar+1)/(npar-fpar+1),whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab))
     end
diff --git a/matlab/convergence_diagnostics/geweke_chi2_test.m b/matlab/convergence_diagnostics/geweke_chi2_test.m
index 7ed38313981fbfaabe39ddcd76f434021236054e..8acf673993479e8e99880ba71c0eeca12f48d076 100644
--- a/matlab/convergence_diagnostics/geweke_chi2_test.m
+++ b/matlab/convergence_diagnostics/geweke_chi2_test.m
@@ -2,7 +2,7 @@ function results_struct = geweke_chi2_test(results1,results2,results_struct,opti
 % results_struct = geweke_chi2_test(results1,results2,results_struct,options)
 % PURPOSE: computes Geweke's chi-squared test for two sets of MCMC sample draws
 %
-% INPUTS 
+% INPUTS
 %   results1         [1 by (4+n_taper*2) vector] vector with post. mean,
 %                           std, NSE_iid, RNE_iid, and tapered NSE and RNE
 %                           for chain part 1
@@ -12,7 +12,7 @@ function results_struct = geweke_chi2_test(results1,results2,results_struct,opti
 %   results_struct   [structure] results structure generated by geweke_moments
 %   Dynareoptions    [structure]
 %
-% OUTPUTS 
+% OUTPUTS
 %   results_struct   [structure]  containing the following fields:
 %       pooled_mean               Pooled mean of the chain parts, weighted
 %                                   with precision
@@ -26,7 +26,7 @@ function results_struct = geweke_chi2_test(results1,results2,results_struct,opti
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -49,26 +49,25 @@ function results_struct = geweke_chi2_test(results1,results2,results_struct,opti
 % J.M. Bernardo, A.P. Dawid, and A.F.M. Smith (eds.) Proceedings of
 % the Fourth Valencia International Meeting on Bayesian Statistics,
 % pp. 169-194, Oxford University Press
-% Geweke (1999): `Using simulation methods for Bayesian econometric models: 
+% Geweke (1999): `Using simulation methods for Bayesian econometric models:
 % Inference, development and communication', Econometric Reviews, 18(1),
 % 1-73
 
-% written by: Johannes Pfeifer, 
-% based on code by James P. LeSage, who in turn 
-% drew on MATLAB programs written by Siddartha Chib 
+% written by: Johannes Pfeifer,
+% based on code by James P. LeSage, who in turn
+% drew on MATLAB programs written by Siddartha Chib
 
-for k=1:length(options.convergence.geweke.taper_steps)+1;
-  NSE=[results1(:,3+(k-1)*2) results2(:,3+(k-1)*2)];
-  means=[results1(:,1) results2(:,1)];
-  diff_Means=means(:,1)-means(:,2);
-  sum_of_weights=sum(1./(NSE.^2),2);
-  pooled_mean=sum(means./(NSE.^2),2)./sum_of_weights;
-  pooled_NSE=1./sqrt(sum_of_weights);
-
-  test_stat=diff_Means.^2./sum(NSE.^2,2); 
-  p = 1-chi2cdf(test_stat,1);
-  results_struct.pooled_mean(:,k) = pooled_mean;
-  results_struct.pooled_nse(:,k) = pooled_NSE;
-  results_struct.prob_chi2_test(:,k) = p;
-end;
+for k=1:length(options.convergence.geweke.taper_steps)+1
+    NSE=[results1(:,3+(k-1)*2) results2(:,3+(k-1)*2)];
+    means=[results1(:,1) results2(:,1)];
+    diff_Means=means(:,1)-means(:,2);
+    sum_of_weights=sum(1./(NSE.^2),2);
+    pooled_mean=sum(means./(NSE.^2),2)./sum_of_weights;
+    pooled_NSE=1./sqrt(sum_of_weights);
 
+    test_stat=diff_Means.^2./sum(NSE.^2,2);
+    p = 1-chi2cdf(test_stat,1);
+    results_struct.pooled_mean(:,k) = pooled_mean;
+    results_struct.pooled_nse(:,k) = pooled_NSE;
+    results_struct.prob_chi2_test(:,k) = p;
+end
diff --git a/matlab/convergence_diagnostics/geweke_moments.m b/matlab/convergence_diagnostics/geweke_moments.m
index 242a9d55016796ca844792e31fa87acda779be87..61c22979fb074658503708bcef980f60051e0276 100644
--- a/matlab/convergence_diagnostics/geweke_moments.m
+++ b/matlab/convergence_diagnostics/geweke_moments.m
@@ -1,13 +1,13 @@
 function [results_vec, results_struct] = geweke_moments(draws,Dynareoptions)
 %[results_vec, results_struct] = geweke_moments(draws,Dynareoptions)
-% PURPOSE: computes Gewke's convergence diagnostics NSE and RNE 
+% PURPOSE: computes Gewke's convergence diagnostics NSE and RNE
 %          (numerical std error and relative numerical efficiencies)
 
-% INPUTS 
-%   draws            [ndraws by 1 vector] 
+% INPUTS
+%   draws            [ndraws by 1 vector]
 %   Dynareoptions    [structure]
-%  
-% OUTPUTS 
+%
+% OUTPUTS
 %   results_vec
 %   results_struct   [structure]  containing the following fields:
 %          posteriormean= posterior parameter mean
@@ -22,7 +22,7 @@ function [results_vec, results_struct] = geweke_moments(draws,Dynareoptions)
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -44,16 +44,16 @@ function [results_vec, results_struct] = geweke_moments(draws,Dynareoptions)
 % J.M. Bernardo, A.P. Dawid, and A.F.M. Smith (eds.) Proceedings of
 % the Fourth Valencia International Meeting on Bayesian Statistics,
 % pp. 169-194, Oxford University Press
-% Geweke (1999): `Using simulation methods for Bayesian econometric models: 
+% Geweke (1999): `Using simulation methods for Bayesian econometric models:
 % Inference, development and communication', Econometric Reviews, 18(1),
 % 1-73
 % -----------------------------------------------------------------
 
-% written by: Johannes Pfeifer, 
-% based on code by James P. LeSage, who in turn 
-% drew on MATLAB programs written by Siddartha Chib 
+% written by: Johannes Pfeifer,
+% based on code by James P. LeSage, who in turn
+% drew on MATLAB programs written by Siddartha Chib
+
 
-  
 ndraw = size(draws,1);
 n_groups=100;
 taper_steps=Dynareoptions.convergence.geweke.taper_steps;
@@ -64,10 +64,10 @@ n_draws_used = ns*n_groups; %effective number of draws used after rounding down
 
 window_means= zeros(n_groups,1);
 window_uncentered_variances= zeros(n_groups,1);
-for ig=1:n_groups;
+for ig=1:n_groups
     window_means(ig,1)=sum(draws((ig-1)*ns+1:ig*ns,1))/ns;
-    window_uncentered_variances(ig,1)=sum(draws((ig-1)*ns+1:ig*ns,1).^2)/ns;        
-end; %for ig
+    window_uncentered_variances(ig,1)=sum(draws((ig-1)*ns+1:ig*ns,1).^2)/ns;
+end %for ig
 total_mean=mean(window_means);
 total_variance=mean(window_uncentered_variances)-total_mean^2;
 
@@ -88,9 +88,9 @@ results_struct.rne_iid = results_vec(1,4);
 %get autocovariance of grouped means
 centered_window_means=window_means-total_mean;
 autocov_grouped_means=zeros(n_groups,1);
-for lag=0:n_groups-1;
+for lag=0:n_groups-1
     autocov_grouped_means(lag+1)=centered_window_means(lag+1:n_groups,1)'*centered_window_means(1:n_groups-lag,1)/100;
-end;
+end
 
 % numerical standard error with tapered autocovariance functions
 for taper_index=1:length(taper_steps)
@@ -105,5 +105,4 @@ for taper_index=1:length(taper_steps)
 
     eval(['results_struct.nse_taper_',num2str(taper),'= NSE_taper;']);
     eval(['results_struct.rne_taper_',num2str(taper),'= total_variance/(n_draws_used*NSE_taper^2);']);
-end; % end of for mm loop
-
+end % end of for mm loop
diff --git a/matlab/convergence_diagnostics/mcmc_ifac.m b/matlab/convergence_diagnostics/mcmc_ifac.m
index 3688153f98f3b3b2d3dddf6658f47055bc3da807..32b72bcee478d68b5b66ea6d27342a369e7995da 100644
--- a/matlab/convergence_diagnostics/mcmc_ifac.m
+++ b/matlab/convergence_diagnostics/mcmc_ifac.m
@@ -1,71 +1,71 @@
-function Ifac = mcmc_ifac(X, Nc)
-% function Ifac = mcmc_ifac(X, Nc)
-% Compute inefficiency factor of a MCMC sample X based on a Parzen Window
-%
-% INPUTS
-%   X:       time series
-%   Nc:      # of lags
-%
-% OUTPUTS
-%   Ifac:       inefficiency factor of MCMC sample
-%
-% SPECIAL REQUIREMENTS
-%   none
-% ALGORITHM:
-%   Inefficiency factors are computed as
-%   \[
-%       Ifac = 1 + 2\sum\limits_{i=1}^{Nc} {\hat \rho(i)} 
-%   \]
-%   where $\hat \rho(i)$ denotes the autocorrelation at lag i and the terms
-%   of the sum are truncated using a Parzen window.
-%   
-%   For inefficiency factors, see Section 6.1 of Paolo Giordani, Michael Pitt, and Robert Kohn (2011): 
-%   "Bayesian Inference for Time Series State Space Models" in : John Geweke, Gary Koop,
-%   Herman van Dijk (editors): "The Oxford Handbook of Bayesian
-%   Econometrics", Oxford University Press
-%
-%   The Parzen-Window is given by
-%  \[
-%   k(x) = \left\{ {\begin{array}{*{20}{c}}
-%        {1 - 6{x^2} + 6|x|^3} \text{ for } 0 \leqslant |x| \leqslant \frac{1}{2}} \\
-%        {2(1-|x|^3) \text{ for } \frac{1}{2} \leqslant |x| \leqslant 1} \\
-%        {0 \text{ otherwise}}
-%        \end{array}} \right.
-%  \]
-% See Donald W.K Andrews (1991): "Heteroskedasticity and autocorrelation
-% consistent covariance matrix estimation", Econometrica, 59(3), p. 817-858
-
-
-% Copyright (C) 2015-16 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/>.
-
-Nc = floor(min(Nc, length(X)/2));
-if mod(Nc,2),
-    Nc=Nc-1;
-end
-AcorrXSIM = dyn_autocorr(X(:), Nc);
-%
-%Calculate the Parzen Weight
-Parzen=zeros(Nc+1,1);
-for i=1: Nc/2+1
-    Parzen(i)=1 - 6*(i/Nc)^2+ 6*(i/Nc)^3;
-end
-for i=(Nc/2)+1: Nc+1
-    Parzen(i)=2 * (1-(i/Nc))^3;
-end
-Parzen=Parzen';
-Ifac= 1+2*sum(Parzen(:).* AcorrXSIM);
+function Ifac = mcmc_ifac(X, Nc)
+% function Ifac = mcmc_ifac(X, Nc)
+% Compute inefficiency factor of a MCMC sample X based on a Parzen Window
+%
+% INPUTS
+%   X:       time series
+%   Nc:      # of lags
+%
+% OUTPUTS
+%   Ifac:       inefficiency factor of MCMC sample
+%
+% SPECIAL REQUIREMENTS
+%   none
+% ALGORITHM:
+%   Inefficiency factors are computed as
+%   \[
+%       Ifac = 1 + 2\sum\limits_{i=1}^{Nc} {\hat \rho(i)}
+%   \]
+%   where $\hat \rho(i)$ denotes the autocorrelation at lag i and the terms
+%   of the sum are truncated using a Parzen window.
+%
+%   For inefficiency factors, see Section 6.1 of Paolo Giordani, Michael Pitt, and Robert Kohn (2011):
+%   "Bayesian Inference for Time Series State Space Models" in : John Geweke, Gary Koop,
+%   Herman van Dijk (editors): "The Oxford Handbook of Bayesian
+%   Econometrics", Oxford University Press
+%
+%   The Parzen-Window is given by
+%  \[
+%   k(x) = \left\{ {\begin{array}{*{20}{c}}
+%        {1 - 6{x^2} + 6|x|^3} \text{ for } 0 \leqslant |x| \leqslant \frac{1}{2}} \\
+%        {2(1-|x|^3) \text{ for } \frac{1}{2} \leqslant |x| \leqslant 1} \\
+%        {0 \text{ otherwise}}
+%        \end{array}} \right.
+%  \]
+% See Donald W.K Andrews (1991): "Heteroskedasticity and autocorrelation
+% consistent covariance matrix estimation", Econometrica, 59(3), p. 817-858
+
+
+% Copyright (C) 2015-2017 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/>.
+
+Nc = floor(min(Nc, length(X)/2));
+if mod(Nc,2)
+    Nc=Nc-1;
+end
+AcorrXSIM = dyn_autocorr(X(:), Nc);
+%
+%Calculate the Parzen Weight
+Parzen=zeros(Nc+1,1);
+for i=1: Nc/2+1
+    Parzen(i)=1 - 6*(i/Nc)^2+ 6*(i/Nc)^3;
+end
+for i=(Nc/2)+1: Nc+1
+    Parzen(i)=2 * (1-(i/Nc))^3;
+end
+Parzen=Parzen';
+Ifac= 1+2*sum(Parzen(:).* AcorrXSIM);
diff --git a/matlab/convergence_diagnostics/raftery_lewis.m b/matlab/convergence_diagnostics/raftery_lewis.m
index c2a162d875d684f2330b042f4befdecc74fb96aa..ab0e51cb73c3f388a16605a08c34326b403c8839 100644
--- a/matlab/convergence_diagnostics/raftery_lewis.m
+++ b/matlab/convergence_diagnostics/raftery_lewis.m
@@ -1,15 +1,15 @@
 function  [raftery_lewis] = raftery_lewis(runs,q,r,s)
 % function  raftery_lewis = raftery_lewis(runs,q,r,s)
-% Computes the convergence diagnostics of Raftery and Lewis (1992), i.e. the 
-% number of draws needed in MCMC to estimate the posterior cdf of the q-quantile 
+% Computes the convergence diagnostics of Raftery and Lewis (1992), i.e. the
+% number of draws needed in MCMC to estimate the posterior cdf of the q-quantile
 % within an accuracy r with probability s
-% 
+%
 % Inputs:
-%   - draws [n_draws by n_var]      double matrix of draws from the sampler 
+%   - draws [n_draws by n_var]      double matrix of draws from the sampler
 %   - q     [scalar]                quantile of the quantity of interest
-%   - r     [scalar]                level of desired precision 
+%   - r     [scalar]                level of desired precision
 %   - s     [scalar]                probability associated with r
-% 
+%
 % Output:
 %   raftery_lewis   [structure]     containing the fields:
 %   - M_burn    [n_draws by 1]      number of draws required for burn-in
@@ -21,7 +21,7 @@ function  [raftery_lewis] = raftery_lewis(runs,q,r,s)
 %                                   iterations due to dependence in chain
 %   - N_min     [scalar]            # draws if the chain is white noise
 %   - N_total   [n_draws by 1]      nburn + nprec
-% 
+%
 
 % ---------------------------------------------------------------------
 % NOTES:   Example values of q, r, s:
@@ -30,23 +30,23 @@ function  [raftery_lewis] = raftery_lewis(runs,q,r,s)
 %
 %  - The result is quite sensitive to r, being proportional to the
 %       inverse of r^2.
-%  - For epsilon (closeness of probabilities to equilibrium values), 
+%  - For epsilon (closeness of probabilities to equilibrium values),
 %       Raftery/Lewis use 0.001 and argue that the results
 %       are quite robust to changes in this value
 %
 % ---------------------------------------------------------------------
-% REFERENCES: 
+% REFERENCES:
 % Raftery, Adrien E./Lewis, Steven (1992a): "How many iterations in the Gibbs sampler?"
-%   in: Bernardo/Berger/Dawid/Smith (eds.): Bayesian Statistics, Vol. 4, Clarendon Press: Oxford, 
-%   pp. 763-773.   
-% Raftery, Adrien E./Lewis, Steven (1992b): "Comment: One long run with diagnostics: 
-%   Implementation strategies for Markov chain Monte Carlo." Statistical Science, 
-%   7(4), pp. 493-497.  
+%   in: Bernardo/Berger/Dawid/Smith (eds.): Bayesian Statistics, Vol. 4, Clarendon Press: Oxford,
+%   pp. 763-773.
+% Raftery, Adrien E./Lewis, Steven (1992b): "Comment: One long run with diagnostics:
+%   Implementation strategies for Markov chain Monte Carlo." Statistical Science,
+%   7(4), pp. 493-497.
 %
 % ----------------------------------------------------
 
 % Copyright (C) 2016 Benjamin Born and Johannes Pfeifer
-% Copyright (C) 2016 Dynare Team
+% Copyright (C) 2016-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -80,42 +80,42 @@ thinned_chain  = zeros(n_runs,1);
 Phi   = norminv((s+1)/2); %note the missing ^{-1} at the Phi in equation top page 5, see RL (1995)
 raftery_lewis.N_min  = fix(Phi^2*(1-q)*q/r^2+1);
 
-for nv = 1:n_vars % big loop over variables    
+for nv = 1:n_vars % big loop over variables
     if q > 0 && q < 1
         work = (runs(:,nv) <= quantile(runs(:,nv),q));
     else
-        error('Quantile must be between 0 and 1'); 
-    end;
-    
-    k_thin_current_var = 1; 
-    bic = 1; 
+        error('Quantile must be between 0 and 1');
+    end
+
+    k_thin_current_var = 1;
+    bic = 1;
     epss = 0.001;
     % Find thinning factor for which first-order Markov Chain is preferred to second-order one
     while(bic > 0)
-        thinned_chain=work(1:k_thin_current_var:n_runs,1); 
+        thinned_chain=work(1:k_thin_current_var:n_runs,1);
         [g2, bic] = first_vs_second_order_MC_test(thinned_chain);
         k_thin_current_var = k_thin_current_var+1;
-    end;
-    
+    end
+
     k_thin_current_var = k_thin_current_var-1; %undo last step
-    
-    %compute transition probabilities 
+
+    %compute transition probabilities
     transition_matrix = zeros(2,2);
     for i1 = 2:size(thinned_chain,1)
         transition_matrix(thinned_chain(i1-1)+1,thinned_chain(i1)+1) = transition_matrix(thinned_chain(i1-1)+1,thinned_chain(i1)+1)+1;
-    end;
+    end
     alpha = transition_matrix(1,2)/(transition_matrix(1,1)+transition_matrix(1,2)); %prob of going from 1 to 2
     beta = transition_matrix(2,1)/(transition_matrix(2,1)+transition_matrix(2,2));  %prob of going from 2 to 1
 
     kmind=k_thin_current_var;
     [g2, bic]=independence_chain_test(thinned_chain);
-    
+
     while(bic > 0)
-        thinned_chain=work(1:kmind:n_runs,1); 
+        thinned_chain=work(1:kmind:n_runs,1);
         [g2, bic] = independence_chain_test(thinned_chain);
         kmind = kmind+1;
-    end;
-    
+    end
+
     m_star  = log((alpha + beta)*epss/max(alpha,beta))/log(abs(1 - alpha - beta)); %equation bottom page 4
     raftery_lewis.M_burn(nv) = fix((m_star+1)*k_thin_current_var);
     n_star  = (2 - (alpha + beta))*alpha*beta*(Phi^2)/((alpha + beta)^3 * r^2); %equation top page 5
@@ -124,35 +124,35 @@ for nv = 1:n_vars % big loop over variables
     raftery_lewis.k_ind(nv)  = max(fix(raftery_lewis.I_stat(nv)+1),kmind);
     raftery_lewis.k_thin(nv) = k_thin_current_var;
     raftery_lewis.N_total(nv)= raftery_lewis.M_burn(nv)+raftery_lewis.N_prec(nv);
-end;
+end
 
 end
 
 function [g2, bic] = first_vs_second_order_MC_test(d)
 %conducts a test of first vs. second order Markov Chain via BIC criterion
 n_obs=size(d,1);
-g2 = 0; 
+g2 = 0;
 tran=zeros(2,2,2);
 for t_iter=3:n_obs     % count state transitions
     tran(d(t_iter-2,1)+1,d(t_iter-1,1)+1,d(t_iter,1)+1)=tran(d(t_iter-2,1)+1,d(t_iter-1,1)+1,d(t_iter,1)+1)+1;
-end;
+end
 % Compute the log likelihood ratio statistic for second-order MC vs first-order MC. G2 statistic of Bishop, Fienberg and Holland (1975)
 for ind_1 = 1:2
     for ind_2 = 1:2
         for ind_3 = 1:2
             if tran(ind_1,ind_2,ind_3) ~= 0
                 fitted = (tran(ind_1,ind_2,1) + tran(ind_1,ind_2,2))*(tran(1,ind_2,ind_3) + tran(2,ind_2,ind_3))/...
-                    (tran(1,ind_2,1) + tran(1,ind_2,2) + tran(2,ind_2,1) + tran(2,ind_2,2));
+                         (tran(1,ind_2,1) + tran(1,ind_2,2) + tran(2,ind_2,1) + tran(2,ind_2,2));
                 focus = tran(ind_1,ind_2,ind_3);
                 g2 = g2 + log(focus/fitted)*focus;
             end
-        end;       % end of for i3
-    end;        % end of for i2
-end;         % end of for i1
-g2 = g2*2;
-bic = g2 - log(n_obs-2)*2;
+        end       % end of for i3
+    end        % end of for i2
+end         % end of for i1
+    g2 = g2*2;
+    bic = g2 - log(n_obs-2)*2;
 
-end
+    end
 
 
 function [g2, bic] = independence_chain_test(d)
@@ -161,19 +161,19 @@ n_obs=size(d,1);
 trans = zeros(2,2);
 for ind_1 = 2:n_obs
     trans(d(ind_1-1)+1,d(ind_1)+1)=trans(d(ind_1-1)+1,d(ind_1)+1)+1;
-end;
-dcm1 = n_obs - 1;  
+end
+dcm1 = n_obs - 1;
 g2 = 0;
 % Compute the log likelihood ratio statistic for second-order MC vs first-order MC. G2 statistic of Bishop, Fienberg and Holland (1975)
 for ind_1 = 1:2
     for ind_2 = 1:2
         if trans(ind_1,ind_2) ~= 0
-            fitted = ((trans(ind_1,1) + trans(ind_1,2))*(trans(1,ind_2) + trans(2,ind_2)))/dcm1; 
+            fitted = ((trans(ind_1,1) + trans(ind_1,2))*(trans(1,ind_2) + trans(2,ind_2)))/dcm1;
             focus = trans(ind_1,ind_2);
             g2 = g2 + log(focus/fitted)*focus;
-        end;
-    end;
-end;
-g2 = g2*2; 
+        end
+    end
+end
+g2 = g2*2;
 bic = g2 - log(dcm1);
 end
diff --git a/matlab/convertAimCodeToInfo.m b/matlab/convertAimCodeToInfo.m
index 2aaf05be70e1f4c83fa808285489b187aa7683d6..2320c7f6521dee995ce72e67c2509558fe6d4a54 100644
--- a/matlab/convertAimCodeToInfo.m
+++ b/matlab/convertAimCodeToInfo.m
@@ -19,7 +19,7 @@ function [info] = convertAimCodeToInfo(aimCode)
 % OUTPUTS
 %   info        [integer]    Code to be used to print error in print_info.m
 
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -55,7 +55,7 @@ switch aimCode
     info = 161;
   case 62
     info = 162;
-  case 63; 
+  case 63
     info = 163;
   case 64
     info = 164;
diff --git a/matlab/convert_dyn_45_to_44.m b/matlab/convert_dyn_45_to_44.m
index ba3dbc671fc55d793993e98462b5b37ac448a13b..3f0561b5853f21a5c7aea52316009b82eab1562a 100644
--- a/matlab/convert_dyn_45_to_44.m
+++ b/matlab/convert_dyn_45_to_44.m
@@ -13,7 +13,7 @@ function oo_ = convert_dyn_45_to_44(M_, options_, oo_,bayestopt_)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2015-2016 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -40,7 +40,7 @@ if isfield(oo_,'PointForecast')
                 oo_.MeanForecast.(moment_names{moment_iter}).(var_names{var_iter})=...
                     [oo_.SmoothedVariables.(moment_names{moment_iter}).(var_names{var_iter})(:,end)*ones(M_.maximum_endo_lag,1)  oo_.MeanForecast.(moment_names{moment_iter}).(var_names{var_iter})];
                 oo_.PointForecast.(moment_names{moment_iter}).(var_names{var_iter})=...
-                    [oo_.SmoothedVariables.(moment_names{moment_iter}).(var_names{var_iter})(:,end)*ones(M_.maximum_endo_lag,1) oo_.PointForecast.(moment_names{moment_iter}).(var_names{var_iter})];                
+                    [oo_.SmoothedVariables.(moment_names{moment_iter}).(var_names{var_iter})(:,end)*ones(M_.maximum_endo_lag,1) oo_.PointForecast.(moment_names{moment_iter}).(var_names{var_iter})];
             else
                 oo_.MeanForecast.(moment_names{moment_iter}).(var_names{var_iter})=...
                     [oo_.SmoothedVariables.(moment_names{moment_iter}).(var_names{var_iter})(end)*ones(M_.maximum_endo_lag,1); oo_.MeanForecast.(moment_names{moment_iter}).(var_names{var_iter})];
@@ -106,7 +106,7 @@ if isfield(oo_,'UpdatedVariables')
     for ii=1:length(names)
         %make sure Bayesian fields are not affected
         if ~strcmp(names{ii},'Mean') && ~strcmp(names{ii},'Median') && ~strcmp(names{ii},'deciles') ...
-                && ~strcmp(names{ii},'Var') && ~strcmp(names{ii},'HPDinf') && ~strcmp(names{ii},'HPDsup') 
+                && ~strcmp(names{ii},'Var') && ~strcmp(names{ii},'HPDinf') && ~strcmp(names{ii},'HPDsup')
             current_var_index=find(strmatch(names{ii},deblank(M_.endo_names),'exact'));
             if  options_.loglinear == 1 %logged steady state must be used
                 constant_current_variable=log(oo_.dr.ys(current_var_index));
@@ -127,7 +127,7 @@ if isfield(oo_,'FilteredVariables')
     for ii=1:length(names)
         %make sure Bayesian fields are not affected
         if ~strcmp(names{ii},'Mean') && ~strcmp(names{ii},'Median') && ~strcmp(names{ii},'deciles') ...
-                && ~strcmp(names{ii},'Var') && ~strcmp(names{ii},'HPDinf') && ~strcmp(names{ii},'HPDsup') 
+                && ~strcmp(names{ii},'Var') && ~strcmp(names{ii},'HPDinf') && ~strcmp(names{ii},'HPDsup')
             current_var_index=find(strmatch(names{ii},deblank(M_.endo_names),'exact'));
             if  options_.loglinear == 1 %logged steady state must be used
                 constant_current_variable=log(oo_.dr.ys(current_var_index));
@@ -147,11 +147,11 @@ end
 if ~isempty(options_.nk) && options_.nk ~= 0 && ~isempty(bayestopt_)
     if ~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.pshape> 0) && options_.load_mh_file)) %no Bayesian estimation
         positions_in_decision_order=oo_.dr.inv_order_var(bayestopt_.smoother_var_list(bayestopt_.smoother_saved_var_list));
-            if  options_.loglinear == 1 %logged steady state must be used
-                constant_all_variables=log(oo_.dr.ys(bayestopt_.smoother_var_list(bayestopt_.smoother_saved_var_list)));
-            elseif options_.loglinear == 0 %unlogged steady state must be used
-                constant_all_variables=oo_.dr.ys(bayestopt_.smoother_var_list(bayestopt_.smoother_saved_var_list));
-            end
+        if  options_.loglinear == 1 %logged steady state must be used
+            constant_all_variables=log(oo_.dr.ys(bayestopt_.smoother_var_list(bayestopt_.smoother_saved_var_list)));
+        elseif options_.loglinear == 0 %unlogged steady state must be used
+            constant_all_variables=oo_.dr.ys(bayestopt_.smoother_var_list(bayestopt_.smoother_saved_var_list));
+        end
         if ~(options_.selected_variables_only && ~(options_.forecast > 0)) %happens only when selected_variables_only is not used
             oo_.FilteredVariablesKStepAhead(:,positions_in_decision_order,:)=oo_.FilteredVariablesKStepAhead-constant_all_variables;
             if ~isempty(PK) %get K-step ahead variances
@@ -182,11 +182,11 @@ end
 
 %Deal with OSR
 if ~isempty(M_.osr.variable_weights)
-   evalin('base','optim_weights_=M_.osr.variable_weights')
+    evalin('base','optim_weights_=M_.osr.variable_weights')
 end
 if ~isempty(M_.osr.variable_indices)
-   evalin('base','obj_var_=M_.osr.variable_indices')
+    evalin('base','obj_var_=M_.osr.variable_indices')
 end
 if ~isempty(M_.osr.param_names)
-   evalin('base','osr_params_=char(M_.osr.param_names)')
+    evalin('base','osr_params_=char(M_.osr.param_names)')
 end
diff --git a/matlab/convert_oo_.m b/matlab/convert_oo_.m
index ef5f72280d148177844f706ab6ad48184ad80ddc..914cc0adbe36d916f8ecedfb3766df0d248a1dbb 100644
--- a/matlab/convert_oo_.m
+++ b/matlab/convert_oo_.m
@@ -15,7 +15,7 @@ function oo_ = convert_oo_(M_, options_, oo_, from_ver, to_ver)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -63,7 +63,7 @@ else
 end
 
 if strcmp(from_ver, to_ver)
-    return;
+    return
 end
 
 if ver_greater_than(to_ver, from_ver)
@@ -81,5 +81,5 @@ else
 end
 
 eval(['oo_ = convert_dyn_' strrep(new_from_ver, '.', '') '_to_' ...
-                           strrep(to_ver, '.', '') '(M_, options_, oo_);']);
+      strrep(to_ver, '.', '') '(M_, options_, oo_);']);
 end
diff --git a/matlab/correlation_mc_analysis.m b/matlab/correlation_mc_analysis.m
index 6eba19485631e6456db51df31754340bd6203c4b..7b3d63848a162b9f21bedf92333141cfe32444ee 100644
--- a/matlab/correlation_mc_analysis.m
+++ b/matlab/correlation_mc_analysis.m
@@ -2,7 +2,7 @@ function oo_ = correlation_mc_analysis(SampleSize,type,dname,fname,vartan,nvar,v
 % This function analyses the (posterior or prior) distribution of the
 % endogenous variables correlation function.
 
-% Copyright (C) 2008-2013 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -137,7 +137,7 @@ end
 
 function oo_ = fill_output_structure(var1,var2,type,oo_,moment,lag,result)
 switch moment
-  case {'Mean','Median','Variance','HPDinf','HPDsup'} 
+  case {'Mean','Median','Variance','HPDinf','HPDsup'}
     oo_.([type,  'TheoreticalMoments']).dsge.correlation.(moment).(var1).(var2)(lag,1) = result;
   case {'deciles','density'}
     oo_.([type, 'TheoreticalMoments']).dsge.correlation.(moment).(var1).(var2)(lag,1) = {result};
diff --git a/matlab/cosn.m b/matlab/cosn.m
index 8fcf7fb79f7c5acb80918bc173f0611cbb883896..b64245e7b8ee53ae494129b249d9b24b49f74fdd 100644
--- a/matlab/cosn.m
+++ b/matlab/cosn.m
@@ -1,4 +1,4 @@
-function [co, b, yhat] = cosn(H);
+function [co, b, yhat] = cosn(H)
 
 % function co = cosn(H);
 % computes the cosine of the angle between the H(:,1) and its
@@ -7,7 +7,7 @@ function [co, b, yhat] = cosn(H);
 % Not the same as multiple correlation coefficient since the means are not
 % zero
 %
-% Copyright (C) 2008-2012 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -28,15 +28,12 @@ y = H(:,1);
 X = H(:,2:end);
 
 b=(X\y);
-if any(isnan(b)) || any(isinf(b)),
+if any(isnan(b)) || any(isinf(b))
     b=0;
 end
 yhat =  X*b;
-if rank(yhat),
+if rank(yhat)
     co = abs(y'*yhat/sqrt((y'*y)*(yhat'*yhat)));
 else
     co=0;
 end
-
-
-
diff --git a/matlab/covariance_mc_analysis.m b/matlab/covariance_mc_analysis.m
index 60753407b41dead7f5fad6daaa99137a9a713938..ebf3602a224819d6c9de8886b6486ec30bdbef32 100644
--- a/matlab/covariance_mc_analysis.m
+++ b/matlab/covariance_mc_analysis.m
@@ -1,7 +1,7 @@
 function oo_ = covariance_mc_analysis(NumberOfSimulations,type,dname,fname,vartan,nvar,var1,var2,mh_conf_sig,oo_,options_)
 % This function analyses the (posterior or prior) distribution of the
 % endogenous variables' covariance matrix.
-% 
+%
 % INPUTS
 %   NumberOfSimulations     [integer]           scalar, number of simulations.
 %   type                    [string]            'prior' or 'posterior'
@@ -14,12 +14,12 @@ function oo_ = covariance_mc_analysis(NumberOfSimulations,type,dname,fname,varta
 %   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.
-%   options_                [structure]         Dynare options structure 
+%   options_                [structure]         Dynare options structure
 %
 % OUTPUTS
 %   oo_                     [structure]        Dynare structure where the results are saved.
 
-% Copyright (C) 2008-2015 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -64,7 +64,7 @@ var1=deblank(var1);
 var2=deblank(var2);
 
 if isfield(oo_,[ TYPE 'TheoreticalMoments'])
-    temporary_structure = oo_.([TYPE, 'TheoreticalMoments']); 
+    temporary_structure = oo_.([TYPE, 'TheoreticalMoments']);
     if isfield(temporary_structure,'dsge')
         temporary_structure = oo_.([TYPE, 'TheoreticalMoments']).dsge;
         if isfield(temporary_structure,'covariance')
@@ -104,17 +104,17 @@ for file = 1:length(ListOfFiles)
         temp=Covariance_matrix(:,cov_pos)./(sqrt(Covariance_matrix(:,var_pos_1)).*sqrt(Covariance_matrix(:,var_pos_2)));
         temp(Covariance_matrix(:,cov_pos)==0)=0; %filter out 0 correlations that would result in 0/0
         tmp_corr_mat(i1:i2)=temp;
-    end    
+    end
     i1 = i2+1;
 end
 
 if options_.estimation.moments_posterior_density.indicator
     [p_mean, p_median, p_var, hpd_interval, p_deciles, density] = ...
-            posterior_moments(tmp,1,mh_conf_sig);
+        posterior_moments(tmp,1,mh_conf_sig);
     oo_.([TYPE, 'TheoreticalMoments']).dsge.covariance.density.(var1).(var2) = density;
 else
     [p_mean, p_median, p_var, hpd_interval, p_deciles] = ...
-                    posterior_moments(tmp,0,mh_conf_sig);
+        posterior_moments(tmp,0,mh_conf_sig);
 end
 oo_.([TYPE, 'TheoreticalMoments']).dsge.covariance.Mean.(var1).(var2) = p_mean;
 oo_.([TYPE, 'TheoreticalMoments']).dsge.covariance.Median.(var1).(var2) = p_median;
diff --git a/matlab/csolve.m b/matlab/csolve.m
index 3af47243ebc107c391d37c31ac93c1fa7dc8055b..e45a4b2ff82cd70f8bdaf862943778f635257551 100644
--- a/matlab/csolve.m
+++ b/matlab/csolve.m
@@ -12,7 +12,7 @@ function [x,rc] = csolve(FUN,x,gradfun,crit,itmax,varargin)
 %           the equation is solved.
 % itmax:    the solver stops when this number of iterations is reached, with rc=4
 % varargin: in this position the user can place any number of additional arguments, all
-%           of which are passed on to FUN and gradfun (when it is non-empty) as a list of 
+%           of which are passed on to FUN and gradfun (when it is non-empty) as a list of
 %           arguments following x.
 % rc:       0 means normal solution, 1 and 3 mean no solution despite extremely fine adjustments
 %           in step length (very likely a numerical problem, or a discontinuity). 4 means itmax
@@ -22,7 +22,7 @@ function [x,rc] = csolve(FUN,x,gradfun,crit,itmax,varargin)
 % http://sims.princeton.edu/yftp/optimize/mfiles/csolve.m
 
 % Copyright (C) 1993-2007 Christopher Sims
-% Copyright (C) 2007-2011 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -60,7 +60,7 @@ if isempty(varargin)
     f0=feval(FUN,x);
 else
     f0=feval(FUN,x,varargin{:});
-end   
+end
 af0=sum(abs(f0));
 af00=af0;
 itct=0;
@@ -122,7 +122,7 @@ while ~done
                 factor=factor^.6;
                 shrink=1;
             end
-            if abs(lambda*(1-factor))*dxSize > .1*delta;
+            if abs(lambda*(1-factor))*dxSize > .1*delta
                 lambda = factor*lambda;
             elseif (lambda > 0) && (factor==.6) %i.e., we've only been shrinking
                 lambda=-.3;
@@ -162,7 +162,7 @@ while ~done
     if itct >= itmax
         done=1;
         rc=4;
-    elseif af0<crit;
+    elseif af0<crit
         done=1;
         rc=0;
     end
diff --git a/matlab/cubature_with_gaussian_weight.m b/matlab/cubature_with_gaussian_weight.m
index ecc69230dd75847af8841ef993767f254b52f8bf..da93fbe55829d14e83ba4569fbbdf5aa874da119 100644
--- a/matlab/cubature_with_gaussian_weight.m
+++ b/matlab/cubature_with_gaussian_weight.m
@@ -29,12 +29,12 @@ function [nodes, weights] = cubature_with_gaussian_weight(d,n,method)
 %! The routine returns nodes and associated weights to compute a multivariate integral of the form:
 %!
 %! \int_D f(x)*\exp(-<x,x>) dx
-%! 
-%! 
+%!
+%!
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2012-2013 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -52,7 +52,7 @@ function [nodes, weights] = cubature_with_gaussian_weight(d,n,method)
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 % AUTHOR(S) stephane DOT adjemian AT univ DASH lemans DOT fr
-    
+
 % Set default.
 if nargin<3 || isempty(method)
     method = 'Stroud';
@@ -90,7 +90,7 @@ if strcmp(method,'Stroud') &&  isequal(n,5)
     nodes = zeros(d,m);
     weights = zeros(m,1);
     % Set the weight for the first node (0)
-    weights(1) = A; 
+    weights(1) = A;
     skip = 1;
     % Set the remaining nodes and associated weights.
     nodes(:,skip+(1:d)) = r*eye(d);
@@ -117,20 +117,20 @@ end
 
 
 function v = e(n,i)
-    v = zeros(n,1);
-    v(i) = 1;
-    
+v = zeros(n,1);
+v(i) = 1;
+
 function m = ee(n,i,j)
-    m = zeros(n,4);
-    m(:,1) =  e(n,i)+e(n,j);
-    m(:,2) =  e(n,i)-e(n,j);
-    m(:,3) = -m(:,2);
-    m(:,4) = -m(:,1);
-    
+m = zeros(n,4);
+m(:,1) =  e(n,i)+e(n,j);
+m(:,2) =  e(n,i)-e(n,j);
+m(:,3) = -m(:,2);
+m(:,4) = -m(:,1);
+
 %@test:1
 %$ % Set problem
 %$ d = 4;
-%$ 
+%$
 %$ t = zeros(5,1);
 %$
 %$ % Call the tested routine
@@ -289,7 +289,7 @@ function m = ee(n,i,j)
 %@test:5
 %$ % Set problem
 %$ d = 5;
-%$ 
+%$
 %$ t = zeros(6,1);
 %$
 %$ % Call the tested routine
@@ -333,7 +333,7 @@ function m = ee(n,i,j)
 %@test:6
 %$ % Set problem
 %$ d = 3;
-%$ 
+%$
 %$ t = zeros(4,1);
 %$
 %$ % Call the tested routine
diff --git a/matlab/cycle_reduction.m b/matlab/cycle_reduction.m
index 019c39a190dc6e25d8455e4f678441881fb92b84..be8fdb3e8fd78b063e77a84993d8aee75cd3c036 100644
--- a/matlab/cycle_reduction.m
+++ b/matlab/cycle_reduction.m
@@ -43,7 +43,7 @@ function [X, info] = cycle_reduction(A0, A1, A2, cvg_tol, ch) % --*-- Unitary te
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -76,7 +76,7 @@ id0 = 1:n;
 id2 = id0+n;
 
 cont = 1;
-while cont 
+while cont
     tmp = ([A0; A2]/A1)*[A0 A2];
     A1 = A1 - tmp(id0,id2) - tmp(id2,id0);
     A0 = -tmp(id0,id0);
@@ -97,7 +97,7 @@ while cont
             info(2) = log(norm(A1,1));
         end
         return
-    end        
+    end
     it = it + 1;
 end
 
@@ -125,8 +125,8 @@ end
 %$
 %$ % Solve the equation with the cycle reduction algorithm
 %$ try
-%$     t=cputime; X1 = cycle_reduction(C,B,A,1e-7); elapsedtime = cputime-t;
-%$     disp(['cputime for cycle reduction algorithm is: ' num2str(elapsedtime) ' (n=' int2str(n) ').'])
+%$     tic; X1 = cycle_reduction(C,B,A,1e-7); elapsedtime = toc;
+%$     disp(['Elapsed time for cycle reduction algorithm is: ' num2str(elapsedtime) ' (n=' int2str(n) ').'])
 %$     t(1) = 1;
 %$ catch
 %$     % nothing to do here.
@@ -134,8 +134,8 @@ end
 %$
 %$ % Solve the equation with the logarithmic reduction algorithm
 %$ try
-%$     t=cputime; X2 = logarithmic_reduction(A,B,C,1e-16,100); elapsedtime = cputime-t;
-%$     disp(['cputime for logarithmic reduction algorithm is: ' num2str(elapsedtime) ' (n=' int2str(n) ').'])
+%$     tic; X2 = logarithmic_reduction(A,B,C,1e-16,100); elapsedtime = toc;
+%$     disp(['Elapsed time for logarithmic reduction algorithm is: ' num2str(elapsedtime) ' (n=' int2str(n) ').'])
 %$     t(2) = 1;
 %$ catch
 %$     % nothing to do here.
diff --git a/matlab/datatomfile.m b/matlab/datatomfile.m
index 4c7abec23507e94c881ae07681d37834ec78228c..76928c77fa82e3447ebbf9e3713b786453dc1b3d 100644
--- a/matlab/datatomfile.m
+++ b/matlab/datatomfile.m
@@ -1,20 +1,23 @@
-function datatomfile (s,var_list, names)
-% function datatomfile (s,var_list)
-% This optional command saves the simulation results in a text file. The name of each
-% variable preceeds the corresponding results. This command must follow SIMUL.
-% 
+function datatomfile (s, var_list, names)
+
+% This command saves the simulation results in a text file. The name of each
+% variable preceeds the corresponding results. This command must follow SIMUL
+% or STOCH_SIMUL commands.
+%
 % INPUTS
-%    s:              data file name
-%    var_list:       vector of selected endogenous variables
-%    names:          vector of strings (alternative names for the endogenous variables in the data file)
+%  - s:              data file name
+%  - var_list:       vector of selected endogenous variables
+%  - names:          vector of strings (alternative names for the endogenous variables in the data file)
 %
 % OUTPUTS
-%    none
+% none
 %
-% SPECIAL REQUIREMENTS
-%    none
+% REMARKS
+% Only the first argument is mandatory. If only one input argument is
+% provided, all the variables as defined in M_.endo_names will be saved in
+% the generated m file.
 
-% Copyright (C) 2001-2016 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -33,7 +36,7 @@ function datatomfile (s,var_list, names)
 
 global M_ oo_
 
-% Open the data file. 
+% Open the data file.
 sm=[s,'.m'];
 fid=fopen(sm,'w') ;
 
@@ -62,8 +65,8 @@ for i=1:n
     end
 end
 stack = dbstack;
-    fprintf(fid,'%% Dataset generated by %s.\n',stack(2).file);
-    fprintf(fid,['%% ' datestr(now,0) '\n']);
+fprintf(fid,'%% Dataset generated by %s.\n',stack(2).file);
+fprintf(fid,['%% ' datestr(now,0) '\n']);
 % Save the selected data.
 for i = 1:n
     fprintf(fid,[strtrim(names(i,:)), ' = ['],'\n') ;
@@ -75,4 +78,3 @@ end
 
 % Close the data file.
 fclose(fid) ;
-
diff --git a/matlab/dcompare.m b/matlab/dcompare.m
index 6efc5ae2722987d8fa854ef82cf616cda8adb318..d50541f121845620c4914398dc249e29bf9a8afb 100644
--- a/matlab/dcompare.m
+++ b/matlab/dcompare.m
@@ -1,6 +1,6 @@
 function dcompare(s1)
 
-% Copyright (C) 2001-2011 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -52,5 +52,3 @@ z = mean(mean(abs(x(j,i)-y(j,i)))) ;
 disp (['The mean absolute difference between set ' s1(1,:) 'and set ' s1(2,:)]) ;
 disp (['is : ' num2str(z)]) ;
 return ;
-
-
diff --git a/matlab/delete_mh_history_files.m b/matlab/delete_mh_history_files.m
index 64b720ec9ba9f7dd666f2f272b93de9df0240c61..084f3e783da60f0c4a7fac3f75218bcc20c31f70 100644
--- a/matlab/delete_mh_history_files.m
+++ b/matlab/delete_mh_history_files.m
@@ -1,6 +1,6 @@
 function info = delete_mh_history_files(MetropolisFolder, ModelName)
-    
-% Copyright (C) 2013 Dynare Team
+
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/discretionary_policy.m b/matlab/discretionary_policy.m
index d12af30bdae09eff22e58adee05a2fe86a1c3271..e021e33759a40c950dd3eb6590808d86affe4cc3 100644
--- a/matlab/discretionary_policy.m
+++ b/matlab/discretionary_policy.m
@@ -1,6 +1,6 @@
 function info = discretionary_policy(var_list)
 
-% Copyright (C) 2007-2011 Dynare Team
+% Copyright (C) 2007-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/discretionary_policy_1.m b/matlab/discretionary_policy_1.m
index 931d3b596f634a87d3814eca5c1bfc622cc91587..8f8bf6b8a290b60bb34f6e63bb1ea55faaa1b650 100644
--- a/matlab/discretionary_policy_1.m
+++ b/matlab/discretionary_policy_1.m
@@ -1,6 +1,6 @@
 function [dr,ys,info]=discretionary_policy_1(oo_,Instruments)
 
-% Copyright (C) 2007-2016 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -39,7 +39,7 @@ if isfield(M_,'orig_model')
     M_.maximum_lag = orig_model.maximum_lag;
     M_.maximum_endo_lag = orig_model.maximum_endo_lag;
 else
-	M_.orig_model = M_;
+    M_.orig_model = M_;
 end
 
 beta = get_optimal_policy_discount_factor(M_.params,M_.param_names);
@@ -53,10 +53,10 @@ if isfield(M_,'orig_model')
     MaxLead = orig_model.maximum_lead;
     MaxLag = orig_model.maximum_lag;
 else
-	endo_names = M_.endo_names;
-	endo_nbr = M_.endo_nbr;
-	MaxLag=M_.maximum_lag;
-	MaxLead=M_.maximum_lead;
+    endo_names = M_.endo_names;
+    endo_nbr = M_.endo_nbr;
+    MaxLag=M_.maximum_lag;
+    MaxLead=M_.maximum_lead;
     lead_lag_incidence = M_.lead_lag_incidence;
 end
 
@@ -64,7 +64,7 @@ end
 if options_.steadystate_flag
     % explicit steady state file
     [junk,M_.params,info] = evaluate_steady_state_file(oo_.steady_state,[oo_.exo_steady_state; oo_.exo_det_steady_state],M_, ...
-                                                   options_,0);
+                                                      options_,0);
 end
 [U,Uy,W] = feval([M_.fname,'_objective_static'],zeros(endo_nbr,1),[], M_.params);
 if any(any(Uy~=0))
@@ -96,32 +96,34 @@ eq_nbr= size(jacobia_,1);
 instr_nbr=endo_nbr-eq_nbr;
 
 if instr_nbr==0
-    error('discretionary_policy:: There are no available instruments, because the model has as many equations as variables.') 
+    error('discretionary_policy:: There are no available instruments, because the model has as many equations as variables.')
+end
+if size(Instruments,1)< instr_nbr
+    error('discretionary_policy:: There are fewer declared instruments than omitted equations.')
+elseif size(Instruments,1)> instr_nbr
+    error('discretionary_policy:: There are more declared instruments than omitted equations.')    
 end
-if size(Instruments,1)~= instr_nbr
-   error('discretionary_policy:: There are more declared instruments than omitted equations.') 
-end 
 
 instr_id=nan(instr_nbr,1);
 for j=1:instr_nbr
-	vj=deblank(Instruments(j,:));
-	vj_id=strmatch(vj,endo_names,'exact');
-	if ~isempty(vj_id)
-		instr_id(j)=vj_id;
-	else
-		error([mfilename,':: instrument ',vj,' not found'])
-	end
+    vj=deblank(Instruments(j,:));
+    vj_id=strmatch(vj,endo_names,'exact');
+    if ~isempty(vj_id)
+        instr_id(j)=vj_id;
+    else
+        error([mfilename,':: instrument ',vj,' not found'])
+    end
 end
 
 Indices={'lag','0','lead'};
 iter=1;
 for j=1:numel(Indices)
     eval(['A',Indices{j},'=zeros(eq_nbr,endo_nbr);'])
-	if strcmp(Indices{j},'0')||(strcmp(Indices{j},'lag') && MaxLag)||(strcmp(Indices{j},'lead') && MaxLead)
-	    [junk,row,col]=find(lead_lag_incidence(iter,:));
-	    eval(['A',Indices{j},'(:,row)=jacobia_(:,col);'])
-		iter=iter+1;
-	end
+    if strcmp(Indices{j},'0')||(strcmp(Indices{j},'lag') && MaxLag)||(strcmp(Indices{j},'lead') && MaxLead)
+        [junk,row,col]=find(lead_lag_incidence(iter,:));
+        eval(['A',Indices{j},'(:,row)=jacobia_(:,col);'])
+        iter=iter+1;
+    end
 end
 B=jacobia_(:,nnz(iyv)+1:end);
 
@@ -131,17 +133,17 @@ solve_maxit = options_.dp.maxit;
 discretion_tol = options_.discretionary_tol;
 
 if ~isempty(Hold)
-	[H,G,info]=discretionary_policy_engine(Alag,A0,Alead,B,W,instr_id,beta,solve_maxit,discretion_tol,qz_criterium,Hold);
+    [H,G,info]=discretionary_policy_engine(Alag,A0,Alead,B,W,instr_id,beta,solve_maxit,discretion_tol,qz_criterium,Hold);
 else
-	[H,G,info]=discretionary_policy_engine(Alag,A0,Alead,B,W,instr_id,beta,solve_maxit,discretion_tol,qz_criterium);
+    [H,G,info]=discretionary_policy_engine(Alag,A0,Alead,B,W,instr_id,beta,solve_maxit,discretion_tol,qz_criterium);
 end
 
 if info
     dr=[];
     return
 else
-	Hold=H; %save previous solution
-	% Hold=[]; use this line if persistent command is not used.
+    Hold=H; %save previous solution
+            % Hold=[]; use this line if persistent command is not used.
 end
 % set the state
 dr=oo_.dr;
@@ -159,7 +161,7 @@ dr.ys=ys; % <--- dr.ys =zeros(NewEndo_nbr,1);
 
 function ys=NondistortionarySteadyState(M_)
 if exist([M_.fname,'_steadystate.m'],'file')
-	eval(['ys=',M_.fname,'_steadystate.m;'])
+    eval(['ys=',M_.fname,'_steadystate.m;'])
 else
-	ys=zeros(M_.endo_nbr,1);
+    ys=zeros(M_.endo_nbr,1);
 end
diff --git a/matlab/discretionary_policy_engine.m b/matlab/discretionary_policy_engine.m
index 154b66426e19f42b90f33e12b348dae1b53f983b..05c781ae4abccd0cbabfcf55b979f45f8d829abc 100644
--- a/matlab/discretionary_policy_engine.m
+++ b/matlab/discretionary_policy_engine.m
@@ -1,23 +1,23 @@
 function [H,G,retcode]=discretionary_policy_engine(AAlag,AA0,AAlead,BB,bigw,instr_id,beta,solve_maxit,discretion_tol,qz_criterium,H00,verbose)
 
 % Solves the discretionary problem for a model of the form:
-% 
+%
 %   Loss=E_0 sum_{t=0}^{\infty} beta^t [y_t'*W*y+x_t'*Q*x_t]
 %   subject to
 %   AAlag*yy_{t-1}+AA0*yy_t+AAlead*yy_{t+1}+BB*e=0
-% 
+%
 % with W the weight on the variables in vector y_t.
-% 
+%
 % The solution takes the form
 %   y_t=H*y_{t-1}+G*e_t
 % where H=[H1;F1] and G=[H2;F2].
-% 
+%
 % We use the Dennis (2007, Macroeconomic Dynamics) algorithm and so we need
 % to re-write the model in the form
 %  A0*y_t=A1*y_{t-1}+A2*y_{t+1}+A3*x_t+A4*x_{t+1}+A5*e_t, with W the
 % weight on the y_t vector and Q the weight on the x_t vector of
 % instruments.
-% 
+%
 % Inputs:
 %   AAlag               [double]    matrix of coefficients on lagged
 %                                   variables
@@ -28,7 +28,7 @@ function [H,G,retcode]=discretionary_policy_engine(AAlag,AA0,AAlead,BB,bigw,inst
 %   BB                  [double]    matrix of coefficients on
 %                                   shocks
 %   bigw                [double]    matrix of coefficients on variables in
-%                                   loss/objective function; stacks [W and Q]                                   
+%                                   loss/objective function; stacks [W and Q]
 %   instr_id            [double]    location vector of the instruments in the yy_t vector.
 %   beta                [scalar]    planner discount factor
 %   solve_maxit         [scalar]    maximum number of iterations
@@ -41,14 +41,14 @@ function [H,G,retcode]=discretionary_policy_engine(AAlag,AA0,AAlead,BB,bigw,inst
 %   H                   [double]    (endo_nbr*endo_nbr) solution matrix for endogenous
 %                                   variables, stacks [H1 and H1]
 %   G                   [double]    (endo_nbr*exo_nbr) solution matrix for shocks, stacks [H2 and F2]
-%                                   
+%
 %   retcode             [scalar]    return code
 %
 % Algorithm:
 %  Dennis, Richard (2007): Optimal policy in rational expectations models: new solution algorithms,
-%       Macroeconomic Dynamics, 11, 31�55.
+%       Macroeconomic Dynamics, 11, 31–55.
 
-% Copyright (C) 2007-2015 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -121,10 +121,10 @@ while 1
     end
     D=A0-A2*H1-A4*F1; %equation (20)
     Dinv=inv(D);
-    A3DPD=A3'*Dinv'*P*Dinv; 
+    A3DPD=A3'*Dinv'*P*Dinv;
     F1=-(Q+A3DPD*A3)\(A3DPD*A1); %component of (26)
     H1=Dinv*(A1+A3*F1); %component of (27)
-    
+
     [rcode,NQ]=CheckConvergence([H1;F1]-[H10;F10],iter,solve_maxit,discretion_tol);
     if rcode
         break
@@ -174,7 +174,7 @@ else
     H(instr_id,endo_augm_id)=F1;
     G(endo_augm_id,:)=H2;
     G(instr_id,:)=F2;
-    
+
     % Account for auxilliary variables
     H(:,instr_id(aux))=H(:,end-(AuxiliaryVariables_nbr-1:-1:0));
     H=H(1:endo_nbr,1:endo_nbr);
@@ -239,11 +239,11 @@ function v= SylvesterDoubling (d,g,h,tol,maxit)
 %   to solve the  Sylvester equation v  = d + g v h
 
 v = d;
-for i =1:maxit,
+for i =1:maxit
     vadd = g*v*h;
     v = v+vadd;
     if norm (vadd,1) <= (tol*norm(v,1))
-        break;
+        break
     end
     g = g*g;
     h = h*h;
@@ -253,7 +253,7 @@ end
 
 function v = SylvesterHessenbergSchur(d,g,h)
 %
-% DSYLHS  Solves a discrete time sylvester equation	using the
+% DSYLHS  Solves a discrete time sylvester equation     using the
 % Hessenberg-Schur algorithm
 %
 % v = DSYLHS(g,d,h) computes the matrix v that satisfies the
@@ -295,13 +295,13 @@ temp = [];
 
 %First handle the i = 1 case outside the loop
 
-if i< n,
-    if abs(h(i+1,i)) < tol,
+if i< n
+    if abs(h(i+1,i)) < tol
         v(:,i)= (w - g*h(i,i))\d(:,i);
         i = i+1;
     else
         A = [w-g*h(i,i)     (-g*h(i+1,i));...
-            -g*h(i,i+1)    w-g*h(i+1,i+1)];
+             -g*h(i,i+1)    w-g*h(i+1,i+1)];
         C = [d(:,i); d(:,i+1)];
         X = A\C;
         v(:,i) = X(1:m,:);
@@ -312,17 +312,17 @@ end
 
 %Handle the rest of the matrix with the possible exception of i=n
 
-while i<n,
+while i<n
     b= i-1;
     temp = [temp g*v(:,size(temp,2)+1:b)]; %#ok<AGROW>
-    if abs(h(i+1,i)) < tol,
+    if abs(h(i+1,i)) < tol
         v(:,i) = (w - g*h(i,i))\(d(:,i) + temp*h(1:b,i));
         i = i+1;
     else
         A = [w - g*h(i,i)    (-g*h(i+1,i));   ...
-            -g*h(i,i+1)    w - g*h(i+1,i+1)];
+             -g*h(i,i+1)    w - g*h(i+1,i+1)];
         C = [d(:,i) + temp*h(1:b,i);         ...
-            d(:,i+1) + temp*h(1:b,i+1)];
+             d(:,i+1) + temp*h(1:b,i+1)];
         X = A\C;
         v(:,i) = X(1:m,:);
         v(:,i+1) = X(m+1:2*m, :);
@@ -332,7 +332,7 @@ end
 
 %Handle the i = n case if i=n was not in a 2-2 block
 
-if i==n,
+if i==n
     b = i-1;
     temp = [temp g*v(:,size(temp,2)+1:b)];
     v(:,i) = (w-g*h(i,i))\(d(:,i) + temp*h(1:b,i));
diff --git a/matlab/disp_dr.m b/matlab/disp_dr.m
index a23c8f4be221500f2d154bb9a7ed09538d3f317a..d5fcb84fbb5be0b529403ae8a6c02014a2d1e400 100644
--- a/matlab/disp_dr.m
+++ b/matlab/disp_dr.m
@@ -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-2015 Dynare Team
+%
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -27,6 +27,11 @@ function disp_dr(dr,order,var_list)
 
 global M_ options_
 
+if M_.hessian_eq_zero && order~=1
+    order = 1;
+    warning('disp_dr: using order = 1 because Hessian is equal to zero');
+end
+    
 nx =size(dr.ghx,2);
 nu =size(dr.ghu,2);
 if options_.block
@@ -36,7 +41,7 @@ else
     k = find(dr.kstate(:,2) <= M_.maximum_lag+1);
     klag = dr.kstate(k,[1 2]);
     k1 = dr.order_var;
-end;
+end
 
 if size(var_list,1) == 0
     var_list = M_.endo_names(1:M_.orig_endo_nbr, :);
@@ -80,7 +85,7 @@ var_name_width=max([max(size(deblank(M_.endo_names(k1(ivar),:)),2)),max(size(deb
 
 %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    
+    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
@@ -90,7 +95,7 @@ label_format  = sprintf('%%-%ds',var_name_width);
 %% start displayimg
 disp('POLICY AND TRANSITION FUNCTIONS')
 % variable names
-str = char(32*ones(1,var_name_width)); 
+str = char(32*ones(1,var_name_width));
 for i=1:nvar
     str = [str sprintf(header_label_format,deblank(M_.endo_names(k1(ivar(i)),:)))];
 end
@@ -232,7 +237,7 @@ for i = 1:length(M_.aux_vars)
     if M_.aux_vars(i).endo_index == aux_index
         switch M_.aux_vars(i).type
           case 0
-            str = sprintf('%s(%d)',deblank(M_.endo_names(aux_index,:)),aux_lead_lag);                
+            str = sprintf('%s(%d)',deblank(M_.endo_names(aux_index,:)),aux_lead_lag);
             return
           case 1
             orig_name = deblank(M_.endo_names(M_.aux_vars(i).orig_index, :));
@@ -256,10 +261,10 @@ 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
+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/disp_identification.m b/matlab/disp_identification.m
index 5bdb3e8e558122acf7b7b5f7cfcb6848ed9efccc..b8a3421d57688352a53d2c9dd6195a7e69bceaa2 100644
--- a/matlab/disp_identification.m
+++ b/matlab/disp_identification.m
@@ -1,6 +1,6 @@
 function disp_identification(pdraws, idemodel, idemoments, name, advanced)
 
-% Copyright (C) 2008-2012 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -19,7 +19,7 @@ function disp_identification(pdraws, idemodel, idemoments, name, advanced)
 
 global options_
 
-if nargin < 5 || isempty(advanced),
+if nargin < 5 || isempty(advanced)
     advanced=0;
 end
 
@@ -84,16 +84,16 @@ end
 
 disp(['  ']),
 
-if any(idemodel.ino),
+if any(idemodel.ino)
     disp('WARNING !!!')
-    if SampleSize>1,
+    if SampleSize>1
         disp(['The rank of H (model) is deficient for ', num2str(length(find(idemodel.ino))),' out of ',int2str(SampleSize),' MC runs!'  ]),
     else
         disp(['The rank of H (model) is deficient!'  ]),
     end
     skipline()
-    for j=1:npar,
-        if any(idemodel.ind0(:,j)==0),
+    for j=1:npar
+        if any(idemodel.ind0(:,j)==0)
             pno = 100*length(find(idemodel.ind0(:,j)==0))/SampleSize;
             if SampleSize>1
                 disp(['    ',name{j},' is not identified in the model for ',num2str(pno),'% of MC runs!' ])
@@ -107,9 +107,9 @@ if any(idemodel.ino),
     jmap_pair=dyn_unvech(1:npairs);
     jstore=[];
     skipline()
-    for j=1:npairs,
+    for j=1:npairs
         iweak = length(find(idemodel.jweak_pair(:,j)));
-        if iweak,
+        if iweak
             [jx,jy]=find(jmap_pair==j);
             jstore=[jstore jx(1) jy(1)];
             if SampleSize > 1
@@ -118,12 +118,12 @@ if any(idemodel.ino),
                 disp(['    [',name{jx(1)},',',name{jy(1)},'] are PAIRWISE collinear (with tol = 1.e-10) !' ])
             end
         end
-        
+
     end
     skipline()
-    for j=1:npar,
+    for j=1:npar
         iweak = length(find(idemodel.jweak(:,j)));
-        if iweak && ~ismember(j,jstore),
+        if iweak && ~ismember(j,jstore)
             %         disp('WARNING !!!')
             %         disp(['Model derivatives of parameter ',name{j},' are multi-collinear (with tol = 1.e-10) for ',num2str(iweak/SampleSize*100),'% of MC runs!' ])
             if SampleSize>1
@@ -133,23 +133,23 @@ if any(idemodel.ino),
             end
         end
     end
-%         if npar>(j+1),
-%             [ipair, jpair] = find(squeeze(idemodel.Pco(j,j+1:end,:))'>(1-1.e-10));
-%         else
-%             [ipair, jpair] = find(squeeze(idemodel.Pco(j,j+1:end,:))>(1-1.e-10));
-%         end
-%         if ~isempty(jpair),
-%             for jx=j+1:npar,
-%                 ixp = find(jx==(jpair+j));
-%                 if ~isempty(ixp)
-%                     if SampleSize > 1,
-%                         disp(['    [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10) for ',num2str(length(ixp)/SampleSize*100),'% of MC runs!' ])
-%                     else
-%                         disp(['    [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10)!' ])
-%                     end
-%                 end
-%             end
-%         end
+    %         if npar>(j+1),
+    %             [ipair, jpair] = find(squeeze(idemodel.Pco(j,j+1:end,:))'>(1-1.e-10));
+    %         else
+    %             [ipair, jpair] = find(squeeze(idemodel.Pco(j,j+1:end,:))>(1-1.e-10));
+    %         end
+    %         if ~isempty(jpair),
+    %             for jx=j+1:npar,
+    %                 ixp = find(jx==(jpair+j));
+    %                 if ~isempty(ixp)
+    %                     if SampleSize > 1,
+    %                         disp(['    [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10) for ',num2str(length(ixp)/SampleSize*100),'% of MC runs!' ])
+    %                     else
+    %                         disp(['    [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10)!' ])
+    %                     end
+    %                 end
+    %             end
+    %         end
 end
 
 if ~any(idemodel.ino) && ~any(any(idemodel.ind0==0))
@@ -157,24 +157,24 @@ if ~any(idemodel.ino) && ~any(any(idemodel.ind0==0))
     skipline()
 end
 
-if any(idemoments.ino),
+if any(idemoments.ino)
     skipline()
     disp('WARNING !!!')
-    if SampleSize > 1,
+    if SampleSize > 1
         disp(['The rank of J (moments) is deficient for ', num2str(length(find(idemoments.ino))),' out of ',int2str(SampleSize),' MC runs!'  ]),
     else
         disp(['The rank of J (moments) is deficient!'  ]),
     end
     %     disp('WARNING !!!')
     %     disp(['The rank of J (moments) is deficient for ', num2str(length(find(idemoments.ino))/SampleSize*100),'% of MC runs!'  ]),
-%     indno=[];
-%     for j=1:SampleSize, indno=[indno;idemoments.indno{j}]; end
-%     freqno = mean(indno)*100;
-%     ifreq=find(freqno);
+    %     indno=[];
+    %     for j=1:SampleSize, indno=[indno;idemoments.indno{j}]; end
+    %     freqno = mean(indno)*100;
+    %     ifreq=find(freqno);
     %     disp('MOMENT RANK FAILURE DUE TO COLLINEARITY OF PARAMETERS:');
     skipline()
-    for j=1:npar,
-        if any(idemoments.ind0(:,j)==0),
+    for j=1:npar
+        if any(idemoments.ind0(:,j)==0)
             pno = 100*length(find(idemoments.ind0(:,j)==0))/SampleSize;
             if SampleSize > 1
                 disp(['    ',name{j},' is not identified by J moments for ',num2str(pno),'% of MC runs!' ])
@@ -188,9 +188,9 @@ if any(idemoments.ino),
     npairs=size(idemoments.jweak_pair,2);
     jmap_pair=dyn_unvech(1:npairs);
     jstore=[];
-    for j=1:npairs,
+    for j=1:npairs
         iweak = length(find(idemoments.jweak_pair(:,j)));
-        if iweak,
+        if iweak
             [jx,jy]=find(jmap_pair==j);
             jstore=[jstore'  jx(1) jy(1)]';
             if SampleSize > 1
@@ -199,40 +199,40 @@ if any(idemoments.ino),
                 disp(['    [',name{jx(1)},',',name{jy(1)},'] are PAIRWISE collinear (with tol = 1.e-10) !' ])
             end
         end
-        
+
     end
     skipline()
-    for j=1:npar,
+    for j=1:npar
         iweak = length(find(idemoments.jweak(:,j)));
-        if iweak && ~ismember(j,jstore),
+        if iweak && ~ismember(j,jstore)
             %             disp('WARNING !!!')
             %             disp(['Moment derivatives of parameter ',name{j},' are multi-collinear (with tol = 1.e-10) for ',num2str(iweak/SampleSize*100),'% of MC runs!' ])
-            if SampleSize > 1,
+            if SampleSize > 1
                 disp([name{j},' is collinear w.r.t. all other params ',num2str(iweak/SampleSize*100),'% of MC runs!' ])
             else
                 disp([name{j},' is collinear w.r.t. all other params!' ])
             end
         end
     end
-%             if npar>(j+1),
-%                 [ipair, jpair] = find(squeeze(idemoments.Pco(j,j+1:end,:))'>(1-1.e-10));
-%             else
-%                 [ipair, jpair] = find(squeeze(idemoments.Pco(j,j+1:end,:))>(1-1.e-10));
-%             end
-%             if ~isempty(jpair),
-%                 for jx=j+1:npar,
-%                     ixp = find(jx==(jpair+j));
-%                     if ~isempty(ixp)
-%                         if SampleSize > 1
-%                             disp(['    [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10) for ',num2str(length(ixp)/SampleSize*100),'% of MC runs!' ])
-%                         else
-%                             disp(['    [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10) !' ])
-%                         end
-%                     end
-%                 end
-%             end
-%         end
-%     end
+    %             if npar>(j+1),
+    %                 [ipair, jpair] = find(squeeze(idemoments.Pco(j,j+1:end,:))'>(1-1.e-10));
+    %             else
+    %                 [ipair, jpair] = find(squeeze(idemoments.Pco(j,j+1:end,:))>(1-1.e-10));
+    %             end
+    %             if ~isempty(jpair),
+    %                 for jx=j+1:npar,
+    %                     ixp = find(jx==(jpair+j));
+    %                     if ~isempty(ixp)
+    %                         if SampleSize > 1
+    %                             disp(['    [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10) for ',num2str(length(ixp)/SampleSize*100),'% of MC runs!' ])
+    %                         else
+    %                             disp(['    [',name{j},',',name{jx},'] are PAIRWISE collinear (with tol = 1.e-10) !' ])
+    %                         end
+    %                     end
+    %                 end
+    %             end
+    %         end
+    %     end
 end
 if ~any(idemoments.ino) && ~any(any(idemoments.ind0==0))
     skipline()
@@ -255,30 +255,30 @@ end
 % if advanced && (~options_.noprint),
 %     for j=1:length(kokP),
 %         dyntable([name{kokP(j)},' pairwise correlations in the model'],char(' ','min','mean','max'), ...
-%                  char(name{jpM{j}}),[pminM{j}' pmeanM{j}' pmaxM{j}'],10,10,3);  
+%                  char(name{jpM{j}}),[pminM{j}' pmeanM{j}' pmaxM{j}'],10,10,3);
 %     end
-% 
+%
 %     for j=1:length(kokPJ),
 %         dyntable([name{kokPJ(j)},' pairwise correlations in J moments'],char(' ','min','mean','max'), ...
-%                  char(name{jpJ{j}}),[pminJ{j}' pmeanJ{j}' pmaxJ{j}'],10,10,3);  
+%                  char(name{jpJ{j}}),[pminJ{j}' pmeanJ{j}' pmaxJ{j}'],10,10,3);
 %     end
 % end
 % disp(' ')
 
 % identificaton patterns
-if SampleSize==1 && advanced,
+if SampleSize==1 && advanced
     skipline()
     disp('Press ENTER to print advanced diagnostics'), pause(5),
-    for  j=1:size(idemoments.cosnJ,2),
+    for  j=1:size(idemoments.cosnJ,2)
         pax=NaN(npar,npar);
         fprintf('\n')
         disp(['Collinearity patterns with ', int2str(j) ,' parameter(s)'])
         fprintf('%-15s [%-*s] %10s\n','Parameter',(15+1)*j,' Expl. params ','cosn')
-        for i=1:npar,
+        for i=1:npar
             namx='';
-            for in=1:j,
+            for in=1:j
                 dumpindx = idemoments.pars{i,j}(in);
-                if isnan(dumpindx),
+                if isnan(dumpindx)
                     namx=[namx ' ' sprintf('%-15s','--')];
                 else
                     namx=[namx ' ' sprintf('%-15s',name{dumpindx})];
diff --git a/matlab/disp_model_summary.m b/matlab/disp_model_summary.m
index 394bc00d9dea1c385afd6e8958e086f7dad30034..b04d025b46dc418c7b4f453a45ee9c4fbf1757c8 100644
--- a/matlab/disp_model_summary.m
+++ b/matlab/disp_model_summary.m
@@ -4,11 +4,11 @@ function disp_model_summary(M,dr,options)
 %     displays the model summary
 %
 % INPUTS
-%   M         [matlab structure] Definition of the model.           
+%   M         [matlab structure] Definition of the model.
 %   dr        [matlab structure] Decision rules
 %   options   [matlab structure] Options
 %
-% Copyright (C) 2001-2016 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -40,4 +40,3 @@ labels = deblank(M.exo_names);
 headers = char('Variables',labels);
 lh = size(labels,2)+2;
 dyntable(options,my_title,headers,labels,M.Sigma_e,lh,10,6);
-
diff --git a/matlab/disp_moments.m b/matlab/disp_moments.m
index cec582c4e5a7afb464d12af5591a013d55a85973..6e55bb571145d951e9d7704bdf20968d8552b75b 100644
--- a/matlab/disp_moments.m
+++ b/matlab/disp_moments.m
@@ -7,11 +7,11 @@ function oo_=disp_moments(y,var_list,M_,options_,oo_)
 %   M_                  [structure]    Dynare's model structure
 %   oo_                 [structure]    Dynare's results structure
 %   options_            [structure]    Dynare's options structure
-%    
+%
 % OUTPUTS
 %   oo_                 [structure]    Dynare's results structure,
 
-% Copyright (C) 2001-2016 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -57,18 +57,18 @@ s2 = mean(y.*y);
 s = sqrt(s2);
 oo_.mean = transpose(m);
 oo_.var = y'*y/size(y,1);
-oo_.skewness = (mean(y.^3)./s2.^1.5)'; 
+oo_.skewness = (mean(y.^3)./s2.^1.5)';
 oo_.kurtosis = (mean(y.^4)./(s2.*s2)-3)';
 
 labels = deblank(M_.endo_names(ivar,:));
 labels_TeX = deblank(M_.endo_names_tex(ivar,:));
 
 if options_.nomoments == 0
-    z = [ m' s' s2' (mean(y.^3)./s2.^1.5)' (mean(y.^4)./(s2.*s2)-3)' ];    
+    z = [ m' s' s2' (mean(y.^3)./s2.^1.5)' (mean(y.^4)./(s2.*s2)-3)' ];
     title='MOMENTS OF SIMULATED VARIABLES';
-    
+
     title=add_filter_subtitle(title,options_);
-    
+
     headers=char('VARIABLE','MEAN','STD. DEV.','VARIANCE','SKEWNESS', ...
                  'KURTOSIS');
     dyntable(options_,title,headers,labels,z,size(labels,2)+2,16,6);
@@ -79,7 +79,7 @@ end
 
 if options_.nocorr == 0
     corr = (y'*y/size(y,1))./(s'*s);
-    if options_.contemporaneous_correlation 
+    if options_.contemporaneous_correlation
         oo_.contemporaneous_correlation = corr;
     end
     if options_.noprint == 0
@@ -98,7 +98,7 @@ if options_.nocorr == 0
 end
 
 if options_.noprint == 0 && length(options_.conditional_variance_decomposition)
-   fprintf('\nSTOCH_SIMUL: conditional_variance_decomposition requires theoretical moments, i.e. periods=0.\n') 
+    fprintf('\nSTOCH_SIMUL: conditional_variance_decomposition requires theoretical moments, i.e. periods=0.\n')
 end
 
 ar = options_.ar;
@@ -119,7 +119,7 @@ if ar > 0
             dyn_latex_table(M_,options_,title,'sim_autocorr_matrix',headers,labels_TeX,autocorr,size(labels_TeX,2)+2,8,4);
         end
     end
-    
+
 end
 
 
@@ -132,14 +132,18 @@ if ~options_.nodecomposition
         if isempty(M_.endo_histval)
             y0 = oo_.dr.ys;
         else
-            y0 = M_.endo_histval;
+            if options_.loglinear
+                y0 = log_variable(1:M_.endo_nbr,M_.endo_histval,M_);
+            else
+                y0 = M_.endo_histval;
+            end
         end
         %back out shock matrix used for generating y
         i_exo_var = setdiff([1:M_.exo_nbr],find(diag(M_.Sigma_e) == 0)); % find shocks with 0 variance
         chol_S = chol(M_.Sigma_e(i_exo_var,i_exo_var)); %decompose rest
         shock_mat=zeros(options_.periods,M_.exo_nbr); %initialize
         shock_mat(:,i_exo_var)=oo_.exo_simul(:,i_exo_var)/chol_S; %invert construction of oo_.exo_simul from simult.m
-        
+
         for shock_iter=1:length(i_exo_var)
             temp_shock_mat=zeros(size(shock_mat));
             temp_shock_mat(:,i_exo_var(shock_iter))=shock_mat(:,i_exo_var(shock_iter));
@@ -152,9 +156,9 @@ if ~options_.nodecomposition
         if ~options_.noprint %options_.nomoments == 0
             skipline()
             title='VARIANCE DECOMPOSITION SIMULATING ONE SHOCK AT A TIME (in percent)';
-        
+
             title=add_filter_subtitle(title,options_);
-            
+
             headers = M_.exo_names;
             headers(M_.exo_names_orig_ord,:) = headers;
             headers = char(' ',headers);
@@ -177,12 +181,12 @@ if ~options_.nodecomposition
 
     end
 end
-        
+
 warning(warning_old_state);
 end
 
 function y=get_filtered_time_series(y,m,options_)
-        
+
 if options_.hp_filter && ~options_.one_sided_hp_filter  && ~options_.bandpass.indicator
     [hptrend,y] = sample_hp_filter(y,options_.hp_filter);
 elseif ~options_.hp_filter && options_.one_sided_hp_filter && ~options_.bandpass.indicator
@@ -193,8 +197,8 @@ elseif ~options_.hp_filter && ~options_.one_sided_hp_filter && options_.bandpass
     y=data_temp.data;
 elseif ~options_.hp_filter && ~options_.one_sided_hp_filter  && ~options_.bandpass.indicator
     y = bsxfun(@minus, y, m);
-else 
+else
     error('disp_moments:: You cannot use more than one filter at the same time')
 end
-        
+
 end
\ No newline at end of file
diff --git a/matlab/disp_steady_state.m b/matlab/disp_steady_state.m
index 354b0f6a455d3ecc56664cea71c85e71f2827d64..0543affc7d828cd503f65d55e6fdb1d45dcfa65d 100644
--- a/matlab/disp_steady_state.m
+++ b/matlab/disp_steady_state.m
@@ -1,18 +1,18 @@
 function disp_steady_state(M,oo)
 % function disp_steady_state(M,oo)
 % computes and prints the steady state calculations
-%  
+%
 % INPUTS
 %   M      structure of parameters
 %   oo     structure of results
-%  
+%
 % OUTPUTS
 %   none
 %
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2001-2011 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/disp_th_moments.m b/matlab/disp_th_moments.m
index 45d217611cc79637aeb142c4a6b0362df29c46ee..f3227f4f4807724ad52b0ace7b9a6c09cadc5c8f 100644
--- a/matlab/disp_th_moments.m
+++ b/matlab/disp_th_moments.m
@@ -1,7 +1,7 @@
 function oo_=disp_th_moments(dr,var_list,M_,options_,oo_)
 % Display theoretical moments of variables
 
-% Copyright (C) 2001-2015 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -44,7 +44,7 @@ m(non_stationary_vars) = NaN;
 i1 = find(abs(diag(oo_.gamma_y{1})) > 1e-12);
 s2 = diag(oo_.gamma_y{1});
 sd = sqrt(s2);
-if options_.order == 2
+if options_.order == 2 && ~M_.hessian_eq_zero
     m = m+oo_.gamma_y{options_.ar+3};
 end
 
@@ -76,7 +76,7 @@ if size(stationary_vars, 1) > 0
         if M_.exo_nbr > 1 && ~nodecomposition
             skipline()
             if options_.order == 2
-                title='APPROXIMATED VARIANCE DECOMPOSITION (in percent)';            
+                title='APPROXIMATED VARIANCE DECOMPOSITION (in percent)';
             else
                 title='VARIANCE DECOMPOSITION (in percent)';
             end
@@ -86,7 +86,7 @@ if size(stationary_vars, 1) > 0
             headers = char(' ',headers);
             lh = size(deblank(M_.endo_names(ivar(stationary_vars),:)),2)+2;
             dyntable(options_,title,headers,deblank(M_.endo_names(ivar(stationary_vars), ...
-                                                         :)),100* ...
+                                                              :)),100* ...
                      oo_.gamma_y{options_.ar+2}(stationary_vars,:),lh,8,2);
             if options_.TeX
                 headers=M_.exo_names_tex;
@@ -97,7 +97,7 @@ if size(stationary_vars, 1) > 0
             end
         end
     end
-    
+
     conditional_variance_steps = options_.conditional_variance_decomposition;
     if length(conditional_variance_steps)
         StateSpaceModel.number_of_state_equations = M_.endo_nbr;
@@ -107,10 +107,10 @@ if size(stationary_vars, 1) > 0
         StateSpaceModel.state_innovations_covariance_matrix = M_.Sigma_e;
         StateSpaceModel.order_var = dr.order_var;
         oo_.conditional_variance_decomposition = conditional_variance_decomposition(StateSpaceModel,conditional_variance_steps,ivar);
-        
+
         if options_.noprint == 0
             display_conditional_variance_decomposition(oo_.conditional_variance_decomposition,conditional_variance_steps,...
-                                                         ivar,M_,options_);
+                                                       ivar,M_,options_);
         end
     end
 end
@@ -123,14 +123,15 @@ if length(i1) == 0
 end
 
 if options_.nocorr == 0 && size(stationary_vars, 1) > 0
-    corr = oo_.gamma_y{1}(i1,i1)./(sd(i1)*sd(i1)');
+    corr=NaN(size(oo_.gamma_y{1}));
+    corr(i1,i1) = oo_.gamma_y{1}(i1,i1)./(sd(i1)*sd(i1)');
     if options_.contemporaneous_correlation 
         oo_.contemporaneous_correlation = corr;
     end
-    if ~options_.noprint,
+    if ~options_.noprint
         skipline()
         if options_.order == 2
-            title='APPROXIMATED MATRIX OF CORRELATIONS';            
+            title='APPROXIMATED MATRIX OF CORRELATIONS';
         else
             title='MATRIX OF CORRELATIONS';
         end
@@ -138,12 +139,12 @@ if options_.nocorr == 0 && size(stationary_vars, 1) > 0
         labels = deblank(M_.endo_names(ivar(i1),:));
         headers = char('Variables',labels);
         lh = size(labels,2)+2;
-        dyntable(options_,title,headers,labels,corr,lh,8,4);
+        dyntable(options_,title,headers,labels,corr(i1,i1),lh,8,4);
         if options_.TeX
             labels = deblank(M_.endo_names_tex(ivar(i1),:));
             headers=char('Variables',labels);
             lh = size(labels,2)+2;
-            dyn_latex_table(M_,options_,title,'th_corr_matrix',headers,labels,corr,lh,8,4);
+            dyn_latex_table(M_,options_,title,'th_corr_matrix',headers,labels,corr(i1,i1),lh,8,4);
         end
     end
 end
@@ -153,23 +154,23 @@ if options_.ar > 0 && size(stationary_vars, 1) > 0
         oo_.autocorr{i} = oo_.gamma_y{i+1};
         z(:,i) = diag(oo_.gamma_y{i+1}(i1,i1));
     end
-    if ~options_.noprint,      
-        skipline()    
+    if ~options_.noprint
+        skipline()
         if options_.order == 2
-            title='APPROXIMATED COEFFICIENTS OF AUTOCORRELATION';            
+            title='APPROXIMATED COEFFICIENTS OF AUTOCORRELATION';
         else
             title='COEFFICIENTS OF AUTOCORRELATION';
         end
         title=add_filter_subtitle(title,options_);
-        labels = deblank(M_.endo_names(ivar(i1),:));      
+        labels = deblank(M_.endo_names(ivar(i1),:));
         headers = char('Order ',int2str([1:options_.ar]'));
         lh = size(labels,2)+2;
         dyntable(options_,title,headers,labels,z,lh,8,4);
         if options_.TeX
-            labels = deblank(M_.endo_names_tex(ivar(i1),:)); 
+            labels = deblank(M_.endo_names_tex(ivar(i1),:));
             headers=char('Order ',int2str([1:options_.ar]'));
             lh = size(labels,2)+2;
             dyn_latex_table(M_,options_,title,'th_autocorr_matrix',headers,labels,z,lh,8,4);
         end
-    end  
+    end
 end
diff --git a/matlab/display_conditional_variance_decomposition.m b/matlab/display_conditional_variance_decomposition.m
index 597aa0b1b95a9671d121a717b6a2ee50e8e306bd..f0c115ad48991602cc3ab245c829cd9b7b31852a 100644
--- a/matlab/display_conditional_variance_decomposition.m
+++ b/matlab/display_conditional_variance_decomposition.m
@@ -1,8 +1,8 @@
 function display_conditional_variance_decomposition(conditional_decomposition_array,Steps,SubsetOfVariables,M_,options_)
 % This function displays the conditional variance decomposition of a given state space model
 % for a subset of endogenous variables.
-% 
-% INPUTS 
+%
+% INPUTS
 %   conditional_decomposition_array     [matrix]   Output matrix from compute_conditional_variance_decomposition
 %   Steps               [integer]     1*h vector of dates.
 %   SubsetOfVariables   [integer]     1*q vector of indices.
@@ -10,10 +10,10 @@ function display_conditional_variance_decomposition(conditional_decomposition_ar
 %                                     Model description
 %   options_            [structure]   Dynare structure containing the
 %                                     options
-% OUTPUTS 
+% OUTPUTS
 %   none
 %
-% Copyright (C) 2010-2014 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -56,10 +56,10 @@ for i=1:length(Steps)
     dyntable(options_,'',headers,...
              deblank(M_.endo_names(SubsetOfVariables,:)),...
              vardec_i,lh,8,2);
-     if options_.TeX
-         labels_TeX = deblank(M_.endo_names_tex(SubsetOfVariables,:));
-         headers_TeX=char('',deblank(M_.exo_names_tex));
-         lh = size(labels_TeX,2)+2;
-         dyn_latex_table(M_,options_,[title,'; Period ' int2str(Steps(i))],['th_var_decomp_cond_h',int2str(Steps(i))],headers_TeX,labels_TeX,vardec_i,lh,8,2);
-     end    
+    if options_.TeX
+        labels_TeX = deblank(M_.endo_names_tex(SubsetOfVariables,:));
+        headers_TeX=char('',deblank(M_.exo_names_tex));
+        lh = size(labels_TeX,2)+2;
+        dyn_latex_table(M_,options_,[title,'; Period ' int2str(Steps(i))],['th_var_decomp_cond_h',int2str(Steps(i))],headers_TeX,labels_TeX,vardec_i,lh,8,2);
+    end
 end
\ No newline at end of file
diff --git a/matlab/display_estimation_results_table.m b/matlab/display_estimation_results_table.m
index 152ea006b95605375357470ddb4f317498a0deb9..6faf6a834cb6aadf4bfaaeb84c77f01239b902d9 100644
--- a/matlab/display_estimation_results_table.m
+++ b/matlab/display_estimation_results_table.m
@@ -1,26 +1,26 @@
 function oo_=display_estimation_results_table(xparam1,stdh,M_,options_,estim_params_,bayestopt_,oo_,pnames,table_title,field_name)
 %function oo_=display_results_table(xparam1,stdh,M_,estim_params_,bayestopt_,oo_,pnames,table_title,field_name)
 % Display estimation results on screen and write them to TeX-file
-% 
-% INPUTS 
+%
+% INPUTS
 %   o xparam1       [double]   (p*1) vector of estimate parameters.
 %   o stdh          [double]   (p*1) vector of estimate parameters.
-%   o M_                        Matlab's structure describing the Model (initialized by dynare, see @ref{M_}).          
+%   o M_                        Matlab's structure describing the Model (initialized by dynare, see @ref{M_}).
 %   o estim_params_             Matlab's structure describing the estimated_parameters (initialized by dynare, see @ref{estim_params_}).
 %   o options_                  Matlab's structure describing the options (initialized by dynare, see @ref{options_}).
 %   o bayestopt_                Matlab's structure describing the priors (initialized by dynare, see @ref{bayesopt_}).
 %   o oo_                       Matlab's structure gathering the results (initialized by dynare, see @ref{oo_}).
-%   o pnames        [string]    Character Array storing the names for prior distributions     
-%   o table_title   [string]    Title of the Table     
+%   o pnames        [string]    Character Array storing the names for prior distributions
+%   o table_title   [string]    Title of the Table
 %   o field_name    [string]    String storing the name of the fields for oo_ where the parameters are stored
-%  
-% OUTPUTS 
+%
+% OUTPUTS
 %   o oo_                       Matlab's structure gathering the results
 %
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2014-2016 Dynare Team
+% Copyright (C) 2014-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -64,13 +64,13 @@ if np
         name = bayestopt_.name{ip};
         if strcmp(field_name,'posterior')
             fprintf('%-*s %7.3f %8.4f %7.4f %4s %6.4f \n', ...
-                     header_width,name, ...
-                     bayestopt_.p1(ip),xparam1(ip),stdh(ip), ...
-                     pnames(bayestopt_.pshape(ip)+1,:), ...
-                     bayestopt_.p2(ip));
+                    header_width,name, ...
+                    bayestopt_.p1(ip),xparam1(ip),stdh(ip), ...
+                    pnames(bayestopt_.pshape(ip)+1,:), ...
+                    bayestopt_.p2(ip));
         else
             fprintf('%-*s %8.4f %7.4f %7.4f \n', ...
-                 header_width,name,xparam1(ip),stdh(ip),tstath(ip));
+                    header_width,name,xparam1(ip),stdh(ip),tstath(ip));
         end
         eval(['oo_.' field_name '_mode.parameters.' name ' = xparam1(ip);']);
         eval(['oo_.' field_name '_std_at_mode.parameters.' name ' = stdh(ip);']);
@@ -87,9 +87,9 @@ if nvx
         name = deblank(M_.exo_names(k,:));
         if strcmp(field_name,'posterior')
             fprintf('%-*s %7.3f %8.4f %7.4f %4s %6.4f \n', ...
-                     header_width,name,bayestopt_.p1(ip),xparam1(ip), ...
-                     stdh(ip),pnames(bayestopt_.pshape(ip)+1,:), ...
-                     bayestopt_.p2(ip));
+                    header_width,name,bayestopt_.p1(ip),xparam1(ip), ...
+                    stdh(ip),pnames(bayestopt_.pshape(ip)+1,:), ...
+                    bayestopt_.p2(ip));
         else
             fprintf('%-*s %8.4f %7.4f %7.4f \n',header_width,name,xparam1(ip),stdh(ip),tstath(ip));
         end
@@ -99,28 +99,28 @@ if nvx
         ip = ip+1;
     end
     skipline()
- end
- if nvn
+end
+if nvn
     disp('standard deviation of measurement errors')
     disp(tit1)
     ip = nvx+1;
     for i=1:nvn
         name = options_.varobs{estim_params_.nvn_observable_correspondence(i,1)};
-        if strcmp(field_name,'posterior')           
+        if strcmp(field_name,'posterior')
             fprintf('%-*s %7.3f %8.4f %7.4f %4s %6.4f \n', ...
-                     header_width,name,bayestopt_.p1(ip), ...
-                     xparam1(ip),stdh(ip), ...
-                     pnames(bayestopt_.pshape(ip)+1,:), ...
-                     bayestopt_.p2(ip));
+                    header_width,name,bayestopt_.p1(ip), ...
+                    xparam1(ip),stdh(ip), ...
+                    pnames(bayestopt_.pshape(ip)+1,:), ...
+                    bayestopt_.p2(ip));
         else
-            fprintf('%-*s %8.4f %7.4f %7.4f \n',header_width,name,xparam1(ip),stdh(ip),tstath(ip))            
+            fprintf('%-*s %8.4f %7.4f %7.4f \n',header_width,name,xparam1(ip),stdh(ip),tstath(ip))
         end
         eval(['oo_.' field_name '_mode.measurement_errors_std.' name ' = xparam1(ip);']);
         eval(['oo_.' field_name '_std_at_mode.measurement_errors_std.' name ' = stdh(ip);']);
         ip = ip+1;
     end
     skipline()
- end
+end
 
 if ncx
     disp('correlation of shocks')
@@ -131,12 +131,12 @@ if ncx
         k2 = estim_params_.corrx(i,2);
         name = [deblank(M_.exo_names(k1,:)) ',' deblank(M_.exo_names(k2,:))];
         NAME = [deblank(M_.exo_names(k1,:)) '_' deblank(M_.exo_names(k2,:))];
-        if strcmp(field_name,'posterior')           
+        if strcmp(field_name,'posterior')
             fprintf('%-*s %7.3f %8.4f %7.4f %4s %6.4f \n', ...
-                     header_width,name,bayestopt_.p1(ip),xparam1(ip),stdh(ip),  ...
-                     pnames(bayestopt_.pshape(ip)+1,:), bayestopt_.p2(ip));
+                    header_width,name,bayestopt_.p1(ip),xparam1(ip),stdh(ip),  ...
+                    pnames(bayestopt_.pshape(ip)+1,:), bayestopt_.p2(ip));
         else
-            fprintf('%-*s %8.4f %7.4f %7.4f \n', header_width,name,xparam1(ip),stdh(ip),tstath(ip));            
+            fprintf('%-*s %8.4f %7.4f %7.4f \n', header_width,name,xparam1(ip),stdh(ip),tstath(ip));
         end
         M_.Sigma_e(k1,k2) = xparam1(ip)*sqrt(M_.Sigma_e(k1,k1)*M_.Sigma_e(k2,k2));
         M_.Sigma_e(k2,k1) = M_.Sigma_e(k1,k2);
@@ -156,12 +156,12 @@ if ncn
         k2 = estim_params_.corrn(i,2);
         name = [deblank(M_.endo_names(k1,:)) ',' deblank(M_.endo_names(k2,:))];
         NAME = [deblank(M_.endo_names(k1,:)) '_' deblank(M_.endo_names(k2,:))];
-        if strcmp(field_name,'posterior')                 
+        if strcmp(field_name,'posterior')
             fprintf('%-*s %7.3f %8.4f %7.4f %4s %6.4f \n', ...
-                     header_width,name,bayestopt_.p1(ip),xparam1(ip),stdh(ip), ...
-                     pnames(bayestopt_.pshape(ip)+1,:), bayestopt_.p2(ip));
+                    header_width,name,bayestopt_.p1(ip),xparam1(ip),stdh(ip), ...
+                    pnames(bayestopt_.pshape(ip)+1,:), bayestopt_.p2(ip));
         else
-            fprintf('%-*s %8.4f %7.4f %7.4f \n',header_width,name,xparam1(ip),stdh(ip),tstath(ip));            
+            fprintf('%-*s %8.4f %7.4f %7.4f \n',header_width,name,xparam1(ip),stdh(ip),tstath(ip));
         end
         eval(['oo_.' field_name '_mode.measurement_errors_corr.' NAME ' = xparam1(ip);']);
         eval(['oo_.' field_name '_std_at_mode.measurement_errors_corr.' NAME ' = stdh(ip);']);
@@ -268,17 +268,17 @@ if any(bayestopt_.pshape > 0) && options_.TeX %% Bayesian estimation (posterior
         TeXEnd(fidTeX)
     end
 elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
-    if np        
+    if np
         filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_1.tex'];
         fidTeX = fopen(filename,'w');
-        TeXBegin_ML(fidTeX,1,'parameters',table_title,LaTeXtitle)   
+        TeXBegin_ML(fidTeX,1,'parameters',table_title,LaTeXtitle)
         ip = nvx+nvn+ncx+ncn+1;
         for i=1:np
             fprintf(fidTeX,'$%s$ & %8.4f & %7.4f & %7.4f\\\\ \n',...
                     M_.param_names_tex(estim_params_.param_vals(i,1),:),...
                     xparam1(ip),...
                     stdh(ip),...
-                    tstath(ip));                    
+                    tstath(ip));
             ip = ip + 1;
         end
         TeXEnd(fidTeX)
@@ -286,7 +286,7 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
     if nvx
         filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_2.tex'];
         fidTeX = fopen(filename,'w');
-        TeXBegin_ML(fidTeX,2,'standard deviation of structural shocks',table_title,LaTeXtitle)   
+        TeXBegin_ML(fidTeX,2,'standard deviation of structural shocks',table_title,LaTeXtitle)
         ip = 1;
         for i=1:nvx
             k = estim_params_.var_exo(i,1);
@@ -302,11 +302,11 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
     if nvn
         filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_3.tex'];
         fidTeX = fopen(filename,'w');
-        TeXBegin_ML(fidTeX,3,'standard deviation of measurement errors',table_title,LaTeXtitle)   
+        TeXBegin_ML(fidTeX,3,'standard deviation of measurement errors',table_title,LaTeXtitle)
         ip = nvx+1;
         for i=1:nvn
-           idx = strmatch(options_.varobs{estim_params_.nvn_observable_correspondence(i,1)},M_.endo_names);
-           fprintf(fidTeX,'$%s$ & %8.4f & %7.4f & %7.4f \\\\ \n',...
+            idx = strmatch(options_.varobs{estim_params_.nvn_observable_correspondence(i,1)},M_.endo_names);
+            fprintf(fidTeX,'$%s$ & %8.4f & %7.4f & %7.4f \\\\ \n',...
                     deblank(M_.endo_names_tex(idx,:)), ...
                     xparam1(ip),...
                     stdh(ip),...
@@ -318,7 +318,7 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
     if ncx
         filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_4.tex'];
         fidTeX = fopen(filename,'w');
-        TeXBegin_ML(fidTeX,4,'correlation of structural shocks',table_title,LaTeXtitle)   
+        TeXBegin_ML(fidTeX,4,'correlation of structural shocks',table_title,LaTeXtitle)
         ip = nvx+nvn+1;
         for i=1:ncx
             k1 = estim_params_.corrx(i,1);
@@ -335,7 +335,7 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
     if ncn
         filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_5.tex'];
         fidTeX = fopen(filename,'w');
-        TeXBegin_ML(fidTeX,5,'correlation of measurement errors',table_title,LaTeXtitle)   
+        TeXBegin_ML(fidTeX,5,'correlation of measurement errors',table_title,LaTeXtitle)
         ip = nvx+nvn+ncx+1;
         for i=1:ncn
             k1 = estim_params_.corrn(i,1);
@@ -347,7 +347,7 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
                     tstath(ip));
             ip = ip+1;
         end
-    TeXEnd(fidTeX)
+        TeXEnd(fidTeX)
     end
 end
 
@@ -356,51 +356,51 @@ end
 %% subfunctions:
 %
 function TeXBegin_Bayesian(fid,fnum,title)
-    fprintf(fid,'%% TeX-table generated by dynare_estimation (Dynare).\n');
-    fprintf(fid,['%% RESULTS FROM POSTERIOR MAXIMIZATION (' title ')\n']);
-    fprintf(fid,['%% ' datestr(now,0)]);
-    fprintf(fid,' \n');
-    fprintf(fid,' \n');
-    fprintf(fid,'\\begin{center}\n');
-    fprintf(fid,'\\begin{longtable}{llcccc} \n');
-    fprintf(fid,['\\caption{Results from posterior maximization (' title ')}\\\\\n ']);
-    fprintf(fid,['\\label{Table:Posterior:' int2str(fnum)  '}\\\\\n']);
-    fprintf(fid,'\\toprule \n');
-    fprintf(fid,'  & \\multicolumn{3}{c}{Prior}  &  \\multicolumn{2}{c}{Posterior} \\\\\n');
-    fprintf(fid,'  \\cmidrule(r{.75em}){2-4} \\cmidrule(r{.75em}){5-6}\n');
-    fprintf(fid,'  & Dist. & Mean  & Stdev & Mode & Stdev \\\\ \n');
-    fprintf(fid,'\\midrule \\endfirsthead \n');
-    fprintf(fid,'\\caption{(continued)}\\\\\n ');
-    fprintf(fid,'\\bottomrule \n');
-    fprintf(fid,'  & \\multicolumn{3}{c}{Prior}  &  \\multicolumn{2}{c}{Posterior} \\\\\n');
-    fprintf(fid,'  \\cmidrule(r{.75em}){2-4} \\cmidrule(r{.75em}){5-6}\n');
-    fprintf(fid,'  & Dist. & Mean  & Stdev & Mode & Stdev \\\\ \n');
-    fprintf(fid,'\\midrule \\endhead \n');
-    fprintf(fid,'\\bottomrule \\multicolumn{6}{r}{(Continued on next page)}\\endfoot \n');
-    fprintf(fid,'\\bottomrule\\endlastfoot \n');
+fprintf(fid,'%% TeX-table generated by dynare_estimation (Dynare).\n');
+fprintf(fid,['%% RESULTS FROM POSTERIOR MAXIMIZATION (' title ')\n']);
+fprintf(fid,['%% ' datestr(now,0)]);
+fprintf(fid,' \n');
+fprintf(fid,' \n');
+fprintf(fid,'\\begin{center}\n');
+fprintf(fid,'\\begin{longtable}{llcccc} \n');
+fprintf(fid,['\\caption{Results from posterior maximization (' title ')}\\\\\n ']);
+fprintf(fid,['\\label{Table:Posterior:' int2str(fnum)  '}\\\\\n']);
+fprintf(fid,'\\toprule \n');
+fprintf(fid,'  & \\multicolumn{3}{c}{Prior}  &  \\multicolumn{2}{c}{Posterior} \\\\\n');
+fprintf(fid,'  \\cmidrule(r{.75em}){2-4} \\cmidrule(r{.75em}){5-6}\n');
+fprintf(fid,'  & Dist. & Mean  & Stdev & Mode & Stdev \\\\ \n');
+fprintf(fid,'\\midrule \\endfirsthead \n');
+fprintf(fid,'\\caption{(continued)}\\\\\n ');
+fprintf(fid,'\\bottomrule \n');
+fprintf(fid,'  & \\multicolumn{3}{c}{Prior}  &  \\multicolumn{2}{c}{Posterior} \\\\\n');
+fprintf(fid,'  \\cmidrule(r{.75em}){2-4} \\cmidrule(r{.75em}){5-6}\n');
+fprintf(fid,'  & Dist. & Mean  & Stdev & Mode & Stdev \\\\ \n');
+fprintf(fid,'\\midrule \\endhead \n');
+fprintf(fid,'\\bottomrule \\multicolumn{6}{r}{(Continued on next page)}\\endfoot \n');
+fprintf(fid,'\\bottomrule\\endlastfoot \n');
+
+function TeXBegin_ML(fid,fnum,title,table_title,LaTeXtitle)
+fprintf(fid,'%% TeX-table generated by dynare_estimation (Dynare).\n');
+fprintf(fid,['%% RESULTS FROM ' table_title ' MAXIMIZATION (' title ')\n']);
+fprintf(fid,['%% ' datestr(now,0)]);
+fprintf(fid,' \n');
+fprintf(fid,' \n');
+fprintf(fid,'\\begin{center}\n');
+fprintf(fid,'\\begin{longtable}{llcc} \n');
+fprintf(fid,['\\caption{Results from ' table_title ' maximization (' title ')}\\\\\n ']);
+fprintf(fid,['\\label{Table:' LaTeXtitle ':' int2str(fnum) '}\\\\\n']);
+fprintf(fid,'\\toprule \n');
+fprintf(fid,'  & Mode & s.d. & t-stat\\\\ \n');
+fprintf(fid,'\\midrule \\endfirsthead \n');
+fprintf(fid,'\\caption{(continued)}\\\\\n ');
+fprintf(fid,'\\toprule \n');
+fprintf(fid,'  & Mode & s.d. & t-stat\\\\ \n');
+fprintf(fid,'\\midrule \\endhead \n');
+fprintf(fid,'\\bottomrule  \\multicolumn{4}{r}{(Continued on next page)} \\endfoot \n');
+fprintf(fid,'\\bottomrule \\endlastfoot \n');
 
- function TeXBegin_ML(fid,fnum,title,table_title,LaTeXtitle)   
-        fprintf(fid,'%% TeX-table generated by dynare_estimation (Dynare).\n');
-        fprintf(fid,['%% RESULTS FROM ' table_title ' MAXIMIZATION (' title ')\n']);
-        fprintf(fid,['%% ' datestr(now,0)]);
-        fprintf(fid,' \n');
-        fprintf(fid,' \n');
-        fprintf(fid,'\\begin{center}\n');
-        fprintf(fid,'\\begin{longtable}{llcc} \n');
-        fprintf(fid,['\\caption{Results from ' table_title ' maximization (' title ')}\\\\\n ']);
-        fprintf(fid,['\\label{Table:' LaTeXtitle ':' int2str(fnum) '}\\\\\n']);
-        fprintf(fid,'\\toprule \n');
-        fprintf(fid,'  & Mode & s.d. & t-stat\\\\ \n');
-        fprintf(fid,'\\midrule \\endfirsthead \n');
-        fprintf(fid,'\\caption{(continued)}\\\\\n ');
-        fprintf(fid,'\\toprule \n');
-        fprintf(fid,'  & Mode & s.d. & t-stat\\\\ \n');
-        fprintf(fid,'\\midrule \\endhead \n');
-        fprintf(fid,'\\bottomrule  \\multicolumn{4}{r}{(Continued on next page)} \\endfoot \n');
-        fprintf(fid,'\\bottomrule \\endlastfoot \n');
-   
 function TeXEnd(fid)
-fprintf(fid,'\\end{longtable}\n ');    
+fprintf(fid,'\\end{longtable}\n ');
 fprintf(fid,'\\end{center}\n');
 fprintf(fid,'%% End of TeX file.\n');
 fclose(fid);
\ No newline at end of file
diff --git a/matlab/display_problematic_vars_Jacobian.m b/matlab/display_problematic_vars_Jacobian.m
index a4278208b74d604232022e387289eafdb0772533..310b37fa58cdc17cdab39c1f62bfaec490709c60 100644
--- a/matlab/display_problematic_vars_Jacobian.m
+++ b/matlab/display_problematic_vars_Jacobian.m
@@ -1,22 +1,22 @@
 function []=display_problematic_vars_Jacobian(problemrow,problemcol,M_,x,type,caller_string)
 % []=display_problematic_vars_Jacobian(problemrow,problemcol,M_,ys,caller_string)
-% print the equation numbers and variables associated with problematic entries 
-% of the Jacobian 
+% print the equation numbers and variables associated with problematic entries
+% of the Jacobian
 %
 % INPUTS
 %   problemrow      [vector] rows associated with problematic entries
 %   problemcol      [vector] columns associated with problematic entries
-%   M_              [matlab structure] Definition of the model.           
+%   M_              [matlab structure] Definition of the model.
 %   x               [vector] point at which the Jacobian was evaluated
 %   type            [string] 'static' or 'dynamic' depending on the type of
 %                               Jacobian
-%   caller_string   [string] contains name of calling function for printing 
-%    
+%   caller_string   [string] contains name of calling function for printing
+%
 % OUTPUTS
 %   none.
-%  
+%
 
-% Copyright (C) 2014-16 Dynare Team
+% Copyright (C) 2014-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -50,7 +50,7 @@ if strcmp(type,'dynamic')
             type_string='';
         elseif var_row==1
             type_string='lag of';
-        elseif var_row==3;
+        elseif var_row==3
             type_string='lead of';
         end
         if problemcol(ii)<=max(max(M_.lead_lag_incidence)) && var_index<=M_.orig_endo_nbr
@@ -62,25 +62,25 @@ if strcmp(type,'dynamic')
                 fprintf('Derivative of Equation %d with respect to %s Variable %s  (initial value of %s: %g) \n',eq_nbr,type_string,deblank(M_.endo_names(var_index,:)),deblank(M_.endo_names(var_index,:)),x(var_index))
             end
         elseif problemcol(ii)<=max(max(M_.lead_lag_incidence)) && var_index>M_.orig_endo_nbr %auxiliary vars
-            if M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).type ==6 %Ramsey Lagrange Multiplier 
-                if problemrow(ii)<=aux_eq_nbr
-                    eq_nbr=problemrow(ii);
-                    fprintf('Derivative of Auxiliary Equation %d with respect to %s of Langrange multiplier of equation %s (initial value: %g) \n',eq_nbr,type_string,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii)))            
-                else
-                    eq_nbr=problemrow(ii)-aux_eq_nbr;
-                    fprintf('Derivative of Equation %d with respect to %s of Langrange multiplier of equation %s (initial value: %g) \n',eq_nbr,type_string,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii)))            
-                end
+        if M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).type ==6 %Ramsey Lagrange Multiplier
+            if problemrow(ii)<=aux_eq_nbr
+                eq_nbr=problemrow(ii);
+                fprintf('Derivative of Auxiliary Equation %d with respect to %s of Langrange multiplier of equation %s (initial value: %g) \n',eq_nbr,type_string,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii)))
             else
-                if problemrow(ii)<=aux_eq_nbr
-                    eq_nbr=problemrow(ii);
-                    orig_var_index=M_.aux_vars(1,var_index-M_.orig_endo_nbr).orig_index;
-                    fprintf('Derivative of Auxiliary Equation %d with respect to %s Variable %s  (initial value of %s: %g) \n',eq_nbr,type_string,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(orig_var_index))            
-                else
-                    eq_nbr=problemrow(ii)-aux_eq_nbr;
-                    orig_var_index=M_.aux_vars(1,var_index-M_.orig_endo_nbr).orig_index;
-                    fprintf('Derivative of Equation %d with respect to %s Variable %s  (initial value of %s: %g) \n',eq_nbr,type_string,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(orig_var_index))            
-                end
+                eq_nbr=problemrow(ii)-aux_eq_nbr;
+                fprintf('Derivative of Equation %d with respect to %s of Langrange multiplier of equation %s (initial value: %g) \n',eq_nbr,type_string,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii)))
             end
+        else
+            if problemrow(ii)<=aux_eq_nbr
+                eq_nbr=problemrow(ii);
+                orig_var_index=M_.aux_vars(1,var_index-M_.orig_endo_nbr).orig_index;
+                fprintf('Derivative of Auxiliary Equation %d with respect to %s Variable %s  (initial value of %s: %g) \n',eq_nbr,type_string,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(orig_var_index))
+            else
+                eq_nbr=problemrow(ii)-aux_eq_nbr;
+                orig_var_index=M_.aux_vars(1,var_index-M_.orig_endo_nbr).orig_index;
+                fprintf('Derivative of Equation %d with respect to %s Variable %s  (initial value of %s: %g) \n',eq_nbr,type_string,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(orig_var_index))
+            end
+        end
         elseif problemcol(ii)>max(max(M_.lead_lag_incidence)) && var_index<=M_.exo_nbr
             if problemrow(ii)<=aux_eq_nbr
                 eq_nbr=problemrow(ii);
@@ -88,7 +88,7 @@ if strcmp(type,'dynamic')
             else
                 eq_nbr=problemrow(ii)-aux_eq_nbr;
                 fprintf('Derivative of Equation %d with respect to %s shock %s \n',eq_nbr,type_string,deblank(M_.exo_names(var_index,:)));
-            end            
+            end
         else
             error('display_problematic_vars_Jacobian:: The error should not happen. Please contact the developers')
         end
@@ -108,24 +108,24 @@ elseif strcmp(type,'static')
                 fprintf('Derivative of Equation %d with respect to Variable %s  (initial value of %s: %g) \n',eq_nbr,deblank(M_.endo_names(problemcol(ii),:)),deblank(M_.endo_names(problemcol(ii),:)),x(problemcol(ii)))
             end
         else %auxiliary vars
-            if M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).type ==6 %Ramsey Lagrange Multiplier 
+            if M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).type ==6 %Ramsey Lagrange Multiplier
                 if problemrow(ii)<=aux_eq_nbr
                     eq_nbr=problemrow(ii);
-                    fprintf('Derivative of Auxiliary Equation %d with respect to Lagrange multiplier of equation %d (initial value: %g) \n',eq_nbr,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii)))            
+                    fprintf('Derivative of Auxiliary Equation %d with respect to Lagrange multiplier of equation %d (initial value: %g) \n',eq_nbr,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii)))
                 else
                     eq_nbr=problemrow(ii)-aux_eq_nbr;
-                    fprintf('Derivative of Equation %d with respect to Lagrange multiplier of equation %d (initial value: %g) \n',eq_nbr,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii)))            
+                    fprintf('Derivative of Equation %d with respect to Lagrange multiplier of equation %d (initial value: %g) \n',eq_nbr,M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).eq_nbr,x(problemcol(ii)))
                 end
             else
-            if problemrow(ii)<=aux_eq_nbr
-                eq_nbr=problemrow(ii);
-                orig_var_index=M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).orig_index;
-                fprintf('Derivative of Auxiliary Equation %d with respect to Variable %s  (initial value of %s: %g) \n',eq_nbr,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(problemcol(ii)))            
-            else
-                eq_nbr=problemrow(ii)-aux_eq_nbr;
-                orig_var_index=M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).orig_index;
-                fprintf('Derivative of Equation %d with respect to Variable %s  (initial value of %s: %g) \n',eq_nbr,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(problemcol(ii)))            
-            end
+                if problemrow(ii)<=aux_eq_nbr
+                    eq_nbr=problemrow(ii);
+                    orig_var_index=M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).orig_index;
+                    fprintf('Derivative of Auxiliary Equation %d with respect to Variable %s  (initial value of %s: %g) \n',eq_nbr,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(problemcol(ii)))
+                else
+                    eq_nbr=problemrow(ii)-aux_eq_nbr;
+                    orig_var_index=M_.aux_vars(1,problemcol(ii)-M_.orig_endo_nbr).orig_index;
+                    fprintf('Derivative of Equation %d with respect to Variable %s  (initial value of %s: %g) \n',eq_nbr,deblank(M_.endo_names(orig_var_index,:)),deblank(M_.endo_names(orig_var_index,:)),x(problemcol(ii)))
+                end
             end
         end
     end
@@ -134,5 +134,5 @@ elseif strcmp(type,'static')
     fprintf('%s  and evaluating it at the steady state then results in a division by 0.\n',caller_string)
     fprintf('%s  If you are using model-local variables (# operator), check their values as well.\n',caller_string)
 else
-    error('Unknown Type')    
+    error('Unknown Type')
 end
\ No newline at end of file
diff --git a/matlab/distributions/beta_specification.m b/matlab/distributions/beta_specification.m
index 33a38085d36804066a0630228e4d8ef290b6b72a..df804812cac713ee0c19afdec51ed57dc623462f 100644
--- a/matlab/distributions/beta_specification.m
+++ b/matlab/distributions/beta_specification.m
@@ -2,17 +2,17 @@ function [a, b] = beta_specification(mu, sigma2, lb, ub, name)   % --*-- Unitary
 
 % Returns the hyperparameters of the beta distribution given the expectation and variance.
 %
-% INPUTS 
+% INPUTS
 % - mu     [double]   Expectation of the Gamma random variable.
 % - sigma2 [double]   Variance of the Gamma random variable.
 % - lb     [double]   Lower bound of the domain (default is zero).
 % - ub     [double]   Upper bound of the domain (default is one).
 %
-% OUTPUTS 
+% OUTPUTS
 % - a      [double]   First hyperparameter of the Beta density.
 % - b      [double]   Second hyperparameter of the Beta density.
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -63,7 +63,7 @@ if sigma2>(1-mu)*mu
     error('Beta prior%s. Given the declared prior expectation, prior lower and upper bounds, the prior std. has to be smaller than %f.',name2,sqrt((1-mu)*mu))
 end
 
-a = (1-mu)*mu*mu/sigma2-mu; 
+a = (1-mu)*mu*mu/sigma2-mu;
 b = a*(1/mu-1);
 
 %@test:1
diff --git a/matlab/distributions/compute_prior_mode.m b/matlab/distributions/compute_prior_mode.m
index 3286c08eaba15e5ac2c7697766b283da4a3cfde4..86c20dae8147b07e9764cf29b5061f7b42e3c822 100644
--- a/matlab/distributions/compute_prior_mode.m
+++ b/matlab/distributions/compute_prior_mode.m
@@ -1,8 +1,8 @@
 function m = compute_prior_mode(hyperparameters,shape) % --*-- Unitary tests --*--
 % This function computes the mode of the prior distribution given the (two, three or four) hyperparameters
 % of the prior distribution.
-%    
-% INPUTS 
+%
+% INPUTS
 %   hyperparameters     [double]    1*n vector of hyper parameters.
 %   shape               [integer]   scalar specifying the prior shape:
 %                                     shape=1 => Beta distribution,
@@ -12,18 +12,18 @@ function m = compute_prior_mode(hyperparameters,shape) % --*-- Unitary tests --*
 %                                     shape=5 => Uniform distribution,
 %                                     shape=6 => Inverse Gamma (type 2) distribution,
 %                                     shape=8 => Weibull distribution.
-%                                     
-% OUTPUTS 
+%
+% OUTPUTS
 %   m       [double]    scalar or 2*1 vector, the prior mode.
 %
-% REMARKS 
-% [1] The size of the vector of hyperparameters is 3 when the Gamma or Inverse Gamma is shifted and 4 when 
-%     the support of the Beta distribution is not [0,1].      
-% [2] The hyperparameters of the uniform distribution are the lower and upper bounds.    
+% REMARKS
+% [1] The size of the vector of hyperparameters is 3 when the Gamma or Inverse Gamma is shifted and 4 when
+%     the support of the Beta distribution is not [0,1].
+% [2] The hyperparameters of the uniform distribution are the lower and upper bounds.
 % [3] The uniform distribution has an infinity of modes. In this case the function returns the prior mean.
 % [4] For the beta distribution we can have 1, 2 or an infinity of modes.
 
-% Copyright (C) 2009-2016 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/distributions/gamma_specification.m b/matlab/distributions/gamma_specification.m
index 0f7301193285af0311d889ed1f4d6026afe9084c..c78713407b9924e0c271dcea5aa0ed7106104734 100644
--- a/matlab/distributions/gamma_specification.m
+++ b/matlab/distributions/gamma_specification.m
@@ -2,17 +2,17 @@ function [a, b] = gamma_specification(mu, sigma2, lb, name)   % --*-- Unitary te
 
 % Returns the hyperparameters of the gamma distribution given the expectation and variance.
 %
-% INPUTS 
+% INPUTS
 % - mu     [double]   Expectation of the Gamma random variable.
 % - sigma2 [double]   Variance of the Gamma random variable.
 % - lb     [double]   Lower bound of the domain (default is zero).
 % - name   [string]   Name of the parameter (or random variable).
 %
-% OUTPUTS 
+% OUTPUTS
 % - a      [double]   First hyperparameter of the Gamma density (shape).
 % - b      [double]   Second hyperparameter of the Gamma density (scale).
 
-% Copyright (C) 2015-2016 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/distributions/inverse_gamma_specification.m b/matlab/distributions/inverse_gamma_specification.m
index c7f02a19428fa1a939f6beba98791f3e9fbba382..410d4e52b277f6b6409858f80feb75f8f49e22d7 100644
--- a/matlab/distributions/inverse_gamma_specification.m
+++ b/matlab/distributions/inverse_gamma_specification.m
@@ -2,7 +2,7 @@ function [s,nu] = inverse_gamma_specification(mu, sigma2, lb, type, use_fzero_fl
 
 % Computes the inverse Gamma hyperparameters from the prior mean and standard deviation.
 %
-% INPUTS 
+% INPUTS
 % - mu               [double]   scalar, prior mean.
 % - sigma2           [double]   positive scalar, prior variance.
 % - type             [integer]  scalar equal to 1 or 2, type of the inverse gamma distribution
@@ -10,16 +10,16 @@ function [s,nu] = inverse_gamma_specification(mu, sigma2, lb, type, use_fzero_fl
 %                               dynare's implementation of the secant method otherwise.
 % - name             [string]   name of the parameter or random variable.
 %
-% OUTPUS 
+% OUTPUS
 % - s                [double]    scalar, first hyperparameter.
 % - nu               [double]    scalar, second hyperparameter.
 %
-% REMARK 
+% REMARK
 % The call to the matlab's implementation of the secant method is here for testing purpose and should not be used. This routine fails
 % more often in finding an interval for nu containing a signe change because it expands the interval on both sides and eventually
 % violates  the condition nu>2.
 
-% Copyright (C) 2003-2015 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -85,10 +85,10 @@ nu = [];
 sigma = sqrt(sigma2);
 mu2 = mu*mu;
 
-if type == 2;       % Inverse Gamma 2
+if type == 2       % Inverse Gamma 2
     nu   = 2*(2+mu2/sigma2);
     s    = 2*mu*(1+mu2/sigma2);
-elseif type == 1;   % Inverse Gamma 1
+elseif type == 1   % Inverse Gamma 1
     if sigma2 < Inf
         nu = sqrt(2*(2+mu2/sigma2));
         if use_fzero_flag
diff --git a/matlab/distributions/lpdfgweibull.m b/matlab/distributions/lpdfgweibull.m
index 3f2df819d298a2f99bfddff04a1a2355e47747fc..708a5b4d440787a60cadd87065fc183ae796b38a 100644
--- a/matlab/distributions/lpdfgweibull.m
+++ b/matlab/distributions/lpdfgweibull.m
@@ -1,14 +1,14 @@
 function [ldens,Dldens,D2ldens] = lpdfgweibull(x,a,b,c)  % --*-- Unitary tests --*--
 
-% Evaluates the logged Weibull PDF at x. 
+% Evaluates the logged Weibull PDF at x.
 %
-% INPUTS 
+% INPUTS
 % - x       [double]  m*n matrix of points where the (logged) density will be evaluated,
 % - a       [double]  m*n matrix of First Weibull distribution parameters (shape parameter, k),
 % - b       [double]  m*n matrix of Second Weibull distribution parameters (scale parameter, λ),
 % - c       [double]  m*n matrix of Third Weibull distribution parameters (location parameter, default is 0).
 %
-% OUTPUTS 
+% OUTPUTS
 % - ldens   [double]  m*n matrix of logged (generalized) Weibull densities.
 % - Dldens  [double]  m*n matrix (first order derivatives w.r.t. x)
 % - D2ldens [double]  m*n matrix (second order derivatives w.r.t. x)
@@ -16,7 +16,7 @@ function [ldens,Dldens,D2ldens] = lpdfgweibull(x,a,b,c)  % --*-- Unitary tests -
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2015-2016 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -54,11 +54,11 @@ end
 if ~isscalar(x)
     if isscalar(a)
         a = repmat(a, size(x));
-    end 
+    end
     if isscalar(b)
         b = repmat(b, size(x));
     end
-    if isscalar(c) 
+    if isscalar(c)
         c = repmat(c, size(x));
     end
 end
@@ -77,7 +77,7 @@ if isempty(idx), return, end
 
 jdx = find( abs(a-1)<1e-12 & x>=c & (x-c)<1e-12) ;
 ldens(jdx) = 1.0;
-    
+
 if ~isempty(idx)
     x0 = x(idx)-c(idx);
     x1 = x0./b(idx);
@@ -136,7 +136,7 @@ end
 %$ catch
 %$    t(1) = false;
 %$ end
-%$ 
+%$
 %$ if t(1)
 %$    t(2) = isinf(a);
 %$ end
@@ -179,7 +179,7 @@ end
 %$ scale = 1;
 %$ shape = 2;
 %$ mode  = scale*((shape-1)/shape)^(1/shape);
-%$ 
+%$
 %$ try
 %$    [a, b, c] = lpdfgweibull(mode, shape, scale);
 %$    p = rand(1000,1)*4;
@@ -203,7 +203,7 @@ end
 %$ scale = 1;
 %$ shape = 2;
 %$ density  = @(x) exp(lpdfgweibull(x,shape,scale));
-%$ 
+%$
 %$ try
 %$    if isoctave
 %$        s = quadv(density, .0000000001, 100000,1e-10);
@@ -226,7 +226,7 @@ end
 %$ scale = 1;
 %$ shape = 1;
 %$ density  = @(x) exp(lpdfgweibull(x,shape,scale));
-%$ 
+%$
 %$ try
 %$    if isoctave
 %$        s = quadv(density, .0000000001, 100000,1e-10);
@@ -249,7 +249,7 @@ end
 %$ scale = 1;
 %$ shape = .5;
 %$ density  = @(x) exp(lpdfgweibull(x,shape,scale));
-%$ 
+%$
 %$ try
 %$    if isoctave
 %$        s = quadv(density, .0000000001, 100000,1e-10)
@@ -276,7 +276,7 @@ end
 %$ scale = 1;
 %$ shape = 2;
 %$ xdens = @(x) x.*exp(lpdfgweibull(x,shape,scale));
-%$ 
+%$
 %$ try
 %$    if isoctave
 %$        s = quadv(xdens, .0000000001, 20,1e-10)
@@ -299,7 +299,7 @@ end
 %$ scale = 1;
 %$ shape = 1;
 %$ xdens = @(x) x.*exp(lpdfgweibull(x,shape,scale));
-%$ 
+%$
 %$ try
 %$    if isoctave
 %$        s = quadv(xdens, .0000000001, 100000,1e-10)
@@ -322,7 +322,7 @@ end
 %$ scale = 1;
 %$ shape = .5;
 %$ xdens = @(x) x.*exp(lpdfgweibull(x,shape,scale));
-%$ 
+%$
 %$ try
 %$    if isoctave
 %$        s = quadv(xdens, .0000000001, 100000,1e-10)
diff --git a/matlab/distributions/mode_and_variance_to_mean.m b/matlab/distributions/mode_and_variance_to_mean.m
index a69f0cdbe2638710086a821a14213b38a4cd65e2..8611955b0c0ab51237cc14f27d40fbb47c4f549c 100644
--- a/matlab/distributions/mode_and_variance_to_mean.m
+++ b/matlab/distributions/mode_and_variance_to_mean.m
@@ -1,23 +1,23 @@
 function [mu, parameters] = mode_and_variance_to_mean(m,s2,distribution,lower_bound,upper_bound)
 % This function computes the mean of a distribution given the mode and variance of this distribution.
 %
-%  INPUTS 
+%  INPUTS
 %    m                [double]    scalar, mode of the distribution.
 %    s2               [double]    scalar, variance of the distribution.
-%    distribution     [integer]   scalar for the distribution shape 
+%    distribution     [integer]   scalar for the distribution shape
 %                                    1 gamma
 %                                    2 inv-gamma-2
 %                                    3 inv-gamma-1
-%                                    4 beta    
+%                                    4 beta
 %    lower_bound      [double]    scalar, lower bound of the random variable support (optional).
 %    upper_bound      [double]    scalar, upper bound of the random variable support (optional).
-%    
-%  OUTPUT 
+%
+%  OUTPUT
 %    mu               [double]    scalar, mean of the distribution.
 %    parameters       [double]    2*1 vector, parameters of the distribution.
-%    
+%
 
-% Copyright (C) 2009 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -34,7 +34,7 @@ function [mu, parameters] = mode_and_variance_to_mean(m,s2,distribution,lower_bo
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-% Check input aruments. 
+% Check input aruments.
 if ~(nargin==3 || nargin==5 || nargin==4 )
     error('mode_and_variance_to mean:: 3 or 5 input arguments are needed!')
 end
@@ -80,7 +80,7 @@ if (distribution==1)% Gamma distribution
     end
     if (m-lower_bound)<1e-12
         error('The gamma distribution should be specified with the mean and variance.')
-    end        
+    end
     m = m - lower_bound ;
     beta  = -.5*m*(1-sqrt(1+4*s2/(m*m))) ;
     alpha = (m+beta)/beta ;
diff --git a/matlab/distributions/multivariate_normal_pdf.m b/matlab/distributions/multivariate_normal_pdf.m
index 29feabaf638f28e61b3d5a05b2e8220c0ae3f70b..55bae7283a3765857c4087056ccdaf7ad640b363 100644
--- a/matlab/distributions/multivariate_normal_pdf.m
+++ b/matlab/distributions/multivariate_normal_pdf.m
@@ -1,21 +1,21 @@
-function density = multivariate_normal_pdf(X,Mean,Sigma_upper_chol,n);
+function density = multivariate_normal_pdf(X,Mean,Sigma_upper_chol,n)
 % Evaluates the density of a multivariate gaussian, with expectation Mean
 % and variance Sigma_upper_chol'*Sigma_upper_chol, at X.
-% 
 %
-% INPUTS 
 %
-%    X                  [double]    1*n vector        
+% INPUTS
+%
+%    X                  [double]    1*n vector
 %    Mean               [double]    1*n vector, expectation of the multivariate random variable.
 %    Sigma_upper_chol   [double]    n*n matrix, upper triangular Cholesky decomposition of Sigma (the covariance matrix).
 %    n                  [integer]   dimension.
-%    
-% OUTPUTS 
-%    density            [double]    density 
-%        
+%
+% OUTPUTS
+%    density            [double]    density
+%
 % SPECIAL REQUIREMENTS
 
-% Copyright (C) 2003-2009 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -31,6 +31,6 @@ function density = multivariate_normal_pdf(X,Mean,Sigma_upper_chol,n);
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
-density = (2*pi)^(-.5*n) * ... 
+density = (2*pi)^(-.5*n) * ...
           prod(diag(Sigma_upper_chol))^(-1) * ...
           exp(-.5*(X-Mean)*(Sigma_upper_chol\(transpose(Sigma_upper_chol)\transpose(X-Mean))));
\ No newline at end of file
diff --git a/matlab/distributions/multivariate_student_pdf.m b/matlab/distributions/multivariate_student_pdf.m
index 3f498c6734bf34f8d5e4d79d1edb2fdf3d91b354..1465d4402429ffce0ffa5daa00143e57f5735faf 100644
--- a/matlab/distributions/multivariate_student_pdf.m
+++ b/matlab/distributions/multivariate_student_pdf.m
@@ -1,20 +1,20 @@
-function density = multivariate_student_pdf(X,Mean,Sigma_upper_chol,df);
+function density = multivariate_student_pdf(X,Mean,Sigma_upper_chol,df)
 % Evaluates the density of a multivariate student, with expectation Mean,
 % variance Sigma_upper_chol'*Sigma_upper_chol and degrees of freedom df, at X.
 %
-% INPUTS 
+% INPUTS
 %
-%    X                  [double]    1*n vector        
+%    X                  [double]    1*n vector
 %    Mean               [double]    1*n vector, expectation of the multivariate random variable.
 %    Sigma_upper_chol   [double]    n*n matrix, upper triangular Cholesky decomposition of Sigma (the "covariance matrix").
 %    df                 [integer]   degrees of freedom.
-%    
-% OUTPUTS 
-%    density            [double]    density. 
-%        
+%
+% OUTPUTS
+%    density            [double]    density.
+%
 % SPECIAL REQUIREMENTS
 
-% Copyright (C) 2003-2009 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/distributions/rand_inverse_wishart.m b/matlab/distributions/rand_inverse_wishart.m
index c561fb7f466acf57c57aa1ca7ce206054ae66a44..4f3675e3c97f8187954274f25732972bc476e9cd 100644
--- a/matlab/distributions/rand_inverse_wishart.m
+++ b/matlab/distributions/rand_inverse_wishart.m
@@ -17,14 +17,14 @@ function G = rand_inverse_wishart(m, v, H_inv_upper_chol)
 % OUTPUTS:
 %     G:          G ~ IW(m, v, H) where H = inv(H_inv_upper_chol'*H_inv_upper_chol)
 %                 or, equivalently, using the correspondence between Wishart and
-%                 inverse-Wishart: inv(G) ~ W(m, v, S) where 
+%                 inverse-Wishart: inv(G) ~ W(m, v, S) where
 %                 S = H_inv_upper_chol'*H_inv_upper_chol = inv(H)
-%  
+%
 % SPECIAL REQUIREMENT
 %     none
-%    
+%
 
-% Copyright (C) 2003-2009 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -41,7 +41,7 @@ function G = rand_inverse_wishart(m, v, H_inv_upper_chol)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-X = randn(v, m) * H_inv_upper_chol; 
+X = randn(v, m) * H_inv_upper_chol;
 
 
 % At this point, X'*X is Wishart distributed
diff --git a/matlab/distributions/rand_matrix_normal.m b/matlab/distributions/rand_matrix_normal.m
index ff595cca873938cd12b1a011604e8d361a388982..0de2faf0892f8195628a0b6e55a44856c7d157aa 100644
--- a/matlab/distributions/rand_matrix_normal.m
+++ b/matlab/distributions/rand_matrix_normal.m
@@ -2,7 +2,7 @@ function B = rand_matrix_normal(n, p, M, Omega_lower_chol, Sigma_lower_chol)
 
 % function B = rand_matrix_normal(n, p, M, Omega_lower_chol, Sigma_lower_chol)
 % Pseudo random matrices drawn from a matrix-normal distribution
-% B ~ MN_n*p(M, Omega, Sigma) 
+% B ~ MN_n*p(M, Omega, Sigma)
 % Equivalent to vec(B) ~ N(vec(Mu), kron(Omega, Sigma))
 %
 % INPUTS
@@ -13,14 +13,14 @@ function B = rand_matrix_normal(n, p, M, Omega_lower_chol, Sigma_lower_chol)
 %                       (Omega_lower_chol = chol(Omega, 'lower'))
 %    Sigma_lower_chol:  (n*n), lower Cholesky decomposition of Sigma,
 %                       (Sigma_lower_chol = chol(Sigma, 'lower'))
-%    
+%
 % OUTPUTS
 %    B:                 (n*p) matrix drawn from a Matrix-normal distribution
-%        
+%
 % SPECIAL REQUIREMENTS
 %    Same notations than: http://en.wikipedia.org/wiki/Matrix_normal_distribution
 
-% Copyright (C) 2003-2009 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/distributions/rand_multivariate_normal.m b/matlab/distributions/rand_multivariate_normal.m
index 174c3706cceedd5f71cfec03c1e9be39a0c3eedd..d74d74b7be5b5c7b5634519217b43468a7c8e721 100644
--- a/matlab/distributions/rand_multivariate_normal.m
+++ b/matlab/distributions/rand_multivariate_normal.m
@@ -2,19 +2,19 @@ function draw = rand_multivariate_normal(Mean,Sigma_upper_chol,n)
 % Pseudo random draws from a multivariate normal distribution,
 % \mathcal N_n(Mean,Sigma), with expectation Mean and variance Sigma.
 %
-% INPUTS 
+% INPUTS
 %
 %    Mean               [double]    1*n vector, expectation of the multivariate random variable.
 %    Sigma_upper_chol   [double]    n*n matrix, upper triangular Cholesky decomposition of Sigma (the covariance matrix).
 %    n                  [integer]   dimension.
-%    
-% OUTPUTS 
+%
+% OUTPUTS
 %    draw               [double]    1*n vector drawn from a multivariate normal distribution with expectation Mean and
-%                                   covariance Sigma 
-%        
+%                                   covariance Sigma
+%
 % SPECIAL REQUIREMENTS
 
-% Copyright (C) 2003-2009 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/distributions/rand_multivariate_student.m b/matlab/distributions/rand_multivariate_student.m
index eca1d05852c76a88788811e4412ae3c070238128..69b26e85ed62d4148bc9a6d3c9391cec25bf881a 100644
--- a/matlab/distributions/rand_multivariate_student.m
+++ b/matlab/distributions/rand_multivariate_student.m
@@ -3,27 +3,27 @@ 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.
 %
-% INPUTS 
+% INPUTS
 %
 %    Mean               [double]    1*n vector, expectation of the multivariate random variable.
-%    Sigma_upper_chol   [double]    n*n matrix, upper triangular Cholesky decomposition of Sigma 
+%    Sigma_upper_chol   [double]    n*n matrix, upper triangular Cholesky decomposition of Sigma
 %                                   (the covariance matrix up to a factor df/(df-2)).
 %    df                 [integer]   degrees of freedom.
-%    
-% OUTPUTS 
+%
+% OUTPUTS
 %    draw               [double]    1*n vector drawn from a multivariate normal distribution with expectation Mean and
 %                                   covariance Sigma.
-%        
 %
-% NOTE See Zellner (appendix B.2, 1971) for a definition.     
-%    Computes the t-distributed random numbers from 
+%
+% 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 
+%   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
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/distributions/weibull_specification.m b/matlab/distributions/weibull_specification.m
index 8036dcb8dfd21912df52d2580dacbb99ef370c82..b9d498a53fa36fc294fbd50e388749fbc586e857 100644
--- a/matlab/distributions/weibull_specification.m
+++ b/matlab/distributions/weibull_specification.m
@@ -2,14 +2,14 @@ function [shape, scale] = weibull_specification(mu, sigma2, lb, name)   % --*--
 
 % Returns the hyperparameters of the Weibull distribution given the expectation and variance.
 %
-% INPUTS 
+% INPUTS
 %
 %
-% OUTPUTS 
+% OUTPUTS
+%
 %
-% 
 
-% Copyright (C) 2015-2016 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -49,8 +49,8 @@ end
 scale = NaN;
 shape = NaN;
 
-mu = mu-lb; 
-mu2 = mu*mu;   
+mu = mu-lb;
+mu2 = mu*mu;
 
 eqn = @(k) gammaln(1+2./k) - 2*gammaln(1+1./k) - log(1+sigma2/mu2);
 eqn2 = @(k) eqn(k).*eqn(k);
@@ -140,4 +140,3 @@ scale = mu/gamma(1+1/shape);
 %$ end
 %$ T = all(t);
 %@eof:1
-
diff --git a/matlab/do_parameter_initialization.m b/matlab/do_parameter_initialization.m
index 1f18c3f5663995224917fa4098bc4f6d2e03f813..145984cec92e0177eab12ef62af6cf9eb3f71c68 100644
--- a/matlab/do_parameter_initialization.m
+++ b/matlab/do_parameter_initialization.m
@@ -6,24 +6,24 @@ function [xparam1,estim_params_,xparam1_explicitly_initialized,xparam1_properly_
 %    o estim_params_    [structure] characterizing parameters to be estimated.
 %    o xparam1_calib    [double]    vector of parameters to be estimated, with parameters
 %                                   initialized from calibration using get_all_parameters
-%     
+%
 %    o xparam1_NaN_set_to_prior_mean [double]    vector of parameters to be estimated, with parameters
 %                                                initialized using dynare_estimation_init; not explicitly initialized
 %                                                parameters are at prior mean
 % OUTPUTS
 %    o xparam1                           [double]    vector of initialized parameters; uses the hierarchy: 1) explicitly initialized parameters,
 %                                                    2) calibrated parameters, 3) prior mean
-%    o estim_params_    [structure] characterizing parameters to be estimated; it is 
+%    o estim_params_    [structure] characterizing parameters to be estimated; it is
 %                                   updated here to reflect calibrated parameters
 %    o xparam1_explicitly_initialized    [double]    vector of parameters to be estimated that
-%                                                    were explicitly initialized 
+%                                                    were explicitly initialized
 %    o xparam1_properly_calibrated       [double]    vector of parameters to be estimated that
-%                                                    were properly calibrated 
-%    
+%                                                    were properly calibrated
+%
 % SPECIAL REQUIREMENTS
 %    None
 
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -59,7 +59,7 @@ offset=0;
 if nvx
     initialized_par_index=find(~isnan(estim_params_.var_exo(:,2)));
     calibrated_par_index=find(isnan(estim_params_.var_exo(:,2)) & ~isnan(xparam1_calib(offset+1:offset+nvx,1)));
-    uninitialized_par_index=find(isnan(estim_params_.var_exo(:,2)) & isnan(xparam1_calib(offset+1:offset+nvx,1)));    
+    uninitialized_par_index=find(isnan(estim_params_.var_exo(:,2)) & isnan(xparam1_calib(offset+1:offset+nvx,1)));
     xparam1_explicitly_initialized(offset+initialized_par_index,1) = estim_params_.var_exo(initialized_par_index,2);
     %update estim_params_ with calibrated starting values
     estim_params_.var_exo(calibrated_par_index,2)=xparam1_calib(offset+calibrated_par_index,1);
@@ -67,13 +67,13 @@ if nvx
     xparam1_properly_calibrated(offset+calibrated_par_index,1) = xparam1_calib(offset+calibrated_par_index,1);
     inv_gamma_violation=find(estim_params_.var_exo(calibrated_par_index,2)==0 & estim_params_.var_exo(calibrated_par_index,5)==4);
     if inv_gamma_violation
-        estim_params_.var_exo(calibrated_par_index(inv_gamma_violation),2)=NaN;        
-        xparam1_properly_calibrated(offset+calibrated_par_index(inv_gamma_violation),1)=NaN;        
-        fprintf('PARAMETER INITIALIZATION: Some standard deviations of shocks of the calibrated model are 0 and\n') 
-        fprintf('PARAMETER INITIALIZATION: violate the inverse gamma prior. They will instead be initialized with the prior mean.\n')    
+        estim_params_.var_exo(calibrated_par_index(inv_gamma_violation),2)=NaN;
+        xparam1_properly_calibrated(offset+calibrated_par_index(inv_gamma_violation),1)=NaN;
+        fprintf('PARAMETER INITIALIZATION: Some standard deviations of shocks of the calibrated model are 0 and\n')
+        fprintf('PARAMETER INITIALIZATION: violate the inverse gamma prior. They will instead be initialized with the prior mean.\n')
     end
     if uninitialized_par_index
-        fprintf('PARAMETER INITIALIZATION: Warning, some estimated standard deviations of shocks are not\n') 
+        fprintf('PARAMETER INITIALIZATION: Warning, some estimated standard deviations of shocks are not\n')
         fprintf('PARAMETER INITIALIZATION: initialized. They will be initialized with the prior mean.\n')
     end
 end
@@ -88,10 +88,10 @@ if nvn
     xparam1_properly_calibrated(offset+calibrated_par_index,1) = xparam1_calib(offset+calibrated_par_index,1);
     inv_gamma_violation=find(estim_params_.var_endo(calibrated_par_index,2)==0 & estim_params_.var_endo(calibrated_par_index,5)==4);
     if inv_gamma_violation
-        estim_params_.var_endo(calibrated_par_index(inv_gamma_violation),2)=NaN;        
-        xparam1_properly_calibrated(offset+calibrated_par_index(inv_gamma_violation),1)=NaN;        
+        estim_params_.var_endo(calibrated_par_index(inv_gamma_violation),2)=NaN;
+        xparam1_properly_calibrated(offset+calibrated_par_index(inv_gamma_violation),1)=NaN;
         fprintf('PARAMETER INITIALIZATION: Some measurement errors of the calibrated model are 0 and violate the\n')
-        fprintf('PARAMETER INITIALIZATION: inverse gamma prior. They will instead be initialized with the prior mean.\n')    
+        fprintf('PARAMETER INITIALIZATION: inverse gamma prior. They will instead be initialized with the prior mean.\n')
     end
     if uninitialized_par_index
         fprintf('PARAMETER INITIALIZATION: Warning, some measurement errors are not initialized. They will be initialized\n')
@@ -140,4 +140,3 @@ end
 xparam1=xparam1_explicitly_initialized;
 xparam1(isnan(xparam1))=xparam1_properly_calibrated(isnan(xparam1)); %set not explicitly initialized parameters that do not obviously violate prior distribution to calibrated parameter values
 xparam1(isnan(xparam1))=xparam1_NaN_set_to_prior_mean(isnan(xparam1)); %set not yet initialized parameters to prior mean coming from dynare_estimation_init
-
diff --git a/matlab/dr_block.m b/matlab/dr_block.m
index 47c20add23faaf5f244d4a513a2e1ebc8ef31c2a..61826d390f467bdd1a4bad7d976831125d9e1ebb 100644
--- a/matlab/dr_block.m
+++ b/matlab/dr_block.m
@@ -1,40 +1,40 @@
 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_,varargin)
 % computes the reduced form solution of a rational expectations model
-% (first order approximation of the stochastic model around the deterministic steady state). 
+% (first order approximation of the stochastic model around the deterministic steady state).
 %
 % INPUTS
 %   dr         [matlab structure] Decision rules for stochastic simulations.
 %   task       [integer]          if task = 0 then dr_block computes decision rules.
 %                                 if task = 1 then dr_block computes eigenvalues.
-%   M_         [matlab structure] Definition of the model.           
+%   M_         [matlab structure] Definition of the model.
 %   options_   [matlab structure] Global options.
-%   oo_        [matlab structure] Results 
+%   oo_        [matlab structure] Results
 %   oo_        [matlab cell]      Other input arguments
-%    
+%
 % OUTPUTS
 %   dr         [matlab structure] Decision rules for stochastic simulations.
 %   info       [integer]          info=1: the model doesn't define current variables uniquely
-%                                 info=2: problem in mjdgges.dll info(2) contains error code. 
+%                                 info=2: problem in mjdgges.dll info(2) contains error code.
 %                                 info=3: BK order condition not satisfied info(2) contains "distance"
 %                                         absence of stable trajectory.
 %                                 info=4: BK order condition not satisfied info(2) contains "distance"
 %                                         indeterminacy.
 %                                 info=5: BK rank condition not satisfied.
-%                                 info=6: The jacobian matrix evaluated at the steady state is complex.        
-%   M_         [matlab structure]            
+%                                 info=6: The jacobian matrix evaluated at the steady state is complex.
+%   M_         [matlab structure]
 %   options_   [matlab structure]
 %   oo_        [matlab structure]
-%  
+%
 % ALGORITHM
 %   first order block relaxation method applied to the model
 %    E[A Yt-1 + B Yt + C Yt+1 + ut] = 0
-%    
+%
 % SPECIAL REQUIREMENTS
 %   none.
-%  
+%
 
-% Copyright (C) 2010-2016 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -54,7 +54,7 @@ function [dr,info,M_,options_,oo_] = dr_block(dr,task,M_,options_,oo_,varargin)
 info = 0;
 verbose = 0;
 if nargin > 5
-  verbose = varargin{1};
+    verbose = varargin{1};
 end
 %verbose = options_.verbosity;
 if options_.order > 1
@@ -69,13 +69,13 @@ if (isfield(M_,'block_structure'))
 else
     data = M_;
     Size = 1;
-end;
+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'], options_, M_, oo_, z', zx, M_.params, dr.ys, M_.maximum_lag+1, data);
     chck = 0;
-end;
+end
 mexErrCheck('bytecode', chck);
 dr.full_rank = 1;
 dr.eigval = [];
@@ -90,7 +90,7 @@ n_sv = size(dr.state_var, 2);
 dr.ghx = zeros(M_.endo_nbr, length(dr.state_var));
 dr.exo_var = 1:M_.exo_nbr;
 dr.ghu = zeros(M_.endo_nbr, M_.exo_nbr);
-for i = 1:Size;
+for i = 1:Size
     ghx = [];
     indexi_0 = 0;
     if (verbose)
@@ -98,7 +98,7 @@ for i = 1:Size;
         disp(['Block ' int2str(i)]);
         disp('-----------');
         data(i)
-    end;
+    end
     n_pred = data(i).n_backward;
     n_fwrd = data(i).n_forward;
     n_both = data(i).n_mixed;
@@ -118,23 +118,23 @@ for i = 1:Size;
         disp(jacob);
         disp('lead_lag_incidence');
         disp(lead_lag_incidence);
-    end;
+    end
     maximum_lag = data(i).maximum_endo_lag;
     maximum_lead = data(i).maximum_endo_lead;
     n = n_dynamic + n_static;
-    
+
     block_type = M_.block_structure.block(i).Simulation_Type;
     if task ~= 1
-        if block_type == 2 || block_type == 4 || block_type == 7 
+        if block_type == 2 || block_type == 4 || block_type == 7
             block_type = 8;
-        end;
-    end;
-    if maximum_lag > 0 && (n_pred > 0  || n_both > 0) && block_type ~= 1 
+        end
+    end
+    if maximum_lag > 0 && (n_pred > 0  || n_both > 0) && block_type ~= 1
         indexi_0 = min(lead_lag_incidence(2,:));
-    end;
+    end
     switch block_type
       case 1
-      %% ------------------------------------------------------------------
+        %% ------------------------------------------------------------------
         %Evaluate Forward
         if maximum_lag > 0 && n_pred > 0
             indx_r = find(M_.block_structure.block(i).lead_lag_incidence(1,:));
@@ -153,7 +153,7 @@ for i = 1:Size;
             if (maximum_lag > 0 && n_pred > 0)
                 [indx_r, tmp1, indx_r_v]  = find(M_.block_structure.block(i).lead_lag_incidence(1,:));
                 ghx = - B \ jacob(:,indx_r_v);
-            end;
+            end
             if other_endo_nbr
                 fx = data(i).g1_o;
                 % retrieves the derivatives with respect to endogenous
@@ -175,11 +175,11 @@ for i = 1:Size;
                 l_x_sv = dr.ghx(dr.state_var, 1:n_sv);
 
                 selector_tm1 = M_.block_structure.block(i).tm1;
-               
+
                 ghx_other = - B \ (fx_t * l_x + (fx_tp1 * l_x * l_x_sv) + fx_tm1 * selector_tm1);
                 dr.ghx(endo, :) = dr.ghx(endo, :) + ghx_other;
-            end;
-            
+            end
+
             if exo_nbr
                 fu = data(i).g1_x;
                 exo = dr.exo_var;
@@ -194,21 +194,21 @@ for i = 1:Size;
                     fu_complet = zeros(n, M_.exo_nbr);
                     fu_complet(:,data(i).exogenous) = fu;
                     ghu = - B \ fu_complet;
-                end;
+                end
             else
                 exo = dr.exo_var;
                 if other_endo_nbr > 0
-                     l_u_sv = dr.ghu(dr.state_var,:);
-                     l_x = dr.ghx(data(i).other_endogenous,:);
-                     l_u = dr.ghu(data(i).other_endogenous,:);
-                     ghu = -B \ (fx_tp1 * l_x * l_u_sv + (fx_t) * l_u );
+                    l_u_sv = dr.ghu(dr.state_var,:);
+                    l_x = dr.ghx(data(i).other_endogenous,:);
+                    l_u = dr.ghu(data(i).other_endogenous,:);
+                    ghu = -B \ (fx_tp1 * l_x * l_u_sv + (fx_t) * l_u );
                 else
                     ghu = [];
                 end
             end
         end
       case 2
-      %% ------------------------------------------------------------------
+        %% ------------------------------------------------------------------
         %Evaluate Backward
         if maximum_lead > 0 && n_fwrd > 0
             indx_r = find(M_.block_structure.block(i).lead_lag_incidence(3,:));
@@ -229,11 +229,11 @@ for i = 1:Size;
                 indx_r = find(M_.block_structure.block(i).lead_lag_incidence(3,:));
                 indx_c = M_.block_structure.block(i).lead_lag_incidence(3,indx_r);
                 ghx = - inv(jacob(indx_r, indx_c));
-            end;
+            end
             ghu =  - inv(jacob(indx_r, indx_c)) * data(i).g1_x;
         end
       case 3
-      %% ------------------------------------------------------------------
+        %% ------------------------------------------------------------------
         %Solve Forward single equation
         if maximum_lag > 0 && n_pred > 0
             data(i).eigval = - jacob(1 , 1 : n_pred) / jacob(1 , n_pred + n_static + 1 : n_pred + n_static + n_pred + n_both);
@@ -241,15 +241,15 @@ for i = 1:Size;
         else
             data(i).eigval = [];
             data(i).rank = 0;
-        end;
+        end
         dr.eigval = [dr.eigval ; data(i).eigval];
         %First order approximation
         if task ~= 1
             if (maximum_lag > 0)
-                 ghx = - jacob(1 , 1 : n_pred) / jacob(1 , n_pred + n_static + 1 : n_pred + n_static + n_pred + n_both);
+                ghx = - jacob(1 , 1 : n_pred) / jacob(1 , n_pred + n_static + 1 : n_pred + n_static + n_pred + n_both);
             else
-                 ghx = 0;
-            end;
+                ghx = 0;
+            end
             if other_endo_nbr
                 fx = data(i).g1_o;
                 % retrieves the derivatives with respect to endogenous
@@ -269,12 +269,12 @@ for i = 1:Size;
 
                 l_x = dr.ghx(data(i).other_endogenous,:);
                 l_x_sv = dr.ghx(dr.state_var, 1:n_sv);
-                
+
                 selector_tm1 = M_.block_structure.block(i).tm1;
                 ghx_other = - (fx_t * l_x + (fx_tp1 * l_x * l_x_sv) + fx_tm1 * selector_tm1) / jacob(1 , n_pred + 1 : n_pred + n_static + n_pred + n_both);
                 dr.ghx(endo, :) = dr.ghx(endo, :) + ghx_other;
 
-            end;
+            end
             if exo_nbr
                 fu = data(i).g1_x;
                 if other_endo_nbr > 0
@@ -287,21 +287,21 @@ for i = 1:Size;
                     exo = dr.exo_var;
                 else
                     ghu = - fu  / jacob(1 , n_pred + 1 : n_pred + n_static + n_pred + n_both);
-                end;
+                end
             else
-                 if other_endo_nbr > 0
-                     l_u_sv = dr.ghu(dr.state_var,:);
-                     l_x = dr.ghx(data(i).other_endogenous,:);
-                     l_u = dr.ghu(data(i).other_endogenous,:);
-                     ghu = -(fx_tp1 * l_x * l_u_sv + (fx_t) * l_u ) / jacob(1 , n_pred + 1 : n_pred + n_static + n_pred + n_both);
-                     exo = dr.exo_var;
-                 else
-                     ghu = [];
-                 end
+                if other_endo_nbr > 0
+                    l_u_sv = dr.ghu(dr.state_var,:);
+                    l_x = dr.ghx(data(i).other_endogenous,:);
+                    l_u = dr.ghu(data(i).other_endogenous,:);
+                    ghu = -(fx_tp1 * l_x * l_u_sv + (fx_t) * l_u ) / jacob(1 , n_pred + 1 : n_pred + n_static + n_pred + n_both);
+                    exo = dr.exo_var;
+                else
+                    ghu = [];
+                end
             end
         end
       case 4
-      %% ------------------------------------------------------------------
+        %% ------------------------------------------------------------------
         %Solve Backward single equation
         if maximum_lead > 0 && n_fwrd > 0
             data(i).eigval = - jacob(1 , n_pred + n - n_fwrd + 1 : n_pred + n) / jacob(1 , n_pred + n + 1 : n_pred + n + n_fwrd) ;
@@ -311,18 +311,18 @@ for i = 1:Size;
             data(i).eigval = [];
             data(i).rank = 0;
             full_rank = 1;
-        end;
+        end
         dr.full_rank = dr.full_rank && full_rank;
         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);
+                          + n_pred + n_both) \ jacob(: , 1 : n_pred);
         else
             ghx = 0;
-        end;
+        end
         if maximum_lag > 0 && n_pred > 0
             data(i).eigval = -eig(ghx(n_static+1:end,:));
             data(i).rank = 0;
@@ -331,7 +331,7 @@ for i = 1:Size;
             data(i).eigval = [];
             data(i).rank = 0;
             full_rank = 1;
-        end;
+        end
         dr.eigval = [dr.eigval ; data(i).eigval];
         dr.full_rank = dr.full_rank && full_rank;
         if task ~= 1
@@ -354,11 +354,11 @@ for i = 1:Size;
 
                 l_x = dr.ghx(data(i).other_endogenous,:);
                 l_x_sv = dr.ghx(dr.state_var, 1:n_sv);
-                
+
                 selector_tm1 = M_.block_structure.block(i).tm1;
                 ghx_other = - (fx_t * l_x + (fx_tp1 * l_x * l_x_sv) + fx_tm1 * selector_tm1) / jacob(: , n_pred + 1 : n_pred + n_static + n_pred + n_both);
                 dr.ghx(endo, :) = dr.ghx(endo, :) + ghx_other;
-            end;
+            end
             if exo_nbr
                 fu = data(i).g1_x;
                 if other_endo_nbr > 0
@@ -371,21 +371,21 @@ for i = 1:Size;
                     exo = dr.exo_var;
                 else
                     ghu = - fu  / jacob(: , n_pred + 1 : n_pred + n_static + n_pred + n_both);
-                end;
+                end
             else
-                 if other_endo_nbr > 0
-                     l_u_sv = dr.ghu(dr.state_var,:);
-                     l_x = dr.ghx(data(i).other_endogenous,:);
-                     l_u = dr.ghu(data(i).other_endogenous,:);
-                     ghu = -(fx_tp1 * l_x * l_u_sv + (fx_t) * l_u ) / jacob(1 , n_pred + 1 : n_pred + n_static + n_pred + n_both);
-                     exo = dr.exo_var;
-                 else
-                     ghu = [];
-                 end
+                if other_endo_nbr > 0
+                    l_u_sv = dr.ghu(dr.state_var,:);
+                    l_x = dr.ghx(data(i).other_endogenous,:);
+                    l_u = dr.ghu(data(i).other_endogenous,:);
+                    ghu = -(fx_tp1 * l_x * l_u_sv + (fx_t) * l_u ) / jacob(1 , n_pred + 1 : n_pred + n_static + n_pred + n_both);
+                    exo = dr.exo_var;
+                else
+                    ghu = [];
+                end
             end
         end
       case 7
-      %% ------------------------------------------------------------------
+        %% ------------------------------------------------------------------
         %Solve Backward complete
         if maximum_lead > 0 && n_fwrd > 0
             data(i).eigval = eig(- jacob(: , n_pred + n - n_fwrd + 1: n_pred + n))/ ...
@@ -397,14 +397,14 @@ for i = 1:Size;
             data(i).eigval = [];
             data(i).rank = 0;
             full_rank = 1;
-        end;
+        end
         dr.full_rank = dr.full_rank && full_rank;
         dr.eigval = [dr.eigval ; data(i).eigval];
       case {5,8}
-      %% ------------------------------------------------------------------
+        %% ------------------------------------------------------------------
         %The lead_lag_incidence contains columns in the following order:
         %  static variables, backward variable, mixed variables and forward variables
-        %  
+        %
         %Proceeds to a QR decomposition on the jacobian matrix in order to reduce the problem size
         index_c = lead_lag_incidence(2,:);             % Index of all endogenous variables present at time=t
         index_s = lead_lag_incidence(2,1:n_static);    % Index of all static endogenous variables present at time=t
@@ -413,7 +413,7 @@ for i = 1:Size;
             aa = Q'*jacob;
         else
             aa = jacob;
-        end;
+        end
         index_0m = (n_static+1:n_static+n_pred) + indexi_0 - 1;
         index_0p = (n_static+n_pred+1:n) + indexi_0 - 1;
         index_m = 1:(n_pred+n_both);
@@ -435,7 +435,7 @@ for i = 1:Size;
             hx = ghx(1:n_pred+n_both,:);
             gx = ghx(1+n_pred:end,:);
         end
-        
+
         if (task ~= 1 && ((options_.dr_cycle_reduction == 1 && info ==1) || options_.dr_cycle_reduction == 0)) || task == 1
             D = [[aa(row_indx,index_0m) zeros(n_dynamic,n_both) aa(row_indx,index_p)] ; [zeros(n_both, n_pred) eye(n_both) zeros(n_both, n_both + n_fwrd)]];
             E = [-aa(row_indx,[index_m index_0p])  ; [zeros(n_both, n_both + n_pred) eye(n_both, n_both + n_fwrd) ] ];
@@ -445,7 +445,7 @@ for i = 1:Size;
             if (verbose)
                 disp('eigval');
                 disp(data(i).eigval);
-            end;
+            end
             if info1
                 if info1 == -30
                     % one eigenvalue is close to 0/0
@@ -468,7 +468,7 @@ for i = 1:Size;
                 disp(['sum eigval > 1 = ' int2str(sum(abs(data(i).eigval) > 1.)) ' nyf=' int2str(nyf) ' and dr.rank=' int2str(data(i).rank)]);
                 disp(['data(' int2str(i) ').eigval']);
                 disp(data(i).eigval);
-            end;
+            end
 
             %First order approximation
             if task ~= 1
@@ -483,11 +483,11 @@ for i = 1:Size;
                             nba = nyf;
                         end
                     else
-					    sorted_roots = sort(abs(data(i).eigval));
+                        sorted_roots = sort(abs(data(i).eigval));
                         if nba > nyf
                             temp = sorted_roots(nd-nba+1:nd-nyf)-1-options_.qz_criterium;
                             info(1) = 3;
-                        elseif nba < nyf;
+                        elseif nba < nyf
                             temp = sorted_roots(nd-nyf+1:nd-nba)-1-options_.qz_criterium;
                             info(1) = 4;
                         end
@@ -497,8 +497,8 @@ for i = 1:Size;
                 end
                 indx_stable_root = 1: (nd - nyf);     %=> index of stable roots
                 indx_explosive_root = n_pred + n_both + 1:nd;  %=> index of explosive roots
-                % derivatives with respect to dynamic state variables
-                % forward variables
+                                                               % derivatives with respect to dynamic state variables
+                                                               % forward variables
                 Z = w';
                 Z11t = Z(indx_stable_root,    indx_stable_root)';
                 Z21  = Z(indx_explosive_root, indx_stable_root);
@@ -507,7 +507,7 @@ for i = 1:Size;
                     % condest() fails on a scalar under Octave
                     info(1) = 5;
                     info(2) = condest(Z21);
-                    return;
+                    return
                 else
                     %gx = -inv(Z22) * Z21;
                     gx = - Z22 \ Z21;
@@ -520,20 +520,20 @@ for i = 1:Size;
                 k2 = 1:(n_fwrd+n_both);
 
                 ghx = [hx(k1,:); gx(k2(n_both+1:end),:)];
-            end;
-        end;
-        
-        if  task~= 1 
+            end
+        end
+
+        if  task~= 1
             %lead variables actually present in the model
             j4 = n_static+n_pred+1:n_static+n_pred+n_both+n_fwrd;   % Index on the forward and both variables
             j3 = nonzeros(lead_lag_incidence(2,j4)) - n_static - 2 * n_pred - n_both;  % Index on the non-zeros forward and both variables
-            j4 = find(lead_lag_incidence(2,j4)); 
-            
+            j4 = find(lead_lag_incidence(2,j4));
+
             if n_static > 0
                 B_static = B(:,1:n_static);  % submatrix containing the derivatives w.r. to static variables
             else
                 B_static = [];
-            end;
+            end
             %static variables, backward variable, mixed variables and forward variables
             B_pred = B(:,n_static+1:n_static+n_pred+n_both);
             B_fyd = B(:,n_static+n_pred+n_both+1:end);
@@ -549,16 +549,16 @@ for i = 1:Size;
                 temp = b10\(temp-b11*ghx);
                 ghx = [temp; ghx];
                 temp = [];
-            end;
-            
+            end
+
             A_ = real([B_static C(:,j3)*gx+B_pred B_fyd]); % The state_variable of the block are located at [B_pred B_both]
-            
+
             if other_endo_nbr
                 if n_static > 0
-                     fx = Q' * data(i).g1_o;
+                    fx = Q' * data(i).g1_o;
                 else
                     fx = data(i).g1_o;
-                end;
+                end
                 % retrieves the derivatives with respect to endogenous
                 % variable belonging to previous blocks
                 fx_tm1 = zeros(n,other_endo_nbr);
@@ -575,10 +575,10 @@ for i = 1:Size;
                 fx_tp1(:,c) = fx(:,lead);
 
                 l_x = dr.ghx(data(i).other_endogenous,:);
-                
+
                 l_x_sv = dr.ghx(dr.state_var, :);
-                
-                selector_tm1 = M_.block_structure.block(i).tm1; 
+
+                selector_tm1 = M_.block_structure.block(i).tm1;
 
                 B_ = [zeros(size(B_static)) zeros(n,n_pred) C(:,j3) ];
                 C_ = l_x_sv;
@@ -590,23 +590,23 @@ for i = 1:Size;
                     ghx_other = reshape(vghx_other, size(D_,1), size(D_,2));
                 elseif options_.sylvester_fp == 1
                     ghx_other = gensylv_fp(A_, B_, C_, D_, i, options_.sylvester_fixed_point_tol);
-                else 
+                else
                     [err, ghx_other] = gensylv(1, A_, B_, C_, -D_);
-                end;
+                end
                 if options_.aim_solver ~= 1 && options_.use_qzdiv
-                   % Necessary when using Sims' routines for QZ
-                   ghx_other = real(ghx_other);
+                    % Necessary when using Sims' routines for QZ
+                    ghx_other = real(ghx_other);
                 end
-                
+
                 dr.ghx(endo, :) = dr.ghx(endo, :) + ghx_other;
-            end;
+            end
 
             if exo_nbr
                 if n_static > 0
                     fu = Q' * data(i).g1_x;
                 else
                     fu = data(i).g1_x;
-                end;
+                end
 
                 if other_endo_nbr > 0
                     l_u_sv = dr.ghu(dr.state_var,:);
@@ -616,12 +616,12 @@ for i = 1:Size;
                     fu_complet(:,data(i).exogenous) = fu;
                     % Solve the equation in ghu:
                     % A_ * ghu + (fu_complet + fx_tp1 * l_x * l_u_sv + (fx_t + B_ * ghx_other) * l_u ) = 0
-                    
+
                     ghu = -A_\ (fu_complet + fx_tp1 * l_x * l_u_sv + fx_t * l_u + B_ * ghx_other  * l_u_sv  );
                     exo = dr.exo_var;
                 else
                     ghu = - A_ \ fu;
-                end;
+                end
             else
                 if other_endo_nbr > 0
                     l_u_sv = dr.ghu(dr.state_var,:);
@@ -633,20 +633,20 @@ for i = 1:Size;
                     exo = dr.exo_var;
                 else
                     ghu = [];
-                end;
+                end
             end
 
 
-            
+
             if options_.loglinear
                 error('The loglinear option is not yet supported in first order approximation for a block decomposed model');
-%                 k = find(dr.kstate(:,2) <= M_.maximum_endo_lag+1);
-%                 klag = dr.kstate(k,[1 2]);
-%                 k1 = dr.order_var;
-%                 
-%                 ghx = repmat(1./dr.ys(k1),1,size(ghx,2)).*ghx.* ...
-%                       repmat(dr.ys(k1(klag(:,1)))',size(ghx,1),1);
-%                 ghu = repmat(1./dr.ys(k1),1,size(ghu,2)).*ghu;
+                %                 k = find(dr.kstate(:,2) <= M_.maximum_endo_lag+1);
+                %                 klag = dr.kstate(k,[1 2]);
+                %                 k1 = dr.order_var;
+                %
+                %                 ghx = repmat(1./dr.ys(k1),1,size(ghx,2)).*ghx.* ...
+                %                       repmat(dr.ys(k1(klag(:,1)))',size(ghx,1),1);
+                %                 ghu = repmat(1./dr.ys(k1),1,size(ghu,2)).*ghu;
             end
 
 
@@ -659,19 +659,19 @@ for i = 1:Size;
             %exogenous deterministic variables
             if exo_det_nbr > 0
                 error('Deterministic exogenous variables are not yet implemented in first order approximation for a block decomposed model');
-%                 f1 = sparse(jacobia_(:,nonzeros(M_.lead_lag_incidence(M_.maximum_endo_lag+2:end,order_var))));
-%                 f0 = sparse(jacobia_(:,nonzeros(M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var))));
-%                 fudet = data(i).g1_xd;
-%                 M1 = inv(f0+[zeros(n,n_static) f1*gx zeros(n,nyf-n_both)]);
-%                 M2 = M1*f1;
-%                 dr.ghud = cell(M_.exo_det_length,1);
-%                 dr.ghud{1} = -M1*fudet;
-%                 for i = 2:M_.exo_det_length
-%                     dr.ghud{i} = -M2*dr.ghud{i-1}(end-nyf+1:end,:);
-%                 end
+                %                 f1 = sparse(jacobia_(:,nonzeros(M_.lead_lag_incidence(M_.maximum_endo_lag+2:end,order_var))));
+                %                 f0 = sparse(jacobia_(:,nonzeros(M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var))));
+                %                 fudet = data(i).g1_xd;
+                %                 M1 = inv(f0+[zeros(n,n_static) f1*gx zeros(n,nyf-n_both)]);
+                %                 M2 = M1*f1;
+                %                 dr.ghud = cell(M_.exo_det_length,1);
+                %                 dr.ghud{1} = -M1*fudet;
+                %                 for i = 2:M_.exo_det_length
+                %                     dr.ghud{i} = -M2*dr.ghud{i-1}(end-nyf+1:end,:);
+                %                 end
             end
         end
-    end;
+    end
     if task ~=1
         if (maximum_lag > 0 && (n_pred > 0 || n_both > 0))
             sorted_col_dr_ghx = M_.block_structure.block(i).sorted_col_dr_ghx;
@@ -680,27 +680,27 @@ for i = 1:Size;
             data(i).pol.i_ghx = sorted_col_dr_ghx;
         else
             data(i).pol.i_ghx = [];
-        end;
+        end
         data(i).ghu = ghu;
         dr.ghu(endo, exo) = ghu;
         data(i).pol.i_ghu = exo;
-    end;
-    
-   if (verbose)
+    end
+
+    if (verbose)
         disp('dr.ghx');
         dr.ghx
         disp('dr.ghu');
         dr.ghu
-   end; 
-   
-end;
+    end
+
+end
 M_.block_structure.block = data ;
 if (verbose)
-        disp('dr.ghx');
-        disp(real(dr.ghx));
-        disp('dr.ghu');
-        disp(real(dr.ghu));
-end; 
+    disp('dr.ghx');
+    disp(real(dr.ghx));
+    disp('dr.ghu');
+    disp(real(dr.ghu));
+end
 if (task == 1)
-    return;
-end;
+    return
+end
diff --git a/matlab/draw_prior_density.m b/matlab/draw_prior_density.m
index 23479b404a62ba63fd497489aaa08c1a3555c531..94f32ac8813c7a4822331dd06567086f35939867 100644
--- a/matlab/draw_prior_density.m
+++ b/matlab/draw_prior_density.m
@@ -1,20 +1,20 @@
-function [x,f,abscissa,dens,binf,bsup] = draw_prior_density(indx,bayestopt_);
+function [x,f,abscissa,dens,binf,bsup] = draw_prior_density(indx,bayestopt_)
 % Computes values of prior densities at many points (before plotting)
 %
 % INPUTS
 %    indx          [integer]    Parameter number.
 %    bayestopt_    [structure]  Describes the prior beliefs.
-%    
+%
 % OUTPUTS
 %    x             [double]     Row vector, subset of 'abscissa' such as the density is less than 10
 %    f             [double]     Row vector, subset of 'dens' such as the density is less than 10
-%    abscissa      [double]     Row vector, abscissa 
+%    abscissa      [double]     Row vector, abscissa
 %    dens          [double]     Row vector, density
 %    binf:         [double]     Scalar, first element of x
 %    bsup:         [double]     Scalar, last element of x
 
 
-% Copyright (C) 2004-2011 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -63,10 +63,10 @@ switch pshape(indx)
     abscissa = linspace(infbound,supbound,steps);
     dens = density(abscissa,p6(indx),p7(indx),p3(indx));
   case 3% Gaussian prior
-    infbound = norminv(truncprior,p6(indx),p7(indx)); 
+    infbound = norminv(truncprior,p6(indx),p7(indx));
     supbound = norminv(1-truncprior,p6(indx),p7(indx));
     abscissa = linspace(infbound,supbound,steps);
-    dens = normpdf(abscissa,p6(indx),p7(indx));  
+    dens = normpdf(abscissa,p6(indx),p7(indx));
   case 4% Inverse-gamma of type 1 prior
     try
         infbound = 1/sqrt(gaminv(1-10*truncprior, p7(indx)/2, 2/p6(indx)))+p3(indx);
@@ -80,7 +80,7 @@ switch pshape(indx)
         end
     end
     abscissa = linspace(infbound,supbound,steps);
-    dens = exp(lpdfig1(abscissa-p3(indx),p6(indx),p7(indx)));  
+    dens = exp(lpdfig1(abscissa-p3(indx),p6(indx),p7(indx)));
   case 5% Uniform prior
     infbound = p6(indx);
     supbound = p7(indx);
@@ -108,9 +108,9 @@ switch pshape(indx)
     dens = density(abscissa,p6(indx),p7(indx),p3(indx));
   otherwise
     error(sprintf('draw_prior_density: unknown distribution shape (index %d, type %d)', indx, pshape(indx)));
-end 
+end
 
-if pshape(indx) ~= 5 
+if pshape(indx) ~= 5
     [junk,k1] = max(dens);
     if k1 == 1 || k1 == length(dens)
         k = find(dens > 10);
diff --git a/matlab/dsample.m b/matlab/dsample.m
index 2e7251ac1853683dca2ca987fa97bcb64ffe3a51..945c0fd86830fd2658aa5aa13a8ce2e5b0165c68 100644
--- a/matlab/dsample.m
+++ b/matlab/dsample.m
@@ -1,21 +1,21 @@
 function dsample(s1,s2)
 % function dsample(s1,s2)
 % This optional command permits to reduce the number of periods considered in following output commands.
-% If only one argument is provided, output is from period 1 to the period specified in the DSAMPLE command. 
+% If only one argument is provided, output is from period 1 to the period specified in the DSAMPLE command.
 % If two arguments are present output is done for the interval between the two periods.
 % DSAMPLE without arguments reset the sample to the one specified by PERIODS
 %
 % INPUTS
 %    s1:      first period
 %    s2:      last period
-%    
+%
 % OUTPUTS
 %    none
-%    
+%
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2001-2009 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/dsge_likelihood.m b/matlab/dsge_likelihood.m
index d911adc6e0031556eb62fe1fdaeee6c73a8e1c9a..0b62e516753e59b6fd4e6c8332f1d08d1e7416ee 100644
--- a/matlab/dsge_likelihood.m
+++ b/matlab/dsge_likelihood.m
@@ -115,7 +115,7 @@ function [fval,info,exit_flag,DLIK,Hess,SteadyState,trend_coeff,Model,DynareOpti
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2004-2016 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -149,7 +149,7 @@ xparam1 = xparam1(:);
 if DynareOptions.estimation_dll
     [fval,exit_flag,SteadyState,trend_coeff,info,params,H,Q] ...
         = logposterior(xparam1,DynareDataset, DynareOptions,Model, ...
-                          EstimatedParameters,BayesInfo,DynareResults);
+                       EstimatedParameters,BayesInfo,DynareResults);
     mexErrCheck('logposterior', exit_flag);
     Model.params = params;
     if ~isequal(Model.H,0)
@@ -167,11 +167,11 @@ if analytic_derivation && DynareOptions.loglinear
     error('The analytic_derivation and loglinear options are not compatible')
 end
 
-if nargout==1,
+if nargout==1
     analytic_derivation=0;
 end
 
-if analytic_derivation,
+if analytic_derivation
     kron_flag=DynareOptions.analytic_derivation_mode;
 end
 
@@ -180,26 +180,26 @@ end
 %------------------------------------------------------------------------------
 
 % Return, with endogenous penalty, if some parameters are smaller than the lower bound of the prior domain.
-if ~isequal(DynareOptions.mode_compute,1) && any(xparam1<BoundsInfo.lb)
+if isestimation(DynareOptions) && ~isequal(DynareOptions.mode_compute,1) && any(xparam1<BoundsInfo.lb)
     k = find(xparam1<BoundsInfo.lb);
     fval = Inf;
     exit_flag = 0;
     info(1) = 41;
     info(4)= sum((BoundsInfo.lb(k)-xparam1(k)).^2);
-    if analytic_derivation,
+    if analytic_derivation
         DLIK=ones(length(xparam1),1);
     end
     return
 end
 
 % Return, with endogenous penalty, if some parameters are greater than the upper bound of the prior domain.
-if ~isequal(DynareOptions.mode_compute,1) && any(xparam1>BoundsInfo.ub)
+if isestimation(DynareOptions) && ~isequal(DynareOptions.mode_compute,1) && any(xparam1>BoundsInfo.ub)
     k = find(xparam1>BoundsInfo.ub);
     fval = Inf;
     exit_flag = 0;
     info(1) = 42;
     info(4)= sum((xparam1(k)-BoundsInfo.ub(k)).^2);
-    if analytic_derivation,
+    if analytic_derivation
         DLIK=ones(length(xparam1),1);
     end
     return
@@ -268,41 +268,38 @@ end
 % Return, with endogenous penalty when possible, if dynare_resolve issues an error code (defined in resol).
 if info(1)
     if info(1) == 3 || info(1) == 4 || info(1) == 5 || info(1)==6 ||info(1) == 19 ||...
-            info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1) == 26 || ...
-            info(1) == 81 || info(1) == 84 ||  info(1) == 85 ||  info(1) == 86
+                info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1) == 26 || ...
+                info(1) == 81 || info(1) == 84 ||  info(1) == 85 ||  info(1) == 86
         %meaningful second entry of output that can be used
         fval = Inf;
         info(4) = info(2);
         exit_flag = 0;
-        if analytic_derivation,
+        if analytic_derivation
             DLIK=ones(length(xparam1),1);
         end
-        
         return
     else
         fval = Inf;
         info(4) = 0.1;
         exit_flag = 0;
-        if analytic_derivation,
+        if analytic_derivation
             DLIK=ones(length(xparam1),1);
         end
-        
         return
     end
 end
 
 % check endogenous prior restrictions
 info=endogenous_prior_restrictions(T,R,Model,DynareOptions,DynareResults);
-if info(1),
+if info(1)
     fval = Inf;
     info(4)=info(2);
     exit_flag = 0;
-    if analytic_derivation,
+    if analytic_derivation
         DLIK=ones(length(xparam1),1);
     end
     return
 end
-%
 
 % Define a vector of indices for the observed variables. Is this really usefull?...
 BayesInfo.mf = BayesInfo.mf1;
@@ -323,8 +320,8 @@ if BayesInfo.with_trend
     [trend_addition, trend_coeff]=compute_trend_coefficients(Model,DynareOptions,DynareDataset.vobs,DynareDataset.nobs);
     trend = repmat(constant,1,DynareDataset.nobs)+trend_addition;
 else
-   trend_coeff = zeros(DynareDataset.vobs,1);
-   trend = repmat(constant,1,DynareDataset.nobs);
+    trend_coeff = zeros(DynareDataset.vobs,1);
+    trend = repmat(constant,1,DynareDataset.nobs);
 end
 
 % Get needed informations for kalman filter routines.
@@ -372,8 +369,8 @@ switch DynareOptions.lik_init
     if kalman_algo == 0
         kalman_algo = 3;
     elseif ~((kalman_algo == 3) || (kalman_algo == 4))
-            error(['The model requires Diffuse filter, but you specified a different Kalman filter. You must set options_.kalman_algo ' ...
-                   'to 0 (default), 3 or 4'])
+        error(['The model requires Diffuse filter, but you specified a different Kalman filter. You must set options_.kalman_algo ' ...
+               'to 0 (default), 3 or 4'])
     end
     [Pstar,Pinf] = compute_Pinf_Pstar(Z,T,R,Q,DynareOptions.qz_criterium,[1:length(T)]);
     Z =zeros(length(BayesInfo.mf),size(T,1));
@@ -387,9 +384,9 @@ switch DynareOptions.lik_init
         Pstar0 = Pstar; % store Pstar
         if no_missing_data_flag
             [dLIK,dlik,a,Pstar] = kalman_filter_d(Y, 1, size(Y,2), ...
-                                                       zeros(mm,1), Pinf, Pstar, ...
-                                                       kalman_tol, diffuse_kalman_tol, riccati_tol, DynareOptions.presample, ...
-                                                       T,R,Q,H,Z,mm,pp,rr);
+                                                  zeros(mm,1), Pinf, Pstar, ...
+                                                  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), ...
@@ -433,27 +430,27 @@ switch DynareOptions.lik_init
                 Pinf  = blkdiag(Pinf,zeros(pp));
                 H1 = zeros(pp,1);
                 mmm   = mm+pp;
-                
+
             end
         end
 
         [dLIK,dlik,a,Pstar] = univariate_kalman_filter_d(DatasetInfo.missing.aindex,...
-                                                        DatasetInfo.missing.number_of_observations,...
-                                                        DatasetInfo.missing.no_more_missing_observations, ...
-                                                        Y, 1, size(Y,2), ...
-                                                        zeros(mmm,1), Pinf, Pstar, ...
-                                                        kalman_tol, diffuse_kalman_tol, riccati_tol, DynareOptions.presample, ...
-                                                        T,R,Q,H1,Z,mmm,pp,rr);
+                                                         DatasetInfo.missing.number_of_observations,...
+                                                         DatasetInfo.missing.no_more_missing_observations, ...
+                                                         Y, 1, size(Y,2), ...
+                                                         zeros(mmm,1), Pinf, Pstar, ...
+                                                         kalman_tol, diffuse_kalman_tol, riccati_tol, DynareOptions.presample, ...
+                                                         T,R,Q,H1,Z,mmm,pp,rr);
         diffuse_periods = size(dlik,1);
     end
-    if isnan(dLIK),
+    if isnan(dLIK)
         fval = Inf;
         info(1) = 45;
         info(4) = 0.1;
         exit_flag = 0;
         return
     end
-    
+
   case 4% Start from the solution of the Riccati equation.
     if kalman_algo ~= 2
         kalman_algo = 1;
@@ -495,20 +492,19 @@ switch DynareOptions.lik_init
     error('dsge_likelihood:: Unknown initialization approach for the Kalman filter!')
 end
 
-if analytic_derivation,
+if analytic_derivation
     offset = EstimatedParameters.nvx;
     offset = offset+EstimatedParameters.nvn;
     offset = offset+EstimatedParameters.ncx;
     offset = offset+EstimatedParameters.ncn;
-
     no_DLIK = 0;
     full_Hess = analytic_derivation==2;
     asy_Hess = analytic_derivation==-2;
     outer_product_gradient = analytic_derivation==-1;
-    if asy_Hess,
+    if asy_Hess
         analytic_derivation=1;
     end
-    if outer_product_gradient,
+    if outer_product_gradient
         analytic_derivation=1;
     end
     DLIK = [];
@@ -526,8 +522,7 @@ if analytic_derivation,
         else
             indparam=[];
         end
-
-        if full_Hess,
+        if full_Hess
             [dum, DT, DOm, DYss, dum2, D2T, D2Om, D2Yss] = getH(A, B, EstimatedParameters, Model,DynareResults,DynareOptions,kron_flag,indparam,indexo,iv);
             clear dum dum2;
         else
@@ -537,15 +532,15 @@ if analytic_derivation,
         DT = derivatives_info.DT(iv,iv,:);
         DOm = derivatives_info.DOm(iv,iv,:);
         DYss = derivatives_info.DYss(iv,:);
-        if isfield(derivatives_info,'full_Hess'),
+        if isfield(derivatives_info,'full_Hess')
             full_Hess = derivatives_info.full_Hess;
         end
-        if full_Hess,
-        D2T = derivatives_info.D2T;
-        D2Om = derivatives_info.D2Om;
-        D2Yss = derivatives_info.D2Yss;
+        if full_Hess
+            D2T = derivatives_info.D2T;
+            D2Om = derivatives_info.D2Om;
+            D2Yss = derivatives_info.D2Yss;
         end
-        if isfield(derivatives_info,'no_DLIK'),
+        if isfield(derivatives_info,'no_DLIK')
             no_DLIK = derivatives_info.no_DLIK;
         end
         clear('derivatives_info');
@@ -554,73 +549,73 @@ if analytic_derivation,
     DH=zeros([length(H),length(H),length(xparam1)]);
     DQ=zeros([size(Q),length(xparam1)]);
     DP=zeros([size(T),length(xparam1)]);
-    if full_Hess,
-        for j=1:size(D2Yss,1),
-        tmp(j,:,:) = blkdiag(zeros(offset,offset), squeeze(D2Yss(j,:,:)));
+    if full_Hess
+        for j=1:size(D2Yss,1)
+            tmp(j,:,:) = blkdiag(zeros(offset,offset), squeeze(D2Yss(j,:,:)));
         end
         D2Yss = tmp;
         D2H=sparse(size(D2Om,1),size(D2Om,2)); %zeros([size(H),length(xparam1),length(xparam1)]);
         D2P=sparse(size(D2Om,1),size(D2Om,2)); %zeros([size(T),length(xparam1),length(xparam1)]);
         jcount=0;
     end
-    if DynareOptions.lik_init==1,
-    for i=1:EstimatedParameters.nvx
-        k =EstimatedParameters.var_exo(i,1);
-        DQ(k,k,i) = 2*sqrt(Q(k,k));
-        dum =  lyapunov_symm(T,DOm(:,:,i),DynareOptions.lyapunov_fixed_point_tol,DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold,[],DynareOptions.debug);
-%         kk = find(abs(dum) < 1e-12);
-%         dum(kk) = 0;
-        DP(:,:,i)=dum;
-        if full_Hess
-        for j=1:i,
-            jcount=jcount+1;
-            dum =  lyapunov_symm(T,dyn_unvech(D2Om(:,jcount)),DynareOptions.lyapunov_fixed_point_tol,DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold,[],DynareOptions.debug);
-%             kk = (abs(dum) < 1e-12);
-%             dum(kk) = 0;
-            D2P(:,jcount)=dyn_vech(dum);
-%             D2P(:,:,j,i)=dum;
-        end
+    if DynareOptions.lik_init==1
+        for i=1:EstimatedParameters.nvx
+            k =EstimatedParameters.var_exo(i,1);
+            DQ(k,k,i) = 2*sqrt(Q(k,k));
+            dum =  lyapunov_symm(T,DOm(:,:,i),DynareOptions.lyapunov_fixed_point_tol,DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold,[],DynareOptions.debug);
+            %         kk = find(abs(dum) < 1e-12);
+            %         dum(kk) = 0;
+            DP(:,:,i)=dum;
+            if full_Hess
+                for j=1:i
+                    jcount=jcount+1;
+                    dum =  lyapunov_symm(T,dyn_unvech(D2Om(:,jcount)),DynareOptions.lyapunov_fixed_point_tol,DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold,[],DynareOptions.debug);
+                    %             kk = (abs(dum) < 1e-12);
+                    %             dum(kk) = 0;
+                    D2P(:,jcount)=dyn_vech(dum);
+                    %             D2P(:,:,j,i)=dum;
+                end
+            end
         end
     end
-    end
     offset = EstimatedParameters.nvx;
     for i=1:EstimatedParameters.nvn
         k = EstimatedParameters.var_endo(i,1);
         DH(k,k,i+offset) = 2*sqrt(H(k,k));
         if full_Hess
-        D2H(k,k,i+offset,i+offset) = 2;
+            D2H(k,k,i+offset,i+offset) = 2;
         end
     end
     offset = offset + EstimatedParameters.nvn;
-    if DynareOptions.lik_init==1,
-    for j=1:EstimatedParameters.np
-        dum =  lyapunov_symm(T,DT(:,:,j+offset)*Pstar*T'+T*Pstar*DT(:,:,j+offset)'+DOm(:,:,j+offset),DynareOptions.lyapunov_fixed_point_tol,DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold,[],DynareOptions.debug);
-%         kk = find(abs(dum) < 1e-12);
-%         dum(kk) = 0;
-        DP(:,:,j+offset)=dum;
-        if full_Hess
-        DTj = DT(:,:,j+offset);
-        DPj = dum;
-        for i=1:j+offset,
-            jcount=jcount+1;
-            DTi = DT(:,:,i);
-            DPi = DP(:,:,i);
-            D2Tij = reshape(D2T(:,jcount),size(T));
-            D2Omij = dyn_unvech(D2Om(:,jcount));
-            tmp = D2Tij*Pstar*T' + T*Pstar*D2Tij' + DTi*DPj*T' + DTj*DPi*T' + T*DPj*DTi' + T*DPi*DTj' + DTi*Pstar*DTj' + DTj*Pstar*DTi' + D2Omij;
-            dum = lyapunov_symm(T,tmp,DynareOptions.lyapunov_fixed_point_tol,DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold,[],DynareOptions.debug);
-%             dum(abs(dum)<1.e-12) = 0;
-            D2P(:,jcount) = dyn_vech(dum);
-%             D2P(:,:,j+offset,i) = dum;
-        end
+    if DynareOptions.lik_init==1
+        for j=1:EstimatedParameters.np
+            dum =  lyapunov_symm(T,DT(:,:,j+offset)*Pstar*T'+T*Pstar*DT(:,:,j+offset)'+DOm(:,:,j+offset),DynareOptions.lyapunov_fixed_point_tol,DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold,[],DynareOptions.debug);
+            %         kk = find(abs(dum) < 1e-12);
+            %         dum(kk) = 0;
+            DP(:,:,j+offset)=dum;
+            if full_Hess
+                DTj = DT(:,:,j+offset);
+                DPj = dum;
+                for i=1:j+offset
+                    jcount=jcount+1;
+                    DTi = DT(:,:,i);
+                    DPi = DP(:,:,i);
+                    D2Tij = reshape(D2T(:,jcount),size(T));
+                    D2Omij = dyn_unvech(D2Om(:,jcount));
+                    tmp = D2Tij*Pstar*T' + T*Pstar*D2Tij' + DTi*DPj*T' + DTj*DPi*T' + T*DPj*DTi' + T*DPi*DTj' + DTi*Pstar*DTj' + DTj*Pstar*DTi' + D2Omij;
+                    dum = lyapunov_symm(T,tmp,DynareOptions.lyapunov_fixed_point_tol,DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold,[],DynareOptions.debug);
+                    %             dum(abs(dum)<1.e-12) = 0;
+                    D2P(:,jcount) = dyn_vech(dum);
+                    %             D2P(:,:,j+offset,i) = dum;
+                end
+            end
         end
     end
-    end
-    if analytic_derivation==1,
+    if analytic_derivation==1
         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 DP D2T D2Yss D2Om D2H D2P,
+        clear DT DYss DOm DP D2T D2Yss D2Om D2H D2P
     end
 else
     analytic_deriv_info={0};
@@ -645,10 +640,9 @@ if ((kalman_algo==1) || (kalman_algo==3))% Multivariate Kalman Filter
                 fval = Inf;
                 info(1) = 55;
                 info(4) = 0.1;
-                exit_flag = 0; 
+                exit_flag = 0;
                 return
             end
-
             [LIK,lik] = kalman_filter_fast(Y,diffuse_periods+1,size(Y,2), ...
                                            a,Pstar, ...
                                            kalman_tol, riccati_tol, ...
@@ -659,6 +653,7 @@ if ((kalman_algo==1) || (kalman_algo==3))% Multivariate Kalman Filter
             [LIK,lik] = kalman_filter(Y,diffuse_periods+1,size(Y,2), ...
                                       a,Pstar, ...
                                       kalman_tol, riccati_tol, ...
+                                      DynareOptions.rescale_prediction_error_covariance, ...
                                       DynareOptions.presample, ...
                                       T,Q,R,H,Z,mm,pp,rr,Zflag,diffuse_periods, ...
                                       analytic_deriv_info{:});
@@ -671,11 +666,12 @@ if ((kalman_algo==1) || (kalman_algo==3))% Multivariate Kalman Filter
             [LIK,lik] = missing_observations_kalman_filter(DatasetInfo.missing.aindex,DatasetInfo.missing.number_of_observations,DatasetInfo.missing.no_more_missing_observations,Y,diffuse_periods+1,size(Y,2), ...
                                                            a, Pstar, ...
                                                            kalman_tol, DynareOptions.riccati_tol, ...
+                                                           DynareOptions.rescale_prediction_error_covariance, ...
                                                            DynareOptions.presample, ...
                                                            T,Q,R,H,Z,mm,pp,rr,Zflag,diffuse_periods);
         end
     end
-    if analytic_derivation,
+    if analytic_derivation
         LIK1=LIK;
         LIK=LIK1{1};
         lik1=lik;
@@ -699,8 +695,8 @@ if ((kalman_algo==1) || (kalman_algo==3))% Multivariate Kalman Filter
     else
         if DynareOptions.lik_init==3
             LIK = LIK + dLIK;
-            if analytic_derivation==0 && nargout>3,
-                if ~singular_diffuse_filter,
+            if analytic_derivation==0 && nargout>3
+                if ~singular_diffuse_filter
                     lik = [dlik; lik];
                 else
                     lik = [sum(dlik,2); lik];
@@ -716,7 +712,7 @@ if (kalman_algo==2) || (kalman_algo==4)
     if isequal(H,0)
         H1 = zeros(pp,1);
         mmm = mm;
-        if analytic_derivation,
+        if analytic_derivation
             DH = zeros(pp,length(xparam1));
         end
     else
@@ -724,8 +720,8 @@ if (kalman_algo==2) || (kalman_algo==4)
             H1 = diag(H);
             mmm = mm;
             clear('tmp')
-            if analytic_derivation,
-                for j=1:pp,
+            if analytic_derivation
+                for j=1:pp
                     tmp(j,:)=DH(j,j,:);
                 end
                 DH=tmp;
@@ -750,21 +746,20 @@ if (kalman_algo==2) || (kalman_algo==4)
             if singularity_has_been_detected
                 a = zeros(mmm,1);
             elseif ~expanded_state_vector_for_univariate_filter
-                a = [a; zeros(pp,1)];                
+                a = [a; zeros(pp,1)];
             end
         end
     end
-    if analytic_derivation,
+    if analytic_derivation
         analytic_deriv_info{5}=DH;
     end
-
     [LIK, lik] = univariate_kalman_filter(DatasetInfo.missing.aindex,DatasetInfo.missing.number_of_observations,DatasetInfo.missing.no_more_missing_observations,Y,diffuse_periods+1,size(Y,2), ...
                                           a,Pstar, ...
                                           DynareOptions.kalman_tol, ...
                                           DynareOptions.riccati_tol, ...
                                           DynareOptions.presample, ...
                                           T,Q,R,H1,Z,mmm,pp,rr,Zflag,diffuse_periods,analytic_deriv_info{:});
-    if analytic_derivation,
+    if analytic_derivation
         LIK1=LIK;
         LIK=LIK1{1};
         lik1=lik;
@@ -772,7 +767,7 @@ if (kalman_algo==2) || (kalman_algo==4)
     end
     if DynareOptions.lik_init==3
         LIK = LIK+dLIK;
-        if analytic_derivation==0 && nargout>3,
+        if analytic_derivation==0 && nargout>3
             lik = [dlik; lik];
         end
     end
@@ -783,12 +778,12 @@ if analytic_derivation
         DLIK = LIK1{2};
         %                 [DLIK] = score(T,R,Q,H,Pstar,Y,DT,DYss,DOm,DH,DP,start,Z,kalman_tol,riccati_tol);
     end
-    if full_Hess ,
+    if full_Hess
         Hess = -LIK1{3};
         %                     [Hess, DLL] = get_Hessian(T,R,Q,H,Pstar,Y,DT,DYss,DOm,DH,DP,D2T,D2Yss,D2Om,D2H,D2P,start,Z,kalman_tol,riccati_tol);
         %                     Hess0 = getHessian(Y,T,DT,D2T, R*Q*transpose(R),DOm,D2Om,Z,DYss,D2Yss);
     end
-    if asy_Hess,
+    if asy_Hess
         %         if ~((kalman_algo==2) || (kalman_algo==4)),
         %             [Hess] = AHessian(T,R,Q,H,Pstar,Y,DT,DYss,DOm,DH,DP,start,Z,kalman_tol,riccati_tol);
         %         else
@@ -827,7 +822,7 @@ likelihood = LIK;
 % 5. Adds prior if necessary
 % ------------------------------------------------------------------------------
 if analytic_derivation
-    if full_Hess,
+    if full_Hess
         [lnprior, dlnprior, d2lnprior] = priordens(xparam1,BayesInfo.pshape,BayesInfo.p6,BayesInfo.p7,BayesInfo.p3,BayesInfo.p4);
         Hess = Hess - d2lnprior;
     else
@@ -836,7 +831,7 @@ if analytic_derivation
     if no_DLIK==0
         DLIK = DLIK - dlnprior';
     end
-    if outer_product_gradient,
+    if outer_product_gradient
         dlik = lik1{2};
         dlik=[- dlnprior; dlik(start:end,:)];
         Hess = dlik'*dlik;
@@ -846,14 +841,14 @@ else
 end
 
 if DynareOptions.endogenous_prior==1
-  if DynareOptions.lik_init==2 || DynareOptions.lik_init==3
-    error('Endogenous prior not supported with non-stationary models')
-  else
-    [lnpriormom]  = endogenous_prior(Y,Pstar,BayesInfo,H);
-    fval    = (likelihood-lnprior-lnpriormom);
-  end
+    if DynareOptions.lik_init==2 || DynareOptions.lik_init==3
+        error('Endogenous prior not supported with non-stationary models')
+    else
+        [lnpriormom]  = endogenous_prior(Y,Pstar,BayesInfo,H);
+        fval    = (likelihood-lnprior-lnpriormom);
+    end
 else
-  fval    = (likelihood-lnprior);
+    fval    = (likelihood-lnprior);
 end
 
 if DynareOptions.prior_restrictions.status
@@ -882,7 +877,7 @@ if ~DynareOptions.kalman.keep_kalman_algo_if_singularity_is_detected
     DynareOptions.kalman_algo = kalman_algo;
 end
 
-if analytic_derivation==0 && nargout>3,
+if analytic_derivation==0 && nargout>3
     lik=lik(start:end,:);
     DLIK=[-lnprior; lik(:)];
-end
\ No newline at end of file
+end
diff --git a/matlab/dsge_simulated_theoretical_correlation.m b/matlab/dsge_simulated_theoretical_correlation.m
index 265336dbb05bb1f2f9342aecbdc1b616eda0d734..ae141905b3a06b45705d0a83788d37db8304d216 100644
--- a/matlab/dsge_simulated_theoretical_correlation.m
+++ b/matlab/dsge_simulated_theoretical_correlation.m
@@ -16,8 +16,8 @@ function [nvar,vartan,CorrFileNumber] = dsge_simulated_theoretical_correlation(S
 %   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
+
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -126,7 +126,7 @@ for file = 1:NumberOfDrawsFiles
                 Correlation_array = zeros(NumberOfLinesInTheLastCorrFile,nvar,nvar,nar);
                 NumberOfCorrLines = NumberOfLinesInTheLastCorrFile;
                 CorrFileNumber = CorrFileNumber - 1;
-            elseif test<0;
+            elseif test<0
                 Correlation_array = zeros(MaXNumberOfCorrLines,nvar,nvar,nar);
             else
                 clear('Correlation_array');
diff --git a/matlab/dsge_simulated_theoretical_covariance.m b/matlab/dsge_simulated_theoretical_covariance.m
index 38ef7c3b60f20266c395e8b791e03ec6a085fa31..304028ba595f598e4331d5a89f7a3fec5d2bb9dc 100644
--- a/matlab/dsge_simulated_theoretical_covariance.m
+++ b/matlab/dsge_simulated_theoretical_covariance.m
@@ -16,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-2015 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -126,7 +126,6 @@ for file = 1:NumberOfDrawsFiles
             if ~test% Prepare the last round...
                 Covariance_matrix = zeros(NumberOfLinesInTheLastCovarFile,nvar*(nvar+1)/2);
                 NumberOfCovarLines = NumberOfLinesInTheLastCovarFile;
-                CovarFileNumber = CovarFileNumber - 1;
             elseif test<0
                 Covariance_matrix = zeros(MaXNumberOfCovarLines,nvar*(nvar+1)/2);
             else
diff --git a/matlab/dsge_simulated_theoretical_variance_decomposition.m b/matlab/dsge_simulated_theoretical_variance_decomposition.m
index a8ddadec6d811cafe453afb6be7f4614eb70bd5d..9eb9851741966edc28c80d5a5ed7e35ecd9967ec 100644
--- a/matlab/dsge_simulated_theoretical_variance_decomposition.m
+++ b/matlab/dsge_simulated_theoretical_variance_decomposition.m
@@ -18,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-2015 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -119,17 +119,17 @@ for file = 1:NumberOfDrawsFiles
         if file==1 && linee==1
             [tmp, stationary_vars] = th_autocovariances(dr,ivar,M_,options_,nodecomposition);
             if isempty(stationary_vars)
-              fprintf('\ndsge_simulated_theoretical_variance_decomposition:: All requested endogenous variables have a unit root and thus infinite variance.\n')
-              fprintf('dsge_simulated_theoretical_variance_decomposition:: No decomposition is performed.\n')
-              only_non_stationary_vars=1; 
+                fprintf('\ndsge_simulated_theoretical_variance_decomposition:: All requested endogenous variables have a unit root and thus infinite variance.\n')
+                fprintf('dsge_simulated_theoretical_variance_decomposition:: No decomposition is performed.\n')
+                only_non_stationary_vars=1;
             end
         end
         if only_non_stationary_vars
-           for i=1:nvar
+            for i=1:nvar
                 for j=1:nexo
                     Decomposition_array(linea,(i-1)*nexo+j) = NaN;
                 end
-           end            
+            end
         else
             tmp = th_autocovariances(dr,ivar,M_,options_,nodecomposition);
             for i=1:nvar
@@ -150,7 +150,7 @@ for file = 1:NumberOfDrawsFiles
             if ~test% Prepare the last round...
                 Decomposition_array = zeros(NumberOfLinesInTheLastDecompFile,nvar*nexo);
                 NumberOfDecompLines = NumberOfLinesInTheLastDecompFile;
-            elseif test<0;
+            elseif test<0
                 Decomposition_array = zeros(MaXNumberOfDecompLines,nvar*nexo);
             else
                 clear('Decomposition_array');
diff --git a/matlab/dsge_var_likelihood.m b/matlab/dsge_var_likelihood.m
index b97beef262e40ad6ccd799c7572ca06fc82beb69..9878d19c97718b0255ca136eb0ed0d2aeeab58c1 100644
--- a/matlab/dsge_var_likelihood.m
+++ b/matlab/dsge_var_likelihood.m
@@ -9,15 +9,15 @@ function [fval,info,exit_flag,grad,hess,SteadyState,trend_coeff,PHI_tilde,SIGMA_
 %   o fval          [double]     Value of the posterior kernel at xparam1.
 %   o info          [integer]    Vector of informations about the penalty.
 %   o exit_flag     [integer]    Zero if the function returns a penalty, one otherwise.
-%   o grad          [double]     place holder for gradient of the likelihood 
+%   o grad          [double]     place holder for gradient of the likelihood
 %                                currently not supported by dsge_var
-%   o hess          [double]     place holder for hessian matrix of the likelihood 
+%   o hess          [double]     place holder for hessian matrix of the likelihood
 %                                currently not supported by dsge_var
 %   o SteadyState   [double]     Steady state vector possibly recomputed
 %                                by call to dynare_resolve()
 %   o trend_coeff   [double]     place holder for trend coefficients,
 %                                currently not supported by dsge_var
-%   o PHI_tilde     [double]     Stacked BVAR-DSGE autoregressive matrices (at the mode associated to xparam1); 
+%   o PHI_tilde     [double]     Stacked BVAR-DSGE autoregressive matrices (at the mode associated to xparam1);
 %                                formula (28), DS (2004)
 %   o SIGMA_u_tilde [double]     Covariance matrix of the BVAR-DSGE (at the mode associated to xparam1),
 %                                formula (29), DS (2004)
@@ -32,8 +32,8 @@ function [fval,info,exit_flag,grad,hess,SteadyState,trend_coeff,PHI_tilde,SIGMA_
 % ALGORITHMS
 %   Follows the computations outlined in Del Negro/Schorfheide (2004):
 %   Priors from general equilibrium models for VARs, International Economic
-%   Review, 45(2), pp. 643-673 
-% 
+%   Review, 45(2), pp. 643-673
+%
 % SPECIAL REQUIREMENTS
 %   None.
 
@@ -102,23 +102,23 @@ mXY = evalin('base', 'mXY');
 mXX = evalin('base', 'mXX');
 
 % Return, with endogenous penalty, if some dsge-parameters are smaller than the lower bound of the prior domain.
-if DynareOptions.mode_compute ~= 1 && any(xparam1 < BoundsInfo.lb)
+if isestimation(DynareOptions) && DynareOptions.mode_compute ~= 1 && any(xparam1 < BoundsInfo.lb)
     k = find(xparam1 < BoundsInfo.lb);
     fval = Inf;
     exit_flag = 0;
     info(1) = 41;
     info(4)= sum((BoundsInfo.lb(k)-xparam1(k)).^2);
-    return;
+    return
 end
 
 % Return, with endogenous penalty, if some dsge-parameters are greater than the upper bound of the prior domain.
-if DynareOptions.mode_compute ~= 1 && any(xparam1 > BoundsInfo.ub)
+if isestimation(DynareOptions) && DynareOptions.mode_compute ~= 1 && any(xparam1 > BoundsInfo.ub)
     k = find(xparam1 > BoundsInfo.ub);
     fval = Inf;
     exit_flag = 0;
     info(1) = 42;
     info(4) = sum((xparam1(k)-BoundsInfo.ub(k)).^2);
-    return;
+    return
 end
 
 % Get the variance of each structural innovation.
@@ -137,7 +137,7 @@ Model.Sigma_e = Q;
 dsge_prior_weight = Model.params(dsge_prior_weight_idx);
 
 % Is the dsge prior proper?
-if dsge_prior_weight<(NumberOfParameters+NumberOfObservedVariables)/NumberOfObservations;
+if dsge_prior_weight<(NumberOfParameters+NumberOfObservedVariables)/NumberOfObservations
     fval = Inf;
     exit_flag = 0;
     info(1) = 51;
@@ -158,8 +158,8 @@ end
 % Return, with endogenous penalty when possible, if dynare_resolve issues an error code (defined in resol).
 if info(1)
     if info(1) == 3 || info(1) == 4 || info(1) == 5 || info(1)==6 ||info(1) == 19 ||...
-            info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1) == 26 || ...
-            info(1) == 81 || info(1) == 84 ||  info(1) == 85
+                info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1) == 26 || ...
+                info(1) == 81 || info(1) == 84 ||  info(1) == 85
         %meaningful second entry of output that can be used
         fval = Inf;
         info(4) = info(2);
@@ -233,11 +233,20 @@ assignin('base','GYX',GYX);
 iGXX = inv(GXX);
 PHI_star = iGXX*transpose(GYX); %formula (22), DS (2004)
 SIGMA_u_star=GYY - GYX*PHI_star; %formula (23), DS (2004)
+[SIGMA_u_star_is_positive_definite, penalty] = ispd(SIGMA_u_star);
+if ~SIGMA_u_star_is_positive_definite
+    fval = Inf;
+    info(1) = 53;
+    info(4) = penalty;
+    exit_flag = 0;
+    return
+end
+
 if ~isinf(dsge_prior_weight)% Evaluation of the likelihood of the dsge-var model when the dsge prior weight is finite.
     tmp0 = dsge_prior_weight*NumberOfObservations*TheoreticalAutoCovarianceOfTheObservedVariables(:,:,1) + mYY ;  %first term of square bracket in formula (29), DS (2004)
     tmp1 = dsge_prior_weight*NumberOfObservations*GYX + mYX;        %first element of second term of square bracket in formula (29), DS (2004)
     tmp2 = inv(dsge_prior_weight*NumberOfObservations*GXX+mXX);     %middle element of second term of square bracket in formula (29), DS (2004)
-    SIGMA_u_tilde = tmp0 - tmp1*tmp2*tmp1';                               %square bracket term in formula (29), DS (2004) 
+    SIGMA_u_tilde = tmp0 - tmp1*tmp2*tmp1';                               %square bracket term in formula (29), DS (2004)
     clear('tmp0');
     [SIGMAu_is_positive_definite, penalty] = ispd(SIGMA_u_tilde);
     if ~SIGMAu_is_positive_definite
@@ -245,7 +254,7 @@ if ~isinf(dsge_prior_weight)% Evaluation of the likelihood of the dsge-var model
         info(1) = 52;
         info(4) = penalty;
         exit_flag = 0;
-        return;
+        return
     end
     SIGMA_u_tilde = SIGMA_u_tilde / (NumberOfObservations*(1+dsge_prior_weight));   %prefactor of formula (29), DS (2004)
     PHI_tilde = tmp2*tmp1';                                                   %formula (28), DS (2004)
@@ -256,7 +265,7 @@ if ~isinf(dsge_prior_weight)% Evaluation of the likelihood of the dsge-var model
     prodlng2 = sum(gammaln(.5*(dsge_prior_weight*NumberOfObservations- ...
                                NumberOfParameters ...
                                +1-(1:NumberOfObservedVariables)')));    %last term in denominator of third line of (A.2), DS (2004)
-    %Compute minus log likelihood according to (A.2), DS (2004)
+                                                                        %Compute minus log likelihood according to (A.2), DS (2004)
     lik = .5*NumberOfObservedVariables*log(det(dsge_prior_weight*NumberOfObservations*GXX+mXX)) ... %first term in numerator of second line of (A.2), DS (2004)
           + .5*((dsge_prior_weight+1)*NumberOfObservations-NumberOfParameters)*log(det((dsge_prior_weight+1)*NumberOfObservations*SIGMA_u_tilde)) ... %second term in numerator of second line of (A.2), DS (2004)
           - .5*NumberOfObservedVariables*log(det(dsge_prior_weight*NumberOfObservations*GXX)) ... %first term in denominator of second line of (A.2), DS (2004)
@@ -269,7 +278,7 @@ else% Evaluation of the likelihood of the dsge-var model when the dsge prior wei
     PHI_star = iGXX*transpose(GYX);
     %Compute minus log likelihood according to (33), DS (2004) (where the last term in the trace operator has been multiplied out)
     lik = NumberOfObservations * ( log(det(SIGMA_u_star)) + NumberOfObservedVariables*log(2*pi) +  ...
-                   trace(inv(SIGMA_u_star)*(mYY - transpose(mYX*PHI_star) - mYX*PHI_star + transpose(PHI_star)*mXX*PHI_star)/NumberOfObservations));
+                                   trace(inv(SIGMA_u_star)*(mYY - transpose(mYX*PHI_star) - mYX*PHI_star + transpose(PHI_star)*mXX*PHI_star)/NumberOfObservations));
     lik = .5*lik;% Minus likelihood
     SIGMA_u_tilde=SIGMA_u_star;
     PHI_tilde=PHI_star;
@@ -328,8 +337,8 @@ if (nargout >= 10)
 end
 
 if (nargout==11)
-    prior.SIGMA_u_star = SIGMA_u_star; 
-    prior.PHI_star = PHI_star; 
+    prior.SIGMA_u_star = SIGMA_u_star;
+    prior.PHI_star = PHI_star;
     prior.ArtificialSampleSize = fix(dsge_prior_weight*NumberOfObservations);
     prior.DF = prior.ArtificialSampleSize - NumberOfParameters - NumberOfObservedVariables;
     prior.iGXX_star = iGXX;
diff --git a/matlab/dy_date.m b/matlab/dy_date.m
index 7ce72e836a1b729356a3d4a1eae7f0cabb8fde6b..9d9bb31f49f3f25068cd453be41631b553aa3d88 100644
--- a/matlab/dy_date.m
+++ b/matlab/dy_date.m
@@ -1,6 +1,6 @@
 function y=dy_date(year,period)
 
-% Copyright (C) 2005-2009 Dynare Team
+% Copyright (C) 2005-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -20,4 +20,3 @@ function y=dy_date(year,period)
 global M_
 
 y = M_.freq*(year-M_.start_date(1))+period-M_.start_date(2)+1;
-
diff --git a/matlab/dyn2vec.m b/matlab/dyn2vec.m
index a944dc1883c25ccc5e080ade2defa8e6526ff08f..50e62b4f1d4d512be431418f39a9d717f90c43e2 100644
--- a/matlab/dyn2vec.m
+++ b/matlab/dyn2vec.m
@@ -12,9 +12,9 @@ function [z,zss]=dyn2vec(s1,s2)
 %
 % SPECIAL REQUIREMENTS
 %   none
-%  
+%
 
-% Copyright (C) 2001-2009 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -50,7 +50,7 @@ if nargin == 0
     end
     return
 else
-    j = strmatch(s1,M_.endo_names,'exact'); 
+    j = strmatch(s1,M_.endo_names,'exact');
     if ~ isempty(j)
         z = oo_.endo_simul(j,k)';
     else
@@ -83,6 +83,3 @@ end
 % 08/24/01 MJ replaced globlize by internal assignin
 % 08/24/01 MJ added 'exact' to strmatch (thanks to David Vavra)
 % 01/31/03 MJ added provision for alternative name of variable
-
-
-
diff --git a/matlab/dyn_autocorr.m b/matlab/dyn_autocorr.m
index 43534d7bee736fb575aa6b60c76e7505de6968fc..e4565cf45790c42fe52c3545107f7a35516ae00f 100644
--- a/matlab/dyn_autocorr.m
+++ b/matlab/dyn_autocorr.m
@@ -35,6 +35,6 @@ acf = NaN(ar+1,1);
 acf(1)=1;
 m = mean(y);
 sd = std(y,1);
-for i=1:ar,
+for i=1:ar
     acf(i+1) = (y(i+1:end)-m)'*(y(1:end-i)-m)./((size(y,1))*sd^2);
 end
diff --git a/matlab/dyn_diag_vech.m b/matlab/dyn_diag_vech.m
index 5d5d9466486b19be9ae52eaec04e87c677b97bd2..e8b9cf338240c3a8e1c7d4ac96ce615305e6b810 100644
--- a/matlab/dyn_diag_vech.m
+++ b/matlab/dyn_diag_vech.m
@@ -1,14 +1,14 @@
 function d = dyn_diag_vech(Vector)
 % This function returns the diagonal elements of a symmetric matrix
 % stored in vech form
-% 
-% INPUTS 
+%
+% INPUTS
 %   Vector             [double]   a m*1 vector.
-%    
-% OUTPUTS 
+%
+% OUTPUTS
 %   d                  [double]   a n*1 vector, where n solves n*(n+1)/2=m.
 
-% Copyright (C) 2010 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/dyn_figure.m b/matlab/dyn_figure.m
index f26a3934560482ea8fb47649811f55f54e3b9149..62182a291bb3d5dbd78da263a8ad149c8f852c0d 100644
--- a/matlab/dyn_figure.m
+++ b/matlab/dyn_figure.m
@@ -1,9 +1,9 @@
-function h=dyn_figure(DynareOptions,varargin)
-%function h=dyn_figure(DynareOptions,varargin)
+function h = dyn_figure(nodisplay, varargin)
+%function h = dyn_figure(nodisplay, varargin)
 % initializes figures for DYNARE
 %
 % INPUTS
-%    DynareOptions: dynare options
+%    nodisplay: the value of the command-specific nodisplay argument or options_.nodisplay
 %    varargin: the same list of possible inputs of the MATLAB function figure
 %
 % OUTPUTS
@@ -12,7 +12,7 @@ function h=dyn_figure(DynareOptions,varargin)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -29,7 +29,7 @@ function h=dyn_figure(DynareOptions,varargin)
 % 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.nodisplay,
+if nodisplay
     h = figure(varargin{:},'visible','off');
 else
     h = figure(varargin{:});
diff --git a/matlab/dyn_first_order_solver.m b/matlab/dyn_first_order_solver.m
index cb5e407a833c14cf36940598f853feb3b2d819eb..a09aa1645e93f64417984dbadd0e2432d7b59291 100644
--- a/matlab/dyn_first_order_solver.m
+++ b/matlab/dyn_first_order_solver.m
@@ -47,7 +47,7 @@ function [dr,info] = dyn_first_order_solver(jacobia,DynareModel,dr,DynareOptions
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2001-2012 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -66,8 +66,8 @@ function [dr,info] = dyn_first_order_solver(jacobia,DynareModel,dr,DynareOptions
 
 persistent reorder_jacobian_columns innovations_idx index_s index_m index_c
 persistent index_p row_indx index_0m index_0p k1 k2 state_var
-persistent ndynamic nstatic nfwrd npred nboth nd nsfwrd n_current index_d 
-persistent index_e index_d1 index_d2 index_e1 index_e2 row_indx_de_1 
+persistent ndynamic nstatic nfwrd npred nboth nd nsfwrd n_current index_d
+persistent index_e index_d1 index_d2 index_e1 index_e2 row_indx_de_1
 persistent row_indx_de_2 cols_b
 
 
@@ -82,7 +82,7 @@ end
 exo_nbr = DynareModel.exo_nbr;
 
 if isempty(reorder_jacobian_columns)
-    
+
     maximum_lag = DynareModel.maximum_endo_lag;
     kstate   = dr.kstate;
     nfwrd    = DynareModel.nfwrd;
@@ -149,7 +149,7 @@ if isempty(reorder_jacobian_columns)
     index_e1 = [1:npred+nboth, npred+nboth+find(llx(maximum_lag+1,nstatic+npred+(1: ...
                                                       nsfwrd)))];
     index_e2 = npred+nboth+(1:nboth);
-    
+
     [junk,cols_b] = find(lead_lag_incidence(maximum_lag+1, order_var));
 
     reorder_jacobian_columns = [nonzeros(lead_lag_incidence(:,order_var)'); ...
@@ -179,12 +179,12 @@ if task ~= 1 && (DynareOptions.dr_cycle_reduction || DynareOptions.dr_logarithmi
     if n_current < DynareModel.endo_nbr
         if DynareOptions.dr_cycle_reduction
             error(['The cycle reduction algorithme can''t be used when the ' ...
-               'coefficient matrix for current variables isn''t invertible'])
+                   'coefficient matrix for current variables isn''t invertible'])
         elseif DynareOptions.dr_logarithmic_reduction
             error(['The logarithmic reduction algorithme can''t be used when the ' ...
                    'coefficient matrix for current variables isn''t invertible'])
         end
-    end  
+    end
     if DynareOptions.gpu
         gpuArray(A1);
         gpuArray(B1);
@@ -212,7 +212,7 @@ else
     D(row_indx_de_2,index_d2) = eye(nboth);
     E(row_indx_de_1,index_e1) = -aa(row_indx,index_e);
     E(row_indx_de_2,index_e2) = eye(nboth);
-    
+
     [err, ss, tt, w, sdim, dr.eigval, info1] = mjdgges(E, D, DynareOptions.qz_criterium, DynareOptions.qz_zero_threshold);
     mexErrCheck('mjdgges', err);
 
@@ -235,7 +235,7 @@ else
             dr.full_rank = 0;
         else
             dr.full_rank = 1;
-        end            
+        end
         return
     end
 
@@ -244,14 +244,13 @@ else
         if nba > nsfwrd
             temp = temp(nd-nba+1:nd-nsfwrd)-1-DynareOptions.qz_criterium;
             info(1) = 3;
-        elseif nba < nsfwrd;
+        elseif nba < nsfwrd
             temp = temp(nd-nsfwrd+1:nd-nba)-1-DynareOptions.qz_criterium;
             info(1) = 4;
         end
         info(2) = temp'*temp;
         return
     end
-
     %First order approximation
     indx_stable_root = 1: (nd - nsfwrd);     %=> index of stable roots
     indx_explosive_root = npred + nboth + 1:nd;  %=> index of explosive roots
@@ -267,7 +266,7 @@ else
         % Z22 is near singular
         info(1) = 5;
         info(2) = -log(rc);
-        return;
+        return
     end
     gx  = -minus_gx;
     % predetermined variables
@@ -285,7 +284,7 @@ if nstatic > 0
     B_static = B(:,1:nstatic);  % submatrix containing the derivatives w.r. to static variables
 else
     B_static = [];
-end;
+end
 %static variables, backward variable, mixed variables and forward variables
 B_pred = B(:,nstatic+1:nstatic+npred+nboth);
 B_fyd = B(:,nstatic+npred+nboth+1:end);
@@ -309,12 +308,12 @@ if exo_nbr
         fu = Q' * jacobia(:,innovations_idx);
     else
         fu = jacobia(:,innovations_idx);
-    end;
+    end
 
     ghu = - A_ \ fu;
 else
     ghu = [];
-end;
+end
 
 dr.ghx = ghx;
 dr.ghu = ghu;
diff --git a/matlab/dyn_forecast.m b/matlab/dyn_forecast.m
index 770d73e41ffd96d42129853cc38d560ebe49173a..a58b126a187b23e3c123cea13cd2c8d862f376fd 100644
--- a/matlab/dyn_forecast.m
+++ b/matlab/dyn_forecast.m
@@ -1,7 +1,7 @@
 function [forecast,info] = dyn_forecast(var_list,M,options,oo,task,dataset_info)
 % function dyn_forecast(var_list,M,options,oo,task,dataset_info)
 %   computes mean forecast for a given value of the parameters
-%   compues also confidence band for the forecast    
+%   compues also confidence band for the forecast
 %
 % INPUTS
 %   var_list:    list of variables (character matrix)
@@ -21,7 +21,7 @@ function [forecast,info] = dyn_forecast(var_list,M,options,oo,task,dataset_info)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2016 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -43,7 +43,7 @@ if nargin<6 && options.prefilter
 elseif nargin==6
     mean_varobs=dataset_info.descriptive.mean';
 end
-    
+
 info = 0;
 
 oo=make_ex_(M,options,oo);
@@ -73,9 +73,17 @@ switch task
         horizon = 5;
     end
     if isempty(M.endo_histval)
-        y0 = repmat(oo.dr.ys,1,maximum_lag);
+        if options.loglinear && ~options.logged_steady_state
+            y0 = repmat(log(oo.dr.ys),1,maximum_lag);
+        else
+            y0 = repmat(oo.dr.ys,1,maximum_lag);
+        end
     else
-        y0 = M.endo_histval;
+        if options.loglinear
+            y0 = log_variable(1:M.endo_nbr,M.endo_histval,M);
+        else
+            y0 = M.endo_histval;
+        end
     end
   case 'smoother'
     horizon = options.forecast;
@@ -84,7 +92,7 @@ switch task
     for i = 1:M.endo_nbr
         v_name = deblank(M.endo_names(i,:));
         y0(i,:) = y_smoothed.(v_name)(end-maximum_lag+1:end); %includes steady state or mean, but simult_ will subtract only steady state
-        % 2. Subtract mean/steady state and add steady state; takes care of prefiltering        
+                                                              % 2. Subtract mean/steady state and add steady state; takes care of prefiltering
         if isfield(oo.Smoother,'Constant') && isfield(oo.Smoother.Constant,v_name)
             y0(i,:)=y0(i,:)-oo.Smoother.Constant.(v_name)(end-maximum_lag+1:end); %subtract mean or steady state
             if options.loglinear
@@ -92,7 +100,7 @@ switch task
             else
                 y0(i,:)=y0(i,:)+oo.dr.ys(strmatch(v_name,deblank(M.endo_names),'exact'));
             end
-        end                
+        end
         % 2. Subtract trend
         if isfield(oo.Smoother,'Trend') && isfield(oo.Smoother.Trend,v_name)
             y0(i,:)=y0(i,:)-oo.Smoother.Trend.(v_name)(end-maximum_lag+1:end); %subtract trend, which is not subtracted by simult_
@@ -113,8 +121,8 @@ switch task
                 trend_coeffs = [trend_coeffs; oo.Smoother.TrendCoeffs(trend_var_index)];
             end
         end
-        if ~isempty(trend_coeffs) 
-            trend = trend_coeffs*(options.first_obs+gend-1+(1-M.maximum_lag:horizon)); 
+        if ~isempty(trend_coeffs)
+            trend = trend_coeffs*(options.first_obs+gend-1+(1-M.maximum_lag:horizon));
             if options.prefilter
                 trend = trend - repmat(mean(trend_coeffs*[options.first_obs:options.first_obs+gend-1],2),1,horizon+1); %subtract mean trend
             end
@@ -124,13 +132,13 @@ switch task
     end
   otherwise
     error('Wrong flag value')
-end 
+end
 
 if M.exo_det_nbr == 0
     if isequal(M.H,0)
         [yf,int_width] = forcst(oo.dr,y0,horizon,var_list,M,oo,options);
     else
-        [yf,int_width,int_width_ME] = forcst(oo.dr,y0,horizon,var_list,M,oo,options);        
+        [yf,int_width,int_width_ME] = forcst(oo.dr,y0,horizon,var_list,M,oo,options);
     end
 else
     exo_det_length = size(oo.exo_det_simul,1)-M.maximum_lag;
@@ -138,17 +146,17 @@ else
         ex = zeros(horizon,M.exo_nbr);
         oo.exo_det_simul = [ oo.exo_det_simul;...
                             repmat(oo.exo_det_steady_state',...
-                                   horizon- ... 
+                                   horizon- ...
                                    exo_det_length,1)];
-    elseif horizon <= exo_det_length 
-        ex = zeros(exo_det_length,M.exo_nbr); 
+    elseif horizon <= exo_det_length
+        ex = zeros(exo_det_length,M.exo_nbr);
     end
     if isequal(M.H,0)
         [yf,int_width] = simultxdet(y0,ex,oo.exo_det_simul,...
-                                options.order,var_list,M,oo,options);
+                                    options.order,var_list,M,oo,options);
     else
         [yf,int_width,int_width_ME] = simultxdet(y0,ex,oo.exo_det_simul,...
-                                options.order,var_list,M,oo,options);
+                                                 options.order,var_list,M,oo,options);
     end
 end
 
@@ -163,7 +171,7 @@ if options.loglinear == 1
 else
     if options.prefilter == 1 %subtract steady state and add mean for observables
         yf(i_var_obs,:)=yf(i_var_obs,:)-repmat(oo.dr.ys(i_var_obs),1,horizon+M.maximum_lag)+ repmat(mean_varobs,1,horizon+M.maximum_lag);
-    end    
+    end
 end
 
 for i=1:n_var
diff --git a/matlab/dyn_latex_table.m b/matlab/dyn_latex_table.m
index 63fb6095f6d392da82b8f39a46d38bf80df9ee05..8cfdc6e53ee8148a938ad30eba0feb3a053e42bc 100644
--- a/matlab/dyn_latex_table.m
+++ b/matlab/dyn_latex_table.m
@@ -1,7 +1,7 @@
 function dyn_latex_table(M_,options_,title,LaTeXtitle,headers,labels,values,label_width,val_width,val_precis,optional_header)
 %function dyn_latex_table(M_,options_,title,LaTeXtitle,headers,labels,values,label_width,val_width,val_precis,optional_header)
 
-% Copyright (C) 2015-2016 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -27,7 +27,7 @@ OutputDirectoryName = CheckPath('Output',M_.dname);
 %% get width of label column
 if ~isempty(label_width)
     label_width = max(size(deblank(char(headers(1,:),labels)),2)+2, ...
-        label_width);
+                      label_width);
 else %use default length
     label_width = max(size(deblank(char(headers(1,:),labels)),2))+2;
 end
diff --git a/matlab/dyn_ramsey_static.m b/matlab/dyn_ramsey_static.m
index 511f5ed1559772913c362bb0fae4dc98116d9aca..25b5301e63ce35c43e0f05e0b1923e355629c01b 100644
--- a/matlab/dyn_ramsey_static.m
+++ b/matlab/dyn_ramsey_static.m
@@ -8,7 +8,7 @@ function [steady_state,params,check] = dyn_ramsey_static(ys_init,M,options_,oo)
 %    M:             Dynare model structure
 %    options:       Dynare options structure
 %    oo:            Dynare results structure
-% 
+%
 % OUTPUTS
 %    steady_state:  steady state value
 %    params:        parameters at steady state, potentially updated by
@@ -18,7 +18,7 @@ function [steady_state,params,check] = dyn_ramsey_static(ys_init,M,options_,oo)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2016 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -39,7 +39,7 @@ function [steady_state,params,check] = dyn_ramsey_static(ys_init,M,options_,oo)
 params = M.params;
 check = 0;
 options_.steadystate.nocheck = 1; %locally disable checking because Lagrange multipliers are not accounted for in evaluate_steady_state_file
-% dyn_ramsey_static_1 is a subfunction
+                                  % dyn_ramsey_static_1 is a subfunction
 nl_func = @(x) dyn_ramsey_static_1(x,M,options_,oo);
 
 % check_static_model is a subfunction
@@ -61,7 +61,7 @@ elseif options_.steadystate_flag
         end
         if info1==4
             check=87;
-        end        
+        end
     else
         %solve for instrument, using multivariate solver, starting at
         %initial value for instrument
@@ -82,7 +82,10 @@ else
     xx = oo.steady_state(1:n_var);
     opt = options_;
     opt.jacobian_flag = 0;
-    [xx,check] = dynare_solve(nl_func,xx,opt);
+    [xx,info1] = dynare_solve(nl_func,xx,opt);
+    if info1~=0
+        check=81;
+    end
     [junk,junk,steady_state] = nl_func(xx);
 end
 
@@ -99,7 +102,7 @@ endo_nbr = M.endo_nbr;
 endo_names = M.endo_names;
 orig_endo_nbr = M.orig_endo_nbr;
 aux_vars_type = [M.aux_vars.type];
-orig_endo_aux_nbr = orig_endo_nbr + min(find(aux_vars_type == 6)) - 1; 
+orig_endo_aux_nbr = orig_endo_nbr + min(find(aux_vars_type == 6)) - 1;
 orig_eq_nbr = M.orig_eq_nbr;
 inst_nbr = orig_endo_aux_nbr - orig_eq_nbr;
 % indices of Lagrange multipliers
@@ -117,12 +120,12 @@ if options_.steadystate_flag
     ys_init(k_inst) = x; %set instrument, the only value required for steady state computation, to current value
     [x,params,check] = evaluate_steady_state_file(ys_init,... %returned x now has size endo_nbr as opposed to input size of n_instruments
                                                   [oo.exo_steady_state; ...
-                                                  oo.exo_det_steady_state], ...
+                        oo.exo_det_steady_state], ...
                                                   M,options_,~options_.steadystate.nocheck);
     if any(imag(x(1:M.orig_endo_nbr))) %return with penalty
         resids=1+sum(abs(imag(x(1:M.orig_endo_nbr)))); %return with penalty
         steady_state=NaN(endo_nbr,1);
-        return;
+        return
     end
 
 end
@@ -134,7 +137,7 @@ xx(1:M.orig_endo_nbr) = x(1:M.orig_endo_nbr); %set values of original endogenous
 if any([M.aux_vars.type] ~= 6) %auxiliary variables other than multipliers
     needs_set_auxiliary_variables = 1;
     fh = str2func([M.fname '_set_auxiliary_variables']);
-    s_a_v_func = @(z) fh(z,... 
+    s_a_v_func = @(z) fh(z,...
                          [oo.exo_steady_state,...
                         oo.exo_det_steady_state],...
                          params);
@@ -151,12 +154,12 @@ 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_steady_state oo.exo_det_steady_state], ...
-               params, 'evaluate');
-   fJ = junk.g1;
+    [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_steady_state oo.exo_det_steady_state], ...
-               params);
+    [res,fJ] = feval([fname '_static'],xx,[oo.exo_steady_state oo.exo_det_steady_state], ...
+                     params);
 end
 % index of multipliers and corresponding equations
 % the auxiliary variables before the Lagrange multipliers are treated
@@ -190,7 +193,7 @@ function result = check_static_model(ys,M,options_,oo)
 result = false;
 if (options_.bytecode)
     [chck, res, junk] = bytecode('static',ys,[oo.exo_steady_state oo.exo_det_steady_state], ...
-                                 M.params, 'evaluate'); 
+                                 M.params, 'evaluate');
 else
     res = feval([M.fname '_static'],ys,[oo.exo_steady_state oo.exo_det_steady_state], ...
                 M.params);
@@ -198,4 +201,3 @@ end
 if norm(res) < options_.solve_tolf
     result = true;
 end
-
diff --git a/matlab/dyn_risky_steadystate_solver.m b/matlab/dyn_risky_steadystate_solver.m
index a7e09b1bd3ca4fc09221c83a3feb32e33089c0f3..b677c78406149e66e0e5dca85dac37bb3b73d7f8 100644
--- a/matlab/dyn_risky_steadystate_solver.m
+++ b/matlab/dyn_risky_steadystate_solver.m
@@ -1,550 +1,550 @@
 function [dr,info] = dyn_risky_steadystate_solver(ys0,M, ...
                                                   dr,options,oo)
 
-    %@info:
-    %! @deftypefn {Function File} {[@var{dr},@var{info}] =} dyn_risky_steadystate_solver (@var{ys0},@var{M},@var{dr},@var{options},@var{oo})
-    %! @anchor{dyn_risky_steadystate_solver}
-    %! @sp 1
-    %! Computes the second order risky steady state and first and second order reduced form of the DSGE model.
-    %! @sp 2
-    %! @strong{Inputs}
-    %! @sp 1
-    %! @table @ @var
-    %! @item ys0
-    %! Vector containing a guess value for the risky steady state
-    %! @item M
-    %! Matlab's structure describing the model (initialized by @code{dynare}).
-    %! @item dr
-    %! Matlab's structure describing the reduced form solution of the model.
-    %! @item options
-    %! Matlab's structure describing the options (initialized by @code{dynare}).
-    %! @item oo
-    %! Matlab's structure gathering the results (initialized by @code{dynare}).
-    %! @end table
-    %! @sp 2
-    %! @strong{Outputs}
-    %! @sp 1
-    %! @table @ @var
-    %! @item dr
-    %! Matlab's structure describing the reduced form solution of the model.
-    %! @item info
-    %! Integer scalar, error code.
-    %! @sp 1
-    %! @table @ @code
-    %! @item info==0
-    %! No error.
-    %! @item info==1
-    %! The model doesn't determine the current variables uniquely.
-    %! @item info==2
-    %! MJDGGES returned an error code.
-    %! @item info==3
-    %! Blanchard & Kahn conditions are not satisfied: no stable equilibrium.
-    %! @item info==4
-    %! Blanchard & Kahn conditions are not satisfied: indeterminacy.
-    %! @item info==5
-    %! Blanchard & Kahn conditions are not satisfied: indeterminacy due to rank failure.
-    %! @item info==6
-    %! The jacobian evaluated at the deterministic steady state is complex.
-    %! @item info==19
-    %! The steadystate routine thrown an exception (inconsistent deep parameters).
-    %! @item info==20
-    %! Cannot find the steady state, info(2) contains the sum of square residuals (of the static equations).
-    %! @item info==21
-    %! The steady state is complex, info(2) contains the sum of square of imaginary parts of the steady state.
-    %! @item info==22
-    %! The steady has NaNs.
-    %! @item info==23
-    %! 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.
-    %! @end table
-    %! @end table
-    %! @end deftypefn
-    %@eod:
-
-    % Copyright (C) 2001-2012 Dynare Team
-    %
-    % This file is part of Dynare.
-    %
-    % Dynare is free software: you can redistribute it and/or modify
-    % it under the terms of the GNU General Public License as published by
-    % the Free Software Foundation, either version 3 of the License, or
-    % (at your option) any later version.
-    %
-    % Dynare is distributed in the hope that it will be useful,
-    % but WITHOUT ANY WARRANTY; without even the implied warranty of
-    % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    % GNU General Public License for more details.
-    %
-    % You should have received a copy of the GNU General Public License
-    % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
-
-    
-    info = 0;
-    lead_lag_incidence = M.lead_lag_incidence;
-    order_var = dr.order_var;
-    endo_nbr = M.endo_nbr;
-    exo_nbr = M.exo_nbr;
-    
-    M.var_order_endo_names = M.endo_names(dr.order_var,:);
-    
-    [junk,dr.i_fwrd_g,i_fwrd_f] = find(lead_lag_incidence(3,order_var));
-    dr.i_fwrd_f = i_fwrd_f;
-    nd = nnz(lead_lag_incidence) + M.exo_nbr;
-    dr.nd = nd;
-    kk = reshape(1:nd^2,nd,nd);
-    kkk = reshape(1:nd^3,nd^2,nd);
-    dr.i_fwrd2_f = kk(i_fwrd_f,i_fwrd_f);
-    dr.i_fwrd2a_f = kk(i_fwrd_f,:);
-    dr.i_fwrd3_f = kkk(dr.i_fwrd2_f,:);
-    dr.i_uu = kk(end-exo_nbr+1:end,end-exo_nbr+1:end);
-    if options.k_order_solver
-        func = @risky_residuals_k_order;
-    else
-        func = @risky_residuals;
-    end
-    
-    if isfield(options,'portfolio') && options.portfolio == 1
-        pm = portfolio_model_structure(M,options);
-        
-        x0 = ys0(pm.v_p);
-        n = length(x0);
-        [x, info] = solve1(@risky_residuals_ds,x0,1:n,1:n,0,options.gstep, ...
-                           options.solve_tolf,options.solve_tolx, ...
-                           options.steady.maxit,options.debug,pm,M,dr, ...
-                           options,oo);
-        if info
-            error('DS approach can''t be computed')
-        end
-        %[x, info] = csolve(@risky_residuals_ds,x0,[],1e-10,100,M,dr,options,oo);
-        %        ys0(l_var) = x;
-        [resids,dr1] = risky_residuals_ds(x,pm,M,dr,options,oo); 
-        ys1 = dr1.ys;
-    else
-        pm = model_structure(M,options);
-    end
-    
-    [ys, info] = solve1(func,ys0,1:endo_nbr,1:endo_nbr,0,options.gstep, ...
-                        options.solve_tolf,options.solve_tolx, ...
-                        options.steady.maxit,options.debug,pm,M,dr,options,oo);
-    %    [ys, info] = csolve(func,ys0,[],1e-10,100,M,dr,options,oo);
-    if info
-        error('RSS approach can''t be computed')
-    end
-    dr.ys = ys;
+%@info:
+%! @deftypefn {Function File} {[@var{dr},@var{info}] =} dyn_risky_steadystate_solver (@var{ys0},@var{M},@var{dr},@var{options},@var{oo})
+%! @anchor{dyn_risky_steadystate_solver}
+%! @sp 1
+%! Computes the second order risky steady state and first and second order reduced form of the DSGE model.
+%! @sp 2
+%! @strong{Inputs}
+%! @sp 1
+%! @table @ @var
+%! @item ys0
+%! Vector containing a guess value for the risky steady state
+%! @item M
+%! Matlab's structure describing the model (initialized by @code{dynare}).
+%! @item dr
+%! Matlab's structure describing the reduced form solution of the model.
+%! @item options
+%! Matlab's structure describing the options (initialized by @code{dynare}).
+%! @item oo
+%! Matlab's structure gathering the results (initialized by @code{dynare}).
+%! @end table
+%! @sp 2
+%! @strong{Outputs}
+%! @sp 1
+%! @table @ @var
+%! @item dr
+%! Matlab's structure describing the reduced form solution of the model.
+%! @item info
+%! Integer scalar, error code.
+%! @sp 1
+%! @table @ @code
+%! @item info==0
+%! No error.
+%! @item info==1
+%! The model doesn't determine the current variables uniquely.
+%! @item info==2
+%! MJDGGES returned an error code.
+%! @item info==3
+%! Blanchard & Kahn conditions are not satisfied: no stable equilibrium.
+%! @item info==4
+%! Blanchard & Kahn conditions are not satisfied: indeterminacy.
+%! @item info==5
+%! Blanchard & Kahn conditions are not satisfied: indeterminacy due to rank failure.
+%! @item info==6
+%! The jacobian evaluated at the deterministic steady state is complex.
+%! @item info==19
+%! The steadystate routine thrown an exception (inconsistent deep parameters).
+%! @item info==20
+%! Cannot find the steady state, info(2) contains the sum of square residuals (of the static equations).
+%! @item info==21
+%! The steady state is complex, info(2) contains the sum of square of imaginary parts of the steady state.
+%! @item info==22
+%! The steady has NaNs.
+%! @item info==23
+%! 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.
+%! @end table
+%! @end table
+%! @end deftypefn
+%@eod:
+
+% Copyright (C) 2001-2017 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+
+info = 0;
+lead_lag_incidence = M.lead_lag_incidence;
+order_var = dr.order_var;
+endo_nbr = M.endo_nbr;
+exo_nbr = M.exo_nbr;
+
+M.var_order_endo_names = M.endo_names(dr.order_var,:);
+
+[junk,dr.i_fwrd_g,i_fwrd_f] = find(lead_lag_incidence(3,order_var));
+dr.i_fwrd_f = i_fwrd_f;
+nd = nnz(lead_lag_incidence) + M.exo_nbr;
+dr.nd = nd;
+kk = reshape(1:nd^2,nd,nd);
+kkk = reshape(1:nd^3,nd^2,nd);
+dr.i_fwrd2_f = kk(i_fwrd_f,i_fwrd_f);
+dr.i_fwrd2a_f = kk(i_fwrd_f,:);
+dr.i_fwrd3_f = kkk(dr.i_fwrd2_f,:);
+dr.i_uu = kk(end-exo_nbr+1:end,end-exo_nbr+1:end);
+if options.k_order_solver
+    func = @risky_residuals_k_order;
+else
+    func = @risky_residuals;
+end
 
-    [resid,dr] = func(ys,pm,M,dr,options,oo);
-    dr.ghs2 = zeros(M.endo_nbr,1);
-    
-    for i=1:M.endo_nbr
-        if isfield(options,'portfolio') && options.portfolio == 1
-            disp(sprintf('%16s %12.6f %12.6f',M.endo_names(i,:),ys1(i), ...
-                         ys(i)))
-        else
-            disp(sprintf('%16s %12.6f %12.6f',M.endo_names(i,:),ys(i)))
-        end
+if isfield(options,'portfolio') && options.portfolio == 1
+    pm = portfolio_model_structure(M,options);
+
+    x0 = ys0(pm.v_p);
+    n = length(x0);
+    [x, info] = solve1(@risky_residuals_ds,x0,1:n,1:n,0,options.gstep, ...
+                       options.solve_tolf,options.solve_tolx, ...
+                       options.steady.maxit,options.debug,pm,M,dr, ...
+                       options,oo);
+    if info
+        error('DS approach can''t be computed')
     end
+    %[x, info] = csolve(@risky_residuals_ds,x0,[],1e-10,100,M,dr,options,oo);
+    %        ys0(l_var) = x;
+    [resids,dr1] = risky_residuals_ds(x,pm,M,dr,options,oo);
+    ys1 = dr1.ys;
+else
+    pm = model_structure(M,options);
+end
 
+[ys, info] = solve1(func,ys0,1:endo_nbr,1:endo_nbr,0,options.gstep, ...
+                    options.solve_tolf,options.solve_tolx, ...
+                    options.steady.maxit,options.debug,pm,M,dr,options,oo);
+%    [ys, info] = csolve(func,ys0,[],1e-10,100,M,dr,options,oo);
+if info
+    error('RSS approach can''t be computed')
 end
+dr.ys = ys;
 
-function [resid,dr] = risky_residuals(ys,pm,M,dr,options,oo)
-    
-    lead_lag_incidence = M.lead_lag_incidence;
-    iyv = lead_lag_incidence';
-    iyv = iyv(:);
-    iyr0 = find(iyv) ;
-    
-    if M.exo_nbr == 0
-        oo.exo_steady_state = [] ;
-    end
-    
-    z = repmat(ys,1,3);
-    z = z(iyr0) ;
-    [resid1,d1,d2] = feval([M.fname '_dynamic'],z,...
-                           [oo.exo_simul ...
-                        oo.exo_det_simul], M.params, dr.ys, 2);
-    if ~isreal(d1) || ~isreal(d2)
-        pause
-    end
-    
-    if options.use_dll
-        % In USE_DLL mode, the hessian is in the 3-column sparse representation
-        d2 = sparse(d2(:,1), d2(:,2), d2(:,3), ...
-                    size(d1, 1), size(d1, 2)*size(d1, 2));
-    end
+[resid,dr] = func(ys,pm,M,dr,options,oo);
+dr.ghs2 = zeros(M.endo_nbr,1);
 
+for i=1:M.endo_nbr
     if isfield(options,'portfolio') && options.portfolio == 1
-        pm = portfolio_model_structure(M,options);
-        x = ys(pm.v_p);
-        dr = first_step_ds(x,pm,M,dr,options,oo);
-        dr.ys = ys;
+        disp(sprintf('%16s %12.6f %12.6f',M.endo_names(i,:),ys1(i), ...
+                     ys(i)))
     else
-        pm = model_structure(M,options);
-        [dr,info] = dyn_first_order_solver(d1,M,dr,options,0);
-        if info
-            print_info(info,options.noprint,options);
-        end
-        dr = dyn_second_order_solver(d1,d2,dr,M,...
-                                     options.threads.kronecker.A_times_B_kronecker_C,...
-                                     options.threads.kronecker.sparse_hessian_times_B_kronecker_C);
+        disp(sprintf('%16s %12.6f %12.6f',M.endo_names(i,:),ys(i)))
     end
-    
-    gu1 = dr.ghu(pm.i_fwrd_g,:);
+end
 
-    resid = resid1+0.5*(d1(:,pm.i_fwrd_f1)*dr.ghuu(pm.i_fwrd_g,:)+ ...
-                        d2(:,pm.i_fwrd_f2)*kron(gu1,gu1))*vec(M.Sigma_e);
 end
 
-function [resid,dr] = risky_residuals_ds(x,pm,M,dr,options,oo)
-    
-    v_p = pm.v_p;
-    v_np = pm.v_np;
-    
-    % computing steady state of non-portfolio variables  consistent with
-    % assumed portfolio 
-    dr.ys(v_p) = x;
-    ys0 = dr.ys(v_np);
-    f_h =str2func([M.fname '_static']);
-    [dr.ys(v_np),info] = csolve(@ds_static_model,ys0,[],1e-10,100,f_h,x,pm.eq_np,v_np,v_p, ...
-                                M.endo_nbr,M.exo_nbr,M.params);
+function [resid,dr] = risky_residuals(ys,pm,M,dr,options,oo)
+
+lead_lag_incidence = M.lead_lag_incidence;
+iyv = lead_lag_incidence';
+iyv = iyv(:);
+iyr0 = find(iyv) ;
+
+if M.exo_nbr == 0
+    oo.exo_steady_state = [] ;
+end
+
+z = repmat(ys,1,3);
+z = z(iyr0) ;
+[resid1,d1,d2] = feval([M.fname '_dynamic'],z,...
+                       [oo.exo_simul ...
+                    oo.exo_det_simul], M.params, dr.ys, 2);
+if ~isreal(d1) || ~isreal(d2)
+    pause
+end
+
+if options.use_dll
+    % In USE_DLL mode, the hessian is in the 3-column sparse representation
+    d2 = sparse(d2(:,1), d2(:,2), d2(:,3), ...
+                size(d1, 1), size(d1, 2)*size(d1, 2));
+end
+
+if isfield(options,'portfolio') && options.portfolio == 1
+    pm = portfolio_model_structure(M,options);
+    x = ys(pm.v_p);
+    dr = first_step_ds(x,pm,M,dr,options,oo);
+    dr.ys = ys;
+else
+    pm = model_structure(M,options);
+    [dr,info] = dyn_first_order_solver(d1,M,dr,options,0);
     if info
-        error('can''t compute non-portfolio steady state')
-    end
-    
-    dr_np = first_step_ds(x,pm,M,dr,options,oo);
-
-    lead_lag_incidence = M.lead_lag_incidence;
-    iyv = lead_lag_incidence';
-    iyv = iyv(:);
-    iyr0 = find(iyv) ;
-    
-    z = repmat(dr.ys,1,3);
-    z = z(iyr0) ;
-    [resid1,d1,d2] = feval([M.fname '_dynamic'],z,...
-                           [oo.exo_simul ...
-                        oo.exo_det_simul], M.params, dr.ys, 2);
-    if ~isreal(d1) || ~isreal(d2)
-        pause
-    end
-    
-    if options.use_dll
-        % In USE_DLL mode, the hessian is in the 3-column sparse representation
-        d2 = sparse(d2(:,1), d2(:,2), d2(:,3), ...
-                    size(d1, 1), size(d1, 2)*size(d1, 2));
+        print_info(info,options.noprint,options);
     end
+    dr = dyn_second_order_solver(d1,d2,dr,M,...
+                                 options.threads.kronecker.A_times_B_kronecker_C,...
+                                 options.threads.kronecker.sparse_hessian_times_B_kronecker_C);
+end
+
+gu1 = dr.ghu(pm.i_fwrd_g,:);
+
+resid = resid1+0.5*(d1(:,pm.i_fwrd_f1)*dr.ghuu(pm.i_fwrd_g,:)+ ...
+                    d2(:,pm.i_fwrd_f2)*kron(gu1,gu1))*vec(M.Sigma_e);
+end
+
+function [resid,dr] = risky_residuals_ds(x,pm,M,dr,options,oo)
+
+v_p = pm.v_p;
+v_np = pm.v_np;
+
+% computing steady state of non-portfolio variables  consistent with
+% assumed portfolio
+dr.ys(v_p) = x;
+ys0 = dr.ys(v_np);
+f_h =str2func([M.fname '_static']);
+[dr.ys(v_np),info] = csolve(@ds_static_model,ys0,[],1e-10,100,f_h,x,pm.eq_np,v_np,v_p, ...
+                            M.endo_nbr,M.exo_nbr,M.params);
+if info
+    error('can''t compute non-portfolio steady state')
+end
+
+dr_np = first_step_ds(x,pm,M,dr,options,oo);
+
+lead_lag_incidence = M.lead_lag_incidence;
+iyv = lead_lag_incidence';
+iyv = iyv(:);
+iyr0 = find(iyv) ;
+
+z = repmat(dr.ys,1,3);
+z = z(iyr0) ;
+[resid1,d1,d2] = feval([M.fname '_dynamic'],z,...
+                       [oo.exo_simul ...
+                    oo.exo_det_simul], M.params, dr.ys, 2);
+if ~isreal(d1) || ~isreal(d2)
+    pause
+end
+
+if options.use_dll
+    % In USE_DLL mode, the hessian is in the 3-column sparse representation
+    d2 = sparse(d2(:,1), d2(:,2), d2(:,3), ...
+                size(d1, 1), size(d1, 2)*size(d1, 2));
+end
+
 
-    
-    gu1 = dr_np.ghu(pm.i_fwrd_g,:);
+gu1 = dr_np.ghu(pm.i_fwrd_g,:);
 
-    resid = resid1+0.5*(d2(:,pm.i_fwrd_f2)*kron(gu1,gu1))*vec(M.Sigma_e);
+resid = resid1+0.5*(d2(:,pm.i_fwrd_f2)*kron(gu1,gu1))*vec(M.Sigma_e);
 
-    resid = resid(pm.eq_p)
+resid = resid(pm.eq_p)
 end
 
 function dr_np = first_step_ds(x,pm,M,dr,options,oo)
 
-    lead_lag_incidence = M.lead_lag_incidence;
-    iyv = lead_lag_incidence';
-    iyv = iyv(:);
-    iyr0 = find(iyv) ;
-
-    ys = dr.ys;
-    ys(pm.v_p) = x;
-    
-    z = repmat(ys,1,3);
-    z = z(iyr0) ;
-    [resid1,d1,d2] = feval([M.fname '_dynamic'],z,...
-                           [oo.exo_simul ...
-                        oo.exo_det_simul], M.params, dr.ys, 2);
-    if ~isreal(d1) || ~isreal(d2)
-        pause
-    end
-    
-    if options.use_dll
-        % In USE_DLL mode, the hessian is in the 3-column sparse representation
-        d2 = sparse(d2(:,1), d2(:,2), d2(:,3), ...
-                    size(d1, 1), size(d1, 2)*size(d1, 2));
-    end
+lead_lag_incidence = M.lead_lag_incidence;
+iyv = lead_lag_incidence';
+iyv = iyv(:);
+iyr0 = find(iyv) ;
+
+ys = dr.ys;
+ys(pm.v_p) = x;
+
+z = repmat(ys,1,3);
+z = z(iyr0) ;
+[resid1,d1,d2] = feval([M.fname '_dynamic'],z,...
+                       [oo.exo_simul ...
+                    oo.exo_det_simul], M.params, dr.ys, 2);
+if ~isreal(d1) || ~isreal(d2)
+    pause
+end
+
+if options.use_dll
+    % In USE_DLL mode, the hessian is in the 3-column sparse representation
+    d2 = sparse(d2(:,1), d2(:,2), d2(:,3), ...
+                size(d1, 1), size(d1, 2)*size(d1, 2));
+end
+
+d1_np = d1(pm.eq_np,pm.i_d1_np);
+d2_np = d2(pm.eq_np,pm.i_d2_np);
+
+[dr_np,info] = dyn_first_order_solver(d1_np,pm.M_np,pm.dr_np,options,0);
+if info
+    print_info(info, 0, options);
+    return
+end
+
+dr_np = dyn_second_order_solver(d1_np,d2_np,dr_np,pm.M_np,...
+                                options.threads.kronecker.A_times_B_kronecker_C,...
+                                options.threads.kronecker.sparse_hessian_times_B_kronecker_C);
+end
+
+function [resid,dr] = risky_residuals_k_order(ys,pm,M,dr,options,oo)
+exo_nbr = M.exo_nbr;
+endo_nbr = M.endo_nbr;
+
+iyv = M.lead_lag_incidence';
+iyv = iyv(:);
+iyr0 = find(iyv) ;
+
+if exo_nbr == 0
+    oo.exo_steady_state = [] ;
+end
+
+z = repmat(ys,1,3);
+z = z(iyr0) ;
+[resid1,d1,d2] = feval([M.fname '_dynamic'],z,...
+                       [oo.exo_simul ...
+                    oo.exo_det_simul], M.params, dr.ys, 2);
+
+if isfield(options,'portfolio') && options.portfolio == 1
+    eq_np = pm.eq_np;
+
+    d1_np = d1(eq_np,pm.i_d1_np);
+    d2_np = d2(eq_np,pm.i_d2_np);
+
+    M_np = pm.M_np;
+    dr_np = pm.dr_np;
 
-    d1_np = d1(pm.eq_np,pm.i_d1_np);
-    d2_np = d2(pm.eq_np,pm.i_d2_np);
-    
     [dr_np,info] = dyn_first_order_solver(d1_np,pm.M_np,pm.dr_np,options,0);
     if info
         print_info(info, 0, options);
         return
     end
-    
+
     dr_np = dyn_second_order_solver(d1_np,d2_np,dr_np,pm.M_np,...
                                     options.threads.kronecker.A_times_B_kronecker_C,...
                                     options.threads.kronecker.sparse_hessian_times_B_kronecker_C);
 end
 
-function [resid,dr] = risky_residuals_k_order(ys,pm,M,dr,options,oo)
-    exo_nbr = M.exo_nbr;
-    endo_nbr = M.endo_nbr;
-    
-    iyv = M.lead_lag_incidence';
-    iyv = iyv(:);
-    iyr0 = find(iyv) ;
-    
-    if exo_nbr == 0
-        oo.exo_steady_state = [] ;
-    end
-    
-    z = repmat(ys,1,3);
-    z = z(iyr0) ;
-    [resid1,d1,d2] = feval([M.fname '_dynamic'],z,...
+i_fwrd_f1 = pm.i_fwrd_f1;
+i_fwrd_f2 = pm.i_fwrd_f2;
+i_fwrd_f3 = pm.i_fwrd_f3;
+i_fwrd_g = pm.i_fwrd_g;
+gu1 = dr_np.ghu(i_fwrd_g,:);
+ghuu = dr_np.ghuu;
+
+resid = resid1+0.5*(d1(:,i_fwrd_f1)*ghuu(i_fwrd_g,:)+d2(:,i_fwrd_f2)* ...
+                    kron(gu1,gu1))*vec(M.Sigma_e);
+
+if nargout > 1
+    [resid1,d1,d2,d3] = feval([M.fname '_dynamic'],z,...
                               [oo.exo_simul ...
                         oo.exo_det_simul], M.params, dr.ys, 2);
-    
-    if isfield(options,'portfolio') && options.portfolio == 1
-        eq_np = pm.eq_np;
-        
-        d1_np = d1(eq_np,pm.i_d1_np);
-        d2_np = d2(eq_np,pm.i_d2_np);
-
-        M_np = pm.M_np;
-        dr_np = pm.dr_np;
-        
-        [dr_np,info] = dyn_first_order_solver(d1_np,pm.M_np,pm.dr_np,options,0);
-        if info
-            print_info(info, 0, options);
-            return
-        end
-        
-        dr_np = dyn_second_order_solver(d1_np,d2_np,dr_np,pm.M_np,...
-                                        options.threads.kronecker.A_times_B_kronecker_C,...
-                                        options.threads.kronecker.sparse_hessian_times_B_kronecker_C);
-    end
-    
-    i_fwrd_f1 = pm.i_fwrd_f1;
-    i_fwrd_f2 = pm.i_fwrd_f2;
-    i_fwrd_f3 = pm.i_fwrd_f3;
-    i_fwrd_g = pm.i_fwrd_g;
-    gu1 = dr_np.ghu(i_fwrd_g,:);
-    ghuu = dr_np.ghuu;
-    
-    resid = resid1+0.5*(d1(:,i_fwrd_f1)*ghuu(i_fwrd_g,:)+d2(:,i_fwrd_f2)* ...
-                        kron(gu1,gu1))*vec(M.Sigma_e);
-
-    if nargout > 1
-        [resid1,d1,d2,d3] = feval([M.fname '_dynamic'],z,...
-                                  [oo.exo_simul ...
-                            oo.exo_det_simul], M.params, dr.ys, 2);
-
-        
-        [a,b,c] = find(d2(eq_np,pm.i_d2_np));
-        d2_np = [a b c];
-        
-        [a,b,c] = find(d3(eq_np,pm.i_d3_np));
-        d3_np = [a b c];
-         
-        options.order = 3;
-        % space holder, unused by k_order_pertrubation
-        dr_np.ys = dr.ys(pm.v_np);
-        nu2 = exo_nbr*(exo_nbr+1)/2;
-        nu3 = exo_nbr*(exo_nbr+1)*(exo_nbr+2)/3;
-        M_np.NZZDerivatives = [nnz(d1_np); nnz(d2_np); nnz(d3_np)];
-        [err,g_0, g_1, g_2, g_3] = k_order_perturbation(dr_np,M_np,options,d1_np,d2_np,d3_np);
-        mexErrCheck('k_order_perturbation', err);
-
-        gu1 = g_1(i_fwrd_g,end-exo_nbr+1:end);
-        ghuu = unfold2(g_2(:,end-nu2+1:end),exo_nbr);
-        ghsuu = get_ghsuu(g_3,size(g_1,2),exo_nbr);
-
-        i_fwrd1_f2 = pm.i_fwrd1_f2;
-        i_fwrd1_f3 = pm.i_fwrd1_f3;
-        n = size(d1,2);
-        d1b = d1 + 0.5*( ...
-            d1(:,i_fwrd_f1)*...
-            d2(:,i_fwrd1_f2)*kron(eye(n),dr_np.ghuu(i_fwrd_g,:)*vec(M.Sigma_e))...
-            + 0.5*d3(:,i_fwrd1_f3)*kron(eye(n),kron(gu1,gu1)*vec(M.Sigma_e)));
-        format short
-        kk1 = [nonzeros(M.lead_lag_incidence(:,1:6)'); ...
-               nnz(M.lead_lag_incidence)+[1; 2]]
-        kk2 = [nonzeros(M.lead_lag_incidence(:,1:6)'); ...
-               nnz(M.lead_lag_incidence)+[3; 4]]
-        format short
-        gu1
-        kron(gu1,gu1)*vec(M.Sigma_e)
-        disp(d1(:,:))
-        disp(d1b(:,:))
-        aa2=d2(:,i_fwrd1_f2)*kron(eye(n),dr_np.ghuu(i_fwrd_g,:)*vec(M.Sigma_e));
-        aa3=d3(:,i_fwrd1_f3)*kron(eye(n),kron(gu1,gu1)*vec(M.Sigma_e));
-        disp(d3(4,7+6*n+6*n*n))
-        disp(d3(4,8+16*n+17*n*n))   %8,17,18
-        disp(d3(4,8+17*n+16*n*n))   %8,17,18
-        disp(d3(4,7*n+17+17*n*n))   %8,17,18
-        disp(d3(4,7*n+18+16*n*n))   %8,17,18
-        disp(d3(4,7*n*n+16*n+18))   %8,17,18
-        disp(d3(4,7*n*n+17+17*n))   %8,17,18
-        pause
-        disp(aa2(:,kk1))
-        disp(aa2(:,kk2))
-        disp(aa3(:,kk1))
-        disp(aa3(:,kk2))
-        [dr,info] = dyn_first_order_solver(d1b,M,dr,options,0);
-        if info
-            print_info(info, 0, options);
-            return
-        end
-        
-        disp_dr(dr,dr.order_var,[]);
-        
+
+
+    [a,b,c] = find(d2(eq_np,pm.i_d2_np));
+    d2_np = [a b c];
+
+    [a,b,c] = find(d3(eq_np,pm.i_d3_np));
+    d3_np = [a b c];
+
+    options.order = 3;
+    % space holder, unused by k_order_pertrubation
+    dr_np.ys = dr.ys(pm.v_np);
+    nu2 = exo_nbr*(exo_nbr+1)/2;
+    nu3 = exo_nbr*(exo_nbr+1)*(exo_nbr+2)/3;
+    M_np.NZZDerivatives = [nnz(d1_np); nnz(d2_np); nnz(d3_np)];
+    [err,g_0, g_1, g_2, g_3] = k_order_perturbation(dr_np,M_np,options,d1_np,d2_np,d3_np);
+    mexErrCheck('k_order_perturbation', err);
+
+    gu1 = g_1(i_fwrd_g,end-exo_nbr+1:end);
+    ghuu = unfold2(g_2(:,end-nu2+1:end),exo_nbr);
+    ghsuu = get_ghsuu(g_3,size(g_1,2),exo_nbr);
+
+    i_fwrd1_f2 = pm.i_fwrd1_f2;
+    i_fwrd1_f3 = pm.i_fwrd1_f3;
+    n = size(d1,2);
+    d1b = d1 + 0.5*( ...
+        d1(:,i_fwrd_f1)*...
+        d2(:,i_fwrd1_f2)*kron(eye(n),dr_np.ghuu(i_fwrd_g,:)*vec(M.Sigma_e))...
+        + 0.5*d3(:,i_fwrd1_f3)*kron(eye(n),kron(gu1,gu1)*vec(M.Sigma_e)));
+    format short
+    kk1 = [nonzeros(M.lead_lag_incidence(:,1:6)'); ...
+           nnz(M.lead_lag_incidence)+[1; 2]]
+    kk2 = [nonzeros(M.lead_lag_incidence(:,1:6)'); ...
+           nnz(M.lead_lag_incidence)+[3; 4]]
+    format short
+    gu1
+    kron(gu1,gu1)*vec(M.Sigma_e)
+    disp(d1(:,:))
+    disp(d1b(:,:))
+    aa2=d2(:,i_fwrd1_f2)*kron(eye(n),dr_np.ghuu(i_fwrd_g,:)*vec(M.Sigma_e));
+    aa3=d3(:,i_fwrd1_f3)*kron(eye(n),kron(gu1,gu1)*vec(M.Sigma_e));
+    disp(d3(4,7+6*n+6*n*n))
+    disp(d3(4,8+16*n+17*n*n))   %8,17,18
+    disp(d3(4,8+17*n+16*n*n))   %8,17,18
+    disp(d3(4,7*n+17+17*n*n))   %8,17,18
+    disp(d3(4,7*n+18+16*n*n))   %8,17,18
+    disp(d3(4,7*n*n+16*n+18))   %8,17,18
+    disp(d3(4,7*n*n+17+17*n))   %8,17,18
+    pause
+    disp(aa2(:,kk1))
+    disp(aa2(:,kk2))
+    disp(aa3(:,kk1))
+    disp(aa3(:,kk2))
+    [dr,info] = dyn_first_order_solver(d1b,M,dr,options,0);
+    if info
+        print_info(info, 0, options);
+        return
     end
+
+    disp_dr(dr,dr.order_var,[]);
+
+end
 end
 
 function y=unfold2(x,n)
-    y = zeros(size(x,1),n*n);
-    k = 1;
-    for i=1:n
-        for j=i:n
-            y(:,(i-1)*n+j) = x(:,k);
-            if i ~= j
-                y(:,(j-1)*n+i) = x(:,k);
-            end
-            k = k+1;
+y = zeros(size(x,1),n*n);
+k = 1;
+for i=1:n
+    for j=i:n
+        y(:,(i-1)*n+j) = x(:,k);
+        if i ~= j
+            y(:,(j-1)*n+i) = x(:,k);
         end
+        k = k+1;
     end
 end
+end
 
 function y=unfold3(x,n)
-    y = zeros(size(x,1),n*n*n);
-    k = 1;
-    for i=1:n
-        for j=i:n
-            for m=j:n
-                y(:,(i-1)*n*n+(j-1)*n+m) = x(:,k);
-                y(:,(i-1)*n*n+(m-1)*n+j) = x(:,k);
-                y(:,(j-1)*n*n+(i-1)*n+m) = x(:,k);
-                y(:,(j-1)*n*n+(m-1)*n+i) = x(:,k);
-                y(:,(m-1)*n*n+(i-1)*n+j) = x(:,k);
-                y(:,(m-1)*n*n+(j-1)*n+i) = x(:,k);
-                
-                k = k+1;
-            end
+y = zeros(size(x,1),n*n*n);
+k = 1;
+for i=1:n
+    for j=i:n
+        for m=j:n
+            y(:,(i-1)*n*n+(j-1)*n+m) = x(:,k);
+            y(:,(i-1)*n*n+(m-1)*n+j) = x(:,k);
+            y(:,(j-1)*n*n+(i-1)*n+m) = x(:,k);
+            y(:,(j-1)*n*n+(m-1)*n+i) = x(:,k);
+            y(:,(m-1)*n*n+(i-1)*n+j) = x(:,k);
+            y(:,(m-1)*n*n+(j-1)*n+i) = x(:,k);
+
+            k = k+1;
         end
     end
 end
+end
 
 function pm  = model_structure(M,options)
 
 
-    lead_index = M.maximum_endo_lag+2;
-    lead_lag_incidence = M.lead_lag_incidence;
-    dr = struct();
-    dr = set_state_space(dr,M,options);
-    pm.i_fwrd_g = find(lead_lag_incidence(lead_index,dr.order_var)');    
-
-    i_fwrd_f1 = nonzeros(lead_lag_incidence(lead_index,dr.order_var));
-    pm.i_fwrd_f1 = i_fwrd_f1;
-    n = nnz(lead_lag_incidence)+M.exo_nbr;
-    ih = reshape(1:n*n,n,n);
-    i_fwrd_f2 = ih(i_fwrd_f1,i_fwrd_f1);
-    pm.i_fwrd_f2 = i_fwrd_f2(:);
-    i_fwrd1_f2 = ih(i_fwrd_f1,:);
-    pm.i_fwrd1_f2 = i_fwrd1_f2(:);
-
-    ih = reshape(1:n*n*n,n,n,n);
-    i_fwrd_f3 = ih(i_fwrd_f1,i_fwrd_f1,i_fwrd_f1);
-    pm.i_fwrd_f3 = i_fwrd_f3(:);
-    i_fwrd1_f3 = ih(i_fwrd_f1,i_fwrd_f1,:);
-    pm.i_fwrd1_f3 = i_fwrd1_f3(:);
+lead_index = M.maximum_endo_lag+2;
+lead_lag_incidence = M.lead_lag_incidence;
+dr = struct();
+dr = set_state_space(dr,M,options);
+pm.i_fwrd_g = find(lead_lag_incidence(lead_index,dr.order_var)');
+
+i_fwrd_f1 = nonzeros(lead_lag_incidence(lead_index,dr.order_var));
+pm.i_fwrd_f1 = i_fwrd_f1;
+n = nnz(lead_lag_incidence)+M.exo_nbr;
+ih = reshape(1:n*n,n,n);
+i_fwrd_f2 = ih(i_fwrd_f1,i_fwrd_f1);
+pm.i_fwrd_f2 = i_fwrd_f2(:);
+i_fwrd1_f2 = ih(i_fwrd_f1,:);
+pm.i_fwrd1_f2 = i_fwrd1_f2(:);
+
+ih = reshape(1:n*n*n,n,n,n);
+i_fwrd_f3 = ih(i_fwrd_f1,i_fwrd_f1,i_fwrd_f1);
+pm.i_fwrd_f3 = i_fwrd_f3(:);
+i_fwrd1_f3 = ih(i_fwrd_f1,i_fwrd_f1,:);
+pm.i_fwrd1_f3 = i_fwrd1_f3(:);
 end
 
 function pm  = portfolio_model_structure(M,options)
 
-    i_d3_np = [];
-    i_d3_p = [];
-
-    lead_index = M.maximum_endo_lag+2;
-    lead_lag_incidence = M.lead_lag_incidence;
-    eq_tags = M.equations_tags;
-    n_tags = size(eq_tags,1);
-    eq_p = cell2mat(eq_tags(strcmp(eq_tags(:,2), ...
-                                   'portfolio'),1));
-    pm.eq_p = eq_p;
-    pm.eq_np = setdiff(1:M.endo_nbr,eq_p);
-    v_p = zeros(n_tags,1);
-    for i=1:n_tags
-        v_p(i) = find(strncmp(eq_tags(i,3),M.endo_names, ...
-                              length(cell2mat(eq_tags(i,3)))));
-    end
-    if any(lead_lag_incidence(lead_index,v_p))
-        error(['portfolio variables appear in the model as forward ' ...
-               'variable'])
-    end
-    pm.v_p = v_p;
-    v_np = setdiff(1:M.endo_nbr,v_p);
-    pm.v_np = v_np;
-    lli_np = lead_lag_incidence(:,v_np)';
-    k = find(lli_np);
-    lead_lag_incidence_np = lli_np;
-    lead_lag_incidence_np(k) = 1:nnz(lli_np);
-    lead_lag_incidence_np = lead_lag_incidence_np';
-    pm.lead_lag_incidence_np = lead_lag_incidence_np;
-    i_d1_np = [nonzeros(lli_np); nnz(lead_lag_incidence)+(1:M.exo_nbr)'];
-    pm.i_d1_np = i_d1_np;
-    
-    n = nnz(lead_lag_incidence)+M.exo_nbr;
-    ih = reshape(1:n*n,n,n);
-    i_d2_np = ih(i_d1_np,i_d1_np);
-    pm.i_d2_np = i_d2_np(:);
-
-    ih = reshape(1:n*n*n,n,n,n);
-    i_d3_np = ih(i_d1_np,i_d1_np,i_d1_np);
-    pm.i_d3_np = i_d3_np(:);
-
-    M_np = M;
-    M_np.lead_lag_incidence = lead_lag_incidence_np;
-    M_np.lead_lag_incidence = lead_lag_incidence_np;
-    M_np.endo_nbr = length(v_np);
-    M_np.endo_names = M.endo_names(v_np,:);
-    dr_np = struct();
-    dr_np = set_state_space(dr_np,M_np,options);
-    pm.dr_np = dr_np;
-    M_np.var_order_endo_names = M_np.endo_names(dr_np.order_var,:);
-    pm.M_np = M_np;
-    pm.i_fwrd_g = find(lead_lag_incidence_np(lead_index,dr_np.order_var)');    
-
-    i_fwrd_f1 = nonzeros(lead_lag_incidence(lead_index,:));
-    pm.i_fwrd_f1 = i_fwrd_f1;
-    n = nnz(lead_lag_incidence)+M.exo_nbr;
-    ih = reshape(1:n*n,n,n);
-    i_fwrd_f2 = ih(i_fwrd_f1,i_fwrd_f1);
-    pm.i_fwrd_f2 = i_fwrd_f2(:);
-    i_fwrd1_f2 = ih(i_fwrd_f1,:);
-    pm.i_fwrd1_f2 = i_fwrd1_f2(:);
-
-    ih = reshape(1:n*n*n,n,n,n);
-    i_fwrd_f3 = ih(i_fwrd_f1,i_fwrd_f1,i_fwrd_f1);
-    pm.i_fwrd_f3 = i_fwrd_f3(:);
-    i_fwrd1_f3 = ih(i_fwrd_f1,i_fwrd_f1,:);
-    pm.i_fwrd1_f3 = i_fwrd1_f3(:);
+i_d3_np = [];
+i_d3_p = [];
+
+lead_index = M.maximum_endo_lag+2;
+lead_lag_incidence = M.lead_lag_incidence;
+eq_tags = M.equations_tags;
+n_tags = size(eq_tags,1);
+eq_p = cell2mat(eq_tags(strcmp(eq_tags(:,2), ...
+                               'portfolio'),1));
+pm.eq_p = eq_p;
+pm.eq_np = setdiff(1:M.endo_nbr,eq_p);
+v_p = zeros(n_tags,1);
+for i=1:n_tags
+    v_p(i) = find(strncmp(eq_tags(i,3),M.endo_names, ...
+                          length(cell2mat(eq_tags(i,3)))));
+end
+if any(lead_lag_incidence(lead_index,v_p))
+    error(['portfolio variables appear in the model as forward ' ...
+           'variable'])
+end
+pm.v_p = v_p;
+v_np = setdiff(1:M.endo_nbr,v_p);
+pm.v_np = v_np;
+lli_np = lead_lag_incidence(:,v_np)';
+k = find(lli_np);
+lead_lag_incidence_np = lli_np;
+lead_lag_incidence_np(k) = 1:nnz(lli_np);
+lead_lag_incidence_np = lead_lag_incidence_np';
+pm.lead_lag_incidence_np = lead_lag_incidence_np;
+i_d1_np = [nonzeros(lli_np); nnz(lead_lag_incidence)+(1:M.exo_nbr)'];
+pm.i_d1_np = i_d1_np;
+
+n = nnz(lead_lag_incidence)+M.exo_nbr;
+ih = reshape(1:n*n,n,n);
+i_d2_np = ih(i_d1_np,i_d1_np);
+pm.i_d2_np = i_d2_np(:);
+
+ih = reshape(1:n*n*n,n,n,n);
+i_d3_np = ih(i_d1_np,i_d1_np,i_d1_np);
+pm.i_d3_np = i_d3_np(:);
+
+M_np = M;
+M_np.lead_lag_incidence = lead_lag_incidence_np;
+M_np.lead_lag_incidence = lead_lag_incidence_np;
+M_np.endo_nbr = length(v_np);
+M_np.endo_names = M.endo_names(v_np,:);
+dr_np = struct();
+dr_np = set_state_space(dr_np,M_np,options);
+pm.dr_np = dr_np;
+M_np.var_order_endo_names = M_np.endo_names(dr_np.order_var,:);
+pm.M_np = M_np;
+pm.i_fwrd_g = find(lead_lag_incidence_np(lead_index,dr_np.order_var)');
+
+i_fwrd_f1 = nonzeros(lead_lag_incidence(lead_index,:));
+pm.i_fwrd_f1 = i_fwrd_f1;
+n = nnz(lead_lag_incidence)+M.exo_nbr;
+ih = reshape(1:n*n,n,n);
+i_fwrd_f2 = ih(i_fwrd_f1,i_fwrd_f1);
+pm.i_fwrd_f2 = i_fwrd_f2(:);
+i_fwrd1_f2 = ih(i_fwrd_f1,:);
+pm.i_fwrd1_f2 = i_fwrd1_f2(:);
+
+ih = reshape(1:n*n*n,n,n,n);
+i_fwrd_f3 = ih(i_fwrd_f1,i_fwrd_f1,i_fwrd_f1);
+pm.i_fwrd_f3 = i_fwrd_f3(:);
+i_fwrd1_f3 = ih(i_fwrd_f1,i_fwrd_f1,:);
+pm.i_fwrd1_f3 = i_fwrd1_f3(:);
 end
 
 function r=ds_static_model(y0,f_h,p0,eq_np,v_np,v_p,endo_nbr,exo_nbr,params)
-    ys = zeros(endo_nbr,1);
-    ys(v_p) = p0;
-    ys(v_np) = y0;
-    r = f_h(ys,zeros(exo_nbr,1),params);
-    r = r(eq_np);
+ys = zeros(endo_nbr,1);
+ys(v_p) = p0;
+ys(v_np) = y0;
+r = f_h(ys,zeros(exo_nbr,1),params);
+r = r(eq_np);
 end
 
 function ghsuu = get_ghsuu(g,ns,nx)
-    nxx = nx*(nx+1)/2;
-    m1 = 0;
-    m2 = ns*(ns+1)/2;
-    kk = 1:(nx*nx);
-    ghsuu = zeros(size(g,1),(ns*nx*nx));
-    
-    for i=1:n
-        j = m1+(1:m2);
-        k = j(end-nxx+1:end);
-        ghsuu(:,kk) = unfold2(g(:,k),nx);
-        m1 = m1+m2;
-        m2 = m2 - (n-i+1);
-        kk = kk + nx*nx;
-    end
+nxx = nx*(nx+1)/2;
+m1 = 0;
+m2 = ns*(ns+1)/2;
+kk = 1:(nx*nx);
+ghsuu = zeros(size(g,1),(ns*nx*nx));
+
+for i=1:n
+    j = m1+(1:m2);
+    k = j(end-nxx+1:end);
+    ghsuu(:,kk) = unfold2(g(:,k),nx);
+    m1 = m1+m2;
+    m2 = m2 - (n-i+1);
+    kk = kk + nx*nx;
+end
 end
\ No newline at end of file
diff --git a/matlab/dyn_saveas.m b/matlab/dyn_saveas.m
index 4c897a620c1eecaa5385a0a8c6d72011af7ee8f3..009a49d5e8af99ede13d9cdefd99d3e80590f85f 100644
--- a/matlab/dyn_saveas.m
+++ b/matlab/dyn_saveas.m
@@ -1,11 +1,12 @@
-function dyn_saveas(h,fname,DynareOptions)
-%function dyn_saveas(h,fname,DynareOptions)
+function dyn_saveas(h, fname, nodisplay, graph_format)
+%function dyn_saveas(h, fname, nodisplay, graph_format)
 % save figures for DYNARE
 %
 % INPUTS
 %    h     : figure handle
 %    fname : name of the saved figure
-%    DynareOptions: dynare options
+%    nodisplay: the value of the command-specific nodisplay argument or options_.nodisplay
+%    graph_format: the value of the command-specific graph_format argument or options_.graph_format
 %
 % OUTPUTS
 %    none
@@ -13,7 +14,7 @@ function dyn_saveas(h,fname,DynareOptions)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2012-2013 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -30,42 +31,42 @@ function dyn_saveas(h,fname,DynareOptions)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-if any(strcmp('eps',cellstr(DynareOptions.graph_format)))
+if any(strcmp('eps',cellstr(graph_format)))
     if isoctave
         fname = strrep(fname,'/',filesep);
         fname = strrep(fname,'\',filesep);
-        if DynareOptions.nodisplay && ispc,
+        if nodisplay && ispc
             set(h, 'Visible','on');
         end
     end
-    print(h,'-depsc2',[fname,'.eps']) 
+    print(h,'-depsc2',[fname,'.eps'])
 end
-if any(strcmp('pdf',cellstr(DynareOptions.graph_format)))
+if any(strcmp('pdf',cellstr(graph_format)))
     if isoctave
         error('Octave cannot create pdf files!')
     else
-        print(h,'-dpdf',[fname,'.pdf']) 
+        print(h,'-dpdf',[fname,'.pdf'])
     end
 end
-if any(strcmp('fig',cellstr(DynareOptions.graph_format)))
+if any(strcmp('fig',cellstr(graph_format)))
     if isoctave
         error('Octave cannot create fig files!')
     else
-        if DynareOptions.nodisplay
-%  THE FOLLOWING LINES COULD BE USED IF BUGS/PROBLEMS ARE REPORTED USING LINE 60		
-%             set(h,'Units','Normalized')
-%             mypos=get(h,'Position');
-%             set(h,'Position',[-1 -1 mypos(3:4)])
-%             set(h, 'Visible','on');
+        if nodisplay
+            %  THE FOLLOWING LINES COULD BE USED IF BUGS/PROBLEMS ARE REPORTED USING LINE 60
+            %             set(h,'Units','Normalized')
+            %             mypos=get(h,'Position');
+            %             set(h,'Position',[-1 -1 mypos(3:4)])
+            %             set(h, 'Visible','on');
             set(h,'CreateFcn','set(gcf, ''Visible'',''on'')') ;
         end
         saveas(h,[fname '.fig']);
     end
 end
-if any(strcmp('none',cellstr(DynareOptions.graph_format)))
-% don't save
-% check here as a reminder that none is an option to graph_format
+if any(strcmp('none',cellstr(graph_format)))
+    % don't save
+    % check here as a reminder that none is an option to graph_format
 end
-if DynareOptions.nodisplay
+if nodisplay
     close(h);
 end
diff --git a/matlab/dyn_second_order_solver.m b/matlab/dyn_second_order_solver.m
index dd2d2bfb8ee849ba80fc47f28ffbf509ddad68c4..df6ba76939e7217aa97a9dab88ed4dcad48e839e 100644
--- a/matlab/dyn_second_order_solver.m
+++ b/matlab/dyn_second_order_solver.m
@@ -32,7 +32,7 @@ function dr = dyn_second_order_solver(jacobia,hessian_mat,dr,M_,threads_ABC,thre
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2001-2012 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -48,135 +48,135 @@ function dr = dyn_second_order_solver(jacobia,hessian_mat,dr,M_,threads_ABC,thre
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
-    
-    dr.ghxx = [];
-    dr.ghuu = [];
-    dr.ghxu = [];
-    dr.ghs2 = [];
-    Gy = dr.Gy;
-    
-    kstate = dr.kstate;
-    nstatic = M_.nstatic;
-    nfwrd = M_.nfwrd;
-    nspred = M_.nspred;
-    nboth = M_.nboth;
-    nsfwrd = M_.nsfwrd;
-    order_var = dr.order_var;
-    nd = size(kstate,1);
-    lead_lag_incidence = M_.lead_lag_incidence;
-
-    np = nd - nsfwrd;
-
-    k1 = nonzeros(lead_lag_incidence(:,order_var)');
-    kk = [k1; length(k1)+(1:M_.exo_nbr+M_.exo_det_nbr)'];
-    nk = size(kk,1);
-    kk1 = reshape([1:nk^2],nk,nk);
-    kk1 = kk1(kk,kk);
-    % reordering second order derivatives
-    hessian_mat = hessian_mat(:,kk1(:));
-
-    zx = zeros(np,np);
-    zu=zeros(np,M_.exo_nbr);
-    zx(1:np,:)=eye(np);
-    k0 = [1:M_.endo_nbr];
-    gx1 = dr.ghx;
-    hu = dr.ghu(nstatic+[1:nspred],:);
-    k0 = find(lead_lag_incidence(M_.maximum_endo_lag+1,order_var)');
-    zx = [zx; gx1(k0,:)];
-    zu = [zu; dr.ghu(k0,:)];
-    k1 = find(lead_lag_incidence(M_.maximum_endo_lag+2,order_var)');
-    zu = [zu; gx1(k1,:)*hu];
-    zx = [zx; gx1(k1,:)*Gy];
-    zx=[zx; zeros(M_.exo_nbr,np);zeros(M_.exo_det_nbr,np)];
-    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_mat,zx,threads_BC);
-    mexErrCheck('sparse_hessian_times_B_kronecker_C', err);
-    rhs = -rhs;
-
-    %lhs
-    n = M_.endo_nbr+sum(kstate(:,2) > M_.maximum_endo_lag+1 & kstate(:,2) < M_.maximum_endo_lag+M_.maximum_endo_lead+1);
-    A = zeros(M_.endo_nbr,M_.endo_nbr);
-    B = zeros(M_.endo_nbr,M_.endo_nbr);
-    A(:,k0) = jacobia(:,nonzeros(lead_lag_incidence(M_.maximum_endo_lag+1,order_var)));
-    % variables with the highest lead
-    k1 = find(kstate(:,2) == M_.maximum_endo_lag+2);
-    % Jacobian with respect to the variables with the highest lead
-    fyp = jacobia(:,kstate(k1,3)+nnz(M_.lead_lag_incidence(M_.maximum_endo_lag+1,:)));
-    B(:,nstatic+M_.npred+1:end) = fyp;
-    [junk,k1,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+M_.maximum_endo_lead+1,order_var));
-    A(1:M_.endo_nbr,nstatic+1:nstatic+nspred)=...
-        A(1:M_.endo_nbr,nstatic+[1:nspred])+fyp*gx1(k1,1:nspred);
-    C = Gy;
-    D = [rhs; zeros(n-M_.endo_nbr,size(rhs,2))];
-
-
-    [err, dr.ghxx] = gensylv(2,A,B,C,D);
-    mexErrCheck('gensylv', err);
-
-    %ghxu
-    %rhs
-    hu = dr.ghu(nstatic+1:nstatic+nspred,:);
-    [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)];
-    [nrhx,nchx] = size(Gy);
-    [nrhu1,nchu1] = size(hu1);
-
-    [abcOut,err] = A_times_B_kronecker_C(dr.ghxx,Gy,hu1,threads_ABC);
-    mexErrCheck('A_times_B_kronecker_C', err);
-    B1 = B*abcOut;
-    rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1;
-
-
-    %lhs
-    dr.ghxu = A\rhs;
-
-    %ghuu
-    %rhs
-    [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);
-    mexErrCheck('A_times_B_kronecker_C', err);
-    rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1;
-
-    %lhs
-    dr.ghuu = A\rhs;
-
-    % dr.ghs2
-    % derivatives of F with respect to forward variables
-    % reordering predetermined variables in diminishing lag order
-    O1 = zeros(M_.endo_nbr,nstatic);
-    O2 = zeros(M_.endo_nbr,M_.endo_nbr-nstatic-nspred);
-    LHS = zeros(M_.endo_nbr,M_.endo_nbr);
-    LHS(:,k0) = jacobia(:,nonzeros(lead_lag_incidence(M_.maximum_endo_lag+1,order_var)));
-    RHS = zeros(M_.endo_nbr,M_.exo_nbr^2);
-    gu = dr.ghu; 
-    guu = dr.ghuu; 
-    E = eye(M_.endo_nbr);
-    kh = reshape([1:nk^2],nk,nk);
-    kp = sum(kstate(:,2) <= M_.maximum_endo_lag+1);
-    E1 = [eye(nspred); zeros(kp-nspred,nspred)];
-    H = E1;
-    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_mat(:,kh(k3,k3)),gu(k2a,:),threads_BC);
-    mexErrCheck('sparse_hessian_times_B_kronecker_C', err);
-    RHS = RHS + jacobia(:,k2)*guu(k2a,:)+B1;
-
-    % LHS
-    LHS = LHS + jacobia(:,k2)*(E(k2a,:)+[O1(k2a,:) dr.ghx(k2a,:)*H O2(k2a,:)]);
-    
-    RHS = RHS*M_.Sigma_e(:);
-    dr.fuu = RHS;
-    %RHS = -RHS-dr.fbias;
-    RHS = -RHS;
-    dr.ghs2 = LHS\RHS;
-
-    % deterministic exogenous variables
-    if M_.exo_det_nbr > 0
-    end
+
+dr.ghxx = [];
+dr.ghuu = [];
+dr.ghxu = [];
+dr.ghs2 = [];
+Gy = dr.Gy;
+
+kstate = dr.kstate;
+nstatic = M_.nstatic;
+nfwrd = M_.nfwrd;
+nspred = M_.nspred;
+nboth = M_.nboth;
+nsfwrd = M_.nsfwrd;
+order_var = dr.order_var;
+nd = size(kstate,1);
+lead_lag_incidence = M_.lead_lag_incidence;
+
+np = nd - nsfwrd;
+
+k1 = nonzeros(lead_lag_incidence(:,order_var)');
+kk = [k1; length(k1)+(1:M_.exo_nbr+M_.exo_det_nbr)'];
+nk = size(kk,1);
+kk1 = reshape([1:nk^2],nk,nk);
+kk1 = kk1(kk,kk);
+% reordering second order derivatives
+hessian_mat = hessian_mat(:,kk1(:));
+
+zx = zeros(np,np);
+zu=zeros(np,M_.exo_nbr);
+zx(1:np,:)=eye(np);
+k0 = [1:M_.endo_nbr];
+gx1 = dr.ghx;
+hu = dr.ghu(nstatic+[1:nspred],:);
+k0 = find(lead_lag_incidence(M_.maximum_endo_lag+1,order_var)');
+zx = [zx; gx1(k0,:)];
+zu = [zu; dr.ghu(k0,:)];
+k1 = find(lead_lag_incidence(M_.maximum_endo_lag+2,order_var)');
+zu = [zu; gx1(k1,:)*hu];
+zx = [zx; gx1(k1,:)*Gy];
+zx=[zx; zeros(M_.exo_nbr,np);zeros(M_.exo_det_nbr,np)];
+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_mat,zx,threads_BC);
+mexErrCheck('sparse_hessian_times_B_kronecker_C', err);
+rhs = -rhs;
+
+%lhs
+n = M_.endo_nbr+sum(kstate(:,2) > M_.maximum_endo_lag+1 & kstate(:,2) < M_.maximum_endo_lag+M_.maximum_endo_lead+1);
+A = zeros(M_.endo_nbr,M_.endo_nbr);
+B = zeros(M_.endo_nbr,M_.endo_nbr);
+A(:,k0) = jacobia(:,nonzeros(lead_lag_incidence(M_.maximum_endo_lag+1,order_var)));
+% variables with the highest lead
+k1 = find(kstate(:,2) == M_.maximum_endo_lag+2);
+% Jacobian with respect to the variables with the highest lead
+fyp = jacobia(:,kstate(k1,3)+nnz(M_.lead_lag_incidence(M_.maximum_endo_lag+1,:)));
+B(:,nstatic+M_.npred+1:end) = fyp;
+[junk,k1,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+M_.maximum_endo_lead+1,order_var));
+A(1:M_.endo_nbr,nstatic+1:nstatic+nspred)=...
+    A(1:M_.endo_nbr,nstatic+[1:nspred])+fyp*gx1(k1,1:nspred);
+C = Gy;
+D = [rhs; zeros(n-M_.endo_nbr,size(rhs,2))];
+
+
+[err, dr.ghxx] = gensylv(2,A,B,C,D);
+mexErrCheck('gensylv', err);
+
+%ghxu
+%rhs
+hu = dr.ghu(nstatic+1:nstatic+nspred,:);
+[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)];
+[nrhx,nchx] = size(Gy);
+[nrhu1,nchu1] = size(hu1);
+
+[abcOut,err] = A_times_B_kronecker_C(dr.ghxx,Gy,hu1,threads_ABC);
+mexErrCheck('A_times_B_kronecker_C', err);
+B1 = B*abcOut;
+rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1;
+
+
+%lhs
+dr.ghxu = A\rhs;
+
+%ghuu
+%rhs
+[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);
+mexErrCheck('A_times_B_kronecker_C', err);
+rhs = -[rhs; zeros(n-M_.endo_nbr,size(rhs,2))]-B1;
+
+%lhs
+dr.ghuu = A\rhs;
+
+% dr.ghs2
+% derivatives of F with respect to forward variables
+% reordering predetermined variables in diminishing lag order
+O1 = zeros(M_.endo_nbr,nstatic);
+O2 = zeros(M_.endo_nbr,M_.endo_nbr-nstatic-nspred);
+LHS = zeros(M_.endo_nbr,M_.endo_nbr);
+LHS(:,k0) = jacobia(:,nonzeros(lead_lag_incidence(M_.maximum_endo_lag+1,order_var)));
+RHS = zeros(M_.endo_nbr,M_.exo_nbr^2);
+gu = dr.ghu;
+guu = dr.ghuu;
+E = eye(M_.endo_nbr);
+kh = reshape([1:nk^2],nk,nk);
+kp = sum(kstate(:,2) <= M_.maximum_endo_lag+1);
+E1 = [eye(nspred); zeros(kp-nspred,nspred)];
+H = E1;
+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_mat(:,kh(k3,k3)),gu(k2a,:),threads_BC);
+mexErrCheck('sparse_hessian_times_B_kronecker_C', err);
+RHS = RHS + jacobia(:,k2)*guu(k2a,:)+B1;
+
+% LHS
+LHS = LHS + jacobia(:,k2)*(E(k2a,:)+[O1(k2a,:) dr.ghx(k2a,:)*H O2(k2a,:)]);
+
+RHS = RHS*M_.Sigma_e(:);
+dr.fuu = RHS;
+%RHS = -RHS-dr.fbias;
+RHS = -RHS;
+dr.ghs2 = LHS\RHS;
+
+% deterministic exogenous variables
+if M_.exo_det_nbr > 0
+end
diff --git a/matlab/dyn_unvech.m b/matlab/dyn_unvech.m
index f70670a986f44a3be3275a4ac5ea14942e4e7f49..0c6c853cc3272911a6ea6e5352073ec6fb114710 100644
--- a/matlab/dyn_unvech.m
+++ b/matlab/dyn_unvech.m
@@ -1,13 +1,13 @@
 function Matrix = dyn_unvech(Vector)
 % This function implements the unvech operator.
-% 
-% INPUTS 
+%
+% INPUTS
 %   Vector             [double]   a m*1 vector.
-%    
-% OUTPUTS 
+%
+% OUTPUTS
 %   Matrix             [double]   a n*n symetric matrix, where n solves n*(n+1)/2=m.
 
-% Copyright (C) 2010 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/dyn_vech.m b/matlab/dyn_vech.m
index 6e54c40502b7f70cc2ebbdf0fa4fd8c5c59ff314..dc18f974bbfa20d902b2dd6447da89a875b5084f 100644
--- a/matlab/dyn_vech.m
+++ b/matlab/dyn_vech.m
@@ -1,13 +1,13 @@
 function Vector = dyn_vech(Matrix)
 % This function implements the vech operator.
-% 
-% INPUTS 
+%
+% INPUTS
 %   Matrix             [double]   a squared n*n symetric matrix.
-%    
-% OUTPUTS 
+%
+% OUTPUTS
 %   Vector             [double]   a n*(n+1)/2 vector.
 
-% Copyright (C) 2010 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/dyn_waitbar.m b/matlab/dyn_waitbar.m
index f9665c950982b6cc879fc9af6c4489c5120be9b7..43567dcd34a9c57d546910c1556c10ab6db47b42 100644
--- a/matlab/dyn_waitbar.m
+++ b/matlab/dyn_waitbar.m
@@ -4,7 +4,7 @@ function h = dyn_waitbar(prctdone, varargin)
 % octave and when console_mode=1
 
 %
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -30,7 +30,7 @@ if iscell(prctdone)
     prctdone=prctdone{1};
 end
 
-if prctdone==0,
+if prctdone==0
     init=1;
     if isempty(whoiam)
         whoiam=0;
@@ -38,23 +38,20 @@ if prctdone==0,
 else
     init=0;
 end
-if nargout,
+if nargout
     h=[];
 end
 
 if ~whoiam
-    
     if isoctave || options_.console_mode
-                
-        if init,
+        if init
             diary off;
             running_text = varargin{1};
             newString='';
-            return;
-        elseif nargin>2,
+            return
+        elseif nargin>2
             running_text =  varargin{2};
         end
-        
         if isoctave
             printf([running_text,' %3.f%% done\r'], prctdone*100);
         else
@@ -62,26 +59,23 @@ if ~whoiam
             newString=sprintf([running_text,' %3.f%% done'], prctdone*100);
             fprintf([s0,'%s'],newString);
         end
-        
     else
-        if nargout,
+        if nargout
             h = waitbar(prctdone,varargin{:});
         else
             waitbar(prctdone,varargin{:});
         end
     end
-    
 else
-    if init,
+    if init
         running_text = varargin{1};
     elseif nargin>2
         running_text = varargin{2};
     end
-    if Parallel.Local,
+    if Parallel.Local
         waitbarTitle=['Local '];
     else
         waitbarTitle=[Parallel.ComputerName];
     end
     fMessageStatus(prctdone,whoiam,running_text, waitbarTitle, Parallel);
 end
-
diff --git a/matlab/dyn_waitbar_close.m b/matlab/dyn_waitbar_close.m
index 894e4c6fad6663652c0d2ec339e3d1dacfe49c18..c2864a9b6ad8cf748af934e56e4bc70b93c9d757 100644
--- a/matlab/dyn_waitbar_close.m
+++ b/matlab/dyn_waitbar_close.m
@@ -1,10 +1,10 @@
 function dyn_waitbar_close(h)
 % h = dyn_waitbar_close(h)
-% adaptive close waitbar, compatible with 
+% adaptive close waitbar, compatible with
 % octave and when console_mode=1
 
 %
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -22,14 +22,12 @@ function dyn_waitbar_close(h)
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 global options_
 
-if isoctave || options_.console_mode,
+if isoctave || options_.console_mode
     clear dyn_waitbar;
-    diary on,
+    diary on
     fprintf('\n');
 else
-    close(h),
+    close(h)
 end
 
 clear dyn_waitbar;
-
-
diff --git a/matlab/dynare.m b/matlab/dynare.m
index 34ee711488c31910a0a8136f46a128ea7fdb571c..91ae8beb4fa970dae26726674e53cca3f9cf4bf0 100644
--- a/matlab/dynare.m
+++ b/matlab/dynare.m
@@ -1,7 +1,7 @@
 function dynare(fname, varargin)
 %       This command runs dynare with specified model file in argument
 %       Filename.
-%       The name of model file begins with an alphabetic character, 
+%       The name of model file begins with an alphabetic character,
 %       and has a filename extension of .mod or .dyn.
 %       When extension is omitted, a model file with .mod extension
 %       is processed.
@@ -9,10 +9,10 @@ function dynare(fname, varargin)
 % INPUTS
 %   fname:      file name
 %   varargin:   list of arguments following fname
-%             
+%
 % OUTPUTS
 %   none
-%        
+%
 % SPECIAL REQUIREMENTS
 %   none
 
@@ -64,7 +64,7 @@ dynareroot = dynare_config;
 
 warning_config()
 
-if isoctave 
+if isoctave
     if octave_ver_less_than('3.6.0')
         warning('This version of Dynare has only been tested on Octave 3.6.0 and above. Since your Octave version is older than that, Dynare may fail to run, or give unexpected results. Consider upgrading your Octave installation.');
     end
@@ -111,12 +111,12 @@ if isempty(strfind(fname,'.'))
     % Checking file extension
 else
     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))),'.MOD') ...
             && ~strcmp(upper(fname(size(fname,2)-3:size(fname,2))),'.DYN')
         error('DYNARE: argument must be a filename with .mod or .dyn extension and must not include any other periods')
-    end;
+    end
     fnamelength = length(fname) - 4;
-end;
+end
 
 if fnamelength + length('_set_auxiliary_variables') > namelengthmax()
     error('The name of your MOD file is too long, please shorten it')
@@ -176,11 +176,11 @@ else
 end
 
 if isempty(strfind(arch, '64'))
-  arch_ext = '32';
-  disp('Using 32-bit preprocessor');
+    arch_ext = '32';
+    disp('Using 32-bit preprocessor');
 else
-  arch_ext = '64';
-  disp('Using 64-bit preprocessor');
+    arch_ext = '64';
+    disp('Using 64-bit preprocessor');
 end
 
 command = ['"' dynareroot 'preprocessor' arch_ext filesep 'dynare_m" ' fname] ;
@@ -192,7 +192,7 @@ end
 disp(result)
 if ismember('onlymacro', varargin)
     disp('Preprocesser stopped after macroprocessing step because of ''onlymacro'' option.');
-    return;
+    return
 end
 
 if ismember('onlyjson', varargin)
diff --git a/matlab/dynare_config.m b/matlab/dynare_config.m
index c70e0a89f66df02cc8059f12930007ae7b9f0b6f..ae65aab15f0ee4cd43b4f323c9e7d69ced3ede65 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-2016 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -58,6 +58,7 @@ p = {'/distributions/' ; ...
      '/particles/src' ; ...
      '/gsa/' ; ...
      '/ep/' ; ...
+     '/backward/' ; ...
      '/convergence_diagnostics/' ; ... 
      '/cli/' ; ...
      '/lmmcp/' ; ...
@@ -68,6 +69,7 @@ p = {'/distributions/' ; ...
      '/utilities/tests/src/' ; ...
      '/utilities/dataset/' ; ...
      '/utilities/general/' ; ...
+     '/utilities/graphics/' ; ...
      '/modules/reporting/src/' ; ...
      '/modules/reporting/macros/'};
 
@@ -113,10 +115,15 @@ end
 % nanmean is in Octave Forge Statistics package and in MATLAB Statistics
 % toolbox
 if (isoctave && ~user_has_octave_forge_package('statistics')) ...
-    || (~isoctave && ~user_has_matlab_license('statistics_toolbox'))
+        || (~isoctave && ~user_has_matlab_license('statistics_toolbox'))
     p{end+1} = '/missing/nanmean';
 end
 
+% Check if struct2array is available.
+if ~exist('struct2array')
+    p{end+1} = '/missing/struct2array';
+end
+
 P = cellfun(@(c)[dynareroot(1:end-1) c], p, 'uni',false);
 
 % Get mex files folder(s)
diff --git a/matlab/dynare_estimation.m b/matlab/dynare_estimation.m
index dff898fb4e8944bd0c43af0cbb68781ddea14d14..98ad16c32d5fa7e335dd7377ee56dd25c26d4086 100644
--- a/matlab/dynare_estimation.m
+++ b/matlab/dynare_estimation.m
@@ -12,7 +12,7 @@ function oo_recursive_=dynare_estimation(var_list,dname)
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2003-2015 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -32,8 +32,8 @@ function oo_recursive_=dynare_estimation(var_list,dname)
 global options_ oo_ M_ dataset_ dataset_info
 
 oo_recursive_={};
-
-% Test if the order of approximation is nonzero (the preprocessor tests if order is non negative).
+mode_file0 = options_.mode_file; % store mode_file set by the user
+                                 % Test if the order of approximation is nonzero (the preprocessor tests if order is non negative).
 if isequal(options_.order,0)
     error('Estimation:: The order of the Taylor approximation cannot be 0!')
 end
@@ -46,8 +46,8 @@ end
 var_list = check_list_of_variables(options_, M_, var_list);
 options_.varlist = var_list;
 
-nobs = sort(options_.nobs); 
-first_obs = sort(options_.first_obs); 
+nobs = sort(options_.nobs);
+first_obs = sort(options_.first_obs);
 
 nnobs = length(nobs);
 nfirstobs = length(first_obs);
@@ -55,7 +55,7 @@ nfirstobs = length(first_obs);
 if nnobs~=1 && nfirstobs~=1
     error('You cannot simultaneously do rolling window and recursive estimation')
 end
-    
+
 horizon = options_.forecast;
 
 if nargin<2 || ~exist('dname','var') || isempty(dname)
@@ -82,8 +82,8 @@ if nnobs>1 || nfirstobs > 1
         if nnobs>1
             options_.nobs = nobs(i);
             M_.dname = [dname '_' int2str(nobs(i))];
-        elseif nfirstobs>1;
-            options_.first_obs=first_obs(i);            
+        elseif nfirstobs>1
+            options_.first_obs=first_obs(i);
             M_.dname = [dname '_' int2str(first_obs(i))];
         end
         dynare_estimation_1(var_list,M_.dname);
@@ -97,7 +97,7 @@ if nnobs>1 || nfirstobs > 1
         end
         if nnobs>1
             oo_recursive_{nobs(i)} = oo_;
-        elseif nfirstobs>1;
+        elseif nfirstobs>1
             oo_recursive_{first_obs(i)} = oo_;
         end
     end
@@ -105,7 +105,7 @@ else
     dynare_estimation_1(var_list,dname);
 end
 
-if isnumeric(options_.mode_compute) && options_.mode_compute && options_.analytic_derivation,
+if isnumeric(options_.mode_compute) && options_.mode_compute && options_.analytic_derivation
     options_.analytic_derivation=analytic_derivation0;
 end
 
@@ -138,11 +138,11 @@ 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(dataset_.data,1)-nobs(1));
+                        size(dataset_.data,1)-nobs(1));
     data2 = dataset_info.rawdata(end-k+1:end,:);
     [nbplt,nr,nc,lr,lc,nstar] = pltorg(nvar);
     m = 1;
@@ -151,7 +151,7 @@ if nnobs > 1 && horizon > 0
     for i = 1:size(var_list,1)
         if mod(i,nstar) == 1
             plot_index=plot_index+1;
-            hfig = dyn_figure(options_,'Name',['Out of sample forecasts (',num2str(plot_index),')']);
+            hfig = dyn_figure(options_.nodisplay,'Name',['Out of sample forecasts (',num2str(plot_index),')']);
             m = 1;
         end
         subplot(nr,nc,m)
@@ -167,23 +167,23 @@ if nnobs > 1 && horizon > 0
         for j=1:nnobs
             if mh_replic > 0
                 oo_.RecursiveForecast.Mean.(vname)(j,:) = ...
-                      oo_recursive_{nobs(j)}.MeanForecast.Mean.(vname);
+                    oo_recursive_{nobs(j)}.MeanForecast.Mean.(vname);
                 oo_.RecursiveForecast.HPDinf.(vname)(j,:) = ...
-                      oo_recursive_{nobs(j)}.MeanForecast.HPDinf.(vname);
+                    oo_recursive_{nobs(j)}.MeanForecast.HPDinf.(vname);
                 oo_.RecursiveForecast.HPDsup.(vname)(j,:) = ...
-                      oo_recursive_{nobs(j)}.MeanForecast.HPDsup.(vname);
+                    oo_recursive_{nobs(j)}.MeanForecast.HPDsup.(vname);
                 oo_.RecursiveForecast.HPDTotalinf.(vname)(j,:) = ...
-                      oo_recursive_{nobs(j)}.PointForecast.HPDinf.(vname);
+                    oo_recursive_{nobs(j)}.PointForecast.HPDinf.(vname);
                 oo_.RecursiveForecast.HPDTotalsup.(vname)(j,:) = ...
-                      oo_recursive_{nobs(j)}.PointForecast.HPDsup.(vname);
+                    oo_recursive_{nobs(j)}.PointForecast.HPDsup.(vname);
             else
                 oo_.RecursiveForecast.Mean.(vname)(j,:) =...
-                      oo_recursive_{nobs(j)}.forecast.Mean.(vname);
+                    oo_recursive_{nobs(j)}.forecast.Mean.(vname);
                 oo_.RecursiveForecast.HPDinf.(vname)(j,:) =...
-                      oo_recursive_{nobs(j)}.forecast.HPDinf.(vname);
+                    oo_recursive_{nobs(j)}.forecast.HPDinf.(vname);
                 oo_.RecursiveForecast.HPDsup.(vname)(j,:) =...
-                      oo_recursive_{nobs(j)}.forecast.HPDsup.(vname);
-              end
+                    oo_recursive_{nobs(j)}.forecast.HPDsup.(vname);
+            end
             x = nobs(1)+nobs(j)-nobs(1)+(1:horizon);
 
             y = oo_.RecursiveForecast.Mean.(vname)(j,:);
@@ -208,8 +208,9 @@ if nnobs > 1 && horizon > 0
         xlim([nobs(1)-offsetx nobs(end)+horizon])
         m = m + 1;
         if mod(i+1,nstar) == 1 || i ==size(var_list,1)
-            dyn_saveas(hfig,[M_.fname,filesep,'graphs',filesep M_.fname '_RecursiveForecasts_' int2str(plot_index)],options_);
+            dyn_saveas(hfig,[M_.fname,filesep,'graphs',filesep M_.fname '_RecursiveForecasts_' int2str(plot_index)],options_.nodisplay,options_.graph_format);
         end
     end
 end
-options_.mode_file = ''; %delete stored mode-file so that it is not reaccessed in later calls (and in case it was only set by the recursive estimation)
+options_.mode_file = mode_file0;
+%reset stored mode-file to user defined one (and in case it was only set by the recursive estimation)
diff --git a/matlab/dynare_estimation_1.m b/matlab/dynare_estimation_1.m
index 6077501ca6a1a0c2cacab6b85156d9ecf2dea33d..a4b4166145fae3a0184c98d5bf5d1c1d7bf32583 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-2016 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -31,17 +31,33 @@ function dynare_estimation_1(var_list_,dname)
 
 global M_ options_ oo_ estim_params_ bayestopt_ dataset_ dataset_info
 
+if isempty(estim_params_)
+    mode_compute_o = options_.mode_compute;
+    mh_replic_o = options_.mh_replic;
+    options_.mode_compute = 0;
+    options_.mh_replic = 0;
+    reset_options_related_to_estimation = true;
+else
+    reset_options_related_to_estimation = false;
+end
+
+
 %store qz_criterium
 qz_criterium_old=options_.qz_criterium;
+if isnan(options_.first_obs)
+    first_obs_nan_indicator=true;
+else
+    first_obs_nan_indicator=false;
+end
 
 % Set particle filter flag.
 if options_.order > 1
-    if options_.particle.status && options_.order==2  
+    if options_.particle.status && options_.order==2
         skipline()
         disp('Estimation using a non linear filter!')
         skipline()
         if ~options_.nointeractive && ismember(options_.mode_compute,[1,3,4]) && ~strcmpi(options_.particle.filter_algorithm,'gf')% Known gradient-based optimizers
-            disp('You are using a gradient-based mode-finder. Particle filtering introduces discontinuities in the') 
+            disp('You are using a gradient-based mode-finder. Particle filtering introduces discontinuities in the')
             disp('objective function w.r.t the parameters. Thus, should use a non-gradient based optimizer.')
             fprintf('\nPlease choose a mode-finder:\n')
             fprintf('\t 0 - Continue using gradient-based method (it is most likely that you will no get any sensible result).\n')
@@ -154,7 +170,7 @@ catch % if check fails, provide info on using calibration if present
         fprintf('ESTIMATION_CHECKS: There was an error in computing the likelihood for initial parameter values.\n')
         fprintf('ESTIMATION_CHECKS: If this is not a problem with the setting of options (check the error message below),\n')
         fprintf('ESTIMATION_CHECKS: you should try using the calibrated version of the model as starting values. To do\n')
-        fprintf('ESTIMATION_CHECKS: this, add an empty estimated_params_init-block with use_calibration option immediately before the estimation\n')    
+        fprintf('ESTIMATION_CHECKS: this, add an empty estimated_params_init-block with use_calibration option immediately before the estimation\n')
         fprintf('ESTIMATION_CHECKS: command (and after the estimated_params-block so that it does not get overwritten):\n');
         skipline(2);
     end
@@ -186,7 +202,7 @@ if ~isequal(options_.mode_compute,0) && ~options_.mh_posterior_mode_estimation
                 end
             end
         end
-        if options_.analytic_derivation,
+        if options_.analytic_derivation
             options_analytic_derivation_old = options_.analytic_derivation;
             options_.analytic_derivation = -1;
             if ~isempty(newratflag) && newratflag~=0 %numerical hessian explicitly specified
@@ -194,32 +210,32 @@ if ~isequal(options_.mode_compute,0) && ~options_.mh_posterior_mode_estimation
             else %use default
                 newratflag=0; %exclude DYNARE numerical hessian
             end
-        elseif ~options_.analytic_derivation 
-            if isempty(newratflag) 
-                newratflag=options_.newrat.hess; %use default numerical dynare hessian                
+        elseif ~options_.analytic_derivation
+            if isempty(newratflag)
+                newratflag=options_.newrat.hess; %use default numerical dynare hessian
             end
         end
     end
-    
+
     [xparam1, fval, exitflag, hh, options_, Scale, new_rat_hess_info] = 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      
+        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       
+    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'),
+            if options_.analytic_derivation && strcmp(func2str(objective_function),'dsge_likelihood')
                 ana_deriv_old = options_.analytic_derivation;
                 options_.analytic_derivation = 2;
                 [junk1, junk2,junk3, junk4, hh] = feval(objective_function,xparam1, ...
-                    dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
+                                                        dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
                 options_.analytic_derivation = ana_deriv_old;
-            elseif ~isnumeric(options_.mode_compute) || ~(isequal(options_.mode_compute,5) && newratflag~=1), 
+            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
                 if options_.hessian.use_penalized_objective
                     penalized_objective_function = str2func('penalty_objective_function');
@@ -242,15 +258,15 @@ if ~isequal(options_.mode_compute,0) && ~options_.mh_posterior_mode_estimation
                 % densitities for outer product gradient
                 kalman_algo0 = options_.kalman_algo;
                 compute_hessian = 1;
-                if ~((options_.kalman_algo == 2) || (options_.kalman_algo == 4)),
+                if ~((options_.kalman_algo == 2) || (options_.kalman_algo == 4))
                     options_.kalman_algo=2;
-                    if options_.lik_init == 3,
+                    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;                                            
+                elseif newratflag==0 % hh already contains outer product gradient with univariate filter
+                    compute_hessian = 0;
                 end
-                if compute_hessian,
+                if compute_hessian
                     crit = options_.newrat.tolerance.f;
                     newratflag = newratflag>0;
                     hh = reshape(mr_hessian(xparam1,objective_function,fval,newratflag,crit,new_rat_hess_info,dataset_, dataset_info, options_,M_,estim_params_,bayestopt_,bounds,oo_), nx, nx);
@@ -280,7 +296,7 @@ if ~options_.mh_posterior_mode_estimation && options_.cova_compute
         params_at_bound=find(abs(xparam1-bounds.ub)<1.e-10 | abs(xparam1-bounds.lb)<1.e-10);
         if ~isempty(params_at_bound)
             for ii=1:length(params_at_bound)
-            params_at_bound_name{ii,1}=get_the_name(params_at_bound(ii),0,M_,estim_params_,options_);
+                params_at_bound_name{ii,1}=get_the_name(params_at_bound(ii),0,M_,estim_params_,options_);
             end
             disp_string=[params_at_bound_name{1,:}];
             for ii=2:size(params_at_bound_name,1)
@@ -369,41 +385,40 @@ if np > 0
 end
 
 switch options_.MCMC_jumping_covariance
-    case 'hessian' %Baseline
-        %do nothing and use hessian from mode_compute
-    case 'prior_variance' %Use prior variance
-        if any(isinf(bayestopt_.p2))
-            error('Infinite prior variances detected. You cannot use the prior variances as the proposal density, if some variances are Inf.')
-        else
-            hh = diag(1./(bayestopt_.p2.^2));
-        end
+  case 'hessian' %Baseline
+                 %do nothing and use hessian from mode_compute
+  case 'prior_variance' %Use prior variance
+    if any(isinf(bayestopt_.p2))
+        error('Infinite prior variances detected. You cannot use the prior variances as the proposal density, if some variances are Inf.')
+    else
+        hh = diag(1./(bayestopt_.p2.^2));
+    end
+    hsd = sqrt(diag(hh));
+    invhess = inv(hh./(hsd*hsd'))./(hsd*hsd');
+  case 'identity_matrix' %Use identity
+    invhess = eye(nx);
+  otherwise %user specified matrix in file
+    try
+        load(options_.MCMC_jumping_covariance,'jumping_covariance')
+        hh=jumping_covariance;
+    catch
+        error(['No matrix named ''jumping_covariance'' could be found in ',options_.MCMC_jumping_covariance,'.mat'])
+    end
+    [nrow, ncol]=size(hh);
+    if ~isequal(nrow,ncol) && ~isequal(nrow,nx) %check if square and right size
+        error(['jumping_covariance matrix must be square and have ',num2str(nx),' rows and columns'])
+    end
+    try %check for positive definiteness
+        chol(hh);
         hsd = sqrt(diag(hh));
         invhess = inv(hh./(hsd*hsd'))./(hsd*hsd');
-    case 'identity_matrix' %Use identity
-        invhess = eye(nx);
-    otherwise %user specified matrix in file
-        try
-            load(options_.MCMC_jumping_covariance,'jumping_covariance')
-            hh=jumping_covariance;
-        catch
-            error(['No matrix named ''jumping_covariance'' could be found in ',options_.MCMC_jumping_covariance,'.mat'])
-        end
-        [nrow, ncol]=size(hh);
-        if ~isequal(nrow,ncol) && ~isequal(nrow,nx) %check if square and right size
-            error(['jumping_covariance matrix must be square and have ',num2str(nx),' rows and columns'])
-        end
-        try %check for positive definiteness
-            chol(hh);
-            hsd = sqrt(diag(hh));
-            invhess = inv(hh./(hsd*hsd'))./(hsd*hsd');
-        catch
-            error(['Specified jumping_covariance is not positive definite'])
-        end
+    catch
+        error(['Specified jumping_covariance is not positive definite'])
+    end
 end
 
 if (any(bayestopt_.pshape  >0 ) && options_.mh_replic) || ...
         (any(bayestopt_.pshape >0 ) && options_.load_mh_file)  %% not ML estimation
-    bounds = prior_bounds(bayestopt_, options_.prior_trunc);
     outside_bound_pars=find(xparam1 < bounds.lb | xparam1 > bounds.ub);
     if ~isempty(outside_bound_pars)
         for ii=1:length(outside_bound_pars)
@@ -420,16 +435,18 @@ if (any(bayestopt_.pshape  >0 ) && options_.mh_replic) || ...
         end
     end
     % runs MCMC
-    if options_.mh_replic
-        ana_deriv_old = options_.analytic_derivation;
-        options_.analytic_derivation = 0;
+    if options_.mh_replic || options_.load_mh_file
         posterior_sampler_options = options_.posterior_sampler_options.current_options;
         posterior_sampler_options.invhess = invhess;
         [posterior_sampler_options, options_] = check_posterior_sampler_options(posterior_sampler_options, options_);
         % store current options in global
         options_.posterior_sampler_options.current_options = posterior_sampler_options;
-        posterior_sampler(objective_function,posterior_sampler_options.proposal_distribution,xparam1,posterior_sampler_options,bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_);
-        options_.analytic_derivation = ana_deriv_old;
+        if options_.mh_replic
+            ana_deriv_old = options_.analytic_derivation;
+            options_.analytic_derivation = 0;
+            posterior_sampler(objective_function,posterior_sampler_options.proposal_distribution,xparam1,posterior_sampler_options,bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_);
+            options_.analytic_derivation = ana_deriv_old;
+        end
     end
     %% Here I discard first mh_drop percent of the draws:
     CutSample(M_, options_, estim_params_);
@@ -440,9 +457,9 @@ if (any(bayestopt_.pshape  >0 ) && options_.mh_replic) || ...
     else
         %get stored results if required
         if options_.load_mh_file && options_.load_results_after_load_mh
-            oo_load_mh=load([M_.fname '_results'],'oo_');    
+            oo_load_mh=load([M_.fname '_results'],'oo_');
         end
-        if ~options_.nodiagnostic 
+        if ~options_.nodiagnostic
             if (options_.mh_replic>0 || (options_.load_mh_file && ~options_.load_results_after_load_mh))
                 oo_= McMCDiagnostics(options_, estim_params_, M_,oo_);
             elseif options_.load_mh_file && options_.load_results_after_load_mh
@@ -464,20 +481,20 @@ if (any(bayestopt_.pshape  >0 ) && options_.mh_replic) || ...
             [oo_.posterior.metropolis.mean,oo_.posterior.metropolis.Variance] ...
                 = GetPosteriorMeanVariance(M_,options_.mh_drop);
         elseif options_.load_mh_file && options_.load_results_after_load_mh
-            %% load fields from previous MCMC run stored in results-file            
+            %% load fields from previous MCMC run stored in results-file
             field_names={'posterior_mode','posterior_std_at_mode',...% fields set by marginal_density
-                'posterior_mean','posterior_hpdinf','posterior_hpdsup','posterior_median','posterior_variance','posterior_std','posterior_deciles','posterior_density',...% fields set by GetPosteriorParametersStatistics
-                'prior_density',...%fields set by PlotPosteriorDistributions
-                };
+                         'posterior_mean','posterior_hpdinf','posterior_hpdsup','posterior_median','posterior_variance','posterior_std','posterior_deciles','posterior_density',...% fields set by GetPosteriorParametersStatistics
+                         'prior_density',...%fields set by PlotPosteriorDistributions
+                        };
             for field_iter=1:size(field_names,2)
                 if isfield(oo_load_mh.oo_,field_names{1,field_iter})
                     oo_.(field_names{1,field_iter})=oo_load_mh.oo_.(field_names{1,field_iter});
                 end
-            end            
+            end
             % field set by marginal_density
             if isfield(oo_load_mh.oo_,'MarginalDensity') && isfield(oo_load_mh.oo_.MarginalDensity,'ModifiedHarmonicMean')
                 oo_.MarginalDensity.ModifiedHarmonicMean=oo_load_mh.oo_.MarginalDensity.ModifiedHarmonicMean;
-            end            
+            end
             % field set by GetPosteriorMeanVariance
             if isfield(oo_load_mh.oo_,'posterior') && isfield(oo_load_mh.oo_.posterior,'metropolis')
                 oo_.posterior.metropolis=oo_load_mh.oo_.posterior.metropolis;
@@ -513,14 +530,13 @@ if options_.particle.status
     return
 end
 
-if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.pshape ...
-                                                      > 0) && options_.load_mh_file)) ...
+if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.pshape> 0) && options_.load_mh_file)) ...
     || ~options_.smoother ) && options_.partial_information == 0  % to be fixed
     %% ML estimation, or posterior mode without Metropolis-Hastings or Metropolis without Bayesian smoothes variables
     [atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,T,R,P,PK,decomp,Trend,state_uncertainty,M_,oo_,options_,bayestopt_] = DsgeSmoother(xparam1,dataset_.nobs,transpose(dataset_.data),dataset_info.missing.aindex,dataset_info.missing.state,M_,oo_,options_,bayestopt_,estim_params_);
     [oo_,yf]=store_smoother_results(M_,oo_,options_,bayestopt_,dataset_,dataset_info,atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,P,PK,decomp,Trend,state_uncertainty);
 
-    if ~options_.nograph,
+    if ~options_.nograph
         [nbplt,nr,nc,lr,lc,nstar] = pltorg(M_.exo_nbr);
         if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
             fidTeX = fopen([M_.fname '_SmoothedShocks.tex'],'w');
@@ -528,8 +544,8 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
             fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
             fprintf(fidTeX,' \n');
         end
-        for plt = 1:nbplt,
-            fh = dyn_figure(options_,'Name','Smoothed shocks');
+        for plt = 1:nbplt
+            fh = dyn_figure(options_.nodisplay,'Name','Smoothed shocks');
             NAMES = [];
             if options_.TeX, TeXNAMES = []; end
             nstar0=min(nstar,M_.exo_nbr-(plt-1)*nstar);
@@ -540,7 +556,7 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
                 marker_string{1,1}='-r';
                 marker_string{2,1}='-k';
             end
-            for i=1:nstar0,
+            for i=1:nstar0
                 k = (plt-1)*nstar+i;
                 subplot(nr,nc,i);
                 plot([1 gend],[0 0],marker_string{1,1},'linewidth',.5)
@@ -570,7 +586,7 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
                 end
                 title(name,'Interpreter','none')
             end
-            dyn_saveas(fh,[M_.fname '_SmoothedShocks' int2str(plt)],options_);
+            dyn_saveas(fh,[M_.fname '_SmoothedShocks' int2str(plt)],options_.nodisplay,options_.graph_format);
             if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                 fprintf(fidTeX,'\\begin{figure}[H]\n');
                 for jj = 1:nstar0
@@ -608,7 +624,7 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
                 fprintf(fidTeX,' \n');
             end
             for plt = 1:nbplt
-                fh = dyn_figure(options_,'Name','Smoothed observation errors');
+                fh = dyn_figure(options_.nodisplay,'Name','Smoothed observation errors');
                 NAMES = [];
                 if options_.TeX, TeXNAMES = []; end
                 nstar0=min(nstar,number_of_plots_to_draw-(nbplt-1)*nstar);
@@ -650,7 +666,7 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
                     end
                     title(name,'Interpreter','none')
                 end
-                dyn_saveas(fh,[M_.fname '_SmoothedObservationErrors' int2str(plt)],options_);
+                dyn_saveas(fh,[M_.fname '_SmoothedObservationErrors' int2str(plt)],options_.nodisplay,options_.graph_format);
                 if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                     fprintf(fidTeX,'\\begin{figure}[H]\n');
                     for jj = 1:nstar0
@@ -675,76 +691,76 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
     %%  Historical and smoothed variabes
     %%
     if ~options_.nograph
-    [nbplt,nr,nc,lr,lc,nstar] = pltorg(n_varobs);
-    if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
-        fidTeX = fopen([M_.fname '_HistoricalAndSmoothedVariables.tex'],'w');
-        fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation_1.m (Dynare).\n');
-        fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
-        fprintf(fidTeX,' \n');
-    end
-    for plt = 1:nbplt,
-        fh = dyn_figure(options_,'Name','Historical and smoothed variables');
-        NAMES = [];
-        if options_.TeX, TeXNAMES = []; end
-        nstar0=min(nstar,n_varobs-(plt-1)*nstar);
-        if gend==1
-           marker_string{1,1}='-ro';
-           marker_string{2,1}='--ko';
-        else
-           marker_string{1,1}='-r';
-           marker_string{2,1}='--k';
+        [nbplt,nr,nc,lr,lc,nstar] = pltorg(n_varobs);
+        if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
+            fidTeX = fopen([M_.fname '_HistoricalAndSmoothedVariables.tex'],'w');
+            fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation_1.m (Dynare).\n');
+            fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
+            fprintf(fidTeX,' \n');
         end
-        for i=1:nstar0,
-            k = (plt-1)*nstar+i;
-            subplot(nr,nc,i);
-            plot(1:gend,yf(k,:),marker_string{1,1},'linewidth',1)
-            hold on
-            plot(1:gend,rawdata(:,k),marker_string{2,1},'linewidth',1)
-            hold off
-            name = options_.varobs{k};
-            if isempty(NAMES)
-                NAMES = name;
+        for plt = 1:nbplt
+            fh = dyn_figure(options_.nodisplay,'Name','Historical and smoothed variables');
+            NAMES = [];
+            if options_.TeX, TeXNAMES = []; end
+            nstar0=min(nstar,n_varobs-(plt-1)*nstar);
+            if gend==1
+                marker_string{1,1}='-ro';
+                marker_string{2,1}='--ko';
             else
-                NAMES = char(NAMES,name);
-            end
-            if ~isempty(options_.XTick)
-                set(gca,'XTick',options_.XTick)
-                set(gca,'XTickLabel',options_.XTickLabel)
-            end
-            if gend>1
-                xlim([1 gend])
+                marker_string{1,1}='-r';
+                marker_string{2,1}='--k';
             end
-            if options_.TeX
-                idx = strmatch(options_.varobs{k},M_.endo_names,'exact');
-                texname = M_.endo_names_tex(idx,:);
-                if isempty(TeXNAMES)
-                    TeXNAMES = ['$ ' deblank(texname) ' $'];
+            for i=1:nstar0
+                k = (plt-1)*nstar+i;
+                subplot(nr,nc,i);
+                plot(1:gend,yf(k,:),marker_string{1,1},'linewidth',1)
+                hold on
+                plot(1:gend,rawdata(:,k),marker_string{2,1},'linewidth',1)
+                hold off
+                name = options_.varobs{k};
+                if isempty(NAMES)
+                    NAMES = name;
                 else
-                    TeXNAMES = char(TeXNAMES,['$ ' deblank(texname) ' $']);
+                    NAMES = char(NAMES,name);
+                end
+                if ~isempty(options_.XTick)
+                    set(gca,'XTick',options_.XTick)
+                    set(gca,'XTickLabel',options_.XTickLabel)
+                end
+                if gend>1
+                    xlim([1 gend])
+                end
+                if options_.TeX
+                    idx = strmatch(options_.varobs{k},M_.endo_names,'exact');
+                    texname = M_.endo_names_tex(idx,:);
+                    if isempty(TeXNAMES)
+                        TeXNAMES = ['$ ' deblank(texname) ' $'];
+                    else
+                        TeXNAMES = char(TeXNAMES,['$ ' deblank(texname) ' $']);
+                    end
                 end
+                title(name,'Interpreter','none')
+            end
+            dyn_saveas(fh,[M_.fname '_HistoricalAndSmoothedVariables' int2str(plt)],options_.nodisplay,options_.graph_format);
+            if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
+                fprintf(fidTeX,'\\begin{figure}[H]\n');
+                for jj = 1:nstar0
+                    fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:)));
+                end
+                fprintf(fidTeX,'\\centering \n');
+                fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_HistoricalAndSmoothedVariables%s}\n',options_.figures.textwidth*min(i/nc,1),M_.fname,int2str(plt));
+                fprintf(fidTeX,'\\caption{Historical and smoothed variables.}');
+                fprintf(fidTeX,'\\label{Fig:HistoricalAndSmoothedVariables:%s}\n',int2str(plt));
+                fprintf(fidTeX,'\\end{figure}\n');
+                fprintf(fidTeX,'\n');
             end
-            title(name,'Interpreter','none')
         end
-        dyn_saveas(fh,[M_.fname '_HistoricalAndSmoothedVariables' int2str(plt)],options_);
         if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
-            fprintf(fidTeX,'\\begin{figure}[H]\n');
-            for jj = 1:nstar0,
-                fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:)));
-            end
-            fprintf(fidTeX,'\\centering \n');
-            fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_HistoricalAndSmoothedVariables%s}\n',options_.figures.textwidth*min(i/nc,1),M_.fname,int2str(plt));
-            fprintf(fidTeX,'\\caption{Historical and smoothed variables.}');
-            fprintf(fidTeX,'\\label{Fig:HistoricalAndSmoothedVariables:%s}\n',int2str(plt));
-            fprintf(fidTeX,'\\end{figure}\n');
             fprintf(fidTeX,'\n');
+            fprintf(fidTeX,'%% End of TeX file.\n');
+            fclose(fidTeX);
         end
     end
-    if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
-        fprintf(fidTeX,'\n');
-        fprintf(fidTeX,'%% End of TeX file.\n');
-        fclose(fidTeX);
-    end
-    end
 end
 
 if options_.forecast > 0 && options_.mh_replic == 0 && ~options_.load_mh_file
@@ -758,3 +774,11 @@ end
 
 %reset qz_criterium
 options_.qz_criterium=qz_criterium_old;
+
+if reset_options_related_to_estimation
+    options_.mode_compute = mode_compute_o;
+    options_.mh_replic = mh_replic_o;
+end
+if first_obs_nan_indicator
+    options_.first_obs=NaN;
+end
\ No newline at end of file
diff --git a/matlab/dynare_estimation_init.m b/matlab/dynare_estimation_init.m
index 05c6c8983e7b4d76a7008922a44623c276983d1e..3cbbf6d6090b25820d3a4ad5c3160f44271aafe9 100644
--- a/matlab/dynare_estimation_init.m
+++ b/matlab/dynare_estimation_init.m
@@ -14,7 +14,7 @@ function [dataset_, dataset_info, xparam1, hh, M_, options_, oo_, estim_params_,
 %   estim_params_:  structure storing information about estimated
 %                   parameters
 %   bayestopt_:     structure storing information about priors
-    
+
 % OUTPUTS
 %   dataset_:       the dataset after required transformation
 %   dataset_info:   Various informations about the dataset (descriptive statistics and missing observations).
@@ -28,11 +28,11 @@ function [dataset_, dataset_info, xparam1, hh, M_, options_, oo_, estim_params_,
 %                   parameters
 %   bayestopt_:     structure storing information about priors
 %   bounds:         structure containing prior bounds
-% 
+%
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2003-2016 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -50,6 +50,7 @@ function [dataset_, dataset_info, xparam1, hh, M_, options_, oo_, estim_params_,
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 hh = [];
+xparam1 = [];
 
 if isempty(gsa_flag)
     gsa_flag = 0;
@@ -104,13 +105,13 @@ if options_.analytic_derivation && options_.fast_kalman_filter
 end
 
 % fast kalman filter is only available with kalman_algo == 0,1,3
-if options_.fast_kalman_filter 
+if options_.fast_kalman_filter
     if ~ismember(options_.kalman_algo, [0,1,3])
         error(['estimation option conflict: fast_kalman_filter is only available ' ...
-            'with kalman_algo = 0, 1 or 3'])
+               'with kalman_algo = 0, 1 or 3'])
     elseif options_.block
         error(['estimation option conflict: fast_kalman_filter is not available ' ...
-            'with block'])
+               'with block'])
     end
 end
 
@@ -126,6 +127,9 @@ end
 options_=select_qz_criterium_value(options_);
 
 % Set options related to filtered variables.
+if  isequal(options_.filtered_vars,0) && ~isempty(options_.filter_step_ahead)
+    options_.filtered_vars = 1;
+end
 if ~isequal(options_.filtered_vars,0) && isempty(options_.filter_step_ahead)
     options_.filter_step_ahead = 1;
 end
@@ -186,7 +190,7 @@ if ~isempty(estim_params_) && ~(isfield(estim_params_,'nvx') && sum(estim_params
             % The posterior mode is not estimated.
             error('Please change the mode_file option, the list of estimated parameters or set mode_compute>0.')
         else
-            % The posterior mode is estimated, the Hessian evaluated at the mode is not needed so we set values for the parameters missing in the mode file using the prior mean. 
+            % The posterior mode is estimated, the Hessian evaluated at the mode is not needed so we set values for the parameters missing in the mode file using the prior mean.
             if ~isempty(xd)
                 xparam1(xd) = mode_file.xparam1(md);
             else
@@ -226,7 +230,7 @@ if ~isempty(estim_params_) && ~(isfield(estim_params_,'nvx') && sum(estim_params
                 error('Please change the mode_file option, the list of estimated parameters or set mode_compute>0.')
             end
         else
-            % The posterior mode is estimated, the Hessian evaluated at the mode is not needed so we set values for the parameters missing in the mode file using the prior mean. 
+            % The posterior mode is estimated, the Hessian evaluated at the mode is not needed so we set values for the parameters missing in the mode file using the prior mean.
             if ~isempty(xd)
                 xparam1(xd) = mode_file.xparam1(md);
             else
@@ -235,7 +239,7 @@ if ~isempty(estim_params_) && ~(isfield(estim_params_,'nvx') && sum(estim_params
             end
         end
     else
-        % The number of declared estimated parameters match the number of parameters in the mode file. 
+        % The number of declared estimated parameters match the number of parameters in the mode file.
         % Check that the parameters in the mode file and according to the current mod file are identical.
         if ~isfield(mode_file,'parameter_names')
             disp(['The posterior mode file ' options_.mode_file ' has been generated using an older version of Dynare. It cannot be verified if it matches the present model. Proceed at your own risk.'])
@@ -272,7 +276,7 @@ if ~isempty(estim_params_) && ~(isfield(estim_params_,'nvx') && sum(estim_params
                     error('Please change the mode_file option, the list of estimated parameters or set mode_compute>0.')
                 end
             else
-                % The posterior mode is estimated, the Hessian evaluated at the mode is not needed so we set values for the parameters missing in the mode file using the prior mean. 
+                % The posterior mode is estimated, the Hessian evaluated at the mode is not needed so we set values for the parameters missing in the mode file using the prior mean.
                 if ~isempty(xd)
                     xparam1(xd) = mode_file.xparam1(md);
                     if isfield(mode_file,'hh')
@@ -308,6 +312,10 @@ if options_.use_calibration_initialization %set calibration as starting values
     end
 end
 
+if ~isempty(bayestopt_) && all(bayestopt_.pshape==0) && any(isnan(xparam1))
+    error('ML estimation requires all estimated parameters to be initialized, either in an estimated_params or estimated_params_init-block ')
+end
+
 if ~isempty(estim_params_) && ~(all(strcmp(fieldnames(estim_params_),'full_calibration_detected'))  || (isfield(estim_params_,'nvx') && sum(estim_params_.nvx+estim_params_.nvn+estim_params_.ncx+estim_params_.ncn+estim_params_.np)==0))
     if ~isempty(bayestopt_) && any(bayestopt_.pshape > 0)
         % Plot prior densities.
@@ -319,8 +327,8 @@ if ~isempty(estim_params_) && ~(all(strcmp(fieldnames(estim_params_),'full_calib
         bounds.lb = max(bounds.lb,lb);
         bounds.ub = min(bounds.ub,ub);
     else  % estimated parameters but no declared priors
-        % No priors are declared so Dynare will estimate the model by
-        % maximum likelihood with inequality constraints for the parameters.
+          % No priors are declared so Dynare will estimate the model by
+          % maximum likelihood with inequality constraints for the parameters.
         options_.mh_replic = 0;% No metropolis.
         bounds.lb = lb;
         bounds.ub = ub;
@@ -336,7 +344,7 @@ if ~isempty(estim_params_) && ~(all(strcmp(fieldnames(estim_params_),'full_calib
         end
     else
         check_prior_bounds(xparam1,bounds,M_,estim_params_,options_,bayestopt_)
-    end        
+    end
 end
 
 if isempty(estim_params_) || all(strcmp(fieldnames(estim_params_),'full_calibration_detected')) || (isfield(estim_params_,'nvx') && sum(estim_params_.nvx+estim_params_.nvn+estim_params_.ncx+estim_params_.ncn+estim_params_.np)==0) % If estim_params_ is empty (e.g. when running the smoother on a calibrated model)
@@ -397,12 +405,12 @@ nstatic = M_.nstatic;          % Number of static variables.
 npred = M_.nspred;             % Number of predetermined variables.
 nspred = M_.nspred;            % Number of predetermined variables in the state equation.
 
-%% Setting resticted state space (observed + predetermined variables)
+%% Setting restricted state space (observed + predetermined variables)
 % oo_.dr.restrict_var_list: location of union of observed and state variables in decision rules (decision rule order)
 % bayestopt_.mfys: position of observables in oo_.dr.ys (declaration order)
 % bayestopt_.mf0: position of state variables in restricted state vector (oo_.dr.restrict_var_list)
-% bayestopt_.mf1: positions of observed variables in decision rules (oo_.dr.restrict_var_list)
-% bayestopt_.mf2: positions of observed variables in decision rules (decision rule order)
+% bayestopt_.mf1: positions of observed variables in restricted state vector (oo_.dr.restrict_var_list order)
+% bayestopt_.mf2: positions of observed variables in decision rules/expanded state vector (decision rule order)
 % bayestopt_.smoother_var_list: positions of observed variables and requested smoothed variables in decision rules (decision rule order)
 % bayestopt_.smoother_saved_var_list: positions of requested smoothed variables in bayestopt_.smoother_var_list
 % bayestopt_.smoother_restrict_columns: positions of states in observed variables and requested smoothed variables in decision rules (decision rule order)
@@ -420,7 +428,7 @@ if options_.selected_variables_only
     if options_.forecast > 0 && options_.mh_replic == 0 && ~options_.load_mh_file
         fprintf('\nEstimation: The selected_variables_only option is incompatible with classical forecasts. It will be ignored.\n')
         k3 = (1:M_.endo_nbr)';
-        k3p = (1:M_.endo_nbr)';    
+        k3p = (1:M_.endo_nbr)';
     else
         for i=1:size(var_list_,1)
             k3 = [k3; strmatch(var_list_(i,:),M_.endo_names(dr.order_var,:), 'exact')];
@@ -471,18 +479,18 @@ else
     [junk,ic] = intersect(bayestopt_.smoother_var_list,nstatic+(1:npred)');
     bayestopt_.smoother_restrict_columns = ic;
     [junk,bayestopt_.smoother_mf] = ismember(var_obs_index_dr, bayestopt_.smoother_var_list);
-end;
+end
 
-if options_.analytic_derivation,
-    if options_.lik_init == 3,
+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),
+    if ~(exist('sylvester3','file')==2)
         dynareroot = strrep(which('dynare'),'dynare.m','');
         addpath([dynareroot 'gensylv'])
     end
-    if estim_params_.np,
+    if estim_params_.np
         % check if steady state changes param values
         M=M_;
         M.params(estim_params_.param_vals(:,1)) = xparam1(estim_params_.nvx+estim_params_.ncx+estim_params_.nvn+estim_params_.ncn+1:end); %set parameters
@@ -494,8 +502,8 @@ if options_.analytic_derivation,
         end
         [tmp1, params] = evaluate_steady_state(oo_.steady_state,M,options_,oo_,steadystate_check_flag);
         change_flag=any(find(params-M.params));
-        if change_flag,
-            skipline();
+        if change_flag
+            skipline()
             if any(isnan(params))
                 disp('After computing the steadystate, the following parameters are still NaN: '),
                 disp(M.param_names(isnan(params),:))
@@ -524,13 +532,16 @@ if ~isempty(options_.datafile)
     end
 end
 
+if isnan(options_.first_obs)
+    options_.first_obs=1;
+end
 [dataset_, dataset_info, newdatainterfaceflag] = makedataset(options_, options_.dsge_var*options_.dsge_varlag, gsa_flag);
 
 %set options for old interface from the ones for new interface
 if ~isempty(dataset_)
     options_.nobs = dataset_.nobs;
-    options_.first_obs=double(dataset_.init);
 end
+
 % setting steadystate_check_flag option
 if options_.diffuse_filter || options_.steadystate.nocheck
     steadystate_check_flag = 0;
@@ -545,12 +556,12 @@ ncx = estim_params_.ncx;
 nvn = estim_params_.nvn;
 ncn = estim_params_.ncn;
 if estim_params_.np
-  M.params(estim_params_.param_vals(:,1)) = xparam1(nvx+ncx+nvn+ncn+1:end);
+    M.params(estim_params_.param_vals(:,1)) = xparam1(nvx+ncx+nvn+ncn+1:end);
 end
 [oo_.steady_state, params,info] = evaluate_steady_state(oo_.steady_state,M,options_,oo_,steadystate_check_flag);
 
 if info(1)
-    fprintf('\ndynare_estimation_init:: The steady state at the initial parameters cannot be computed.')
+    fprintf('\ndynare_estimation_init:: The steady state at the initial parameters cannot be computed.\n')
     print_info(info, 0, options_);
 end
 
@@ -603,7 +614,7 @@ if options_.load_results_after_load_mh
     end
 end
 
-if options_.mh_replic
+if options_.mh_replic || options_.load_mh_file
     [current_options, options_] = check_posterior_sampler_options([], options_, bounds);
     options_.posterior_sampler_options.current_options = current_options;
 end
diff --git a/matlab/dynare_gradient.m b/matlab/dynare_gradient.m
index 91b4140c15bbd6b969518712854447f0b73188e8..2f4dfc9d499623d5a4ef250d4bc7dad0adb7a868 100644
--- a/matlab/dynare_gradient.m
+++ b/matlab/dynare_gradient.m
@@ -4,15 +4,15 @@ function [F,G] = dynare_gradient(fcn,x,epsilon,varargin)
 % INPUTS:
 %  fcn      [string]  name of the matlab's function.
 %  x        [double]  m*1 vector (where the gradient is evaluated).
-%  epsilon  [double]  scalar or m*1 vector of steps. 
+%  epsilon  [double]  scalar or m*1 vector of steps.
 %
-% OUTPUTS: 
+% OUTPUTS:
 %  F        [double]  n*1 vector, evaluation of the function at x.
 %  G        [double]  n*m matrix, evaluation of the gradient at x.
 %
 % OUTPUTS
-% 
-% Copyright (C) 2010-2012 Dynare Team
+%
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -51,7 +51,7 @@ for i=1:m
         h = H(i,:);
     else
         h = H(:,i);
-    end   
+    end
     [Fh,junk1,junk2,flag] = feval(fcn, x+transpose(h), varargin{:});
     if flag
         G(:,i) = (Fh-F)/epsilon;
diff --git a/matlab/dynare_graph.m b/matlab/dynare_graph.m
index 9af832f7f917d68cfc7d8ea49cc9a161befa30a5..3717efa45f1b317078accec6217e2ba82bf6ad08 100644
--- a/matlab/dynare_graph.m
+++ b/matlab/dynare_graph.m
@@ -1,5 +1,5 @@
 function dyn_graph=dynare_graph(dyn_graph,y,tit,x)
-% function dynare_graph(y,tit,x) 
+% function dynare_graph(y,tit,x)
 % graphs
 %
 % INPUT
@@ -12,7 +12,7 @@ function dyn_graph=dynare_graph(dyn_graph,y,tit,x)
 % SPECIAL REQUIREMENT
 %   none
 
-% Copyright (C) 2006-2013 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -32,7 +32,7 @@ function dyn_graph=dynare_graph(dyn_graph,y,tit,x)
 if nargin < 4
     x = (1:size(y,1))';
 end
-nplot = dyn_graph.plot_nbr + 1; 
+nplot = dyn_graph.plot_nbr + 1;
 if nplot > dyn_graph.max_nplot
     figure('Name',dyn_graph.figure_name);
     nplot = 1;
@@ -42,11 +42,11 @@ subplot(dyn_graph.nr,dyn_graph.nc,nplot);
 
 line_types = dyn_graph.line_types;
 line_type = line_types{1};
-for i=1:size(y,2);
+for i=1:size(y,2)
     if length(line_types) > 1
         line_type = line_types{i};
     end
-    
+
     plot(x,y(:,i),line_type);
     hold on
 end
diff --git a/matlab/dynare_graph_close.m b/matlab/dynare_graph_close.m
index ed4371034c6e55cc2dc6c2edee2bb580c8d7fc44..72622314dcfcdc9f1d510abcecf640205185f255 100644
--- a/matlab/dynare_graph_close.m
+++ b/matlab/dynare_graph_close.m
@@ -1,5 +1,5 @@
 function dynare_graph_close()
-% function dynare_graph_close() 
+% function dynare_graph_close()
 % close a figure
 %
 % INPUT
@@ -11,7 +11,7 @@ function dynare_graph_close()
 % SPECIAL REQUIREMENT
 %   none
 
-% Copyright (C) 2006-2009 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -27,4 +27,3 @@ function dynare_graph_close()
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
-
diff --git a/matlab/dynare_graph_init.m b/matlab/dynare_graph_init.m
index 4e0af5b8c9d9211e8a86fffad59cf1ecdad81aa7..b97c2b5f84a4e38f1397d60902852ba604e4aeec 100644
--- a/matlab/dynare_graph_init.m
+++ b/matlab/dynare_graph_init.m
@@ -1,5 +1,5 @@
 function dyn_graph=dynare_graph_init(figure_name,nplot,line_types,line_width)
-% function dynare_graph_init(figure_name,colors) 
+% function dynare_graph_init(figure_name,colors)
 % initializes set of graphs
 %
 % INPUTS:
@@ -12,7 +12,7 @@ function dyn_graph=dynare_graph_init(figure_name,nplot,line_types,line_width)
 % SPECIAL REQUIREMENT
 %   none
 
-% Copyright (C) 2006-2013 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -31,7 +31,7 @@ function dyn_graph=dynare_graph_init(figure_name,nplot,line_types,line_width)
 
 global options_
 
-dyn_graph.fh = dyn_figure(options_,'Name',figure_name);
+dyn_graph.fh = dyn_figure(options_.nodisplay,'Name',figure_name);
 dyn_graph.figure_name = figure_name;
 if nargin > 2
     dyn_graph.line_types = line_types;
diff --git a/matlab/dynare_identification.m b/matlab/dynare_identification.m
index c84faf2c67a57d4dd42d9f3d60f34430d01de45d..7b5c1e5569e803ecd1d8a1f952620e8896452288 100644
--- a/matlab/dynare_identification.m
+++ b/matlab/dynare_identification.m
@@ -3,8 +3,8 @@ function [pdraws, TAU, GAM, LRE, gp, H, JJ] = dynare_identification(options_iden
 %
 % INPUTS
 %    o options_ident    [structure] identification options
-%    o pdraws0          [matrix] optional: matrix of MC sample of model params. 
-%    
+%    o pdraws0          [matrix] optional: matrix of MC sample of model params.
+%
 % OUTPUTS
 %    o pdraws           [matrix] matrix of MC sample of model params used
 %    o TAU,             [matrix] MC sample of entries in the model solution (stacked vertically)
@@ -13,13 +13,13 @@ function [pdraws, TAU, GAM, LRE, gp, H, JJ] = dynare_identification(options_iden
 %    o gp,              [matrix] derivatives of the Jacobian (LRE model)
 %    o H,               [matrix] derivatives of the model solution
 %    o JJ               [matrix] derivatives of the  moments
-%    
+%
 % SPECIAL REQUIREMENTS
 %    None
 
-% main 
+% main
 %
-% Copyright (C) 2010-2016 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -67,7 +67,7 @@ else
     if options_.diffuse_filter==1 %warning if estimation with diffuse filter was done, but not passed
         warning('IDENTIFICATION:: Previously the diffuse_filter option was used, but it was not passed to the identification command. This may result in problems if your model contains unit roots.')
     end
-    if isfield(options_ident,'lik_init') 
+    if isfield(options_ident,'lik_init')
         options_.lik_init=options_ident.lik_init; %make options_ inherit lik_init
         if options_ident.lik_init==3 %user specified diffuse filter using the lik_init option
             options_ident.analytic_derivation=0; %diffuse filter not compatible with analytic derivation
@@ -78,48 +78,48 @@ end
 options_ident = set_default_option(options_ident,'lik_init',1);
 options_ident = set_default_option(options_ident,'analytic_derivation',1);
 
-if isfield(options_ident,'nograph'),
+if isfield(options_ident,'nograph')
     options_.nograph=options_ident.nograph;
 end
-if isfield(options_ident,'nodisplay'),
+if isfield(options_ident,'nodisplay')
     options_.nodisplay=options_ident.nodisplay;
 end
-if isfield(options_ident,'graph_format'),
+if isfield(options_ident,'graph_format')
     options_.graph_format=options_ident.graph_format;
 end
-if isfield(options_ident,'prior_trunc'),
+if isfield(options_ident,'prior_trunc')
     options_.prior_trunc=options_ident.prior_trunc;
 end
 
-if options_ident.gsa_sample_file,
+if options_ident.gsa_sample_file
     GSAFolder = checkpath('gsa',M_.dname);
-    if options_ident.gsa_sample_file==1,
+    if options_ident.gsa_sample_file==1
         load([GSAFolder,filesep,fname_,'_prior'],'lpmat','lpmat0','istable');
-    elseif options_ident.gsa_sample_file==2,
+    elseif options_ident.gsa_sample_file==2
         load([GSAFolder,filesep,fname_,'_mc'],'lpmat','lpmat0','istable');
     else
         load([GSAFolder,filesep,options_ident.gsa_sample_file],'lpmat','lpmat0','istable');
     end
-    if isempty(istable),
+    if isempty(istable)
         istable=1:size(lpmat,1);
     end
-    if ~isempty(lpmat0),
+    if ~isempty(lpmat0)
         lpmatx=lpmat0(istable,:);
     else
         lpmatx=[];
     end
     pdraws0 = [lpmatx lpmat(istable,:)];
     clear lpmat lpmat0 istable;
-elseif nargin==1,
+elseif nargin==1
     pdraws0=[];
 end
 external_sample=0;
-if nargin==2 || ~isempty(pdraws0),
+if nargin==2 || ~isempty(pdraws0)
     options_ident.prior_mc=size(pdraws0,1);
     options_ident.load_ident_files = 0;
     external_sample=1;
 end
-if isempty(estim_params_),
+if isempty(estim_params_)
     options_ident.prior_mc=1;
     options_ident.prior_range=0;
     prior_exist=0;
@@ -164,28 +164,24 @@ end
 
 SampleSize = options_ident.prior_mc;
 
-if ~(exist('sylvester3','file')==2),
-
+if ~(exist('sylvester3','file')==2)
     dynareroot = strrep(which('dynare'),'dynare.m','');
     addpath([dynareroot 'gensylv'])
 end
 
 IdentifDirectoryName = CheckPath('identification',M_.dname);
-if prior_exist,
-
+if prior_exist
     indx = [];
-    if ~isempty(estim_params_.param_vals),
+    if ~isempty(estim_params_.param_vals)
         indx = estim_params_.param_vals(:,1);
     end
     indexo=[];
     if ~isempty(estim_params_.var_exo)
         indexo = estim_params_.var_exo(:,1);
     end
-
     nparam = length(bayestopt_.name);
     np = estim_params_.np;
-
-    if estim_params_.nvn || estim_params_.ncn,
+    if estim_params_.nvn || estim_params_.ncn
         error('Identification does not support measurement errors. Instead, define them explicitly in measurement equations in model definition.')
     else
         offset = estim_params_.nvx;
@@ -199,7 +195,7 @@ if prior_exist,
     end
     name=cell(nparam,1);
     name_tex=cell(nparam,1);
-    for jj=1:nparam        
+    for jj=1:nparam
         if options_.TeX
             [param_name_temp, param_name_tex_temp]= get_the_name(jj,options_.TeX,M_,estim_params_,options_);
             name_tex{jj,1} = strrep(param_name_tex_temp,'$','');
@@ -229,9 +225,9 @@ else
 end
 
 skipline()
-disp(['==== Identification analysis ====' ]),
+disp(['==== Identification analysis ====' ])
 skipline()
-if nparam<2,
+if nparam<2
     options_ident.advanced=0;
     advanced = options_ident.advanced;
     disp('There is only one parameter to study for identitification.')
@@ -246,22 +242,21 @@ options_ident.max_dim_cova_group = min([options_ident.max_dim_cova_group,nparam-
 MaxNumberOfBytes=options_.MaxNumberOfBytes;
 store_options_ident = options_ident;
 
-if iload <=0,
-    
+if iload <=0
     [I,J]=find(M_.lead_lag_incidence');
-    if prior_exist,
-%         if exist([fname_,'_mean.mat'],'file'),
-% %             disp('Testing posterior mean')
-%             load([fname_,'_mean'],'xparam1')
-%             pmean = xparam1';
-%             clear xparam1
-%         end
-%         if exist([fname_,'_mode.mat'],'file'),
-% %             disp('Testing posterior mode')
-%             load([fname_,'_mode'],'xparam1')
-%             pmode = xparam1';
-%             clear xparam1
-%         end
+    if prior_exist
+        %         if exist([fname_,'_mean.mat'],'file'),
+        % %             disp('Testing posterior mean')
+        %             load([fname_,'_mean'],'xparam1')
+        %             pmean = xparam1';
+        %             clear xparam1
+        %         end
+        %         if exist([fname_,'_mode.mat'],'file'),
+        % %             disp('Testing posterior mode')
+        %             load([fname_,'_mode'],'xparam1')
+        %             pmode = xparam1';
+        %             clear xparam1
+        %         end
         params = set_prior(estim_params_,M_,options_)';
         if all(bayestopt_.pshape == 0)
             parameters = 'ML_Starting_value';
@@ -269,38 +264,38 @@ if iload <=0,
             disp('Testing ML Starting value')
         else
             switch parameters
-                case 'calibration'
-                    parameters_TeX = 'Calibration';
-                    disp('Testing calibration')
-                    params(1,:) = get_all_parameters(estim_params_,M_);;
-                case 'posterior_mode'
-                    parameters_TeX = 'Posterior mode';
-                    disp('Testing posterior mode')
-                    params(1,:) = get_posterior_parameters('mode');
-                case 'posterior_mean'
-                    parameters_TeX = 'Posterior mean';
-                    disp('Testing posterior mean')
-                    params(1,:) = get_posterior_parameters('mean');
-                case 'posterior_median'
-                    parameters_TeX = 'Posterior median';
-                    disp('Testing posterior median')
-                    params(1,:) = get_posterior_parameters('median');
-                case 'prior_mode'
-                    parameters_TeX = 'Prior mode';
-                    disp('Testing prior mode')
-                    params(1,:) = bayestopt_.p5(:);
-                case 'prior_mean'
-                    parameters_TeX = 'Prior mean';                    
-                    disp('Testing prior mean')
-                    params(1,:) = bayestopt_.p1;
-                otherwise
-                    disp('The option parameter_set has to be equal to:')
-                    disp('                   ''posterior_mode'', ')
-                    disp('                   ''posterior_mean'', ')
-                    disp('                   ''posterior_median'', ')
-                    disp('                   ''prior_mode'' or')
-                    disp('                   ''prior_mean''.')
-                    error;
+              case 'calibration'
+                parameters_TeX = 'Calibration';
+                disp('Testing calibration')
+                params(1,:) = get_all_parameters(estim_params_,M_);
+              case 'posterior_mode'
+                parameters_TeX = 'Posterior mode';
+                disp('Testing posterior mode')
+                params(1,:) = get_posterior_parameters('mode');
+              case 'posterior_mean'
+                parameters_TeX = 'Posterior mean';
+                disp('Testing posterior mean')
+                params(1,:) = get_posterior_parameters('mean');
+              case 'posterior_median'
+                parameters_TeX = 'Posterior median';
+                disp('Testing posterior median')
+                params(1,:) = get_posterior_parameters('median');
+              case 'prior_mode'
+                parameters_TeX = 'Prior mode';
+                disp('Testing prior mode')
+                params(1,:) = bayestopt_.p5(:);
+              case 'prior_mean'
+                parameters_TeX = 'Prior mean';
+                disp('Testing prior mean')
+                params(1,:) = bayestopt_.p1;
+              otherwise
+                disp('The option parameter_set has to be equal to:')
+                disp('                   ''posterior_mode'', ')
+                disp('                   ''posterior_mean'', ')
+                disp('                   ''posterior_median'', ')
+                disp('                   ''prior_mode'' or')
+                disp('                   ''prior_mean''.')
+                error;
             end
         end
     else
@@ -311,45 +306,45 @@ if iload <=0,
     end
     [idehess_point, idemoments_point, idemodel_point, idelre_point, derivatives_info_point, info, options_ident] = ...
         identification_analysis(params,indx,indexo,options_ident,dataset_, dataset_info, prior_exist, name_tex,1,parameters,bounds);
-    if info(1)~=0,
+    if info(1)~=0
         skipline()
         disp('----------- ')
         disp('Parameter error:')
         disp(['The model does not solve for ', parameters, ' with error code info = ', int2str(info(1))]),
         skipline()
-        if info(1)==1,
-        disp('info==1 %! The model doesn''t determine the current variables uniquely.')
-        elseif info(1)==2,
-        disp('info==2 %! MJDGGES returned an error code.')
-        elseif info(1)==3,
-        disp('info==3 %! Blanchard & Kahn conditions are not satisfied: no stable equilibrium. ')
-        elseif info(1)==4,
-        disp('info==4 %! Blanchard & Kahn conditions are not satisfied: indeterminacy. ')
-        elseif info(1)==5,
-        disp('info==5 %! Blanchard & Kahn conditions are not satisfied: indeterminacy due to rank failure. ')
-        elseif info(1)==6,
-        disp('info==6 %! The jacobian evaluated at the deterministic steady state is complex.')
-        elseif info(1)==19,
-        disp('info==19 %! The steadystate routine thrown an exception (inconsistent deep parameters). ')
-        elseif info(1)==20,
-        disp('info==20 %! Cannot find the steady state, info(2) contains the sum of square residuals (of the static equations). ')
-        elseif info(1)==21,
-        disp('info==21 %! The steady state is complex, info(2) contains the sum of square of imaginary parts of the steady state.')
-        elseif info(1)==22,
-        disp('info==22 %! The steady has NaNs. ')
-        elseif info(1)==23,
-        disp('info==23 %! M_.params has been updated in the steadystate routine and has complex valued scalars. ')
-        elseif info(1)==24,
-        disp('info==24 %! M_.params has been updated in the steadystate routine and has some NaNs. ')
-        elseif info(1)==30,
-        disp('info==30 %! Ergodic variance can''t be computed. ')
+        if info(1)==1
+            disp('info==1 %! The model doesn''t determine the current variables uniquely.')
+        elseif info(1)==2
+            disp('info==2 %! MJDGGES returned an error code.')
+        elseif info(1)==3
+            disp('info==3 %! Blanchard & Kahn conditions are not satisfied: no stable equilibrium. ')
+        elseif info(1)==4
+            disp('info==4 %! Blanchard & Kahn conditions are not satisfied: indeterminacy. ')
+        elseif info(1)==5
+            disp('info==5 %! Blanchard & Kahn conditions are not satisfied: indeterminacy due to rank failure. ')
+        elseif info(1)==6
+            disp('info==6 %! The jacobian evaluated at the deterministic steady state is complex.')
+        elseif info(1)==19
+            disp('info==19 %! The steadystate routine thrown an exception (inconsistent deep parameters). ')
+        elseif info(1)==20
+            disp('info==20 %! Cannot find the steady state, info(2) contains the sum of square residuals (of the static equations). ')
+        elseif info(1)==21
+            disp('info==21 %! The steady state is complex, info(2) contains the sum of square of imaginary parts of the steady state.')
+        elseif info(1)==22
+            disp('info==22 %! The steady has NaNs. ')
+        elseif info(1)==23
+            disp('info==23 %! M_.params has been updated in the steadystate routine and has complex valued scalars. ')
+        elseif info(1)==24
+            disp('info==24 %! M_.params has been updated in the steadystate routine and has some NaNs. ')
+        elseif info(1)==30
+            disp('info==30 %! Ergodic variance can''t be computed. ')
         end
         disp('----------- ')
         skipline()
         if any(bayestopt_.pshape)
             disp('Try sampling up to 50 parameter sets from the prior.')
             kk=0;
-            while kk<50 && info(1),
+            while kk<50 && info(1)
                 kk=kk+1;
                 params = prior_draw();
                 [idehess_point, idemoments_point, idemodel_point, idelre_point, derivatives_info_point, info, options_ident] = ...
@@ -372,20 +367,20 @@ if iload <=0,
         end
     end
     idehess_point.params=params;
-%     siH = idemodel_point.siH;
-%     siJ = idemoments_point.siJ;
-%     siLRE = idelre_point.siLRE;
-%     normH = max(abs(siH)')';
-%     normJ = max(abs(siJ)')';
-%     normLRE = max(abs(siLRE)')';
+    %     siH = idemodel_point.siH;
+    %     siJ = idemoments_point.siJ;
+    %     siLRE = idelre_point.siLRE;
+    %     normH = max(abs(siH)')';
+    %     normJ = max(abs(siJ)')';
+    %     normLRE = max(abs(siLRE)')';
     save([IdentifDirectoryName '/' M_.fname '_identif.mat'], 'idehess_point', 'idemoments_point','idemodel_point', 'idelre_point','store_options_ident')
     save([IdentifDirectoryName '/' M_.fname '_' parameters '_identif.mat'], 'idehess_point', 'idemoments_point','idemodel_point', 'idelre_point','store_options_ident')
     disp_identification(params, idemodel_point, idemoments_point, name, advanced);
-    if ~options_.nograph,
+    if ~options_.nograph
         plot_identification(params,idemoments_point,idehess_point,idemodel_point,idelre_point,advanced,parameters,name,IdentifDirectoryName,parameters_TeX,name_tex);
     end
 
-    if SampleSize > 1,
+    if SampleSize > 1
         skipline()
         disp('Monte Carlo Testing')
         h = dyn_waitbar(0,'Monte Carlo identification checks ...');
@@ -399,16 +394,16 @@ if iload <=0,
         iteration = 1;
         pdraws = [];
     end
-    while iteration < SampleSize,
+    while iteration < SampleSize
         loop_indx = loop_indx+1;
-        if external_sample,
+        if external_sample
             params = pdraws0(iteration+1,:);
         else
             params = prior_draw();
         end
         [dum1, ideJ, ideH, ideGP, dum2 , info, options_MC] = ...
             identification_analysis(params,indx,indexo,options_MC,dataset_, dataset_info, prior_exist, name_tex,0,[],bounds);
-        if iteration==0 && info(1)==0,
+        if iteration==0 && info(1)==0
             MAX_tau   = min(SampleSize,ceil(MaxNumberOfBytes/(size(ideH.siH,1)*nparam)/8));
             stoH = zeros([size(ideH.siH,1),nparam,MAX_tau]);
             stoJJ = zeros([size(ideJ.siJ,1),nparam,MAX_tau]);
@@ -439,7 +434,7 @@ if iload <=0,
             idemoments.V = zeros(SampleSize,nparam,min(8,nparam));
             delete([IdentifDirectoryName '/' M_.fname '_identif_*.mat'])
         end
-        if info(1)==0,
+        if info(1)==0
             iteration = iteration + 1;
             run_index = run_index + 1;
             TAU(:,iteration)=ideH.TAU;
@@ -469,9 +464,9 @@ if iload <=0,
             stoH(:,:,run_index) = ideH.siH;
             stoJJ(:,:,run_index) = ideJ.siJ;
             pdraws(iteration,:) = params;
-            if run_index==MAX_tau || iteration==SampleSize,
+            if run_index==MAX_tau || iteration==SampleSize
                 file_index = file_index + 1;
-                if run_index<MAX_tau,
+                if run_index<MAX_tau
                     stoH = stoH(:,:,1:run_index);
                     stoJJ = stoJJ(:,:,1:run_index);
                     stoLRE = stoLRE(:,:,1:run_index);
@@ -481,142 +476,142 @@ if iload <=0,
                 stoH = zeros(size(stoH));
                 stoJJ = zeros(size(stoJJ));
                 stoLRE = zeros(size(stoLRE));
-                
+
             end
-            
-            if SampleSize > 1,
-%                 if isoctave || options_.console_mode,
-%                     console_waitbar(0,iteration/SampleSize);
-%                 else
-                    dyn_waitbar(iteration/SampleSize,h,['MC identification checks ',int2str(iteration),'/',int2str(SampleSize)])
-%                 end
+
+            if SampleSize > 1
+                %                 if isoctave || options_.console_mode,
+                %                     console_waitbar(0,iteration/SampleSize);
+                %                 else
+                dyn_waitbar(iteration/SampleSize,h,['MC identification checks ',int2str(iteration),'/',int2str(SampleSize)])
+                %                 end
             end
         end
-        
+
     end
-    
-    
-    if SampleSize > 1,
-        if isoctave || options_.console_mode,
+
+
+    if SampleSize > 1
+        if isoctave || options_.console_mode
             fprintf('\n');
             diary on;
         else
-            close(h),
+            close(h)
         end
         normTAU=std(TAU')';
         normLRE=std(LRE')';
         normGAM=std(GAM')';
         normaliz1=std(pdraws);
         iter=0;
-        for ifile_index = 1:file_index,
+        for ifile_index = 1:file_index
             load([IdentifDirectoryName '/' M_.fname '_identif_' int2str(ifile_index) '.mat'], 'stoH', 'stoJJ', 'stoLRE')
-            for irun=1:size(stoH,3),
+            for irun=1:size(stoH,3)
                 iter=iter+1;
                 siJnorm(iter,:) = vnorm(stoJJ(:,:,irun)./repmat(normGAM,1,nparam)).*normaliz1;
                 siHnorm(iter,:) = vnorm(stoH(:,:,irun)./repmat(normTAU,1,nparam)).*normaliz1;
                 siLREnorm(iter,:) = vnorm(stoLRE(:,:,irun)./repmat(normLRE,1,nparam-offset)).*normaliz1(offset+1:end);
             end
-            
+
         end
         idemoments.siJnorm = siJnorm;
         idemodel.siHnorm = siHnorm;
         idelre.siLREnorm = siLREnorm;
         save([IdentifDirectoryName '/' M_.fname '_identif.mat'], 'pdraws', 'idemodel', 'idemoments', 'idelre', ... %'indJJ', 'indH', 'indLRE', ...
-            'TAU', 'GAM', 'LRE','-append')
+             'TAU', 'GAM', 'LRE','-append')
     else
         siJnorm = idemoments_point.siJnorm;
         siHnorm = idemodel_point.siHnorm;
         siLREnorm = idelre_point.siLREnorm;
     end
-    
+
 else
     load([IdentifDirectoryName '/' M_.fname '_identif'])
-%     identFiles = dir([IdentifDirectoryName '/' M_.fname '_identif_*']);
+    %     identFiles = dir([IdentifDirectoryName '/' M_.fname '_identif_*']);
     parameters = store_options_ident.parameter_set;
     options_ident.parameter_set = parameters;
     options_ident.prior_mc=size(pdraws,1);
     SampleSize = options_ident.prior_mc;
     options_.options_ident = options_ident;
-end  
+end
 
-if nargout>3 && iload,
+if nargout>3 && iload
     filnam = dir([IdentifDirectoryName '/' M_.fname '_identif_*.mat']);
     H=[];
     JJ = [];
     gp = [];
-    for j=1:length(filnam),
+    for j=1:length(filnam)
         load([IdentifDirectoryName '/' M_.fname '_identif_',int2str(j),'.mat']);
         H = cat(3,H, stoH(:,abs(iload),:));
         JJ = cat(3,JJ, stoJJ(:,abs(iload),:));
         gp = cat(3,gp, stoLRE(:,abs(iload),:));
-        
+
     end
 end
 
-if iload,
+if iload
     disp(['Testing ',parameters])
     disp_identification(idehess_point.params, idemodel_point, idemoments_point, name,advanced);
-    if ~options_.nograph,
+    if ~options_.nograph
         plot_identification(idehess_point.params,idemoments_point,idehess_point,idemodel_point,idelre_point,advanced,parameters,name,IdentifDirectoryName,[],name_tex);
     end
 end
-if SampleSize > 1,
+if SampleSize > 1
     fprintf('\n')
     disp('Testing MC sample')
     disp_identification(pdraws, idemodel, idemoments, name);
-    if ~options_.nograph,
+    if ~options_.nograph
         plot_identification(pdraws,idemoments,idehess_point,idemodel,idelre,advanced,'MC sample ',name, IdentifDirectoryName,[],name_tex);
     end
-    if advanced,
+    if advanced
         jcrit=find(idemoments.ino);
-        if length(jcrit)<SampleSize,
-            if isempty(jcrit),
+        if length(jcrit)<SampleSize
+            if isempty(jcrit)
                 [dum,jmax]=max(idemoments.cond);
                 fprintf('\n')
                 tittxt = 'Draw with HIGHEST condition number';
                 fprintf('\n')
                 disp(['Testing ',tittxt, '. Press ENTER']), pause(5),
-                if ~iload,
+                if ~iload
                     [idehess_max, idemoments_max, idemodel_max, idelre_max, derivatives_info_max, info_max, options_ident] = ...
                         identification_analysis(pdraws(jmax,:),indx,indexo,options_ident,dataset_,dataset_info, prior_exist, name_tex,1,tittxt);
                     save([IdentifDirectoryName '/' M_.fname '_identif.mat'], 'idehess_max', 'idemoments_max','idemodel_max', 'idelre_max', 'jmax', '-append');
                 end
                 disp_identification(pdraws(jmax,:), idemodel_max, idemoments_max, name,1);
                 close all,
-                if ~options_.nograph,
+                if ~options_.nograph
                     plot_identification(pdraws(jmax,:),idemoments_max,idehess_max,idemodel_max,idelre_max,1,tittxt,name,IdentifDirectoryName,tittxt,name_tex);
                 end
                 [dum,jmin]=min(idemoments.cond);
                 fprintf('\n')
                 tittxt = 'Draw with SMALLEST condition number';
                 fprintf('\n')
-                disp(['Testing ',tittxt, '. Press ENTER']), pause(5),
-                if ~iload,
+                disp(['Testing ',tittxt, '. Press ENTER']), pause(5)
+                if ~iload
                     [idehess_min, idemoments_min, idemodel_min, idelre_min, derivatives_info_min, info_min, options_ident] = ...
                         identification_analysis(pdraws(jmin,:),indx,indexo,options_ident,dataset_, dataset_info, prior_exist, name_tex,1,tittxt);
                     save([IdentifDirectoryName '/' M_.fname '_identif.mat'], 'idehess_min', 'idemoments_min','idemodel_min', 'idelre_min', 'jmin', '-append');
                 end
                 disp_identification(pdraws(jmin,:), idemodel_min, idemoments_min, name,1);
                 close all,
-                if ~options_.nograph,
+                if ~options_.nograph
                     plot_identification(pdraws(jmin,:),idemoments_min,idehess_min,idemodel_min,idelre_min,1,tittxt,name,IdentifDirectoryName,tittxt,name_tex);
                 end
             else
-                for j=1:length(jcrit),
+                for j=1:length(jcrit)
                     tittxt = ['Rank deficient draw n. ',int2str(j)];
                     fprintf('\n')
                     disp(['Testing ',tittxt, '. Press ENTER']), pause(5),
-                    if ~iload,
+                    if ~iload
                         [idehess_(j), idemoments_(j), idemodel_(j), idelre_(j), derivatives_info_(j), info_resolve, options_ident] = ...
                             identification_analysis(pdraws(jcrit(j),:),indx,indexo,options_ident,dataset_, dataset_info, prior_exist, name_tex,1,tittxt);
                     end
                     disp_identification(pdraws(jcrit(j),:), idemodel_(j), idemoments_(j), name,1);
-                    close all,
-                    if ~options_.nograph,
+                    close all
+                    if ~options_.nograph
                         plot_identification(pdraws(jcrit(j),:),idemoments_(j),idehess_(j),idemodel_(j),idelre_(j),1,tittxt,name,IdentifDirectoryName,tittxt,name_tex);
                     end
                 end
-                if ~iload,
+                if ~iload
                     save([IdentifDirectoryName '/' M_.fname '_identif.mat'], 'idehess_', 'idemoments_','idemodel_', 'idelre_', 'jcrit', '-append');
                 end
             end
@@ -625,13 +620,13 @@ if SampleSize > 1,
 end
 
 if isoctave
-    warning('on'),
+    warning('on')
 else
-    warning on,
+    warning on
 end
 
 skipline()
-disp(['==== Identification analysis completed ====' ]),
+disp(['==== Identification analysis completed ====' ])
 skipline(2)
 
 options_ = options0_;
diff --git a/matlab/dynare_resolve.m b/matlab/dynare_resolve.m
index a2fad992ac939689997c47e751bee5cb6ee2a857..32a1a885d4497160e5b67fe0a51a2c3770b0209a 100644
--- a/matlab/dynare_resolve.m
+++ b/matlab/dynare_resolve.m
@@ -49,7 +49,7 @@ function [A,B,ys,info,Model,DynareOptions,DynareResults] = dynare_resolve(Model,
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2001-2016 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -90,7 +90,7 @@ switch nargin
         ic = [ nstatic+(1:nspred) endo_nbr+(1:size(DynareResults.dr.ghx,2)-nspred) ]';
     else
         ic = DynareResults.dr.restrict_columns;
-    end;
+    end
   case 4
     iv = DynareResults.dr.restrict_var_list;
     ic = DynareResults.dr.restrict_columns;
diff --git a/matlab/dynare_sensitivity.m b/matlab/dynare_sensitivity.m
index 0aad64e1c44ebf9350f9b53a8fd93a284769fd78..acb0f12b543e436faebceebf95ac08b43990544b 100644
--- a/matlab/dynare_sensitivity.m
+++ b/matlab/dynare_sensitivity.m
@@ -4,7 +4,7 @@ function x0=dynare_sensitivity(options_gsa)
 % Reference:
 % M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006.
 
-% Copyright (C) 2008-2016 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -24,64 +24,95 @@ function x0=dynare_sensitivity(options_gsa)
 global M_ options_ oo_ bayestopt_ estim_params_
 
 if options_.dsge_var
-   error('Identification does not support DSGE-VARs at the current stage') 
+    error('Identification does not support DSGE-VARs at the current stage')
 end
 
 fname_ = M_.fname;
 lgy_ = M_.endo_names;
 x0=[];
 
+% check user defined options
+if isfield(options_gsa,'neighborhood_width') && options_gsa.neighborhood_width
+    if isfield(options_gsa,'pprior') && options_gsa.pprior
+        error('sensitivity:: neighborhood_width is incompatible with prior sampling')
+    end
+    if isfield(options_gsa,'ppost') && options_gsa.ppost
+        error('sensitivity:: neighborhood_width is incompatible with posterior sampling')
+    end
+end
+
+if isfield(options_gsa,'morris') && options_gsa.morris==1
+    if isfield(options_gsa,'identification') && options_gsa.identification==0
+        %         options_gsa.redform=1;
+    end
+    if isfield(options_gsa,'ppost') && options_gsa.ppost
+        error('sensitivity:: Morris is incompatible with posterior sampling')
+    elseif isfield(options_gsa,'pprior') && options_gsa.pprior==0
+        if ~(isfield(options_gsa,'neighborhood_width') && options_gsa.neighborhood_width)
+            error('sensitivity:: Morris is incompatible with MC sampling with correlation matrix')
+        end
+    end
+    if isfield(options_gsa,'rmse') && options_gsa.rmse
+        error('sensitivity:: Morris is incompatible with rmse analysis')
+    end
+    if (isfield(options_gsa,'alpha2_stab') && options_gsa.alpha2_stab<1) || ...
+            (isfield(options_gsa,'pvalue_ks') && options_gsa.pvalue_ks) || ...
+            (isfield(options_gsa,'pvalue_corr') && options_gsa.pvalue_corr)
+        error('sensitivity:: Morris is incompatible with Monte Carlo filtering')
+    end
+end
+
+% end check user defined options
 options_gsa = set_default_option(options_gsa,'datafile',[]);
 options_gsa = set_default_option(options_gsa,'rmse',0);
 options_gsa = set_default_option(options_gsa,'useautocorr',0);
 
 options_gsa = set_default_option(options_gsa,'moment_calibration',options_.endogenous_prior_restrictions.moment);
 options_gsa = set_default_option(options_gsa,'irf_calibration',options_.endogenous_prior_restrictions.irf);
-if isfield(options_gsa,'nograph'),
+if isfield(options_gsa,'nograph')
     options_.nograph=options_gsa.nograph;
 end
-if isfield(options_gsa,'nodisplay'),
+if isfield(options_gsa,'nodisplay')
     options_.nodisplay=options_gsa.nodisplay;
 end
-if isfield(options_gsa,'graph_format'),
+if isfield(options_gsa,'graph_format')
     options_.graph_format=options_gsa.graph_format;
 end
-if isfield(options_gsa,'mode_file'),
+if isfield(options_gsa,'mode_file')
     options_.mode_file=options_gsa.mode_file;
-elseif isfield(options_gsa,'neighborhood_width') && options_gsa.neighborhood_width>0,
-    options_.mode_file='';    
+elseif isfield(options_gsa,'neighborhood_width') && options_gsa.neighborhood_width>0
+    options_.mode_file='';
 end
 
 options_.order = 1;
 
-if ~isempty(options_gsa.datafile) || isempty(bayestopt_) || options_gsa.rmse,
-    if isempty(options_gsa.datafile) && options_gsa.rmse,
+if ~isempty(options_gsa.datafile) || isempty(bayestopt_) || options_gsa.rmse
+    if isempty(options_gsa.datafile) && options_gsa.rmse
         disp('The data file and all relevant estimation options ')
         disp('[first_obs, nobs, presample, prefilter, loglinear, lik_init, kalman_algo, ...]')
         disp('must be specified for RMSE analysis!');
-        error('Sensitivity anaysis error!');
+        error('Sensitivity anaysis error!')
     end
-    
     options_.datafile = options_gsa.datafile;
-    if isfield(options_gsa,'first_obs'),
+    if isfield(options_gsa,'first_obs')
         options_.first_obs=options_gsa.first_obs;
     end
-    if isfield(options_gsa,'nobs'),
+    if isfield(options_gsa,'nobs')
         options_.nobs=options_gsa.nobs;
     end
-    if isfield(options_gsa,'presample'),
+    if isfield(options_gsa,'presample')
         options_.presample=options_gsa.presample;
     end
-    if isfield(options_gsa,'prefilter'),
+    if isfield(options_gsa,'prefilter')
         options_.prefilter=options_gsa.prefilter;
     end
-    if isfield(options_gsa,'loglinear'),
+    if isfield(options_gsa,'loglinear')
         options_.loglinear=options_gsa.loglinear;
     end
-    if isfield(options_gsa,'lik_init'),
+    if isfield(options_gsa,'lik_init')
         options_.lik_init=options_gsa.lik_init;
     end
-    if isfield(options_gsa,'kalman_algo'),
+    if isfield(options_gsa,'kalman_algo')
         options_.kalman_algo=options_gsa.kalman_algo;
     end
     options_.mode_compute = 0;
@@ -92,28 +123,28 @@ if ~isempty(options_gsa.datafile) || isempty(bayestopt_) || options_gsa.rmse,
 else
     if isempty(options_.qz_criterium)
         options_.qz_criterium = 1+1e-6;
-    end    
+    end
 end
 [make,my,day,punk,M_,options_,oo_] = dynare_resolve(M_,options_,oo_);
 
 options_gsa = set_default_option(options_gsa,'identification',0);
-if options_gsa.identification,
+if options_gsa.identification
     options_gsa.redform=0;
     options_gsa = set_default_option(options_gsa,'morris',1);
     options_gsa = set_default_option(options_gsa,'trans_ident',0);
     options_gsa = set_default_option(options_gsa,'load_ident_files',0);
     options_gsa = set_default_option(options_gsa,'ar',1);
     options_.ar = options_gsa.ar;
-    if options_gsa.morris==0,
+    if options_gsa.morris==0
         disp('The option morris = 0 is no longer supported (Type I errors)')
         disp('This option is reset at morris = 2 (local identification analysis).')
         options_gsa.morris=2;
     end
-    if options_gsa.morris==2,
-        if isfield(options_,'options_ident'),
+    if options_gsa.morris==2
+        if isfield(options_,'options_ident')
             options_.options_ident.load_ident_files = options_gsa.load_ident_files;
             options_.options_ident.useautocorr = options_gsa.useautocorr;
-            options_.options_ident.ar = options_gsa.ar;            
+            options_.options_ident.ar = options_gsa.ar;
             options_ident=options_.options_ident;
         else
             options_ident=[];
@@ -127,7 +158,6 @@ end
 
 % map stability
 options_gsa = set_default_option(options_gsa,'stab',1);
-options_gsa = set_default_option(options_gsa,'redform',0);
 options_gsa = set_default_option(options_gsa,'pprior',1);
 options_gsa = set_default_option(options_gsa,'prior_range',1);
 options_gsa = set_default_option(options_gsa,'ppost',0);
@@ -138,15 +168,14 @@ options_gsa = set_default_option(options_gsa,'glue',0);
 options_gsa = set_default_option(options_gsa,'morris_nliv',6);
 options_gsa = set_default_option(options_gsa,'morris_ntra',20);
 options_gsa = set_default_option(options_gsa,'Nsam',2048);
-options_gsa = set_default_option(options_gsa,'load_redform',0);
-options_gsa = set_default_option(options_gsa,'load_rmse',0);
 options_gsa = set_default_option(options_gsa,'load_stab',0);
 options_gsa = set_default_option(options_gsa,'alpha2_stab',0);
-options_gsa = set_default_option(options_gsa,'ksstat',0.1);
 options_gsa = set_default_option(options_gsa,'pvalue_ks',0.001);
 options_gsa = set_default_option(options_gsa,'pvalue_corr',1.e-5);
 %options_gsa = set_default_option(options_gsa,'load_mh',0);
 % REDFORM mapping
+options_gsa = set_default_option(options_gsa,'redform',0);
+options_gsa = set_default_option(options_gsa,'load_redform',0);
 options_gsa = set_default_option(options_gsa,'logtrans_redform',0);
 options_gsa = set_default_option(options_gsa,'threshold_redform',[]);
 options_gsa = set_default_option(options_gsa,'ksstat_redform',0.001);
@@ -155,6 +184,7 @@ options_gsa = set_default_option(options_gsa,'namendo',[]);
 options_gsa = set_default_option(options_gsa,'namlagendo',[]);
 options_gsa = set_default_option(options_gsa,'namexo',[]);
 % RMSE mapping
+options_gsa = set_default_option(options_gsa,'load_rmse',0);
 options_gsa = set_default_option(options_gsa,'lik_only',0);
 options_gsa = set_default_option(options_gsa,'var_rmse',char(options_.varobs));
 %get corresponding TeX-names;
@@ -168,27 +198,27 @@ 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,
+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),
+if options_gsa.redform && options_gsa.neighborhood_width==0 && isempty(options_gsa.threshold_redform)
     options_gsa.pprior=1;
     options_gsa.ppost=0;
 end
 
-if options_gsa.morris>2,
+if options_gsa.morris>2
     disp('The option morris = 3 is no longer supported')
     disp('the option is reset at morris = 1 .')
     options_gsa.morris=1;
 end
-   
-if options_gsa.morris==1,
-    if ~options_gsa.identification,
+
+if options_gsa.morris==1
+    if ~options_gsa.identification
         options_gsa.redform=1;
     end
-    if options_gsa.neighborhood_width,
+    if options_gsa.neighborhood_width
         options_gsa.pprior=0;
     else
         options_gsa.pprior=1;
@@ -199,53 +229,51 @@ if options_gsa.morris==1,
     options_gsa.rmse=0;
     options_gsa.load_rmse=0;
     options_gsa.alpha2_stab=1;
-    options_gsa.ksstat=1;
     options_gsa.pvalue_ks=0;
     options_gsa.pvalue_corr=0;
-%     if options_gsa.morris==3,
-%         options_gsa = set_default_option(options_gsa,'Nsam',256);
-%         OutputDirectoryName = CheckPath('gsa/identif',M_.dname);
-%     else
-        OutputDirectoryName = CheckPath('gsa/screen',M_.dname);
-%     end
+    %     if options_gsa.morris==3,
+    %         options_gsa = set_default_option(options_gsa,'Nsam',256);
+    %         OutputDirectoryName = CheckPath('gsa/identif',M_.dname);
+    %     else
+    OutputDirectoryName = CheckPath('gsa/screen',M_.dname);
+    %     end
 else
     OutputDirectoryName = CheckPath('gsa',M_.dname);
 end
 
 % options_.opt_gsa = options_gsa;
 
-if (options_gsa.load_stab || options_gsa.load_rmse || options_gsa.load_redform) ...
-        && options_gsa.pprior,
+if (options_gsa.load_stab || options_gsa.load_rmse || options_gsa.load_redform) && options_gsa.pprior
     filetoload=[OutputDirectoryName '/' fname_ '_prior.mat'];
-    if ~exist(filetoload),
+    if ~exist(filetoload)
         disp([filetoload,' not found!'])
         disp(['You asked to load a non existent analysis'])
         %options_gsa.load_stab=0;
-        return,
+        return
     else
-        if isempty(strmatch('bkpprior',who('-file', filetoload),'exact')),
-            disp('Warning! Missing prior info for saved sample') % trap for files previous 
-            disp('The saved files are generated with previous version of GSA package') % trap for files previous 
+        if isempty(strmatch('bkpprior',who('-file', filetoload),'exact'))
+            disp('Warning! Missing prior info for saved sample') % trap for files previous
+            disp('The saved files are generated with previous version of GSA package') % trap for files previous
         else
-            load(filetoload,'bkpprior'),
+            load(filetoload,'bkpprior')
             if any(bayestopt_.pshape~=bkpprior.pshape) || ...
                     any(bayestopt_.p1~=bkpprior.p1) || ...
                     any(bayestopt_.p2~=bkpprior.p2) || ...
                     any(bayestopt_.p3(~isnan(bayestopt_.p3))~=bkpprior.p3(~isnan(bkpprior.p3))) || ...
-                    any(bayestopt_.p4(~isnan(bayestopt_.p4))~=bkpprior.p4(~isnan(bkpprior.p4))),
+                    any(bayestopt_.p4(~isnan(bayestopt_.p4))~=bkpprior.p4(~isnan(bkpprior.p4)))
                 disp('WARNING!')
                 disp('The saved sample has different priors w.r.t. to current ones!!')
                 skipline()
                 disp('Press ENTER to continue')
-                pause;
+                pause
             end
         end
     end
 end
 
-if options_gsa.stab && ~options_gsa.ppost,
+if options_gsa.stab && ~options_gsa.ppost
     x0 = stab_map_(OutputDirectoryName,options_gsa);
-    if isempty(x0),
+    if isempty(x0)
         skipline()
         disp('Sensitivity computations stopped: no parameter set provided a unique solution')
         return
@@ -256,20 +284,19 @@ end
 % redform_map(namendo, namlagendo, namexo, icomp, pprior, ilog, threshold)
 
 options_.opt_gsa = options_gsa;
-if ~isempty(options_gsa.moment_calibration) || ~isempty(options_gsa.irf_calibration),
+if ~isempty(options_gsa.moment_calibration) || ~isempty(options_gsa.irf_calibration)
     map_calibration(OutputDirectoryName, M_, options_, oo_, estim_params_,bayestopt_);
 end
 
-if options_gsa.identification,
+if options_gsa.identification
     map_ident_(OutputDirectoryName,options_gsa);
 end
 
-if options_gsa.redform && ~isempty(options_gsa.namendo),% ...
-    %         && ~options_gsa.ppost,
-    if options_gsa.ppost,
+if options_gsa.redform && ~isempty(options_gsa.namendo)
+    if options_gsa.ppost
         filnam = dir([M_.dname filesep 'metropolis' filesep '*param_irf*.mat']);
         lpmat=[];
-        for j=1:length(filnam),
+        for j=1:length(filnam)
             load ([M_.dname filesep 'metropolis' filesep M_.fname '_param_irf' int2str(j) '.mat'])
             lpmat=[lpmat; stock];
         end
@@ -278,7 +305,7 @@ if options_gsa.redform && ~isempty(options_gsa.namendo),% ...
         nshock = nshock + estim_params_.nvn;
         nshock = nshock + estim_params_.ncx;
         nshock = nshock + estim_params_.ncn;
-        
+
         lpmat0=lpmat(:,1:nshock);
         lpmat=lpmat(:,nshock+1:end);
         istable=(1:size(lpmat,1));
@@ -287,25 +314,24 @@ if options_gsa.redform && ~isempty(options_gsa.namendo),% ...
         iindeterm=[];
         save([OutputDirectoryName filesep M_.fname '_mc.mat'],'lpmat','lpmat0','istable','iunstable','iwrong','iindeterm')
         options_gsa.load_stab=1;
-        
+
         x0 = stab_map_(OutputDirectoryName,options_gsa);
     end
-    if strmatch(':',options_gsa.namendo,'exact'),
+    if strmatch(':',options_gsa.namendo,'exact')
         options_gsa.namendo=M_.endo_names(1:M_.orig_endo_nbr,:);
     end
-    if strmatch(':',options_gsa.namexo,'exact'),
+    if strmatch(':',options_gsa.namexo,'exact')
         options_gsa.namexo=M_.exo_names;
     end
-    if strmatch(':',options_gsa.namlagendo,'exact'),
+    if strmatch(':',options_gsa.namlagendo,'exact')
         options_gsa.namlagendo=M_.endo_names(1:M_.orig_endo_nbr,:);
     end
-%     options_.opt_gsa = options_gsa;
-    if options_gsa.morris==1,
+    %     options_.opt_gsa = options_gsa;
+    if options_gsa.morris==1
         redform_screen(OutputDirectoryName,options_gsa);
     else
         % check existence of the SS_ANOVA toolbox
-        if isempty(options_gsa.threshold_redform) && ...
-         ~(exist('gsa_sdp','file')==6 || exist('gsa_sdp','file')==2),
+        if isempty(options_gsa.threshold_redform) && ~(exist('gsa_sdp','file')==6 || exist('gsa_sdp','file')==2)
             fprintf('\nThe "SS-ANOVA-R: MATLAB Toolbox for the estimation of Smoothing Spline ANOVA models with Recursive algorithms" is missing.\n')
             fprintf('To obtain it, go to:\n\n')
             fprintf('http://ipsc.jrc.ec.europa.eu/?id=790 \n\n')
@@ -320,79 +346,79 @@ end
 % RMSE mapping
 % function [rmse_MC, ixx] = filt_mc_(vvarvecm, loadSA, pfilt, alpha, alpha2)
 options_.opt_gsa = options_gsa;
-if options_gsa.rmse,
+if options_gsa.rmse
     if ~options_gsa.ppost
         if options_gsa.pprior
             a=whos('-file',[OutputDirectoryName,'/',fname_,'_prior'],'logpo2');
         else
             a=whos('-file',[OutputDirectoryName,'/',fname_,'_mc'],'logpo2');
         end
-        if isoctave
+        if isoctave()
             aflag=0;
-            for ja=1:length(a),
+            for ja=1:length(a)
                 aflag=aflag+strcmp('logpo2',a(ja).name);
             end
-            if aflag==0,
+            if aflag==0
                 a=[];
             else
                 a=1;
             end
         end
-        if isempty(a),
-           if options_gsa.lik_only,
-               options_.smoother=0;
-               options_.filter_step_ahead=[];
-               options_.forecast=0;
-               options_.filtered_vars=0;               
-           end
-%             dynare_MC([],OutputDirectoryName,data,rawdata,data_info);
-        if options_gsa.pprior
-            TmpDirectoryName = ([M_.dname filesep 'gsa' filesep 'prior']);
-        else
-            TmpDirectoryName = ([M_.dname filesep 'gsa' filesep 'mc']);
-        end
-        if exist(TmpDirectoryName,'dir');
-            mydelete([M_.fname '_filter_step_ahead*.mat'],[TmpDirectoryName filesep]);
-            mydelete([M_.fname '_inno*.mat'],[TmpDirectoryName filesep]);
-            mydelete([M_.fname '_smooth*.mat'],[TmpDirectoryName filesep]);
-            mydelete([M_.fname '_update*.mat'],[TmpDirectoryName filesep]);
-            filparam = dir([TmpDirectoryName filesep M_.fname '_param*.mat']);
-            for j=1:length(filparam),
-                if isempty(strmatch([M_.fname '_param_irf'],filparam(j).name))
-                    delete([TmpDirectoryName filesep filparam(j).name]);
+        if isempty(a)
+            if options_gsa.lik_only
+                options_.smoother=0;
+                options_.filter_step_ahead=[];
+                options_.forecast=0;
+                options_.filtered_vars=0;
+            end
+            %             dynare_MC([],OutputDirectoryName,data,rawdata,data_info);
+            if options_gsa.pprior
+                TmpDirectoryName = ([M_.dname filesep 'gsa' filesep 'prior']);
+            else
+                TmpDirectoryName = ([M_.dname filesep 'gsa' filesep 'mc']);
+            end
+            if exist(TmpDirectoryName,'dir')
+                mydelete([M_.fname '_filter_step_ahead*.mat'],[TmpDirectoryName filesep]);
+                mydelete([M_.fname '_inno*.mat'],[TmpDirectoryName filesep]);
+                mydelete([M_.fname '_smooth*.mat'],[TmpDirectoryName filesep]);
+                mydelete([M_.fname '_update*.mat'],[TmpDirectoryName filesep]);
+                filparam = dir([TmpDirectoryName filesep M_.fname '_param*.mat']);
+                for j=1:length(filparam)
+                    if isempty(strmatch([M_.fname '_param_irf'],filparam(j).name))
+                        delete([TmpDirectoryName filesep filparam(j).name]);
+                    end
                 end
+
             end
-            
-        end
-        prior_posterior_statistics('gsa',dataset_, dataset_info);
-        if options_.bayesian_irf
-            PosteriorIRF('gsa');
-        end
-        options_gsa.load_rmse=0;
-        %   else
-        %     if options_gsa.load_rmse==0,
-        %       disp('You already saved a MC filter/smoother analysis ')
-        %       disp('Do you want to overwrite ?')
-        %       pause;
-        %       if options_gsa.pprior
-        %         delete([OutputDirectoryName,'/',fname_,'_prior_*.mat'])
-        %       else
-        %         delete([OutputDirectoryName,'/',fname_,'_mc_*.mat'])
-        %       end
-        %       dynare_MC([],OutputDirectoryName);
-        %       options_gsa.load_rmse=0;
-        %     end
-            
+            prior_posterior_statistics('gsa',dataset_, dataset_info);
+            if options_.bayesian_irf
+                PosteriorIRF('gsa');
+            end
+            options_gsa.load_rmse=0;
+            %   else
+            %     if options_gsa.load_rmse==0,
+            %       disp('You already saved a MC filter/smoother analysis ')
+            %       disp('Do you want to overwrite ?')
+            %       pause;
+            %       if options_gsa.pprior
+            %         delete([OutputDirectoryName,'/',fname_,'_prior_*.mat'])
+            %       else
+            %         delete([OutputDirectoryName,'/',fname_,'_mc_*.mat'])
+            %       end
+            %       dynare_MC([],OutputDirectoryName);
+            %       options_gsa.load_rmse=0;
+            %     end
+
         end
     end
     clear a;
-%     filt_mc_(OutputDirectoryName,data_info);
+    %     filt_mc_(OutputDirectoryName,data_info);
     filt_mc_(OutputDirectoryName,options_gsa,dataset_,dataset_info);
 end
 options_.opt_gsa = options_gsa;
 
 
-if options_gsa.glue,
+if options_gsa.glue
     dr_ = oo_.dr;
     if options_gsa.ppost
         load([OutputDirectoryName,'/',fname_,'_post']);
@@ -404,7 +430,7 @@ if options_gsa.glue,
             load([OutputDirectoryName,'/',fname_,'_mc']);
         end
     end
-    if ~exist('x'),
+    if ~exist('x')
         disp(['No RMSE analysis is available for current options'])
         disp(['No GLUE file prepared'])
         return,
@@ -422,14 +448,14 @@ if options_gsa.glue,
     else
         data = transpose(rawdata);
     end
-    
+
     Obs.data = data;
     Obs.time = [1:gend];
     Obs.num  = gend;
     for j=1:length(options_.varobs)
         Obs.name{j} = options_.varobs{j};
         vj = options_.varobs{j};
-        
+
         jxj = strmatch(vj,lgy_(dr_.order_var,:),'exact');
         js = strmatch(vj,lgy_,'exact');
         if ~options_gsa.ppost
@@ -451,7 +477,7 @@ if options_gsa.glue,
         Lik(j).ini  = 'yes';
         Lik(j).isam = 1;
         Lik(j).data = rmse_MC(:,j)';
-        
+
         if ~options_gsa.ppost
             %       y0 = squeeze(stock_smooth(:,jxj,:)) + ...
             %         kron(stock_ys(js,:),ones(size(stock_smooth,1),1));
@@ -464,14 +490,14 @@ if options_gsa.glue,
             Out1=Out;
         end
         ismoo(j)=jxj;
-        
+
     end
     jsmoo = length(options_.varobs);
-    for j=1:M_.endo_nbr,
-        if ~ismember(j,ismoo),
+    for j=1:M_.endo_nbr
+        if ~ismember(j,ismoo)
             jsmoo=jsmoo+1;
             vj=deblank(M_.endo_names(dr_.order_var(j),:));
-            if ~options_gsa.ppost        
+            if ~options_gsa.ppost
                 %         y0 = squeeze(stock_smooth(:,j,:)) + ...
                 %           kron(stock_ys(j,:),ones(size(stock_smooth,1),1));
                 %         Out1(jsmoo).time = [1:size(y0,1)];
@@ -487,8 +513,8 @@ if options_gsa.glue,
         end
     end
     tit(M_.exo_names_orig_ord,:) = M_.exo_names;
-    for j=1:M_.exo_nbr,
-        Exo(j).name = deblank(tit(j,:));    
+    for j=1:M_.exo_nbr
+        Exo(j).name = deblank(tit(j,:));
     end
     if ~options_gsa.ppost
         Lik(length(options_.varobs)+1).name = 'logpo';
@@ -499,10 +525,10 @@ if options_gsa.glue,
     Sam.name = bayestopt_.name;
     Sam.dim  = [size(x) 0];
     Sam.data = [x];
-    
+
     Rem.id = 'Original';
     Rem.ind= [1:size(x,1)];
-    
+
     Info.dynare=M_.fname;
     Info.order_var=dr_.order_var;
     Out=Out1;
@@ -513,7 +539,7 @@ if options_gsa.glue,
         Info.TypeofSample='post';
         save([OutputDirectoryName,'/',fname_,'_glue_post.mat'], 'Out', 'Sam', 'Lik', 'Obs', 'Rem','Info', 'Exo')
         %save([fname_,'_post_glue_smooth'], 'Out', 'Sam', 'Lik', 'Obs', 'Rem','Info')
-        
+
     else
         if options_gsa.pprior
             Info.TypeofSample='prior';
@@ -529,5 +555,5 @@ if options_gsa.glue,
             %       save([OutputDirectoryName,'/',fname_,'_mc_glue_smooth'], 'Out', 'Sam', 'Lik', 'Obs', 'Rem')
         end
     end
-    
+
 end
diff --git a/matlab/dynare_solve.m b/matlab/dynare_solve.m
index 149d2f9edaf8e8b097c43f58544e4492b4a7e3ea..366bfa3a45235c97dba303d861f43f92c6c673b4 100644
--- a/matlab/dynare_solve.m
+++ b/matlab/dynare_solve.m
@@ -17,7 +17,7 @@ function [x,info,fvec,fjac] = dynare_solve(func,x,options,varargin)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2001-2016 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -58,29 +58,91 @@ else
     maxit = options.steady.maxit;
 end
 
-
 info = 0;
 nn = size(x,1);
 
+% Get status of the initial guess (default values?)
+if any(x)
+    % The current initial guess is not the default for all the variables.
+    idx = find(x);      % Indices of the variables with default initial guess values. 
+    in0 = length(idx);
+else
+    % The current initial guess is the default for all the variables.
+    idx = transpose(1:nn);
+    in0 = nn;
+end
+
 % checking initial values
 if jacobian_flag
-    [fvec,fjac] = feval(func,x,varargin{:});
-    if any(any(isinf(fjac) | isnan(fjac)))
-        info=1;
-        x = NaN(size(fvec));
-        return
+    [fvec, fjac] = feval(func, x, varargin{:});
+    wrong_initial_guess_flag = false;
+    if ~all(isfinite(fvec)) || any(isinf(fjac(:))) || any(isnan((fjac(:))))
+        % Let's try random numbers for the variables initialized with the default value.
+        wrong_initial_guess_flag = true;
+        % First try with positive numbers.
+        tentative_number = 0;
+        while wrong_initial_guess_flag && tentative_number<=in0*10
+            tentative_number = tentative_number+1;
+            x(idx) = rand(in0, 1)*10;
+            [fvec, fjac] = feval(func, x, varargin{:});
+            wrong_initial_guess_flag = ~all(isfinite(fvec)) || any(isinf(fjac(:))) || any(isnan((fjac(:))));
+        end
+        % If all previous attempts failed, try with real numbers.
+        tentative_number = 0;
+        while wrong_initial_guess_flag && tentative_number<=in0*10
+            tentative_number = tentative_number+1;
+            x(idx) = randn(in0, 1)*10;
+            [fvec, fjac] = feval(func, x, varargin{:});
+            wrong_initial_guess_flag = ~all(isfinite(fvec)) || any(isinf(fjac(:))) || any(isnan((fjac(:))));
+        end
+        % Last tentative, ff all previous attempts failed, try with negative numbers.
+        tentative_number = 0;
+        while wrong_initial_guess_flag && tentative_number<=in0*10
+            tentative_number = tentative_number+1;
+            x(idx) = -rand(in0, 1)*10;
+            [fvec, fjac] = feval(func, x, varargin{:});
+            wrong_initial_guess_flag = ~all(isfinite(fvec)) || any(isinf(fjac(:))) || any(isnan((fjac(:))));
+        end
     end
 else
     fvec = feval(func,x,varargin{:});
-    fjac = zeros(nn,nn) ;
+    fjac = zeros(nn,nn);
+    wrong_initial_guess_flag = false;
+    if ~all(isfinite(fvec))
+        % Let's try random numbers for the variables initialized with the default value.
+        wrong_initial_guess_flag = true;
+        % First try with positive numbers.
+        tentative_number = 0;
+        while wrong_initial_guess_flag && tentative_number<=in0*10
+            tentative_number = tentative_number+1;
+            x(idx) = rand(in0, 1)*10;
+            fvec = feval(func, x, varargin{:});
+            wrong_initial_guess_flag = ~all(isfinite(fvec));
+        end
+        % If all previous attempts failed, try with real numbers.
+        tentative_number = 0;
+        while wrong_initial_guess_flag && tentative_number<=in0*10
+            tentative_number = tentative_number+1;
+            x(idx) = randn(in0, 1)*10;
+            fvec = feval(func, x, varargin{:});
+            wrong_initial_guess_flag = ~all(isfinite(fvec));
+        end
+        % Last tentative, ff all previous attempts failed, try with negative numbers.
+        tentative_number = 0;
+        while wrong_initial_guess_flag && tentative_number<=in0*10
+            tentative_number = tentative_number+1;
+            x(idx) = -rand(in0, 1)*10;
+            fvec = feval(func, x, varargin{:});
+            wrong_initial_guess_flag = ~all(isfinite(fvec));
+        end
+    end
 end
 
-i = find(~isfinite(fvec));
-
-if ~isempty(i)
-    info = 1;
+% Exit with error if no initial guess has been found.
+if wrong_initial_guess_flag
+    info=1;
     x = NaN(size(fvec));
-    return;
+    return
 end
 
 % this test doesn't check complementarity conditions and is not used for
@@ -125,7 +187,7 @@ if options.solve_algo == 0
             [x,fval,exitval,output] = fsolve(func,x,options4fsolve);
         else
             exitval = 3;
-        end;
+        end
     end
 
     if exitval == 1
@@ -141,19 +203,19 @@ if options.solve_algo == 0
         if max(abs(fvec)) >= tolf
             info = 1;
         else
-            info = 0;        
+            info = 0;
         end
     else
         info = 1;
     end
 elseif options.solve_algo == 1
-        [x,info]=solve1(func,x,1:nn,1:nn,jacobian_flag,options.gstep, ...
+    [x,info]=solve1(func,x,1:nn,1:nn,jacobian_flag,options.gstep, ...
                     tolf,options.solve_tolx, ...
                     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, ...
-                    maxit,options.debug,varargin{:});
+    [x,info]=trust_region(func,x,1:nn,1:nn,jacobian_flag,options.gstep, ...
+                          tolf,options.solve_tolx, ...
+                          maxit,options.debug,varargin{:});
 elseif options.solve_algo == 2 || options.solve_algo == 4
 
     if options.solve_algo == 2
@@ -233,4 +295,3 @@ elseif options.solve_algo == 11
 else
     error('DYNARE_SOLVE: option solve_algo must be one of [0,1,2,3,4,9,10,11]')
 end
-
diff --git a/matlab/dynare_solve_block_or_bytecode.m b/matlab/dynare_solve_block_or_bytecode.m
index 1032d0921ecdc0246beb172fc23dbecdeadac6f9..2a1f547b9bdca73af050837253a5a054d4d370c4 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-2015 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -22,7 +22,7 @@ if options.block && ~options.bytecode
     for b = 1:length(M.block_structure_stat.block)
         ss = x;
         if M.block_structure_stat.block(b).Simulation_Type ~= 1 && ...
-           M.block_structure_stat.block(b).Simulation_Type ~= 2
+                M.block_structure_stat.block(b).Simulation_Type ~= 2
             if options.solve_algo <= 4
                 [y, check] = dynare_solve('block_mfs_steadystate', ...
                                           ss(M.block_structure_stat.block(b).variable), ...
@@ -60,7 +60,7 @@ elseif options.bytecode
     elseif options.block
         for b = 1:length(M.block_structure_stat.block)
             if M.block_structure_stat.block(b).Simulation_Type ~= 1 && ...
-               M.block_structure_stat.block(b).Simulation_Type ~= 2
+                    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), ...
@@ -80,7 +80,7 @@ elseif options.bytecode
                     info = 1;
                     return
                 end
-            end;
+            end
         end
     else
         [x, check] = dynare_solve('bytecode_steadystate', y, ...
diff --git a/matlab/dynare_squeeze.m b/matlab/dynare_squeeze.m
index b01be342ff1c35a7c9b7196fdff8029a9d8483b2..85e66f332e971b3e8bf22b5c0d21ae7528d1eae8 100644
--- a/matlab/dynare_squeeze.m
+++ b/matlab/dynare_squeeze.m
@@ -1,7 +1,7 @@
-function B = dynare_squeeze(A);
+function B = dynare_squeeze(A)
 % Same as matlab's squeeze function except that it also affects 2D arrays.
 
-% Copyright (C) 2009 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -18,7 +18,7 @@ function B = dynare_squeeze(A);
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-sizA = size(A); 
+sizA = size(A);
 dimA = length(sizA);
 switch dimA
   case 1
diff --git a/matlab/dynare_version.m.in b/matlab/dynare_version.m.in
index 6a139161377daf6416583273c47a4ec5bc399e0b..f2c502ea052cc0bc173bc3ecd09d5b5946903b61 100644
--- a/matlab/dynare_version.m.in
+++ b/matlab/dynare_version.m.in
@@ -1,6 +1,6 @@
-function v = dynare_version
-% function v = dynare_version
-%	This command returns Dynare version number
+function v = dynare_version()
+
+% This command returns Dynare version number.
 %
 % INPUTS
 %   none
@@ -11,7 +11,7 @@ function v = dynare_version
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2008-2009 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -28,4 +28,4 @@ function v = dynare_version
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-    v = '@PACKAGE_VERSION@';
+v = '@PACKAGE_VERSION@';
diff --git a/matlab/dynasave.m b/matlab/dynasave.m
index f2cc991ca02d60cd5566892ad9f71fab90aba210..ef938dbc2bdac3ff59819e488a4b1585a8d79034 100644
--- a/matlab/dynasave.m
+++ b/matlab/dynasave.m
@@ -12,7 +12,7 @@ function dynasave(s,var_list)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2001-2010 Dynare Team
+% Copyright (C) 2001-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/dynatype.m b/matlab/dynatype.m
index 35276028f42e90d2d20a3d105d5251c5b6064f1f..517bcc0b137cb8405f6e9098234788485fc9146b 100644
--- a/matlab/dynatype.m
+++ b/matlab/dynatype.m
@@ -1,19 +1,19 @@
 function dynatype (s,var_list)
 % function dynatype (s,var_list)
-% This optional command saves the simulation results in a text file. The name of each 
+% This optional command saves the simulation results in a text file. The name of each
 % variable preceeds the corresponding results. This command must follow SIMUL.
-%  
+%
 % INPUTS
 %   s:         filename
 %   var_list:  vector of selected endogenous variables
-%  
+%
 % OUTPUTS
 %   none
 %
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2001-2009 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/dyntable.m b/matlab/dyntable.m
index 23d56feff1a507e8ae93286bd5504a78e50a61b1..5b632cde3a5abc57d86b058e10758ab3dfddde62 100644
--- a/matlab/dyntable.m
+++ b/matlab/dyntable.m
@@ -7,11 +7,11 @@ function dyntable(options_,title,headers,labels,values,label_width,val_width,val
 %   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_width   [scalar]            Width of value column
 %   val_precis  [integer]           precision of displayed values
-% 
-% 
-% Copyright (C) 2002-2015 Dynare Team
+%
+%
+% Copyright (C) 2002-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -33,9 +33,9 @@ if options_.noprint
 end
 
 %% get width of label column
-if ~isempty(label_width) 
+if ~isempty(label_width)
     label_width = max(size(deblank(char(headers(1,:),labels)),2)+2, ...
-                     label_width);
+                      label_width);
 else %use default length
     label_width = max(size(deblank(char(headers(1,:),labels)),2))+2;
 end
@@ -51,7 +51,7 @@ if any(values) < 0 %add one character for minus sign
     values_length = values_length+1;
 end
 
-%% get width of header strings 
+%% 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);
diff --git a/matlab/endogenous_prior.m b/matlab/endogenous_prior.m
index c2930abad8a9b82e316df4ce2c4e26483bb0c85f..26ea7ce5f5b9028f0ab68f28a0ca546e67f84278 100644
--- a/matlab/endogenous_prior.m
+++ b/matlab/endogenous_prior.m
@@ -2,17 +2,17 @@ function [lnpriormom] = endogenous_prior(data,Pstar,BayesInfo,H)
 % Computes the endogenous log prior addition to the initial prior
 %
 % INPUTS
-%    data           [double]     n*T vector of data observations 
+%    data           [double]     n*T vector of data observations
 %    Pstar          [double]     k*k matrix of
-%    BayesInfo      [structure]   
+%    BayesInfo      [structure]
 %
 % OUTPUTS
 %    lnpriormom     [double]     scalar of log endogenous prior value
 
 % Code to implement notes on endogenous priors by Lawrence Christiano,
 % specified in the appendix of:
-% �Introducing Financial Frictions and Unemployment into a Small Open Economy Model�
-% by Lawrence J. Christiano, Mathias Trabandt and Karl Walentin (2011), Journal of Economic Dynamics and Control      
+% ’Introducing Financial Frictions and Unemployment into a Small Open Economy Model’
+% by Lawrence J. Christiano, Mathias Trabandt and Karl Walentin (2011), Journal of Economic Dynamics and Control
 % this is the 'mother' of the priors on the model parameters.
 % the priors include a metric across some choosen moments of the (supposedly
 % pre-sample) data.
@@ -23,8 +23,8 @@ function [lnpriormom] = endogenous_prior(data,Pstar,BayesInfo,H)
 % appropriate adjustment to the following code.
 
 
-% Copyright (C) 2011 Lawrence J. Christiano, Mathias Trabandt and Karl Walentin 
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2011 Lawrence J. Christiano, Mathias Trabandt and Karl Walentin
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -75,7 +75,7 @@ end
 
 % Finally, we have the sampling uncertainty measure Shat:
 Shat=C0 +(1-1/(2+1))*(C1+C1')...
-    +(1-2/(2+1))*(C2+C2');
+     +(1-2/(2+1))*(C2+C2');
 
 % Model variances below:
 mf=BayesInfo.mf1;
@@ -86,4 +86,3 @@ Ftheta=diag(Z*Pstar(:,mf)+H);
 % below commented out line is for Del Negro Schorfheide style priors:
 %     lnpriormom=-.5*n*TT*log(2*pi)-.5*TT*log(det(sigma))-.5*TT*trace(inv(sigma)*(gamyy-2*phi'*gamxy+phi'*gamxx*phi));
 lnpriormom=.5*n*log(Tsamp/(2*pi))-.5*log(det(Shat))-.5*Tsamp*(Fhat-Ftheta)'/Shat*(Fhat-Ftheta);
-
diff --git a/matlab/endogenous_prior_restrictions.m b/matlab/endogenous_prior_restrictions.m
index 617116a890dbca4e70feb197227384e9d02f5861..ef734acd125ce59ce0c1c565f6a7ef72a72497eb 100644
--- a/matlab/endogenous_prior_restrictions.m
+++ b/matlab/endogenous_prior_restrictions.m
@@ -1,178 +1,173 @@
-function [info, info_irf, info_moment, data_irf, data_moment] = endogenous_prior_restrictions(T,R,Model,DynareOptions,DynareResults);
-% Check for prior (sign) restrictions on irf's and theoretical moments
-%
-% INPUTS
-%    T          [double]     n*n state space matrix
-%    R          [double]     n*k matrix of shocks
-%    Model      [structure]
-%    DynareOptions [structure]
-%    DynareResults [structure]
-
-% OUTPUTS
-%    info     [double]  check if prior restrictions are matched by the
-%                       model and related info
-%    info_irf [double] array of test checks for all individual irf restrictions
-%    info_moment [double] array of test checks for all individual moment restrictions
-%    
-
-% 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/>.
-
-info=[0 0];
-info_irf=[];
-info_moment=[];
-data_irf=[];
-data_moment=[];
-
-endo_prior_restrictions.irf= DynareOptions.endogenous_prior_restrictions.irf;
-endo_prior_restrictions.moment= DynareOptions.endogenous_prior_restrictions.moment;
-
-if ~isempty(endo_prior_restrictions.irf),
-   data_irf=cell(size(endo_prior_restrictions.irf,1),1);    
-    if DynareOptions.order>1,
-        error('The algorithm for prior (sign) restrictions on irf''s is currently restricted to first-order decision rules')
-        return
-    end
-    varlist=Model.endo_names(DynareResults.dr.order_var,:);
-    if isempty(T),
-        [T,R,SteadyState,infox,Model,DynareOptions,DynareResults] = dynare_resolve(Model,DynareOptions,DynareResults);
-    else % check if T and R are given in the restricted form!!!
-        if size(T,1)<size(varlist,1),
-            varlist=varlist(DynareResults.dr.restrict_var_list,:); 
-        end
-        % check if endo_prior_restrictions.irf{:,1} variables are in varlist
-        varlistok=1;
-        for j=1:size(endo_prior_restrictions.irf,1)
-            if isempty(strmatch(endo_prior_restrictions.irf{j,1},varlist,'exact'))
-                varlistok=0;
-            end
-        end
-        if ~varlistok
-            varlist=Model.endo_names(DynareResults.dr.order_var,:);
-            [T,R,SteadyState,infox,Model,DynareOptions,DynareResults] = dynare_resolve(Model,DynareOptions,DynareResults);
-        end
-    end
-    NT=1;
-    for j=1:size(endo_prior_restrictions.irf,1),
-        NT=max(NT,max(endo_prior_restrictions.irf{j,3}));
-    end
-    info_irf=ones(size(endo_prior_restrictions.irf,1),2);
-    for t=1:NT,
-        if ~DynareOptions.relative_irf,
-            RR = T^(t-1)*R*diag(sqrt(diag(Model.Sigma_e)));
-        else
-            RR = T^(t-1)*R*100;
-        end
-        for j=1:size(endo_prior_restrictions.irf,1),
-            if endo_prior_restrictions.irf{j,3}~=t,
-                continue,
-            end
-            iendo=strmatch(endo_prior_restrictions.irf{j,1},varlist,'exact');
-            iexo=strmatch(endo_prior_restrictions.irf{j,2},Model.exo_names,'exact');
-            data_irf{j}=[data_irf{j}; [t RR(iendo,iexo)]];
-            if (RR(iendo,iexo)>endo_prior_restrictions.irf{j,4}(1)) && (RR(iendo,iexo)<endo_prior_restrictions.irf{j,4}(2)),
-                info_irf(j,:)=info_irf(j,:).*[0, 0];
-            else
-                if RR(iendo,iexo)<endo_prior_restrictions.irf{j,4}(1),
-                    delt = (RR(iendo,iexo)-endo_prior_restrictions.irf{j,4}(1))^2;
-                else
-                    delt = (RR(iendo,iexo)-endo_prior_restrictions.irf{j,4}(2))^2;
-                end
-                info_irf(j,:)=info_irf(j,:).*[49, delt];
-            end
-        end
-    end
-    if any(info_irf),
-        info=[49,sum(info_irf(:,2))];
-    end
-    
-end
-
-if ~isempty(endo_prior_restrictions.moment),
-    
-    if DynareOptions.order>1,
-        error('The algorithm for prior (sign) restrictions on moments is currently restricted to first-order decision rules')
-        return
-    end
-    
-    data_moment=cell(size(endo_prior_restrictions.moment,1),1);
-    var_list_=endo_prior_restrictions.moment{1,1};
-    for  j=1:size(endo_prior_restrictions.moment,1),
-        tmp=endo_prior_restrictions.moment{j,1};
-        if ~ismember(tmp,cellstr(var_list_)),
-            var_list_ = char(var_list_, tmp);
-        end
-        tmp=endo_prior_restrictions.moment{j,2};
-        if ~ismember(tmp,cellstr(var_list_)),
-            var_list_ = char(var_list_, tmp);
-        end
-    end
-    NTmax=0;
-    NTmin=0;
-    for j=1:size(endo_prior_restrictions.moment,1),
-        NTmax=max(NTmax,max(endo_prior_restrictions.moment{j,3}));
-        NTmin=min(NTmin,min(endo_prior_restrictions.moment{j,3}));
-    end
-    info_moment=ones(size(endo_prior_restrictions.moment,1),2);
-    nvar = size(var_list_,1);
-    ivar=zeros(nvar,1);
-    for i=1:nvar
-        i_tmp = strmatch(var_list_(i,:),Model.endo_names,'exact');
-        if isempty(i_tmp)
-            error (['One of the variable specified does not exist']) ;
-        else
-            ivar(i) = i_tmp;
-        end
-    end
-    DynareOptions.ar = max(abs(NTmin),NTmax);
-    [gamma_y,stationary_vars] = th_autocovariances(DynareResults.dr, ivar, Model, DynareOptions,1);
-    for t=NTmin:NTmax,
-        RR = gamma_y{abs(t)+1};     
-        if t==0,
-            RR = RR./(sqrt(diag(RR))*sqrt(diag(RR))')-eye(nvar)+diag(diag(gamma_y{t+1})); % becomes correlation            
-        end
-        for j=1:size(endo_prior_restrictions.moment,1),
-            if endo_prior_restrictions.moment{j,3}~=t,
-                continue,
-            end
-            iendo1 = strmatch(endo_prior_restrictions.moment{j,1},var_list_,'exact');
-            iendo2 = strmatch(endo_prior_restrictions.moment{j,2},var_list_,'exact');
-            if t>0
-                tmp0 = iendo1;
-                iendo1=iendo2;
-                iendo2=tmp0;
-            end
-            data_moment{j}=[data_moment{j}; [t RR(iendo1,iendo2)]];
-            if (RR(iendo1,iendo2)>endo_prior_restrictions.moment{j,4}(1)) && (RR(iendo1,iendo2)<endo_prior_restrictions.moment{j,4}(2)),
-                info_moment(j,:)=info_moment(j,:).*[0, 0];
-            else
-                if RR(iendo1,iendo2)<endo_prior_restrictions.moment{j,4}(1),
-                    delt = (RR(iendo1,iendo2)-endo_prior_restrictions.moment{j,4}(1))^2;
-                else
-                    delt = (RR(iendo1,iendo2)-endo_prior_restrictions.moment{j,4}(2))^2;
-                end
-                info_moment(j,:)=info_moment(j,:).*[49, delt];
-            end
-        end
-    end
-    if any(info_moment),
-        info=[49, info(2) + sum(info_moment(:,2))];
-    end
-end
-return
-
-
+function [info, info_irf, info_moment, data_irf, data_moment] = endogenous_prior_restrictions(T,R,Model,DynareOptions,DynareResults)
+% Check for prior (sign) restrictions on irf's and theoretical moments
+%
+% INPUTS
+%    T          [double]     n*n state space matrix
+%    R          [double]     n*k matrix of shocks
+%    Model      [structure]
+%    DynareOptions [structure]
+%    DynareResults [structure]
+
+% OUTPUTS
+%    info     [double]  check if prior restrictions are matched by the
+%                       model and related info
+%    info_irf [double] array of test checks for all individual irf restrictions
+%    info_moment [double] array of test checks for all individual moment restrictions
+%
+
+% Copyright (C) 2013-2017 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+info=[0 0];
+info_irf=[];
+info_moment=[];
+data_irf=[];
+data_moment=[];
+
+endo_prior_restrictions.irf= DynareOptions.endogenous_prior_restrictions.irf;
+endo_prior_restrictions.moment= DynareOptions.endogenous_prior_restrictions.moment;
+
+if ~isempty(endo_prior_restrictions.irf)
+    data_irf=cell(size(endo_prior_restrictions.irf,1),1);
+    if DynareOptions.order>1
+        error('The algorithm for prior (sign) restrictions on irf''s is currently restricted to first-order decision rules')
+        return
+    end
+    varlist=Model.endo_names(DynareResults.dr.order_var,:);
+    if isempty(T)
+        [T,R,SteadyState,infox,Model,DynareOptions,DynareResults] = dynare_resolve(Model,DynareOptions,DynareResults);
+    else % check if T and R are given in the restricted form!!!
+        if size(T,1)<size(varlist,1)
+            varlist=varlist(DynareResults.dr.restrict_var_list,:);
+        end
+        % check if endo_prior_restrictions.irf{:,1} variables are in varlist
+        varlistok=1;
+        for j=1:size(endo_prior_restrictions.irf,1)
+            if isempty(strmatch(endo_prior_restrictions.irf{j,1},varlist,'exact'))
+                varlistok=0;
+            end
+        end
+        if ~varlistok
+            varlist=Model.endo_names(DynareResults.dr.order_var,:);
+            [T,R,SteadyState,infox,Model,DynareOptions,DynareResults] = dynare_resolve(Model,DynareOptions,DynareResults);
+        end
+    end
+    NT=1;
+    for j=1:size(endo_prior_restrictions.irf,1)
+        NT=max(NT,max(endo_prior_restrictions.irf{j,3}));
+    end
+    info_irf=ones(size(endo_prior_restrictions.irf,1),2);
+    for t=1:NT
+        if ~DynareOptions.relative_irf
+            RR = T^(t-1)*R*diag(sqrt(diag(Model.Sigma_e)));
+        else
+            RR = T^(t-1)*R*100;
+        end
+        for j=1:size(endo_prior_restrictions.irf,1)
+            if endo_prior_restrictions.irf{j,3}~=t
+                continue
+            end
+            iendo=strmatch(endo_prior_restrictions.irf{j,1},varlist,'exact');
+            iexo=strmatch(endo_prior_restrictions.irf{j,2},Model.exo_names,'exact');
+            data_irf{j}=[data_irf{j}; [t RR(iendo,iexo)]];
+            if (RR(iendo,iexo)>endo_prior_restrictions.irf{j,4}(1)) && (RR(iendo,iexo)<endo_prior_restrictions.irf{j,4}(2))
+                info_irf(j,:)=info_irf(j,:).*[0, 0];
+            else
+                if RR(iendo,iexo)<endo_prior_restrictions.irf{j,4}(1)
+                    delt = (RR(iendo,iexo)-endo_prior_restrictions.irf{j,4}(1))^2;
+                else
+                    delt = (RR(iendo,iexo)-endo_prior_restrictions.irf{j,4}(2))^2;
+                end
+                info_irf(j,:)=info_irf(j,:).*[49, delt];
+            end
+        end
+    end
+    if any(info_irf)
+        info=[49,sum(info_irf(:,2))];
+    end
+
+end
+
+if ~isempty(endo_prior_restrictions.moment)
+    if DynareOptions.order>1
+        error('The algorithm for prior (sign) restrictions on moments is currently restricted to first-order decision rules')
+        return
+    end
+    data_moment=cell(size(endo_prior_restrictions.moment,1),1);
+    var_list_=endo_prior_restrictions.moment{1,1};
+    for  j=1:size(endo_prior_restrictions.moment,1)
+        tmp=endo_prior_restrictions.moment{j,1};
+        if ~ismember(tmp,cellstr(var_list_))
+            var_list_ = char(var_list_, tmp);
+        end
+        tmp=endo_prior_restrictions.moment{j,2};
+        if ~ismember(tmp,cellstr(var_list_))
+            var_list_ = char(var_list_, tmp);
+        end
+    end
+    NTmax=0;
+    NTmin=0;
+    for j=1:size(endo_prior_restrictions.moment,1)
+        NTmax=max(NTmax,max(endo_prior_restrictions.moment{j,3}));
+        NTmin=min(NTmin,min(endo_prior_restrictions.moment{j,3}));
+    end
+    info_moment=ones(size(endo_prior_restrictions.moment,1),2);
+    nvar = size(var_list_,1);
+    ivar=zeros(nvar,1);
+    for i=1:nvar
+        i_tmp = strmatch(var_list_(i,:),Model.endo_names,'exact');
+        if isempty(i_tmp)
+            error (['One of the variable specified does not exist'])
+        else
+            ivar(i) = i_tmp;
+        end
+    end
+    DynareOptions.ar = max(abs(NTmin),NTmax);
+    [gamma_y,stationary_vars] = th_autocovariances(DynareResults.dr, ivar, Model, DynareOptions,1);
+    for t=NTmin:NTmax
+        RR = gamma_y{abs(t)+1};
+        if t==0
+            RR = RR./(sqrt(diag(RR))*sqrt(diag(RR))')-eye(nvar)+diag(diag(gamma_y{t+1})); % becomes correlation
+        end
+        for j=1:size(endo_prior_restrictions.moment,1)
+            if endo_prior_restrictions.moment{j,3}~=t
+                continue
+            end
+            iendo1 = strmatch(endo_prior_restrictions.moment{j,1},var_list_,'exact');
+            iendo2 = strmatch(endo_prior_restrictions.moment{j,2},var_list_,'exact');
+            if t>0
+                tmp0 = iendo1;
+                iendo1=iendo2;
+                iendo2=tmp0;
+            end
+            data_moment{j}=[data_moment{j}; [t RR(iendo1,iendo2)]];
+            if (RR(iendo1,iendo2)>endo_prior_restrictions.moment{j,4}(1)) && (RR(iendo1,iendo2)<endo_prior_restrictions.moment{j,4}(2))
+                info_moment(j,:)=info_moment(j,:).*[0, 0];
+            else
+                if RR(iendo1,iendo2)<endo_prior_restrictions.moment{j,4}(1)
+                    delt = (RR(iendo1,iendo2)-endo_prior_restrictions.moment{j,4}(1))^2;
+                else
+                    delt = (RR(iendo1,iendo2)-endo_prior_restrictions.moment{j,4}(2))^2;
+                end
+                info_moment(j,:)=info_moment(j,:).*[49, delt];
+            end
+        end
+    end
+    if any(info_moment)
+        info=[49, info(2) + sum(info_moment(:,2))];
+    end
+end
\ No newline at end of file
diff --git a/matlab/ep/ep_problem_2.m b/matlab/ep/ep_problem_2.m
index d31f0e7aa1da97e66a04521493fe6548661a3bd8..9168631bfe5a06927da76bb836f360d2357e36b6 100644
--- a/matlab/ep/ep_problem_2.m
+++ b/matlab/ep/ep_problem_2.m
@@ -78,7 +78,7 @@ for i = 1:order+1
                 else
                     k1 = (nnodes-1)*(i-1)+k;
                 end
-                if hybrid_order == 2 && (k > 1 || i == order) 
+                if hybrid_order == 2 && (k > 1 || i == order)
                     z = [Y(i_cols_p,1);
                          Y(i_cols_s,1);
                          Y(i_cols_f,k1)+h_correction(i_hc)];
@@ -93,10 +93,10 @@ for i = 1:order+1
                         % in first period we don't keep track of
                         % predetermined variables
                         i_cols_A = [i_cols_As - ny; i_cols_Af];
-                        A1(i_rows,i_cols_A) = A1(i_rows,i_cols_A) + weights(k)*jacobian(eq_index,i_cols_1);  
+                        A1(i_rows,i_cols_A) = A1(i_rows,i_cols_A) + weights(k)*jacobian(eq_index,i_cols_1);
                     else
                         i_cols_A = [i_cols_Ap; i_cols_As; i_cols_Af];
-                        A1(i_rows,i_cols_A) = A1(i_rows,i_cols_A) + weights(k)*jacobian(eq_index,i_cols_j);  
+                        A1(i_rows,i_cols_A) = A1(i_rows,i_cols_A) + weights(k)*jacobian(eq_index,i_cols_j);
                     end
                 else
                     d1 = dynamic_model(z,innovation,params,steady_state,i+1);
@@ -180,7 +180,7 @@ for j=1:world_nbr
             nzA{i,j} = [offset_r+ir,offset_c+icA(ic), v]';
         else
             d1 = dynamic_model(Y(i_rows_y,j),x,params, ...
-                                          steady_state,i+1);
+                               steady_state,i+1);
         end
         res(:,i,j) = d1(eq_index);
         i_rows_y = i_rows_y + ny;
diff --git a/matlab/ep/euler_equation_error.m b/matlab/ep/euler_equation_error.m
index 16de7a4b1681310943a1a6674235933ae50e2771..7496852fbbcb6d3ccd21d4e7faa8cd319914c329 100644
--- a/matlab/ep/euler_equation_error.m
+++ b/matlab/ep/euler_equation_error.m
@@ -1,5 +1,22 @@
 function e = euler_equation_error(y0,x,innovations,M,options,oo,pfm,nodes,weights)
 
+% Copyright (C) 2016-2017 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/>.    
+
 dynamic_model = str2func([M.fname '_dynamic']);
 ep = options.ep;
 [y1, info_convergence, endogenousvariablespaths] = extended_path_core(ep.periods, ...
@@ -18,7 +35,7 @@ i_fwrd = find(M.lead_lag_incidence(3,:));
 x1 = [x(2:end,:); zeros(1,M.exo_nbr)];
 for i=1:length(nodes)
     x2 = x1;
-    x2(2,:) = x2(2,:) + nodes(i,:); 
+    x2(2,:) = x2(2,:) + nodes(i,:);
     [y2, info_convergence, endogenousvariablespaths] = ...
         extended_path_core(ep.periods, M.endo_nbr, M.exo_nbr, ...
                            innovations.positive_var_indx, x2, ep.init, ...
@@ -26,7 +43,7 @@ for i=1:length(nodes)
                            ep.stochastic.order, M, pfm, ep.stochastic.algo, ...
                            ep.solve_algo, ep.stack_solve_algo, options.lmmcp, ...
                            options, oo, []);
-    
+
     z = [y0(i_pred); y1; y2(i_fwrd)];
     res(:,i) = dynamic_model(z,x,M.params,oo.steady_state,2);
 end
diff --git a/matlab/ep/extended_path.m b/matlab/ep/extended_path.m
index 03a7e4ed70dec7b8844f4f2979db4cf7b053b804..13747890bc40f19209279ecd48eb0b5687cb546e 100644
--- a/matlab/ep/extended_path.m
+++ b/matlab/ep/extended_path.m
@@ -3,7 +3,7 @@ function [ts, DynareResults] = extended_path(initialconditions, samplesize, exog
 % Stochastic simulation of a non linear DSGE model using the Extended Path method (Fair and Taylor 1983). A time
 % series of size T  is obtained by solving T perfect foresight models.
 %
-% INPUTS 
+% INPUTS
 %  o initialconditions      [double]    m*1 array, where m is the number of endogenous variables in the model.
 %  o samplesize             [integer]   scalar, size of the sample to be simulated.
 %  o exogenousvariables     [double]    T*n array, values for the structural innovations.
@@ -11,7 +11,7 @@ function [ts, DynareResults] = extended_path(initialconditions, samplesize, exog
 %  o DynareModel            [struct]    M_
 %  o DynareResults          [struct]    oo_
 %
-% OUTPUTS 
+% OUTPUTS
 %  o ts                     [dseries]   m*samplesize array, the simulations.
 %  o results                [cell]
 %
@@ -19,7 +19,7 @@ function [ts, DynareResults] = extended_path(initialconditions, samplesize, exog
 %
 % SPECIAL REQUIREMENTS
 
-% Copyright (C) 2009-2016 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -96,7 +96,7 @@ end
 if any(isnan(endogenous_variables_paths(:)))
     sl = find(~isnan(endogenous_variables_paths));
     nn = size(endogenous_variables_paths, 1);
-    endogenous_variables_paths = reshape(endogenous_variables_paths(sl), nn, length(sl)/nn); 
+    endogenous_variables_paths = reshape(endogenous_variables_paths(sl), nn, length(sl)/nn);
 end
 ts = dseries(transpose(endogenous_variables_paths), initial_period, cellstr(DynareModel.endo_names));
 
diff --git a/matlab/ep/extended_path_core.m b/matlab/ep/extended_path_core.m
index 33c42b619c5ecc25506af06cc47e01740db7c66c..5a99b6f21d897bc90a58c68ee4d6d4392b6b22be 100644
--- a/matlab/ep/extended_path_core.m
+++ b/matlab/ep/extended_path_core.m
@@ -1,10 +1,10 @@
 function [y, info_convergence, endogenousvariablespaths] = extended_path_core(periods,endo_nbr,exo_nbr,positive_var_indx, ...
-                                exo_simul,init,initial_conditions,...
-                                steady_state, ...
-                                debug,bytecode_flag,order,M,pfm,algo,solve_algo,stack_solve_algo,...
-                                olmmcp,options,oo,initialguess)
+                                                  exo_simul,init,initial_conditions,...
+                                                  steady_state, ...
+                                                  debug,bytecode_flag,order,M,pfm,algo,solve_algo,stack_solve_algo,...
+                                                  olmmcp,options,oo,initialguess)
 
-% Copyright (C) 2016 Dynare Team
+% Copyright (C) 2016-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -58,7 +58,7 @@ if flag
         options.solve_algo = solve_algo;
         options.stack_solve_algo = stack_solve_algo;
         tmp = perfect_foresight_solver_core(M, options, oo);
-        if ~tmp.deterministic_simulation.status 
+        if ~tmp.deterministic_simulation.status
             info_convergence = false;
         else
             info_convergence = true;
diff --git a/matlab/ep/extended_path_homotopy.m b/matlab/ep/extended_path_homotopy.m
index 463003d2bfc5b76559106b46cf97a57c3742a952..8036ae50ff1325ac269ead7610d80b4b405b1ea8 100644
--- a/matlab/ep/extended_path_homotopy.m
+++ b/matlab/ep/extended_path_homotopy.m
@@ -1,6 +1,6 @@
 function [info_convergence, endo_simul] = extended_path_homotopy(endo_simul, exo_simul, M, options, oo, pfm, ep, order, algo, method, debug)
 
-% Copyright (C) 2016 Dynare Team
+% Copyright (C) 2016-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -17,7 +17,7 @@ function [info_convergence, endo_simul] = extended_path_homotopy(endo_simul, exo
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-    
+
 endo_simul0 = endo_simul;
 if ismember(method, [1, 2])
     noconvergence = true;
diff --git a/matlab/ep/extended_path_initialization.m b/matlab/ep/extended_path_initialization.m
index 34d7cdc68bfb28fb7d31f1f46133652ceca5b266..fb8581bc687c0c265ef21214cfbb922ab851abbe 100644
--- a/matlab/ep/extended_path_initialization.m
+++ b/matlab/ep/extended_path_initialization.m
@@ -2,21 +2,21 @@ function [initial_conditions, innovations, pfm, ep, verbosity, DynareOptions, Dy
 
 % Initialization of the extended path routines.
 %
-% INPUTS 
+% INPUTS
 %  o initial_conditions     [double]    m*1 array, where m is the number of endogenous variables in the model.
 %  o sample_size            [integer]   scalar, size of the sample to be simulated.
 %  o exogenousvariables     [double]    T*n array, values for the structural innovations.
-%  o DynareOptions          [struct]    options_ 
+%  o DynareOptions          [struct]    options_
 %  o DynareModel            [struct]    M_
 %  o DynareResults          [struct]    oo_
 %
-% OUTPUTS 
+% OUTPUTS
 %
 % ALGORITHM
 %
 % SPECIAL REQUIREMENTS
 
-% Copyright (C) 2016 Dynare Team
+% Copyright (C) 2016-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -118,7 +118,7 @@ pfm.nnzA = DynareModel.NNZDerivatives(1);
 if ep.stochastic.order > 0
     [nodes,weights,nnodes] = setup_integration_nodes(DynareOptions.ep,pfm);
     pfm.nodes = nodes;
-    pfm.weights = weights; 
+    pfm.weights = weights;
     pfm.nnodes = nnodes;
     % compute number of blocks
     [block_nbr,pfm.world_nbr] = get_block_world_nbr(ep.stochastic.algo,nnodes,ep.stochastic.order,ep.periods);
@@ -134,6 +134,5 @@ if DynareOptions.ep.solve_algo == 10
 elseif DynareOptions.ep.solve_algo == 11
     DynareOptions.mcppath.lb = repmat(lb,block_nbr,1);
     DynareOptions.mcppath.ub = repmat(ub,block_nbr,1);
-end;
+end
 pfm.block_nbr = block_nbr;
-
diff --git a/matlab/ep/extended_path_mc.m b/matlab/ep/extended_path_mc.m
index f03bca8aed605ea79d4aca87b71414c5c30706ef..f31ae2dc9647b4570cd8851dd8695d0ad7ed1ffc 100644
--- a/matlab/ep/extended_path_mc.m
+++ b/matlab/ep/extended_path_mc.m
@@ -3,7 +3,7 @@ function Simulations = extended_path_mc(initialconditions, samplesize, replic, e
 % Stochastic simulation of a non linear DSGE model using the Extended Path method (Fair and Taylor 1983). A time
 % series of size T  is obtained by solving T perfect foresight models.
 %
-% INPUTS 
+% INPUTS
 %  o initialconditions      [double]    m*1 array, where m is the number of endogenous variables in the model.
 %  o samplesize            [integer]   scalar, size of the sample to be simulated.
 %  o exogenousvariables     [double]    T*n array, values for the structural innovations.
@@ -11,7 +11,7 @@ function Simulations = extended_path_mc(initialconditions, samplesize, replic, e
 %  o DynareModel            [struct]    M_
 %  o DynareResults          [struct]    oo_
 %
-% OUTPUTS 
+% OUTPUTS
 %  o ts                     [dseries]   m*samplesize array, the simulations.
 %  o results                [cell]
 %
@@ -19,7 +19,7 @@ function Simulations = extended_path_mc(initialconditions, samplesize, replic, e
 %
 % SPECIAL REQUIREMENTS
 
-% Copyright (C) 2016 Dynare Team
+% Copyright (C) 2016-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -65,7 +65,7 @@ vexo = NaN(innovations.effective_number_of_shocks, samplesize+1, replic);
 info = NaN(replic, 1);
 
 if ep.parallel
-    % Use the Parallel toolbox.    
+    % Use the Parallel toolbox.
     parfor i=1:replic
         innovations_ = innovations;
         DynareResults_ = DynareResults;
diff --git a/matlab/ep/extended_path_shocks.m b/matlab/ep/extended_path_shocks.m
index 6939903404d838f55a5f79f91a6e9d1d1f52d61b..b642f225bd35749ca03e87f42bd7381d1e86c2eb 100644
--- a/matlab/ep/extended_path_shocks.m
+++ b/matlab/ep/extended_path_shocks.m
@@ -1,6 +1,6 @@
-function [shocks, spfm_exo_simul, innovations, DynareResults] = extended_path_shocks(innovations, ep, exogenousvariables, sample_size,DynareModel,DynareOptions, DynareResults); 
+function [shocks, spfm_exo_simul, innovations, DynareResults] = extended_path_shocks(innovations, ep, exogenousvariables, sample_size,DynareModel,DynareOptions, DynareResults)
 
-% Copyright (C) 2016 Dynare Team
+% Copyright (C) 2016-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/ep/setup_integration_nodes.m b/matlab/ep/setup_integration_nodes.m
index 85d1be960c4bc5bdf93b0aa8862ea0c3b04234bc..5a6d206c1bbb7cd4cc1306823fd8c55c348661e1 100644
--- a/matlab/ep/setup_integration_nodes.m
+++ b/matlab/ep/setup_integration_nodes.m
@@ -1,39 +1,39 @@
 function [nodes,weights,nnodes] = setup_integration_nodes(EpOptions,pfm)
-    if EpOptions.stochastic.order
-        % Compute weights and nodes for the stochastic version of the extended path.
-        switch EpOptions.IntegrationAlgorithm
-          case 'Tensor-Gaussian-Quadrature'
-            % Get the nodes and weights from a univariate Gauss-Hermite quadrature.
-            [nodes0,weights0] = gauss_hermite_weights_and_nodes(EpOptions.stochastic.quadrature.nodes);
-            % Replicate the univariate nodes for each innovation and dates, and, if needed, correlate them. 
-            nodes0 = repmat(nodes0,1,pfm.number_of_shocks*pfm.stochastic_order)*kron(eye(pfm.stochastic_order),pfm.Omega);
-            % Put the nodes and weights in cells
-            for i=1:pfm.number_of_shocks
-                rr(i) = {nodes0(:,i)};
-                ww(i) = {weights0};
-            end
-            % Build the tensorial grid
-            nodes = cartesian_product_of_sets(rr{:});
-            weights = prod(cartesian_product_of_sets(ww{:}),2);
-            nnodes = length(weights);
-          case 'Stroud-Cubature-3'
-            [nodes,weights] = cubature_with_gaussian_weight(pfm.number_of_shocks*pfm.stochastic_order,3,'Stroud')
-            nodes = kron(eye(pfm.stochastic_order),transpose(pfm.Omega))*nodes;
-            weights = weights;
-            nnodes = length(weights);
-          case 'Stroud-Cubature-5'
-            [nodes,weights] = cubature_with_gaussian_weight(pfm.number_of_shocks*pfm.stochastic_order,5,'Stroud')
-            nodes = kron(eye(pfm.stochastic_order),transpose(pfm.Omega))*nodes;
-            weights = weights;
-            nnodes = length(weights);
-          case 'Unscented'
-            p = pfm.number_of_shocks;
-            k = EpOptions.ut.k;
-            C = sqrt(pfm.number_of_shocks + k)*pfm.Omega';
-            nodes = [zeros(1,p); -C; C];
-            weights = [k/(p+k); (1/(2*(p+k)))*ones(2*p,1)];
-            nnodes = 2*p+1;
-          otherwise
-            error('Stochastic extended path:: Unknown integration algorithm!')
+if EpOptions.stochastic.order
+    % Compute weights and nodes for the stochastic version of the extended path.
+    switch EpOptions.IntegrationAlgorithm
+      case 'Tensor-Gaussian-Quadrature'
+        % Get the nodes and weights from a univariate Gauss-Hermite quadrature.
+        [nodes0,weights0] = gauss_hermite_weights_and_nodes(EpOptions.stochastic.quadrature.nodes);
+        % Replicate the univariate nodes for each innovation and dates, and, if needed, correlate them.
+        nodes0 = repmat(nodes0,1,pfm.number_of_shocks*pfm.stochastic_order)*kron(eye(pfm.stochastic_order),pfm.Omega);
+        % Put the nodes and weights in cells
+        for i=1:pfm.number_of_shocks
+            rr(i) = {nodes0(:,i)};
+            ww(i) = {weights0};
         end
+        % Build the tensorial grid
+        nodes = cartesian_product_of_sets(rr{:});
+        weights = prod(cartesian_product_of_sets(ww{:}),2);
+        nnodes = length(weights);
+      case 'Stroud-Cubature-3'
+        [nodes,weights] = cubature_with_gaussian_weight(pfm.number_of_shocks*pfm.stochastic_order,3,'Stroud')
+        nodes = kron(eye(pfm.stochastic_order),transpose(pfm.Omega))*nodes;
+        weights = weights;
+        nnodes = length(weights);
+      case 'Stroud-Cubature-5'
+        [nodes,weights] = cubature_with_gaussian_weight(pfm.number_of_shocks*pfm.stochastic_order,5,'Stroud')
+        nodes = kron(eye(pfm.stochastic_order),transpose(pfm.Omega))*nodes;
+        weights = weights;
+        nnodes = length(weights);
+      case 'Unscented'
+        p = pfm.number_of_shocks;
+        k = EpOptions.ut.k;
+        C = sqrt(pfm.number_of_shocks + k)*pfm.Omega';
+        nodes = [zeros(1,p); -C; C];
+        weights = [k/(p+k); (1/(2*(p+k)))*ones(2*p,1)];
+        nnodes = 2*p+1;
+      otherwise
+        error('Stochastic extended path:: Unknown integration algorithm!')
     end
+end
diff --git a/matlab/ep/setup_stochastic_perfect_foresight_model_solver.m b/matlab/ep/setup_stochastic_perfect_foresight_model_solver.m
index 286bd16acb4a11bcb52d2bea6a39ab84906d98b2..732714d4a7d3d32a9440bc025a4072411aaf7eaa 100644
--- a/matlab/ep/setup_stochastic_perfect_foresight_model_solver.m
+++ b/matlab/ep/setup_stochastic_perfect_foresight_model_solver.m
@@ -1,6 +1,6 @@
 function pfm = setup_stochastic_perfect_foresight_model_solver(DynareModel,DynareOptions,DynareOutput)
 
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -16,7 +16,7 @@ function pfm = setup_stochastic_perfect_foresight_model_solver(DynareModel,Dynar
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
-    
+
 pfm.lead_lag_incidence = DynareModel.lead_lag_incidence;
 pfm.ny = DynareModel.endo_nbr;
 pfm.Sigma = DynareModel.Sigma_e;
@@ -71,4 +71,3 @@ 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 ab13e3043ac6c89cd30f80aff549f6fb7f3b57b6..742895f91bf0977e9d3987aa0da4c586c11d82b5 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-2015 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -17,219 +17,219 @@ function [flag,endo_simul,err] = solve_stochastic_perfect_foresight_model(endo_s
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-    flag = 0;
-    err = 0;
-    stop = 0;
+flag = 0;
+err = 0;
+stop = 0;
 
-    params = pfm.params;
-    steady_state = pfm.steady_state;
-    ny = pfm.ny;
-    periods = pfm.periods;
-    dynamic_model = pfm.dynamic_model;
-    lead_lag_incidence = pfm.lead_lag_incidence;
-    nyp = pfm.nyp;
-    nyf = pfm.nyf;
-    i_cols_1 = pfm.i_cols_1;
-    i_cols_A1 = pfm.i_cols_A1;
-    i_cols_j = pfm.i_cols_j;
-    i_cols_T = nonzeros(lead_lag_incidence(1:2,:)');
+params = pfm.params;
+steady_state = pfm.steady_state;
+ny = pfm.ny;
+periods = pfm.periods;
+dynamic_model = pfm.dynamic_model;
+lead_lag_incidence = pfm.lead_lag_incidence;
+nyp = pfm.nyp;
+nyf = pfm.nyf;
+i_cols_1 = pfm.i_cols_1;
+i_cols_A1 = pfm.i_cols_A1;
+i_cols_j = pfm.i_cols_j;
+i_cols_T = nonzeros(lead_lag_incidence(1:2,:)');
 
-    maxit = pfm.maxit_;
-    tolerance = pfm.tolerance;
-    verbose = pfm.verbose;
+maxit = pfm.maxit_;
+tolerance = pfm.tolerance;
+verbose = pfm.verbose;
 
-    number_of_shocks = size(exo_simul,2);
+number_of_shocks = size(exo_simul,2);
 
-    [nodes,weights] = gauss_hermite_weights_and_nodes(nnodes);
+[nodes,weights] = gauss_hermite_weights_and_nodes(nnodes);
 
-    if number_of_shocks>1
-        nodes = repmat(nodes,1,number_of_shocks)*chol(pfm.Sigma);
-        % to be fixed for Sigma ~= I
-        for i=1:number_of_shocks
-            rr(i) = {nodes(:,i)};
-            ww(i) = {weights};
-        end
-        nodes = cartesian_product_of_sets(rr{:});
-        weights = prod(cartesian_product_of_sets(ww{:}),2);
-        nnodes = nnodes^number_of_shocks;
-    else
-        nodes = nodes*sqrt(pfm.Sigma);
+if number_of_shocks>1
+    nodes = repmat(nodes,1,number_of_shocks)*chol(pfm.Sigma);
+    % to be fixed for Sigma ~= I
+    for i=1:number_of_shocks
+        rr(i) = {nodes(:,i)};
+        ww(i) = {weights};
     end
+    nodes = cartesian_product_of_sets(rr{:});
+    weights = prod(cartesian_product_of_sets(ww{:}),2);
+    nnodes = nnodes^number_of_shocks;
+else
+    nodes = nodes*sqrt(pfm.Sigma);
+end
 
-    innovations = zeros(periods+2,number_of_shocks);
+innovations = zeros(periods+2,number_of_shocks);
 
-    if verbose
-        disp ([' -----------------------------------------------------']);
-        disp (['MODEL SIMULATION :']);
-        fprintf('\n');
-    end
+if verbose
+    disp ([' -----------------------------------------------------']);
+    disp (['MODEL SIMULATION :']);
+    fprintf('\n');
+end
 
-    z = endo_simul(find(lead_lag_incidence'));
-    [d1,jacobian] = dynamic_model(z,exo_simul,params,steady_state,2);
+z = endo_simul(find(lead_lag_incidence'));
+[d1,jacobian] = dynamic_model(z,exo_simul,params,steady_state,2);
 
-    % Each column of Y represents a different world
-    % The upper right cells are unused
-    % The first row block is ny x 1
-    % The second row block is ny x nnodes
-    % The third row block is ny x nnodes^2
-    % and so on until size ny x nnodes^order
-    world_nbr = nnodes^order;
-    Y = repmat(endo_simul(:),1,world_nbr);
+% Each column of Y represents a different world
+% The upper right cells are unused
+% The first row block is ny x 1
+% The second row block is ny x nnodes
+% The third row block is ny x nnodes^2
+% and so on until size ny x nnodes^order
+world_nbr = nnodes^order;
+Y = repmat(endo_simul(:),1,world_nbr);
 
-    % The columns of A map the elements of Y such that
-    % each block of Y with ny rows are unfolded column wise
-    dimension = ny*(sum(nnodes.^(0:order-1),2)+(periods-order)*world_nbr);
-    if order == 0
-        i_upd_r = (1:ny*periods);
-        i_upd_y = i_upd_r + ny;
-    else
-        i_upd_r = zeros(dimension,1);
-        i_upd_y = i_upd_r;
-        i_upd_r(1:ny) = (1:ny);
-        i_upd_y(1:ny) = ny+(1:ny);
-        i1 = ny+1;
-        i2 = 2*ny;
-        n1 = ny+1;
-        n2 = 2*ny;
-        for i=2:periods
-            k = n1:n2;
-            for j=1:nnodes^min(i-1,order)
-                i_upd_r(i1:i2) = (n1:n2)+(j-1)*ny*periods;
-                i_upd_y(i1:i2) = (n1:n2)+ny+(j-1)*ny*(periods+2);
-                i1 = i2+1;
-                i2 = i2+ny;
-            end
-            n1 = n2+1;
-            n2 = n2+ny;
+% The columns of A map the elements of Y such that
+% each block of Y with ny rows are unfolded column wise
+dimension = ny*(sum(nnodes.^(0:order-1),2)+(periods-order)*world_nbr);
+if order == 0
+    i_upd_r = (1:ny*periods);
+    i_upd_y = i_upd_r + ny;
+else
+    i_upd_r = zeros(dimension,1);
+    i_upd_y = i_upd_r;
+    i_upd_r(1:ny) = (1:ny);
+    i_upd_y(1:ny) = ny+(1:ny);
+    i1 = ny+1;
+    i2 = 2*ny;
+    n1 = ny+1;
+    n2 = 2*ny;
+    for i=2:periods
+        k = n1:n2;
+        for j=1:nnodes^min(i-1,order)
+            i_upd_r(i1:i2) = (n1:n2)+(j-1)*ny*periods;
+            i_upd_y(i1:i2) = (n1:n2)+ny+(j-1)*ny*(periods+2);
+            i1 = i2+1;
+            i2 = i2+ny;
         end
+        n1 = n2+1;
+        n2 = n2+ny;
     end
-    icA = [find(lead_lag_incidence(1,:)) find(lead_lag_incidence(2,:))+world_nbr*ny ...
-           find(lead_lag_incidence(3,:))+2*world_nbr*ny]';
-    h1 = clock;
-    for iter = 1:maxit
-        h2 = clock;
-        A1 = sparse([],[],[],ny*(sum(nnodes.^(0:order-1),2)+1),dimension,(order+1)*world_nbr*nnz(jacobian));
-        res = zeros(ny,periods,world_nbr);
-        i_rows = 1:ny;
-        i_cols = find(lead_lag_incidence');
-        i_cols_p = i_cols(1:nyp);
-        i_cols_s = i_cols(nyp+(1:ny));
-        i_cols_f = i_cols(nyp+ny+(1:nyf));
-        i_cols_A = i_cols;
-        i_cols_Ap = i_cols_p;
-        i_cols_As = i_cols_s;
-        i_cols_Af = i_cols_f - ny;
-        for i = 1:order+1
-            i_w_p = 1;
-            for j = 1:nnodes^(i-1)
-                innovation = exo_simul;
-                if i > 1
-                    innovation(i+1,:) = nodes(mod(j-1,nnodes)+1,:);
-                end
-                if i <= order
-                    for k=1:nnodes
-                        y = [Y(i_cols_p,i_w_p);
-                             Y(i_cols_s,j);
-                             Y(i_cols_f,(j-1)*nnodes+k)];
-                        [d1,jacobian] = dynamic_model(y,innovation,params,steady_state,i+1);
-                        if i == 1
-                            % in first period we don't keep track of
-                            % predetermined variables
-                            i_cols_A = [i_cols_As - ny; i_cols_Af];
-                            A1(i_rows,i_cols_A) = A1(i_rows,i_cols_A) + weights(k)*jacobian(:,i_cols_1);
-                        else
-                            i_cols_A = [i_cols_Ap; i_cols_As; i_cols_Af];
-                            A1(i_rows,i_cols_A) = A1(i_rows,i_cols_A) + weights(k)*jacobian(:,i_cols_j);
-                        end
-                        res(:,i,j) = res(:,i,j)+weights(k)*d1;
-                        i_cols_Af = i_cols_Af + ny;
-                    end
-                else
+end
+icA = [find(lead_lag_incidence(1,:)) find(lead_lag_incidence(2,:))+world_nbr*ny ...
+       find(lead_lag_incidence(3,:))+2*world_nbr*ny]';
+h1 = clock;
+for iter = 1:maxit
+    h2 = clock;
+    A1 = sparse([],[],[],ny*(sum(nnodes.^(0:order-1),2)+1),dimension,(order+1)*world_nbr*nnz(jacobian));
+    res = zeros(ny,periods,world_nbr);
+    i_rows = 1:ny;
+    i_cols = find(lead_lag_incidence');
+    i_cols_p = i_cols(1:nyp);
+    i_cols_s = i_cols(nyp+(1:ny));
+    i_cols_f = i_cols(nyp+ny+(1:nyf));
+    i_cols_A = i_cols;
+    i_cols_Ap = i_cols_p;
+    i_cols_As = i_cols_s;
+    i_cols_Af = i_cols_f - ny;
+    for i = 1:order+1
+        i_w_p = 1;
+        for j = 1:nnodes^(i-1)
+            innovation = exo_simul;
+            if i > 1
+                innovation(i+1,:) = nodes(mod(j-1,nnodes)+1,:);
+            end
+            if i <= order
+                for k=1:nnodes
                     y = [Y(i_cols_p,i_w_p);
                          Y(i_cols_s,j);
-                         Y(i_cols_f,j)];
+                         Y(i_cols_f,(j-1)*nnodes+k)];
                     [d1,jacobian] = dynamic_model(y,innovation,params,steady_state,i+1);
                     if i == 1
                         % in first period we don't keep track of
                         % predetermined variables
                         i_cols_A = [i_cols_As - ny; i_cols_Af];
-                        A1(i_rows,i_cols_A) = jacobian(:,i_cols_1);
+                        A1(i_rows,i_cols_A) = A1(i_rows,i_cols_A) + weights(k)*jacobian(:,i_cols_1);
                     else
                         i_cols_A = [i_cols_Ap; i_cols_As; i_cols_Af];
-                        A1(i_rows,i_cols_A) = jacobian(:,i_cols_j);
+                        A1(i_rows,i_cols_A) = A1(i_rows,i_cols_A) + weights(k)*jacobian(:,i_cols_j);
                     end
-                    res(:,i,j) = d1;
+                    res(:,i,j) = res(:,i,j)+weights(k)*d1;
                     i_cols_Af = i_cols_Af + ny;
                 end
-                i_rows = i_rows + ny;
-                if mod(j,nnodes) == 0
-                    i_w_p = i_w_p + 1;
-                end
-                if i > 1
-                    if mod(j,nnodes) == 0
-                        i_cols_Ap = i_cols_Ap + ny;
-                    end
-                    i_cols_As = i_cols_As + ny;
-                end
-            end
-            i_cols_p = i_cols_p + ny;
-            i_cols_s = i_cols_s + ny;
-            i_cols_f = i_cols_f + ny;
-        end
-        nzA = cell(periods,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;
-            for i=order+2:periods
-                [d1,jacobian] = dynamic_model(Y(i_rows_y,j), ...
-                                              exo_simul,params, ...
-                                              steady_state,i+1);
-                if i == periods
-                    [ir,ic,v] = find(jacobian(:,i_cols_T));
+            else
+                y = [Y(i_cols_p,i_w_p);
+                     Y(i_cols_s,j);
+                     Y(i_cols_f,j)];
+                [d1,jacobian] = dynamic_model(y,innovation,params,steady_state,i+1);
+                if i == 1
+                    % in first period we don't keep track of
+                    % predetermined variables
+                    i_cols_A = [i_cols_As - ny; i_cols_Af];
+                    A1(i_rows,i_cols_A) = jacobian(:,i_cols_1);
                 else
-                    [ir,ic,v] = find(jacobian(:,i_cols_j));
+                    i_cols_A = [i_cols_Ap; i_cols_As; i_cols_Af];
+                    A1(i_rows,i_cols_A) = jacobian(:,i_cols_j);
                 end
-                nzA{i,j} = [offset_r+ir,offset_c+icA(ic), v]';
                 res(:,i,j) = d1;
-                i_rows_y = i_rows_y + ny;
-                offset_c = offset_c + world_nbr*ny;
-                offset_r = offset_r + world_nbr*ny;
+                i_cols_Af = i_cols_Af + ny;
+            end
+            i_rows = i_rows + ny;
+            if mod(j,nnodes) == 0
+                i_w_p = i_w_p + 1;
+            end
+            if i > 1
+                if mod(j,nnodes) == 0
+                    i_cols_Ap = i_cols_Ap + ny;
+                end
+                i_cols_As = i_cols_As + ny;
             end
         end
-        err = max(abs(res(i_upd_r)));
-        if err < tolerance
-            stop = 1;
-            if verbose
-                fprintf('\n') ;
-                disp([' Total time of simulation        :' num2str(etime(clock,h1))]) ;
-                fprintf('\n') ;
-                disp([' Convergency obtained.']) ;
-                fprintf('\n') ;
+        i_cols_p = i_cols_p + ny;
+        i_cols_s = i_cols_s + ny;
+        i_cols_f = i_cols_f + ny;
+    end
+    nzA = cell(periods,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;
+        for i=order+2:periods
+            [d1,jacobian] = dynamic_model(Y(i_rows_y,j), ...
+                                          exo_simul,params, ...
+                                          steady_state,i+1);
+            if i == periods
+                [ir,ic,v] = find(jacobian(:,i_cols_T));
+            else
+                [ir,ic,v] = find(jacobian(:,i_cols_j));
             end
-            flag = 0;% Convergency obtained.
-            endo_simul = reshape(Y(:,1),ny,periods+2);%Y(ny+(1:ny),1);
-                                                      %            figure;plot(Y(16:ny:(periods+2)*ny,:))
-                                                      %            pause
-            break
+            nzA{i,j} = [offset_r+ir,offset_c+icA(ic), v]';
+            res(:,i,j) = d1;
+            i_rows_y = i_rows_y + ny;
+            offset_c = offset_c + world_nbr*ny;
+            offset_r = offset_r + world_nbr*ny;
         end
-        A2 = [nzA{:}]';
-        A = [A1; sparse(A2(:,1),A2(:,2),A2(:,3),ny*(periods-order-1)*world_nbr,dimension)];
-        dy = -A\res(i_upd_r);
-        Y(i_upd_y) =   Y(i_upd_y) + dy;
     end
-
-    if ~stop
+    err = max(abs(res(i_upd_r)));
+    if err < tolerance
+        stop = 1;
         if verbose
             fprintf('\n') ;
-            disp(['     Total time of simulation        :' num2str(etime(clock,h1))]) ;
+            disp([' Total time of simulation        :' num2str(etime(clock,h1))]) ;
             fprintf('\n') ;
-            disp(['WARNING : maximum number of iterations is reached (modify options_.simul.maxit).']) ;
+            disp([' Convergency obtained.']) ;
             fprintf('\n') ;
         end
-        flag = 1;% more iterations are needed.
-        endo_simul = 1;
+        flag = 0;% Convergency obtained.
+        endo_simul = reshape(Y(:,1),ny,periods+2);%Y(ny+(1:ny),1);
+                                                  %            figure;plot(Y(16:ny:(periods+2)*ny,:))
+                                                  %            pause
+        break
     end
+    A2 = [nzA{:}]';
+    A = [A1; sparse(A2(:,1),A2(:,2),A2(:,3),ny*(periods-order-1)*world_nbr,dimension)];
+    dy = -A\res(i_upd_r);
+    Y(i_upd_y) =   Y(i_upd_y) + dy;
+end
+
+if ~stop
     if verbose
-        disp (['-----------------------------------------------------']) ;
+        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') ;
     end
+    flag = 1;% more iterations are needed.
+    endo_simul = 1;
+end
+if verbose
+    disp (['-----------------------------------------------------']) ;
+end
diff --git a/matlab/ep/solve_stochastic_perfect_foresight_model_1.m b/matlab/ep/solve_stochastic_perfect_foresight_model_1.m
index 638a4fa4b07836f6db7e8c1d37c06d70943175ce..3e0ced538e94a4cc35f40fc0658538e39cd3899f 100644
--- a/matlab/ep/solve_stochastic_perfect_foresight_model_1.m
+++ b/matlab/ep/solve_stochastic_perfect_foresight_model_1.m
@@ -1,6 +1,6 @@
 function [flag,endo_simul,err,y] = solve_stochastic_perfect_foresight_model_1(endo_simul,exo_simul,Options,pfm,order,varargin)
 
-% Copyright (C) 2012-2013 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -83,7 +83,7 @@ end
 % and so on until size ny x nnodes^order
 world_nbr = pfm.world_nbr;
 Y = endo_simul(:,2:end-1);
-Y = repmat(Y,1,world_nbr); 
+Y = repmat(Y,1,world_nbr);
 pfm.y0 = endo_simul(:,1);
 
 % The columns of A map the elements of Y such that
diff --git a/matlab/ep/stroud_judd_7.5.8.m b/matlab/ep/stroud_judd_7.5.8.m
deleted file mode 100644
index 40c9bc08db172e2a6d371d468f099ffa1817e73d..0000000000000000000000000000000000000000
--- a/matlab/ep/stroud_judd_7.5.8.m
+++ /dev/null
@@ -1,9 +0,0 @@
-function [X,w]=stroud_judd_7.5.8(d)
-    
-    E = eye(d);
-    X = cell(2*d,1);
-    m = 1;
-    for i=1:d
-        X{m} = E(:,i);
-        m = m+1;
-        X{m} = -E(:,i);
diff --git a/matlab/ep_residuals.m b/matlab/ep_residuals.m
index 56b554de8738927f8beacbebcba944a72d1b3216..6eea0ef4de0ca6400b0fade5a46b534565a1fca3 100644
--- a/matlab/ep_residuals.m
+++ b/matlab/ep_residuals.m
@@ -1,23 +1,23 @@
 function r = ep_residuals(x, y, ix, iy, steadystate, dr, maximum_lag, endo_nbr)
 % Inversion of the extended path simulation approach. This routine computes the innovations needed to
-% reproduce the time path of a subset of endogenous variables.    
-%    
+% reproduce the time path of a subset of endogenous variables.
+%
 % INPUTS
-%  o x    [double]   n*1 vector, time t innovations.    
+%  o x    [double]   n*1 vector, time t innovations.
 %  o y    [double]   n*1 vector, time t restricted endogenous variables.
 %  o ix   [integer]  index of control innovations in the full vector of innovations.
-%  o iy   [integer]  index of controlled variables in the full vector of endogenous variables.    
-%  o s    [double]   m*1 vector, endogenous variables at time t-1. 
-%    
-% 
+%  o iy   [integer]  index of controlled variables in the full vector of endogenous variables.
+%  o s    [double]   m*1 vector, endogenous variables at time t-1.
+%
+%
 % OUTPUTS
 %  o r    [double]  n*1 vector of residuals.
-%    
+%
 % ALGORITHM
-%  
+%
 % SPECIAL REQUIREMENTS
 
-% Copyright (C) 2010 Dynare Team.
+% Copyright (C) 2010-2017 Dynare Team.
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/evaluate_likelihood.m b/matlab/evaluate_likelihood.m
index 39affdc5ec9b0fd18402c8bcf0fd6669ebb84858..a76534adff87bc0f301bbcbc6e218a024f175dcc 100644
--- a/matlab/evaluate_likelihood.m
+++ b/matlab/evaluate_likelihood.m
@@ -18,7 +18,7 @@ function [llik,parameters] = evaluate_likelihood(parameters)
 % [2] This function use persistent variables for the dataset and the description of the missing observations. Consequently, if this function
 %     is called more than once (by changing the value of parameters) the sample *must not* change.
 
-% Copyright (C) 2009-2012 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -69,6 +69,7 @@ end
 if isempty(dataset)
     [dataset, dataset_info] = makedataset(options_);
 end
+options_=select_qz_criterium_value(options_);
 
 llik = -dsge_likelihood(parameters,dataset,dataset_info,options_,M_,estim_params_,bayestopt_,prior_bounds(bayestopt_,options_.prior_trunc),oo_);
 ldens = evaluate_prior(parameters);
diff --git a/matlab/evaluate_max_dynamic_residual.m b/matlab/evaluate_max_dynamic_residual.m
index 41aa4ec249c2fae2dcfb9721832e2aee20bcedef..9ea67a5fe7fc02b38a69dc50f4e68cab60e0cfaf 100644
--- a/matlab/evaluate_max_dynamic_residual.m
+++ b/matlab/evaluate_max_dynamic_residual.m
@@ -1,6 +1,6 @@
 function err = evaluate_max_dynamic_residual(model_dynamic, Y, exogenous_variables, params, steady_state, periods, ny, max_lag, lead_lag_incidence)
 
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -16,7 +16,7 @@ function err = evaluate_max_dynamic_residual(model_dynamic, Y, exogenous_variabl
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
-    
+
 i_rows = 1:ny;
 i_cols = find(lead_lag_incidence');
 
diff --git a/matlab/evaluate_planner_objective.m b/matlab/evaluate_planner_objective.m
index 40f1865903608528ecad2f69ded09cda08f74866..f8d03f978b49bb8f77b5d8bd034955472f859c42 100644
--- a/matlab/evaluate_planner_objective.m
+++ b/matlab/evaluate_planner_objective.m
@@ -1,17 +1,17 @@
 function planner_objective_value = evaluate_planner_objective(M,options,oo)
 
 %function oo1 = evaluate_planner_objective(dr,M,oo,options)
-%  computes value of planner objective function     
-% 
+%  computes value of planner objective function
+%
 % INPUTS
 %   M:        (structure) model description
 %   options:  (structure) options
 %   oo:       (structure) output results
-%    
+%
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2007-2015 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -40,7 +40,7 @@ if nspred > 180
     return
 end
 beta = get_optimal_policy_discount_factor(M.params,M.param_names);
-    
+
 Gy = dr.ghx(nstatic+(1:nspred),:);
 Gu = dr.ghu(nstatic+(1:nspred),:);
 gy(dr.order_var,:) = dr.ghx;
@@ -113,7 +113,7 @@ if ~options.noprint
     disp('Approximated value of planner objective function')
     if options.ramsey_policy
         disp(['    - with initial Lagrange multipliers set to 0: ' ...
-          num2str(planner_objective_value(2)) ])
+              num2str(planner_objective_value(2)) ])
         disp(['    - with initial Lagrange multipliers set to steady state: ' ...
               num2str(planner_objective_value(1)) ])
     elseif options.discretionary_policy
diff --git a/matlab/evaluate_posterior_kernel.m b/matlab/evaluate_posterior_kernel.m
index 96ccac8d5d35726099a39188ad18a6e51186b3ab..997962127a7a672e38cc6e7529a4828c3d495c5d 100644
--- a/matlab/evaluate_posterior_kernel.m
+++ b/matlab/evaluate_posterior_kernel.m
@@ -2,22 +2,22 @@ function lpkern = evaluate_posterior_kernel(parameters,llik)
 % Evaluate the prior density at parameters.
 %
 % INPUTS
-%    o parameters  a string ('posterior mode','posterior mean','posterior median','prior mode','prior mean') or a vector of values for 
+%    o parameters  a string ('posterior mode','posterior mean','posterior median','prior mode','prior mean') or a vector of values for
 %                  the (estimated) parameters of the model.
-%    
-%    
+%
+%
 % OUTPUTS
 %    o lpkern      [double]  value of the logged posterior kernel.
-%    
+%
 % SPECIAL REQUIREMENTS
 %    None
 %
 % REMARKS
 % [1] This function cannot evaluate the prior density of a dsge-var model...
-% [2] This function use persistent variables for the dataset and the description of the missing observations. Consequently, if this function 
-%     is called more than once (by changing the value of parameters) the sample *must not* change.    
+% [2] This function use persistent variables for the dataset and the description of the missing observations. Consequently, if this function
+%     is called more than once (by changing the value of parameters) the sample *must not* change.
 
-% Copyright (C) 2009 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/evaluate_prior.m b/matlab/evaluate_prior.m
index b8b2f7b0baeed35d10efde8038bf9263c61e07d5..01cede921ea4ccd78acd10cbf38e0d865f2f1ddc 100644
--- a/matlab/evaluate_prior.m
+++ b/matlab/evaluate_prior.m
@@ -2,21 +2,21 @@ function [ldens,parameters] = evaluate_prior(parameters)
 % Evaluate the prior density at parameters.
 %
 % INPUTS
-%    o parameters  a string ('posterior mode','posterior mean','posterior median','prior mode','prior mean') or a vector of values for 
+%    o parameters  a string ('posterior mode','posterior mean','posterior median','prior mode','prior mean') or a vector of values for
 %                  the (estimated) parameters of the model.
-%    
-%    
+%
+%
 % OUTPUTS
 %    o ldens       [double]  value of the logged prior density.
 %    o parameters  [double]  vector of values for the estimated parameters.
-%    
+%
 % SPECIAL REQUIREMENTS
 %    None
 %
 % REMARKS
 % [1] This function cannot evaluate the prior density of a dsge-var model...
 
-% Copyright (C) 2009-2012 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/evaluate_smoother.m b/matlab/evaluate_smoother.m
index 1093786624ce1f34398878be484cf835ab1ba0b4..9ab94654b1f42e0d134fa8ce5193c56817624ed5 100644
--- a/matlab/evaluate_smoother.m
+++ b/matlab/evaluate_smoother.m
@@ -1,4 +1,4 @@
-function [oo_,options_,bayestopt_,Smoothed_variables_declaration_order_deviation_form]=evaluate_smoother(parameters,var_list,M_,oo_,options_,bayestopt_,estim_params_)
+function [oo_,M_,options_,bayestopt_,Smoothed_variables_declaration_order_deviation_form]=evaluate_smoother(parameters,var_list,M_,oo_,options_,bayestopt_,estim_params_)
 % Evaluate the smoother at parameters.
 %
 % INPUTS
@@ -21,13 +21,14 @@ function [oo_,options_,bayestopt_,Smoothed_variables_declaration_order_deviation
 %                              - SmoothedMeasurementErrors
 %                              - FilteredVariablesKStepAhead
 %                              - FilteredVariablesKStepAheadVariances
+%    o M_          [structure]  Definition of the model
+%    o options_    [structure]  Options; returns options_.first_obs
+%    o bayestopt_  [structure]  describing the priors; returns fields like bayestopt_.smoother_var_list from the smoother
 %    o Smoothed_variables_declaration_order_deviation_form
 %                           Smoothed variables from the Kalman smoother in
 %                           order of declaration of variables (M_.endo_names)
 %                           in deviations from their respective mean, i.e.
 %                           without trend and constant part (used for shock_decomposition)
-%    o options_    [structure]  Options; returns options_.first_obs
-%    o bayestopt_  [structure]  describing the priors; returns fields like bayestopt_.smoother_var_list from the smoother 
 %
 % SPECIAL REQUIREMENTS
 %    None
@@ -36,7 +37,7 @@ function [oo_,options_,bayestopt_,Smoothed_variables_declaration_order_deviation
 % [1] This function use persistent variables for the dataset and the description of the missing observations. Consequently, if this function
 %     is called more than once (by changing the value of parameters) the sample *must not* change.
 
-% Copyright (C) 2010-2016 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -53,18 +54,17 @@ function [oo_,options_,bayestopt_,Smoothed_variables_declaration_order_deviation
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-persistent dataset_ dataset_info
-
-%store qz_criterium
+% store qz_criterium
 qz_criterium_old=options_.qz_criterium;
 
 if ischar(parameters) && strcmp(parameters,'calibration')
     options_.smoother=1;
 end
 
-if isempty(dataset_) || isempty(bayestopt_)
-    [dataset_,dataset_info,xparam1, hh, M_, options_, oo_, estim_params_,bayestopt_] = dynare_estimation_init(var_list, M_.fname, [], M_, options_, oo_, estim_params_, bayestopt_);
-end
+[dataset_,dataset_info,xparam1, hh, M_, options_, oo_, estim_params_,bayestopt_] = dynare_estimation_init(var_list, M_.fname, [], M_, options_, oo_, estim_params_, bayestopt_);
+
+% set the qz_criterium
+options_=select_qz_criterium_value(options_);
 
 if nargin==0
     parameters = 'posterior_mode';
@@ -105,8 +105,8 @@ end
     DsgeSmoother(parameters,dataset_.nobs,transpose(dataset_.data),dataset_info.missing.aindex,dataset_info.missing.state,M_,oo_,options_,bayestopt_,estim_params_);
 [oo_]=store_smoother_results(M_,oo_,options_,bayestopt_,dataset_,dataset_info,atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,P,PK,decomp,Trend,state_uncertainty);
 
-if nargout==4
-   Smoothed_variables_declaration_order_deviation_form=atT(oo_.dr.inv_order_var(bayestopt_.smoother_var_list),:);
+if nargout>4
+    Smoothed_variables_declaration_order_deviation_form=atT(oo_.dr.inv_order_var(bayestopt_.smoother_var_list),:);
 end
 
 %reset qz_criterium
diff --git a/matlab/evaluate_static_model.m b/matlab/evaluate_static_model.m
index 92251796423a0c79c6224b65efd0752acb313f13..ecf7ebb39e61055e090b5c1186b446966655cc78 100644
--- a/matlab/evaluate_static_model.m
+++ b/matlab/evaluate_static_model.m
@@ -2,7 +2,7 @@ function [residuals,check1,jacob] = evaluate_static_model(ys,exo_ss,params,M,opt
 
 % function [residuals,check1,jacob] = evaluate_static_model(ys,exo_ss,params,M,options)
 % Evaluates the static model
-%  
+%
 % INPUTS
 %   ys                        vector           initial values used to compute the steady
 %                                                 state
@@ -10,7 +10,7 @@ function [residuals,check1,jacob] = evaluate_static_model(ys,exo_ss,params,M,opt
 %   params                    vector           parameters
 %   M                         struct           model structure
 %   options                   struct           options
-%  
+%
 % OUTPUTS
 %   residuals                 vector           residuals when ys is not
 %                                              the steady state
@@ -20,7 +20,7 @@ function [residuals,check1,jacob] = evaluate_static_model(ys,exo_ss,params,M,opt
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2001-2016 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -37,29 +37,29 @@ function [residuals,check1,jacob] = evaluate_static_model(ys,exo_ss,params,M,opt
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-    check1 = 0;
-    if options.bytecode
-        [check1, residuals] = bytecode('evaluate','static',ys,...
-                                       exo_ss, params, ys, 1);
-        mexErrCheck('bytecode', check1);
-    else
-        fh_static = str2func([M.fname '_static']);
-        if options.block
-            residuals = zeros(M.endo_nbr,1);
-            for b = 1:length(M.block_structure_stat.block)
-                mfsb = M.block_structure_stat.block(b).variable;
-                % blocks that can be directly evaluated (mfsb is empty)
-                % have zero residuals by construction
-                if M.block_structure_stat.block(b).Simulation_Type ~= 1 && ...
-                   M.block_structure_stat.block(b).Simulation_Type ~= 2
-                    residuals(mfsb) = feval(fh_static,b,ys,exo_ss,params);
-                else
-                    %need to evaluate the recursive blocks to compute the
-                    %temporary terms
-                    feval(fh_static,b,ys,exo_ss,params);
-                end
+check1 = 0;
+if options.bytecode
+    [check1, residuals] = bytecode('evaluate','static',ys,...
+                                   exo_ss, params, ys, 1);
+    mexErrCheck('bytecode', check1);
+else
+    fh_static = str2func([M.fname '_static']);
+    if options.block
+        residuals = zeros(M.endo_nbr,1);
+        for b = 1:length(M.block_structure_stat.block)
+            mfsb = M.block_structure_stat.block(b).variable;
+            % blocks that can be directly evaluated (mfsb is empty)
+            % have zero residuals by construction
+            if M.block_structure_stat.block(b).Simulation_Type ~= 1 && ...
+                    M.block_structure_stat.block(b).Simulation_Type ~= 2
+                residuals(mfsb) = feval(fh_static,b,ys,exo_ss,params);
+            else
+                %need to evaluate the recursive blocks to compute the
+                %temporary terms
+                feval(fh_static,b,ys,exo_ss,params);
             end
-        else
-            residuals = feval(fh_static,ys,exo_ss,params);
         end
+    else
+        residuals = feval(fh_static,ys,exo_ss,params);
     end
+end
diff --git a/matlab/evaluate_steady_state.m b/matlab/evaluate_steady_state.m
index 053d62255efbe8a915a6a5a1f5a05990f6361541..d51c08bc8efd463ad0bc49e53a16aadff824f693 100644
--- a/matlab/evaluate_steady_state.m
+++ b/matlab/evaluate_steady_state.m
@@ -22,7 +22,7 @@ function [ys,params,info] = evaluate_steady_state(ys_init,M,options,oo,steadysta
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2001-2016 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -39,309 +39,305 @@ function [ys,params,info] = evaluate_steady_state(ys_init,M,options,oo,steadysta
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-    info = 0;
-    check = 0;
+info = 0;
+check = 0;
 
-    steadystate_flag = options.steadystate_flag;
-    params = M.params;
-    exo_ss = [oo.exo_steady_state; oo.exo_det_steady_state];
+steadystate_flag = options.steadystate_flag;
+params = M.params;
+exo_ss = [oo.exo_steady_state; oo.exo_det_steady_state];
 
-    if length(M.aux_vars) > 0
-        h_set_auxiliary_variables = str2func([M.fname '_set_auxiliary_variables']);
-        if ~steadystate_flag
-            ys_init = h_set_auxiliary_variables(ys_init,exo_ss,M.params);
-        end
+if length(M.aux_vars) > 0
+    h_set_auxiliary_variables = str2func([M.fname '_set_auxiliary_variables']);
+    if ~steadystate_flag
+        ys_init = h_set_auxiliary_variables(ys_init,exo_ss,M.params);
     end
+end
 
-    if options.ramsey_policy
-        if steadystate_flag
-            % explicit steady state file
-            [ys,params,info] = evaluate_steady_state_file(ys_init,exo_ss,M, ...
-                                                           options,steadystate_check_flag);
-            %test whether it solves model conditional on the instruments
-            resids = evaluate_static_model(ys,exo_ss,params,M,options);
-            n_multipliers=M.ramsey_eq_nbr;
-            nan_indices=find(isnan(resids(n_multipliers+1:end)));
-
-            if ~isempty(nan_indices)
-                if options.debug
-                    fprintf('\nevaluate_steady_state: The steady state file computation for the Ramsey problem resulted in NaNs.\n')
-                    fprintf('evaluate_steady_state: The steady state was computed conditional on the following initial instrument values: \n')
-                    for ii = 1:size(options.instruments,1);
-                        fprintf('\t %s \t %f \n',options.instruments(ii,:),ys_init(strmatch(options.instruments(ii,:),M.endo_names,'exact')))
-                    end
-                    fprintf('evaluate_steady_state: The problem occured in the following equations: \n')
-                    fprintf('\t Equation(s): ')
-                    for ii=1:length(nan_indices)
-                        fprintf('%d, ',nan_indices(ii));
-                    end
-                    skipline();
-                    fprintf('evaluate_steady_state: If those initial values are not admissable, change them using an initval-block.\n')
-                    skipline(2);
-                end
-                info(1) = 84;
-                info(2) = resids'*resids;
-                return;
-            end
-            
-            if any(imag(ys(n_multipliers+1:end)))
-                if options.debug
-                    fprintf('\nevaluate_steady_state: The steady state file computation for the Ramsey problem resulted in complex numbers.\n')
-                    fprintf('evaluate_steady_state: The steady state was computed conditional on the following initial instrument values: \n')
-                    for ii = 1:size(options.instruments,1);
-                        fprintf('\t %s \t %f \n',options.instruments(ii,:),ys_init(strmatch(options.instruments(ii,:),M.endo_names,'exact')))
-                    end
-                    fprintf('evaluate_steady_state: If those initial values are not admissable, change them using an initval-block.\n')
-                    skipline(2);
-                end
-                info(1) = 86;
-                info(2) = resids'*resids;
-                return;
-            end
-
-            if max(abs(resids(n_multipliers+1:end))) > options.solve_tolf %does it solve for all variables except for the Lagrange multipliers
-                if options.debug
-                    fprintf('\nevaluate_steady_state: The steady state file does not solve the steady state for the Ramsey problem.\n')
-                    fprintf('evaluate_steady_state: Conditional on the following instrument values: \n')
-                    for ii = 1:size(options.instruments,1);
-                        fprintf('\t %s \t %f \n',options.instruments(ii,:),ys_init(strmatch(options.instruments(ii,:),M.endo_names,'exact')))
-                    end
-                    fprintf('evaluate_steady_state: the following equations have non-zero residuals: \n')
-                    for ii=n_multipliers+1:M.endo_nbr
-                        if abs(resids(ii)) > options.solve_tolf
-                            fprintf('\t Equation number %d: %f\n',ii-n_multipliers, resids(ii))
-                        end
-                    end
-                    skipline(2);
-                end
-                info(1) = 85;
-                info(2) = resids'*resids;
-                return;
-            end
-        end
-        if options.debug
-            infrow=find(isinf(ys_init));
-            if ~isempty(infrow)
-                fprintf('\nevaluate_steady_state: The initial values for the steady state of the following variables are Inf:\n');
-                for iter=1:length(infrow)
-                    fprintf('%s\n',M.endo_names(infrow(iter),:));
-                end
-            end
-            nanrow=find(isnan(ys_init));
-            if ~isempty(nanrow)
-                fprintf('\nevaluate_steady_state: The initial values for the steady state of the following variables are NaN:\n');
-                for iter=1:length(nanrow)
-                    fprintf('%s\n',M.endo_names(nanrow(iter),:));
-                end
-            end
-        end
-        %either if no steady state file or steady state file without problems
-        [ys,params,info] = dyn_ramsey_static(ys_init,M,options,oo);
-        if info
-           return;
-        end
-        %check whether steady state really solves the model
+if options.ramsey_policy
+    if steadystate_flag
+        % explicit steady state file
+        [ys,params,info] = evaluate_steady_state_file(ys_init,exo_ss,M, ...
+                                                      options,steadystate_check_flag);
+        %test whether it solves model conditional on the instruments
         resids = evaluate_static_model(ys,exo_ss,params,M,options);
-
         n_multipliers=M.ramsey_eq_nbr;
-        nan_indices_multiplier=find(isnan(resids(1:n_multipliers)));
         nan_indices=find(isnan(resids(n_multipliers+1:end)));
 
         if ~isempty(nan_indices)
             if options.debug
-                fprintf('\nevaluate_steady_state: The steady state computation for the Ramsey problem resulted in NaNs.\n')
-                fprintf('evaluate_steady_state: The steady state computation resulted in the following instrument values: \n')
-                for i = 1:size(options.instruments,1);
-                    fprintf('\t %s \t %f \n',options.instruments(i,:),ys(strmatch(options.instruments(i,:),M.endo_names,'exact')))
+                fprintf('\nevaluate_steady_state: The steady state file computation for the Ramsey problem resulted in NaNs.\n')
+                fprintf('evaluate_steady_state: The steady state was computed conditional on the following initial instrument values: \n')
+                for ii = 1:size(options.instruments,1)
+                    fprintf('\t %s \t %f \n',options.instruments(ii,:),ys_init(strmatch(options.instruments(ii,:),M.endo_names,'exact')))
                 end
                 fprintf('evaluate_steady_state: The problem occured in the following equations: \n')
                 fprintf('\t Equation(s): ')
                 for ii=1:length(nan_indices)
                     fprintf('%d, ',nan_indices(ii));
                 end
-                skipline();
+                skipline()
+                fprintf('evaluate_steady_state: If those initial values are not admissable, change them using an initval-block.\n')
+                skipline(2)
             end
-            info(1) = 82;
-            return;
+            info(1) = 84;
+            info(2) = resids'*resids;
+            return
         end
 
-        if ~isempty(nan_indices_multiplier)
+        if any(imag(ys(n_multipliers+1:end)))
             if options.debug
-                fprintf('\nevaluate_steady_state: The steady state computation for the Ramsey problem resulted in NaNs in the auxiliary equations.\n')
-                fprintf('evaluate_steady_state: The steady state computation resulted in the following instrument values: \n')
-                for i = 1:size(options.instruments,1);
-                    fprintf('\t %s \t %f \n',options.instruments(i,:),ys(strmatch(options.instruments(i,:),M.endo_names,'exact')))
+                fprintf('\nevaluate_steady_state: The steady state file computation for the Ramsey problem resulted in complex numbers.\n')
+                fprintf('evaluate_steady_state: The steady state was computed conditional on the following initial instrument values: \n')
+                for ii = 1:size(options.instruments,1)
+                    fprintf('\t %s \t %f \n',options.instruments(ii,:),ys_init(strmatch(options.instruments(ii,:),M.endo_names,'exact')))
                 end
-                fprintf('evaluate_steady_state: The problem occured in the following equations: \n')
-                fprintf('\t Auxiliary equation(s): ')
-                for ii=1:length(nan_indices_multiplier)
-                    fprintf('%d, ',nan_indices_multiplier(ii));
-                end
-                skipline();
+                fprintf('evaluate_steady_state: If those initial values are not admissable, change them using an initval-block.\n')
+                skipline(2)
             end
-            info(1) = 83;
-            return;
+            info(1) = 86;
+            info(2) = resids'*resids;
+            return
         end
 
-        if max(abs(resids)) > options.solve_tolf %does it solve for all variables including the auxiliary ones
+        if max(abs(resids(n_multipliers+1:end))) > options.solve_tolf %does it solve for all variables except for the Lagrange multipliers
             if options.debug
-                fprintf('\nevaluate_steady_state: The steady state for the Ramsey problem could not be computed.\n')
-                fprintf('evaluate_steady_state: The steady state computation stopped with the following instrument values:: \n')
-                for i = 1:size(options.instruments,1);
-                    fprintf('\t %s \t %f \n',options.instruments(i,:),ys(strmatch(options.instruments(i,:),M.endo_names,'exact')))
-                end
-                fprintf('evaluate_steady_state: The following equations have non-zero residuals: \n')
-                for ii=1:n_multipliers
-                    if abs(resids(ii)) > options.solve_tolf/100
-                        fprintf('\t Auxiliary Ramsey equation number %d: %f\n',ii, resids(ii))
-                    end
+                fprintf('\nevaluate_steady_state: The steady state file does not solve the steady state for the Ramsey problem.\n')
+                fprintf('evaluate_steady_state: Conditional on the following instrument values: \n')
+                for ii = 1:size(options.instruments,1)
+                    fprintf('\t %s \t %f \n',options.instruments(ii,:),ys_init(strmatch(options.instruments(ii,:),M.endo_names,'exact')))
                 end
+                fprintf('evaluate_steady_state: the following equations have non-zero residuals: \n')
                 for ii=n_multipliers+1:M.endo_nbr
-                    if abs(resids(ii)) > options.solve_tolf/100
+                    if abs(resids(ii)) > options.solve_tolf
                         fprintf('\t Equation number %d: %f\n',ii-n_multipliers, resids(ii))
                     end
                 end
-                skipline(2);
+                skipline(2)
             end
-            info(1) = 81;
+            info(1) = 85;
             info(2) = resids'*resids;
-            return;
-        end
-    elseif steadystate_flag
-        % explicit steady state file
-        [ys,params,info] = evaluate_steady_state_file(ys_init,exo_ss,M, ...
-                                                       options,steadystate_check_flag);
-        if size(ys,2)>size(ys,1)
-            error('STEADY: steady_state-file must return a column vector, not a row vector.')
+            return
         end
-        if info(1)
-            return;
+    end
+    if options.debug
+        infrow=find(isinf(ys_init));
+        if ~isempty(infrow)
+            fprintf('\nevaluate_steady_state: The initial values for the steady state of the following variables are Inf:\n');
+            for iter=1:length(infrow)
+                fprintf('%s\n',M.endo_names(infrow(iter),:));
+            end
         end
-    elseif (options.bytecode == 0 && options.block == 0)
-        if options.linear == 0
-            % non linear model
-            static_model = str2func([M.fname '_static']);
-            [ys,check] = dynare_solve(@static_problem,...
-                                      ys_init,...
-                                      options, exo_ss, params,...
-                                      M.endo_nbr,...
-                                      static_model);
-            if check && options.debug
-                [ys,check,fvec,fjac] = dynare_solve(@static_problem,...
-                          ys_init,...
-                          options, exo_ss, params,...
-                          M.endo_nbr,...
-                          static_model);
-                [infrow,infcol]=find(isinf(fjac) | isnan(fjac));
-                if ~isempty(infrow)
-                    fprintf('\nSTEADY:  The Jacobian at the initial values contains Inf or NaN. The problem arises from: \n')
-                    display_problematic_vars_Jacobian(infrow,infcol,M,ys_init,'static','STEADY: ')
-                end
-                problematic_equation = find(~isfinite(fvec));                
-                if ~isempty(problematic_equation)
-                    fprintf('\nSTEADY:  numerical initial values or parameters incompatible with the following equations\n')
-                    disp(problematic_equation')
-                    fprintf('Please check for example\n')
-                    fprintf('   i) if all parameters occurring in these equations are defined\n')
-                    fprintf('  ii) that no division by an endogenous variable initialized to 0 occurs\n')
-                end
+        nanrow=find(isnan(ys_init));
+        if ~isempty(nanrow)
+            fprintf('\nevaluate_steady_state: The initial values for the steady state of the following variables are NaN:\n');
+            for iter=1:length(nanrow)
+                fprintf('%s\n',M.endo_names(nanrow(iter),:));
             end
-        else
-            % linear model
-            fh_static = str2func([M.fname '_static']);
-            [fvec,jacob] = fh_static(ys_init,exo_ss, ...
-                                     params);
+        end
+    end
+    %either if no steady state file or steady state file without problems
+    [ys,params,info] = dyn_ramsey_static(ys_init,M,options,oo);
+    if info
+        return
+    end
+    %check whether steady state really solves the model
+    resids = evaluate_static_model(ys,exo_ss,params,M,options);
 
-            ii = find(~isfinite(fvec));
-            if ~isempty(ii)
-                ys=fvec;
-                check=1;
-                disp(['STEADY:  numerical initial values or parameters incompatible with the following' ...
-                      ' equations'])
-                disp(ii')
-                disp('Check whether your model is truly linear. Put "resid(1);" before "steady;" to see the problematic equations.\n')
-            elseif isempty(ii) && max(abs(fvec)) > 1e-12
-                ys = ys_init-jacob\fvec;
-                resid = evaluate_static_model(ys,exo_ss,params,M,options);
-                if max(abs(resid)) > 1e-6
-                    check=1;
-                    fprintf('STEADY: No steady state for your model could be found\n')
-                    fprintf('STEADY: Check whether your model is truly linear. Put "resid(1);" before "steady;" to see the problematic equations.\n')
-                end
+    n_multipliers=M.ramsey_eq_nbr;
+    nan_indices_multiplier=find(isnan(resids(1:n_multipliers)));
+    nan_indices=find(isnan(resids(n_multipliers+1:end)));
 
-            else
-                ys = ys_init;
+    if ~isempty(nan_indices)
+        if options.debug
+            fprintf('\nevaluate_steady_state: The steady state computation for the Ramsey problem resulted in NaNs.\n')
+            fprintf('evaluate_steady_state: The steady state computation resulted in the following instrument values: \n')
+            for i = 1:size(options.instruments,1)
+                fprintf('\t %s \t %f \n',options.instruments(i,:),ys(strmatch(options.instruments(i,:),M.endo_names,'exact')))
             end
-            if options.debug
-                if any(any(isinf(jacob) | isnan(jacob)))
-                    [infrow,infcol]=find(isinf(jacob) | isnan(jacob));
-                    fprintf('\nSTEADY:  The Jacobian contains Inf or NaN. The problem arises from: \n\n')
-                    for ii=1:length(infrow)
-                        fprintf('STEADY:  Derivative of Equation %d with respect to Variable %s  (initial value of %s: %g) \n',infrow(ii),deblank(M.endo_names(infcol(ii),:)),deblank(M.endo_names(infcol(ii),:)),ys_init(infcol(ii)))
-                    end
-                    fprintf('Check whether your model is truly linear. Put "resid(1);" before "steady;" to see the problematic equations.\n')
-                end
+            fprintf('evaluate_steady_state: The problem occured in the following equations: \n')
+            fprintf('\t Equation(s): ')
+            for ii=1:length(nan_indices)
+                fprintf('%d, ',nan_indices(ii));
             end
+            skipline()
         end
-    else
-        % block or bytecode
-        [ys,check] = dynare_solve_block_or_bytecode(ys_init,exo_ss, params, ...
-                                                    options, M);
+        info(1) = 82;
+        return
     end
 
-    if check
-        info(1)= 20;
-        %make sure ys contains auxiliary variables in case of problem with dynare_solve
-        if length(M.aux_vars) > 0 && ~steadystate_flag
-            ys = h_set_auxiliary_variables(ys,exo_ss,M.params);
+    if ~isempty(nan_indices_multiplier)
+        if options.debug
+            fprintf('\nevaluate_steady_state: The steady state computation for the Ramsey problem resulted in NaNs in the auxiliary equations.\n')
+            fprintf('evaluate_steady_state: The steady state computation resulted in the following instrument values: \n')
+            for i = 1:size(options.instruments,1)
+                fprintf('\t %s \t %f \n',options.instruments(i,:),ys(strmatch(options.instruments(i,:),M.endo_names,'exact')))
+            end
+            fprintf('evaluate_steady_state: The problem occured in the following equations: \n')
+            fprintf('\t Auxiliary equation(s): ')
+            for ii=1:length(nan_indices_multiplier)
+                fprintf('%d, ',nan_indices_multiplier(ii));
+            end
+            skipline()
         end
-        resid = evaluate_static_model(ys,exo_ss,params,M,options);
-        info(2) = resid'*resid ;
-        if isnan(info(2))
-            info(1)=22;
+        info(1) = 83;
+        return
+    end
+
+    if max(abs(resids)) > options.solve_tolf %does it solve for all variables including the auxiliary ones
+        if options.debug
+            fprintf('\nevaluate_steady_state: The steady state for the Ramsey problem could not be computed.\n')
+            fprintf('evaluate_steady_state: The steady state computation stopped with the following instrument values:: \n')
+            for i = 1:size(options.instruments,1)
+                fprintf('\t %s \t %f \n',options.instruments(i,:),ys(strmatch(options.instruments(i,:),M.endo_names,'exact')))
+            end
+            fprintf('evaluate_steady_state: The following equations have non-zero residuals: \n')
+            for ii=1:n_multipliers
+                if abs(resids(ii)) > options.solve_tolf/100
+                    fprintf('\t Auxiliary Ramsey equation number %d: %f\n',ii, resids(ii))
+                end
+            end
+            for ii=n_multipliers+1:M.endo_nbr
+                if abs(resids(ii)) > options.solve_tolf/100
+                    fprintf('\t Equation number %d: %f\n',ii-n_multipliers, resids(ii))
+                end
+            end
+            skipline(2)
         end
+        info(1) = 81;
+        info(2) = resids'*resids;
+        return
+    end
+elseif steadystate_flag
+    % explicit steady state file
+    [ys,params,info] = evaluate_steady_state_file(ys_init,exo_ss,M, options,steadystate_check_flag);
+    if size(ys,2)>size(ys,1)
+        error('STEADY: steady_state-file must return a column vector, not a row vector.')
+    end
+    if info(1)
         return
     end
+elseif (options.bytecode == 0 && options.block == 0)
+    if options.linear == 0
+        % non linear model
+        static_model = str2func([M.fname '_static']);
+        [ys,check] = dynare_solve(@static_problem,...
+                                  ys_init,...
+                                  options, exo_ss, params,...
+                                  M.endo_nbr,...
+                                  static_model);
+        if check && options.debug
+            [ys,check,fvec,fjac] = dynare_solve(@static_problem,...
+                                                ys_init,...
+                                                options, exo_ss, params,...
+                                                M.endo_nbr,...
+                                                static_model);
+            [infrow,infcol]=find(isinf(fjac) | isnan(fjac));
+            if ~isempty(infrow)
+                fprintf('\nSTEADY:  The Jacobian at the initial values contains Inf or NaN. The problem arises from: \n')
+                display_problematic_vars_Jacobian(infrow,infcol,M,ys_init,'static','STEADY: ')
+            end
+            problematic_equation = find(~isfinite(fvec));
+            if ~isempty(problematic_equation)
+                fprintf('\nSTEADY:  numerical initial values or parameters incompatible with the following equations\n')
+                disp(problematic_equation')
+                fprintf('Please check for example\n')
+                fprintf('   i) if all parameters occurring in these equations are defined\n')
+                fprintf('  ii) that no division by an endogenous variable initialized to 0 occurs\n')
+            end
+        end
+    else
+        % linear model
+        fh_static = str2func([M.fname '_static']);
+        [fvec,jacob] = fh_static(ys_init,exo_ss, ...
+                                 params);
 
-    % If some equations are tagged [static] or [dynamic], verify consistency
-    if M.static_and_dynamic_models_differ
-        % Evaluate residual of *dynamic* model using the steady state
-        % computed on the *static* one
-        z = repmat(ys,1,M.maximum_lead + M.maximum_lag + 1);
-        zx = repmat([exo_ss'], M.maximum_lead + M.maximum_lag + 1, 1);
-        if options.bytecode
-            [chck, r, junk]= bytecode('dynamic','evaluate', z, zx, M.params, ys, 1);
-            mexErrCheck('bytecode', chck);
-        elseif options.block
-            [r, oo.dr] = feval([M.fname '_dynamic'], z', zx, M.params, ys, M.maximum_lag+1, oo.dr);
+        ii = find(~isfinite(fvec));
+        if ~isempty(ii)
+            ys=fvec;
+            check=1;
+            disp(['STEADY:  numerical initial values or parameters incompatible with the following' ...
+                  ' equations'])
+            disp(ii')
+            disp('Check whether your model is truly linear. Put "resid(1);" before "steady;" to see the problematic equations.')
+        elseif isempty(ii) && max(abs(fvec)) > 1e-12
+            ys = ys_init-jacob\fvec;
+            resid = evaluate_static_model(ys,exo_ss,params,M,options);
+            if max(abs(resid)) > 1e-6
+                check=1;
+                fprintf('STEADY: No steady state for your model could be found\n')
+                fprintf('STEADY: Check whether your model is truly linear. Put "resid(1);" before "steady;" to see the problematic equations.\n')
+            end
         else
-            iyv = M.lead_lag_incidence';
-            iyr0 = find(iyv(:));
-            xys = z(iyr0);
-            r = feval([M.fname '_dynamic'], z(iyr0), zx, M.params, ys, M.maximum_lag + 1);
+            ys = ys_init;
         end
-
-        % Fail if residual greater than tolerance
-        if max(abs(r)) > options.solve_tolf
-            info(1) = 25;
-            return
+        if options.debug
+            if any(any(isinf(jacob) | isnan(jacob)))
+                [infrow,infcol]=find(isinf(jacob) | isnan(jacob));
+                fprintf('\nSTEADY:  The Jacobian contains Inf or NaN. The problem arises from: \n\n')
+                for ii=1:length(infrow)
+                    fprintf('STEADY:  Derivative of Equation %d with respect to Variable %s  (initial value of %s: %g) \n',infrow(ii),deblank(M.endo_names(infcol(ii),:)),deblank(M.endo_names(infcol(ii),:)),ys_init(infcol(ii)))
+                end
+                fprintf('Check whether your model is truly linear. Put "resid(1);" before "steady;" to see the problematic equations.\n')
+            end
         end
     end
+else
+    % block or bytecode
+    [ys,check] = dynare_solve_block_or_bytecode(ys_init,exo_ss, params, options, M);
+end
 
-    if ~isreal(ys)
-        info(1) = 21;
-        info(2) = sum(imag(ys).^2);
-        ys = real(ys);
-        return
+if check
+    info(1)= 20;
+    %make sure ys contains auxiliary variables in case of problem with dynare_solve
+    if length(M.aux_vars) > 0 && ~steadystate_flag
+        ys = h_set_auxiliary_variables(ys,exo_ss,M.params);
     end
+    resid = evaluate_static_model(ys,exo_ss,params,M,options);
+    info(2) = resid'*resid ;
+    if isnan(info(2))
+        info(1)=22;
+    end
+    return
+end
 
-    if ~isempty(find(isnan(ys)))
-        info(1) = 22;
-        info(2) = NaN;
+% If some equations are tagged [static] or [dynamic], verify consistency
+if M.static_and_dynamic_models_differ
+    % Evaluate residual of *dynamic* model using the steady state
+    % computed on the *static* one
+    z = repmat(ys,1,M.maximum_lead + M.maximum_lag + 1);
+    zx = repmat([exo_ss'], M.maximum_lead + M.maximum_lag + 1, 1);
+    if options.bytecode
+        [chck, r, junk]= bytecode('dynamic','evaluate', z, zx, M.params, ys, 1);
+        mexErrCheck('bytecode', chck);
+    elseif options.block
+        [r, oo.dr] = feval([M.fname '_dynamic'], z', zx, M.params, ys, M.maximum_lag+1, oo.dr);
+    else
+        iyv = M.lead_lag_incidence';
+        iyr0 = find(iyv(:));
+        xys = z(iyr0);
+        r = feval([M.fname '_dynamic'], z(iyr0), zx, M.params, ys, M.maximum_lag + 1);
+    end
+    % Fail if residual greater than tolerance
+    if max(abs(r)) > options.solve_tolf
+        info(1) = 25;
         return
     end
+end
+
+if ~isreal(ys)
+    info(1) = 21;
+    info(2) = sum(imag(ys).^2);
+    ys = real(ys);
+    return
+end
+
+if ~isempty(find(isnan(ys)))
+    info(1) = 22;
+    info(2) = NaN;
+    return
+end
 
 function [resids,jac] = static_problem(y,x,params,nvar,fh_static_model)
-    [r,j] = fh_static_model(y,x,params);
-    resids = r(1:nvar);
-    jac = j(1:nvar,1:nvar);
+[r,j] = fh_static_model(y,x,params);
+resids = r(1:nvar);
+jac = j(1:nvar,1:nvar);
diff --git a/matlab/evaluate_steady_state_file.m b/matlab/evaluate_steady_state_file.m
index 8f67a5b87de4cee0f022ccd38a08bb6d8828ab7c..67a3b0c4dfe5f13a3d1b833b77fdd5b6f94c174a 100644
--- a/matlab/evaluate_steady_state_file.m
+++ b/matlab/evaluate_steady_state_file.m
@@ -1,14 +1,14 @@
 function [ys,params,info] = evaluate_steady_state_file(ys_init,exo_ss,M,options,steady_state_checkflag)
 % function [ys,params1,info] = evaluate_steady_state_file(ys_init,exo_ss,M,options,steady_state_checkflag)
-% Evaluates steady state files 
-%  
+% Evaluates steady state files
+%
 % INPUTS
 %   ys_init                   vector           initial values used to compute the steady
 %                                                 state
 %   exo_ss                    vector           exogenous steady state
 %   M                         struct           model parameters
 %   options                   struct           options
-%   steady_state_checkflag    boolean          indicator whether to check steady state returned  
+%   steady_state_checkflag    boolean          indicator whether to check steady state returned
 % OUTPUTS
 %   ys                        vector           steady state
 %   params1                   vector           model parameters possibly
@@ -19,7 +19,7 @@ function [ys,params,info] = evaluate_steady_state_file(ys_init,exo_ss,M,options,
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2001-2016 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -36,125 +36,123 @@ function [ys,params,info] = evaluate_steady_state_file(ys_init,exo_ss,M,options,
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-    debug = false;
+debug = false;
 
-    ys = [];
-    params = M.params;
-    info = 0;
+ys = [];
+params = M.params;
+info = 0;
 
-    fname = M.fname;
+fname = M.fname;
 
-    if options.steadystate_flag == 1
-        % old format
-        assignin('base','tmp_00_',params);
-        evalin('base','M_.params=tmp_00_; clear(''tmp_00_'')');
-        h_steadystate = str2func([fname '_steadystate']);                       
-        [ys,check] = h_steadystate(ys_init, exo_ss);
-        params1 = evalin('base','M_.params');
-    else % steadystate_flag == 2
-         % new format
-        h_steadystate = str2func([fname '_steadystate2']);                       
-        [ys,params1,check] = h_steadystate(ys_init, exo_ss, params);
-    end            
-    
-    if check
-        info(1) = 19;
-        info(2) = NaN;
-        return
-    end
-    
-    if M.param_nbr > 0
-        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;
-    end
+if options.steadystate_flag == 1
+    % old format
+    assignin('base','tmp_00_',params);
+    evalin('base','M_.params=tmp_00_; clear(''tmp_00_'')');
+    h_steadystate = str2func([fname '_steadystate']);
+    [ys,check] = h_steadystate(ys_init, exo_ss);
+    params1 = evalin('base','M_.params');
+else % steadystate_flag == 2
+     % new format
+    h_steadystate = str2func([fname '_steadystate2']);
+    [ys,params1,check] = h_steadystate(ys_init, exo_ss, params);
+end
 
-    h_set_auxiliary_variables = str2func([M.fname '_set_auxiliary_variables']);
-    if  isnan(updated_params_flag) || (updated_params_flag  && any(isnan(params(~isnan(params))-params1(~isnan(params))))) %checks if new NaNs were added
-        info(1) = 24;
-        info(2) = NaN;
-        ys = h_set_auxiliary_variables(ys,exo_ss,params);
-        return
-    end
+if check
+    info(1) = 19;
+    info(2) = NaN;
+    return
+end
 
-    if updated_params_flag && ~isreal(params1)
-        info(1) = 23;
-        info(2) = sum(imag(params).^2);
-        ys = h_set_auxiliary_variables(ys,exo_ss,params);
-        return
+if M.param_nbr > 0
+    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;
+end
+
+h_set_auxiliary_variables = str2func([M.fname '_set_auxiliary_variables']);
+if  isnan(updated_params_flag) || (updated_params_flag  && any(isnan(params(~isnan(params))-params1(~isnan(params))))) %checks if new NaNs were added
+    info(1) = 24;
+    info(2) = NaN;
+    ys = h_set_auxiliary_variables(ys,exo_ss,params);
+    return
+end
+
+if updated_params_flag && ~isreal(params1)
+    info(1) = 23;
+    info(2) = sum(imag(params).^2);
+    ys = h_set_auxiliary_variables(ys,exo_ss,params);
+    return
+end
+
+if updated_params_flag
+    params = params1;
+end
+
+% adding values for auxiliary variables
+if length(M.aux_vars) > 0 && ~options.ramsey_policy
+    if debug
+        ys0 = ys;
     end
-    
-    if updated_params_flag
-        params = params1;
+    ys = h_set_auxiliary_variables(ys,exo_ss,params);
+    if debug
+        ys1 = ys;
     end
-
-    % adding values for auxiliary variables
-    if length(M.aux_vars) > 0 && ~options.ramsey_policy
-        if debug
-            ys0 = ys;
-        end
+    ys = h_set_auxiliary_variables(ys,exo_ss,params);
+    if debug
+        ys2 = ys;
+    end
+    if debug
         ys = h_set_auxiliary_variables(ys,exo_ss,params);
-        if debug
-            ys1 = ys;
+        ys3 = ys;
+        idx = find(abs(ys0-ys1)>0);
+        if ~isempty(idx)
+            M.endo_names(idx,:)
+        else
+            disp('1-invariant')
         end
-        ys = h_set_auxiliary_variables(ys,exo_ss,params);
-        if debug
-            ys2 = ys;
+        idx = find(abs(ys2-ys1)>0);
+        if ~isempty(idx)
+            M.endo_names(idx,:)
+        else
+            disp('2-invariant')
         end
-        if debug
-            ys = h_set_auxiliary_variables(ys,exo_ss,params);
-            ys3 = ys;
-            idx = find(abs(ys0-ys1)>0);
-            if ~isempty(idx)
-                M.endo_names(idx,:)
-            else
-                disp('1-invariant')
-            end
-            idx = find(abs(ys2-ys1)>0);
-            if ~isempty(idx)
-                M.endo_names(idx,:)
-            else
-                disp('2-invariant')
-            end
-            idx = find(abs(ys3-ys3)>0);
-            if ~isempty(idx)
-                M.endo_names(idx,:)
-            else
-                disp('3-invariant')
-            end
-            pause
+        idx = find(abs(ys3-ys3)>0);
+        if ~isempty(idx)
+            M.endo_names(idx,:)
+        else
+            disp('3-invariant')
         end
+        pause
     end
+end
 
-    check1 = 0;
-    if steady_state_checkflag
-        % Check whether the steady state obtained from the _steadystate file is a steady state.
-        [residuals, check] = evaluate_static_model(ys, exo_ss, params, M, options);
-        if check
-            info(1) = 19;
-            info(2) = check; % to be improved
-            return;
-        end
-        if max(abs(residuals)) > options.dynatol.f
-            info(1) = 19;
-            info(2) = residuals'*residuals;
-            return
-        end
-        if any(isnan(residuals))
-            info(1) = 22;
-            return
-        end
-    elseif ~isempty(options.steadystate_partial)
-        ssvar = options.steadystate_partial.ssvar;
-        nov   = length(ssvar);
-        indv  = zeros(nov,1);
-        for i = 1:nov
-            indv(i) = strmatch(ssvar(i),M.endo_names,'exact');
-        end
-        [ys,check] = dynare_solve('restricted_steadystate',...
-                                  ys(indv),...
-                                  options, exo_ss,indv);
+check1 = 0;
+if steady_state_checkflag
+    % Check whether the steady state obtained from the _steadystate file is a steady state.
+    [residuals, check] = evaluate_static_model(ys, exo_ss, params, M, options);
+    if check
+        info(1) = 19;
+        info(2) = check; % to be improved
+        return
     end
-
-    
+    if max(abs(residuals)) > options.dynatol.f
+        info(1) = 19;
+        info(2) = residuals'*residuals;
+        return
+    end
+    if any(isnan(residuals))
+        info(1) = 22;
+        return
+    end
+elseif ~isempty(options.steadystate_partial)
+    ssvar = options.steadystate_partial.ssvar;
+    nov   = length(ssvar);
+    indv  = zeros(nov,1);
+    for i = 1:nov
+        indv(i) = strmatch(ssvar(i),M.endo_names,'exact');
+    end
+    [ys,check] = dynare_solve('restricted_steadystate',...
+                              ys(indv),...
+                              options, exo_ss,indv);
+end
diff --git a/matlab/expand_group.m b/matlab/expand_group.m
new file mode 100644
index 0000000000000000000000000000000000000000..c20d38c37ca0429179b72d3377e6d4b3860d64a7
--- /dev/null
+++ b/matlab/expand_group.m
@@ -0,0 +1,49 @@
+function expand_group(use_shock_groups,var_list_, ic)
+% function expand_group(use_shock_groups,var_list_, ic)
+% Expands shocks contributions out of a group of shocks
+%
+% INPUTS
+%    use_shock_groups: [char]  name of the group
+%    var_list_:        [char]  list of variables
+%    ic:               [int]   group # to expand
+%
+% SPECIAL REQUIREMENTS
+%    none
+
+% Copyright (C) 2016-2017 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/>.
+
+M = evalin('base','M_');
+oo = evalin('base','oo_');
+options = evalin('base','options_');
+mydata=get(findobj(gcf,'tag',['group' int2str(ic)]),'userdata');
+if isfield(mydata,'shock_decomp')
+    options.shock_decomp=mydata.shock_decomp;
+end
+% define expanded group
+label = mydata.shock_group.label;
+shocks = mydata.shock_group.shocks;
+options.shock_decomp.fig_name = [mydata.fig_name '. Expand'];
+options.use_shock_groups = strrep(label,' ','_'); %[use_shock_groups_old int2str(ic)];
+for j=1:length(shocks)
+    M.shock_groups.(options.use_shock_groups).(['group' int2str(j)]).label=shocks{j};
+    M.shock_groups.(options.use_shock_groups).(['group' int2str(j)]).shocks=shocks(j);
+end
+
+options.shock_decomp.interactive=0;
+options.shock_decomp.expand=1;
+plot_shock_decomposition(M,oo,options,var_list_);
diff --git a/matlab/fastgensylv.m b/matlab/fastgensylv.m
index 332e46f2829c6cc635028aee5c56c04fdeba4c62..a8e6e386f19282f162b8811a489c0da3046b2e82 100644
--- a/matlab/fastgensylv.m
+++ b/matlab/fastgensylv.m
@@ -39,7 +39,7 @@ function X = fastgensylv(A, B, C, D, tol,maxit,X0)
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -95,19 +95,19 @@ end
 %   B
 %   C
 %   D
-%   block : block number (for storage purpose) 
+%   block : block number (for storage purpose)
 %   tol : convergence criteria
 % OUTPUTS
 %   X solution
-%    
+%
 % ALGORITHM
 %   fixed point method
 %   MARLLINY MONSALVE (2008): "Block linear method for large scale
-%   Sylvester equations", Computational & Applied Mathematics, Vol 27, n�1,
+%   Sylvester equations", Computational & Applied Mathematics, Vol 27, n°1,
 %   p47-59
 %   ||A^-1||.||B||.||C|| < 1 is a suffisant condition:
 %    - to get a unique solution for the Sylvester equation
 %    - to get a convergent fixed-point algorithm
 %
 % SPECIAL REQUIREMENTS
-%   none.  
+%   none.
diff --git a/matlab/ff1_.m b/matlab/ff1_.m
index 4b6b666cef9c959abfabcc796e81eb9b68449274..1ed766d95ef0ad2967c79cccccf393cec1fcfc29 100644
--- a/matlab/ff1_.m
+++ b/matlab/ff1_.m
@@ -5,14 +5,14 @@ function y=ff1_(x)
 %
 % INPUTS
 %    x:          argument splitted between endogenous and exogenous
-%        
+%
 % OUTPUTS
 %    y:         'static' function residuals
-%        
+%
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2001-2008 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -35,6 +35,3 @@ n1 = size(x,1) - M_.exo_nbr;
 oo_.exo_simul(it_+M_.maximum_lag-M_.maximum_lag,:) = x(n1+1:end)';
 fh = str2func([M_.fname '_static']);
 y=feval(fh,x(1:n1),oo_.exo_simul, M_.params);
-
-
-
diff --git a/matlab/ffill.m b/matlab/ffill.m
index fc72c9f9f7a8cbaaab2cf168e81afa2db14f4101..cb8f0d3216ca95705512cc70bb4255fc6e118e91 100644
--- a/matlab/ffill.m
+++ b/matlab/ffill.m
@@ -7,15 +7,15 @@ function [a,b] = ffill(x,ixc,y)
 %    x:         matrix
 %    ixc:       vector of indices
 %    y:         matrix
-%        
+%
 % OUTPUTS
 %    a:         concatenation results
 %    b:         vector
-%        
+%
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2001-2009 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/fjaco.m b/matlab/fjaco.m
index 5217ca93a1e969b39ce25603d72623faff434e19..5f5de07834aa0f6668ceb4cab6e853795ad6bf0e 100644
--- a/matlab/fjaco.m
+++ b/matlab/fjaco.m
@@ -10,7 +10,7 @@ function fjac = fjaco(f,x,varargin)
 % OUTPUT
 %   fjac      : finite differnce Jacobian
 %
-% Copyright (C) 2010 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -34,7 +34,7 @@ h = tol.*max(abs(x),1);
 xh1=x+h; xh0=x-h;
 h=xh1-xh0;
 fjac = NaN(length(ff),length(x));
-for j=1:length(x);
+for j=1:length(x)
     xx = x;
     xx(j) = xh1(j); f1=feval(f,xx,varargin{:});
     xx(j) = xh0(j); f0=feval(f,xx,varargin{:});
diff --git a/matlab/flip_plan.m b/matlab/flip_plan.m
index a5a0952a9fd8cc4ef1ee97f43dbfe75853b7237b..5daf19fc7dc76edebb41eb91b61092df175c320f 100644
--- a/matlab/flip_plan.m
+++ b/matlab/flip_plan.m
@@ -15,7 +15,7 @@ function plan = flip_plan(plan, exogenous, endogenous, expectation_type, date, v
 %  plan                   [structure]        Returns a structure containing the updated forecast scenario.
 %
 %
-% Copyright (C) 2013-2014 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -31,71 +31,71 @@ function plan = flip_plan(plan, exogenous, endogenous, expectation_type, date, v
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
-  if ~ischar(expectation_type) || size(expectation_type,1) ~= 1
-      error(['in flip_plan the fourth argument should be a string containing the simulation type (''perfect_foresight'' or ''surprise'')']);
-  end
-  exogenous = strtrim(exogenous);
-  ix = find(strcmp(exogenous, plan.endo_names));
-  if  isempty(ix)
-      error(['in flip_plan the second argument ' exogenous ' is not an endogenous variable']);
-  end;
-  endogenous = strtrim(endogenous);
-  iy = find(strcmp(endogenous, plan.exo_names));
-  if  isempty(iy)
-      error(['in flip_plan the third argument ' endogenous ' is not an exogenous variable']);
-  end;
-  sdate = length(date);
-  if sdate > 1
-      if date(1) < plan.date(1) || date(end) > plan.date(end)
-          error(['in flip_plan the fifth argument (date='  date ') must lay inside the plan.date ' plan.date]);
-      end
-  else
-      if date < plan.date(1) || date > plan.date(end)
-          error(['in flip_plan the fifth argument (date='  date ') must lay iside the plan.date ' plan.date]);
-      end
-  end
-  if ~isempty(plan.shock_vars_)
-      common_var = find(iy == plan.shock_vars_);
-      if ~isempty(common_var)
-          common_date = intersect(date, plan.shock_date_{common_var});
-          if ~isempty(common_date)
-              if common_date.length > 1
-                  the_dates = [cell2mat(strings(common_date(1))) ':' cell2mat(strings(common_date(end)))];
-              else
-                  the_dates = cell2mat(strings(common_date));
-              end
-              error(['Impossible case: ' plan.exo_names{plan.shock_vars_(common_var)} ' is used both as a shock and as an endogenous variable to control the path of ' plan.endo_names{ix} ' at the dates ' the_dates]);
-          end
-      end
-  end
-  i_ix = find(ix == plan.constrained_vars_);
-  if isempty(i_ix)
+if ~ischar(expectation_type) || size(expectation_type,1) ~= 1
+    error(['in flip_plan the fourth argument should be a string containing the simulation type (''perfect_foresight'' or ''surprise'')']);
+end
+exogenous = strtrim(exogenous);
+ix = find(strcmp(exogenous, plan.endo_names));
+if  isempty(ix)
+    error(['in flip_plan the second argument ' exogenous ' is not an endogenous variable']);
+end
+endogenous = strtrim(endogenous);
+iy = find(strcmp(endogenous, plan.exo_names));
+if  isempty(iy)
+    error(['in flip_plan the third argument ' endogenous ' is not an exogenous variable']);
+end
+sdate = length(date);
+if sdate > 1
+    if date(1) < plan.date(1) || date(end) > plan.date(end)
+        error(['in flip_plan the fifth argument (date='  date ') must lay inside the plan.date ' plan.date]);
+    end
+else
+    if date < plan.date(1) || date > plan.date(end)
+        error(['in flip_plan the fifth argument (date='  date ') must lay iside the plan.date ' plan.date]);
+    end
+end
+if ~isempty(plan.shock_vars_)
+    common_var = find(iy == plan.shock_vars_);
+    if ~isempty(common_var)
+        common_date = intersect(date, plan.shock_date_{common_var});
+        if ~isempty(common_date)
+            if common_date.length > 1
+                the_dates = [cell2mat(strings(common_date(1))) ':' cell2mat(strings(common_date(end)))];
+            else
+                the_dates = cell2mat(strings(common_date));
+            end
+            error(['Impossible case: ' plan.exo_names{plan.shock_vars_(common_var)} ' is used both as a shock and as an endogenous variable to control the path of ' plan.endo_names{ix} ' at the dates ' the_dates]);
+        end
+    end
+end
+i_ix = find(ix == plan.constrained_vars_);
+if isempty(i_ix)
     if isempty(plan.constrained_vars_)
-       plan.constrained_vars_ = ix;
-       plan.options_cond_fcst_.controlled_varexo  = iy;
-       if strcmp(expectation_type, 'perfect_foresight')
-          plan.constrained_perfect_foresight_ = 1;
-       else
-          plan.constrained_perfect_foresight_ = 0;
-       end
+        plan.constrained_vars_ = ix;
+        plan.options_cond_fcst_.controlled_varexo  = iy;
+        if strcmp(expectation_type, 'perfect_foresight')
+            plan.constrained_perfect_foresight_ = 1;
+        else
+            plan.constrained_perfect_foresight_ = 0;
+        end
     else
-       plan.constrained_vars_ = [plan.constrained_vars_ ; ix];
-       plan.options_cond_fcst_.controlled_varexo  = [plan.options_cond_fcst_.controlled_varexo ; iy];
-       if strcmp(expectation_type, 'perfect_foresight')
-          plan.constrained_perfect_foresight_ = [plan.constrained_perfect_foresight_ ; 1];
-       else
-          plan.constrained_perfect_foresight_ = [plan.constrained_perfect_foresight_ ; 0];
-       end
+        plan.constrained_vars_ = [plan.constrained_vars_ ; ix];
+        plan.options_cond_fcst_.controlled_varexo  = [plan.options_cond_fcst_.controlled_varexo ; iy];
+        if strcmp(expectation_type, 'perfect_foresight')
+            plan.constrained_perfect_foresight_ = [plan.constrained_perfect_foresight_ ; 1];
+        else
+            plan.constrained_perfect_foresight_ = [plan.constrained_perfect_foresight_ ; 0];
+        end
     end
     plan.constrained_date_{length(plan.constrained_date_) + 1} = date;
     plan.constrained_str_date_{length(plan.constrained_str_date_) + 1} = strings(date);
     plan.constrained_int_date_{length(plan.constrained_int_date_) + 1} = date - plan.date(1) + 1;
     plan.constrained_paths_{length(plan.constrained_paths_) + 1} = value;
-  elseif plan.options_cond_fcst_.controlled_varexo(i_ix) == iy % same exogenous and endogenous hard tune
-    [plan.constrained_str_date_{i_ix}, i1, i2] = union(strings(date), plan.constrained_str_date_{i_ix});
-    plan.constrained_date_{i_ix} = [date(i1) plan.constrained_date_{i_ix}(i2)];
-    plan.constrained_int_date_{i_ix} = [date(i1) - plan.date(1) + 1; plan.constrained_int_date_{i_ix}(i2)];
-    plan.constrained_paths_{i_ix} = [value(i1)'; plan.constrained_paths_{i_ix}(i2)];
-  else
+elseif plan.options_cond_fcst_.controlled_varexo(i_ix) == iy % same exogenous and endogenous hard tune
+[plan.constrained_str_date_{i_ix}, i1, i2] = union(strings(date), plan.constrained_str_date_{i_ix});
+plan.constrained_date_{i_ix} = [date(i1) plan.constrained_date_{i_ix}(i2)];
+plan.constrained_int_date_{i_ix} = [date(i1) - plan.date(1) + 1; plan.constrained_int_date_{i_ix}(i2)];
+plan.constrained_paths_{i_ix} = [value(i1)'; plan.constrained_paths_{i_ix}(i2)];
+else
     error(['impossible case you have two conditional forecasts:\n - one involving ' plan.endo_names{plan.options_cond_fcst_.controlled_varexo(i_ix),:} ' as control and ' plan_exo_names{plan.constrained_vars_(ix_)} ' as constrined endogenous\n - the other involving  ' plan.endo_names{plan.options_cond_fcst_.controlled_varexo(iy),:} ' as control and ' plan_exo_names{plan.constrained_vars_(ix)} ' as constrined endogenous\n']);
-  end 
+end
diff --git a/matlab/forcst.m b/matlab/forcst.m
index 9c7654ae62d8b6b416ab91fe3b57797c95cf31ca..d760ca892f04b51f56730af93538ccf05770cf26 100644
--- a/matlab/forcst.m
+++ b/matlab/forcst.m
@@ -1,7 +1,7 @@
 function [yf,int_width,int_width_ME]=forcst(dr,y0,horizon,var_list,M_,oo_,options_)
 % function [yf,int_width,int_width_ME]=forecst(dr,y0,horizon,var_list,M_,oo_,options_)
 %   computes mean forecast for a given value of the parameters
-%   computes also confidence band for the forecast    
+%   computes also confidence band for the forecast
 %
 % INPUTS:
 %   dr:          structure containing decision rules
@@ -22,7 +22,7 @@ function [yf,int_width,int_width_ME]=forcst(dr,y0,horizon,var_list,M_,oo_,option
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2016 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -67,7 +67,7 @@ ghx1 = dr.ghx(inv_order_var(ivar),:);
 ghu1 = dr.ghu(inv_order_var(ivar),:);
 
 %initialize recursion
-sigma_u = B*M_.Sigma_e*B'; 
+sigma_u = B*M_.Sigma_e*B';
 sigma_u1 = ghu1*M_.Sigma_e*ghu1';
 sigma_y = 0; %no uncertainty about the states
 
diff --git a/matlab/forcst2.m b/matlab/forcst2.m
index 43c2b4c4e99332f43fc0726b32ef6adc64b795c6..1c0d91b249fa68128955b00afbe2be42f370f902 100644
--- a/matlab/forcst2.m
+++ b/matlab/forcst2.m
@@ -1,6 +1,6 @@
 function yf=forcst2(y0,horizon,dr,n)
 % function yf=forcst2(y0,horizon,dr,n)
-% 
+%
 % computes forecasts based on first order model solution, given shocks
 % drawn from the shock distribution, but not including measurement error
 % Inputs:
@@ -11,8 +11,8 @@ function yf=forcst2(y0,horizon,dr,n)
 %
 % Outputs:
 %   - yf        [horizon+ykmin_ by endo_nbr by n]   array of forecasts
-% 
-% Copyright (C) 2008-2016 Dynare Team
+%
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -64,4 +64,4 @@ for i=ykmin_+(1:horizon)
 end
 
 yf(dr.order_var,:,:) = yf;
-yf=permute(yf,[2 1 3]);  
+yf=permute(yf,[2 1 3]);
diff --git a/matlab/forcst2a.m b/matlab/forcst2a.m
index 16fcdc143daed2867b2f60a4c8d00cd520443d21..bbac43b71c6e90fb1b0f44767050f693ace59fd6 100644
--- a/matlab/forcst2a.m
+++ b/matlab/forcst2a.m
@@ -1,6 +1,6 @@
 function yf=forcst2a(y0,dr,e)
 % function yf=forcst2a(y0,dr,e)
-% computes forecasts based on first order model solution, assuming the absence of shocks 
+% computes forecasts based on first order model solution, assuming the absence of shocks
 % Inputs:
 %   - y0        [endo_nbr by maximum_endo_lag]          matrix of starting values
 %   - dr        [structure]                             structure with Dynare decision rules
@@ -9,7 +9,7 @@ function yf=forcst2a(y0,dr,e)
 % Outputs:
 %   - yf        [horizon+maximum_endo_lag,endo_nbr]               matrix of forecasts
 %
-% Copyright (C) 2008-2015 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -48,4 +48,3 @@ for i=ykmin_+(1:horizon)
 end
 
 yf(:,dr.order_var) = yf;
-
diff --git a/matlab/forecast_graphs.m b/matlab/forecast_graphs.m
index be6f49399145e4041387784e8c8e6986bdc00009..5631ff4b4d4e2a738ed8d1a1d2074862d8db5322 100644
--- a/matlab/forecast_graphs.m
+++ b/matlab/forecast_graphs.m
@@ -1,14 +1,14 @@
 function forecast_graphs(var_list,M_, oo_,options_)
 % function forecast_graphs(var_list,M_, oo_,options_)
 % Plots the classical forecasts created by dyn_forecast.m
-% 
+%
 % Inputs:
 %   o var_list              character array with variable names
 %   o M_                    model structure
 %   o oo_                   outputs structure
 %   o options_              options structure
 
-% Copyright (C) 2008-2016 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -61,10 +61,10 @@ end
 
 m = 1;
 n_fig = 1;
-hh=dyn_figure(options_,'Name','Forecasts (I)');
+hh=dyn_figure(options_.nodisplay,'Name','Forecasts (I)');
 for j= 1:nvar
-    if m > nc*nr; 
-        dyn_saveas(hh,[ dname '/graphs/forcst' int2str(n_fig)],options_);
+    if m > nc*nr
+        dyn_saveas(hh,[ dname '/graphs/forcst' int2str(n_fig)],options_.nodisplay,options_.graph_format);
         if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
             fprintf(fidTeX,'\\begin{figure}[H]\n');
             fprintf(fidTeX,'\\centering \n');
@@ -73,15 +73,15 @@ for j= 1:nvar
             fprintf(fidTeX,'\\caption{Mean forecasts and %2.0f\\%% confidence intervals}\n',options_.forecasts.conf_sig*100);
             fprintf(fidTeX,'\\end{figure}\n');
             fprintf(fidTeX,' \n');
-        end       
+        end
         n_fig =n_fig+1;
-        eval(['hh=dyn_figure(options_,''Name'',''Forecasts (' int2str(n_fig) ')'');']);
+        eval(['hh=dyn_figure(options_.nodisplay,''Name'',''Forecasts (' int2str(n_fig) ')'');']);
         m = 1;
     end
     subplot(nr,nc,m);
     vn = deblank(endo_names(i_var(j),:));
     obs = 0;
-% $$$         k = strmatch(vn,varobs,'exact'); 
+% $$$         k = strmatch(vn,varobs,'exact');
 % $$$   if ~isempty(k)
 % $$$       yy = y.(vn)(end-9:end) + repmat(ys(i_var(j)),10,1)+trend(k,:)';
 % $$$       plot(yy);
@@ -100,7 +100,7 @@ for j= 1:nvar
 end
 
 if m > 1
-    dyn_saveas(hh,[dname '/graphs/forcst' int2str(n_fig)],options_);
+    dyn_saveas(hh,[dname '/graphs/forcst' int2str(n_fig)],options_.nodisplay,options_.graph_format);
     if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
         fprintf(fidTeX,'\\begin{figure}[H]\n');
         fprintf(fidTeX,'\\centering \n');
@@ -118,17 +118,17 @@ end
 
 if isfield(oo_.forecast,'HPDinf_ME')
     var_names=fieldnames(oo_.forecast.HPDinf_ME);
-    
+
     if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
         fidTeX=write_LaTeX_header([M_.dname '/graphs/',fname,'_forcst_ME.tex']);
     end
-    
+
     m = 1;
     n_fig = 1;
-    hh=dyn_figure(options_,'Name','Forecasts including ME (I)');
+    hh=dyn_figure(options_.nodisplay,'Name','Forecasts including ME (I)');
     for j= 1:length(var_names)
-        if m > nc*nr;
-            dyn_saveas(hh,[ dname '/graphs/forcst_ME' int2str(n_fig)],options_);
+        if m > nc*nr
+            dyn_saveas(hh,[ dname '/graphs/forcst_ME' int2str(n_fig)],options_.nodisplay,options_.graph_format);
             if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                 fprintf(fidTeX,'\\begin{figure}[H]\n');
                 fprintf(fidTeX,'\\centering \n');
@@ -139,7 +139,7 @@ if isfield(oo_.forecast,'HPDinf_ME')
                 fprintf(fidTeX,' \n');
             end
             n_fig =n_fig+1;
-            eval(['hh=dyn_figure(options_,''Name'',''Forecasts (' int2str(n_fig) ')'');']);
+            eval(['hh=dyn_figure(options_.nodisplay,''Name'',''Forecasts (' int2str(n_fig) ')'');']);
             m = 1;
         end
         subplot(nr,nc,m);
@@ -156,12 +156,12 @@ if isfield(oo_.forecast,'HPDinf_ME')
         hold off
         m = m + 1;
     end
-    
+
     if m > 1
-        dyn_saveas(hh,[dname '/graphs/forcst_ME' int2str(n_fig)],options_);
+        dyn_saveas(hh,[dname '/graphs/forcst_ME' int2str(n_fig)],options_.nodisplay,options_.graph_format);
         if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
             fprintf(fidTeX,'\\begin{figure}[H]\n');
-            fprintf(fidTeX,'\\centering \n');          
+            fprintf(fidTeX,'\\centering \n');
             fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s/graphs/forcst_ME%d}\n',options_.figures.textwidth*min((m-1)/nc,1),dname,n_fig);
             fprintf(fidTeX,'\\label{Fig:forcst_ME:%d}\n',n_fig);
             fprintf(fidTeX,'\\caption{Mean forecasts and %2.0f\\%% confidence intervals accounting for measurement error}\n',options_.forecasts.conf_sig*100);
@@ -169,10 +169,10 @@ if isfield(oo_.forecast,'HPDinf_ME')
             fprintf(fidTeX,' \n');
         end
     end
-    
+
     if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
         write_LaTeX_footer(fidTeX);
-    end   
+    end
 end
 
 
diff --git a/matlab/formdata.m b/matlab/formdata.m
index 06dba8416a50db447d9a701836b5f9c38e4cfa29..b8040515c5707dbad9b67a9a2ea41f3d14a05e06 100644
--- a/matlab/formdata.m
+++ b/matlab/formdata.m
@@ -11,7 +11,7 @@ function formdata(fname,date)
 % SPECIAL REQUIREMENT
 %   none
 
-% Copyright (C) 2007-2010 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -29,6 +29,7 @@ function formdata(fname,date)
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 global M_ oo_
+
 fid = fopen([fname '_endo.frm'],'w');
 n=size(oo_.endo_simul,1);
 t=size(oo_.endo_simul,2);
@@ -46,11 +47,10 @@ for i=1:n
             fprintf(fid,'%10.5f %10.5f\n',oo_.endo_simul(i,floor(t/4)*4+1:t));
           case 3
             fprintf(fid,'%10.5f %10.5f %10.5f\n',oo_.endo_simul(i,floor(t/4)*4+1:t));
-        end;
-        %else
-        %    fprintf(fid,'\n');
-    end;
-end;
+        end
+    end
+end
+
 fclose(fid);
 
 fid = fopen([fname '_exo.frm'],'w');
@@ -70,10 +70,8 @@ for i=1:n
             fprintf(fid,'%10.5f %10.5f\n',oo_.exo_simul(floor(t/4)*4+1:t,i)');
           case 3
             fprintf(fid,'%10.5f %10.5f %10.5f\n',oo_.exo_simul(floor(t/4)*4+1:t,i)');
-        end;
-        %else
-        %    fprintf(fid,'\n');
-    end;
-end;
-fclose(fid);
-return;
\ No newline at end of file
+        end
+    end
+end
+
+fclose(fid);
\ No newline at end of file
diff --git a/matlab/ftest.m b/matlab/ftest.m
index 97bedb6e56299b82552641b589f0d0f4c5e01af0..c433bb453458bf220683a1e8ded7507ee85a5fa3 100644
--- a/matlab/ftest.m
+++ b/matlab/ftest.m
@@ -1,6 +1,6 @@
 function ftest (s1,s2)
 
-% Copyright (C) 2001-2010 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -20,7 +20,7 @@ function ftest (s1,s2)
 global nvx nvy x y lag1
 
 if size(s1,1) ~= 2
-    error ('Sp�cifiez deux fichiers pour la comparaison.') ;
+    error ('Spécifiez deux fichiers pour la comparaison.') ;
 end
 
 for i = 1:2
@@ -59,7 +59,7 @@ end
 
 for i = 1:size(x,1)
     if ~ strcmp(nvx(i,:),nvy(i,:))
-        error ('FTEST: The two files don''t have the same  variables.') ;       
+        error ('FTEST: The two files don''t have the same  variables.') ;
     end
 end
 
diff --git a/matlab/@dynTimeIndex/display.m b/matlab/fwriten.m
similarity index 79%
rename from matlab/@dynTimeIndex/display.m
rename to matlab/fwriten.m
index 87162fd40f6f24586cdc7f559e32bef330cd6b5d..1fd5e11603f3649e54771cdd28ae7dbdca722b99 100644
--- a/matlab/@dynTimeIndex/display.m
+++ b/matlab/fwriten.m
@@ -1,6 +1,8 @@
-function display(t)
+function fwriten(fid, str)
 
-% Copyright (C) 2013 Dynare Team
+% Writes a line in a file, with newline character at the end of the line.
+
+% Copyright (C) 2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -17,4 +19,4 @@ function display(t)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-fprintf('%s = <dynTimeIndex: %s>\n', inputname(1), int2str(t.index));
+fwrite(fid, sprintf('%s\n', str));
\ No newline at end of file
diff --git a/matlab/gauss_hermite_weights_and_nodes.m b/matlab/gauss_hermite_weights_and_nodes.m
index a9a75b4e1bc3c151cccee441c11c2e8e3160ccd2..646033c0603a7d656621934e0105131822d8786f 100644
--- a/matlab/gauss_hermite_weights_and_nodes.m
+++ b/matlab/gauss_hermite_weights_and_nodes.m
@@ -31,7 +31,7 @@ function [nodes,weights] = gauss_hermite_weights_and_nodes(n)
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -66,7 +66,7 @@ nodes = sqrt(2)*nodes;
 %$ sum_of_weights = sum(weights);
 %$
 %$ % Expected nodes (taken from Judd (1998, table 7.4).
-%$ enodes = [-2.020182870; -0.9585724646; 0; 0.9585724646;   2.020182870]; 
+%$ enodes = [-2.020182870; -0.9585724646; 0; 0.9585724646;   2.020182870];
 %$
 %$ % Check the results.
 %$ t(1) = dassert(1.0,sum_of_weights,1e-12);
@@ -79,7 +79,7 @@ nodes = sqrt(2)*nodes;
 %$ [nodes,weights] = gauss_hermite_weights_and_nodes(n);
 %$
 %$ sum_of_weights = sum(weights);
-%$ expectation = sum(weights.*nodes); 
+%$ expectation = sum(weights.*nodes);
 %$ variance = sum(weights.*(nodes.^2));
 %$
 %$ % Check the results.
@@ -113,7 +113,7 @@ nodes = sqrt(2)*nodes;
 %$ [nodes,weights] = gauss_hermite_weights_and_nodes(n);
 %$
 %$ sum_of_weights = sum(weights);
-%$ expectation = sum(weights.*nodes*.1); 
+%$ expectation = sum(weights.*nodes*.1);
 %$ variance = sum(weights.*((nodes*.1).^2));
 %$
 %$ % Check the results.
diff --git a/matlab/gauss_legendre_weights_and_nodes.m b/matlab/gauss_legendre_weights_and_nodes.m
index a1b6fc2903421f21c55fb6e71a19508880146f49..074f520d7a4cc4f11089805295e1dcb7d20b3be9 100644
--- a/matlab/gauss_legendre_weights_and_nodes.m
+++ b/matlab/gauss_legendre_weights_and_nodes.m
@@ -40,7 +40,7 @@ function [nodes,weights] = gauss_legendre_weights_and_nodes(n,a,b)
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -124,7 +124,7 @@ end
 
 %@test:3
 %$ [n,w] = gauss_legendre_weights_and_nodes(9,pi,2*pi);
-%$ % Check that the 
+%$ % Check that the
 %$ t(1) = all(n>pi);
 %$ t(2) = all(n<2*pi);
 %$ t(3) = dassert(sum(w),pi,1e-12);
diff --git a/matlab/gcompare.m b/matlab/gcompare.m
index d8a1e2ae831de756e29b8317de4d0f75e4fe5704..6cb02f6a18fbae3f77e6826d58244c5722440254 100644
--- a/matlab/gcompare.m
+++ b/matlab/gcompare.m
@@ -1,12 +1,12 @@
 function gcompare(s1,s2)
-% GCOMPARE :    GCOMPARE ( [ 'file1' ; 'file2' ] , [ 'var1' ; 'var2' ...] )     
+% GCOMPARE :    GCOMPARE ( [ 'file1' ; 'file2' ] , [ 'var1' ; 'var2' ...] )
 %               This optional command plots the trajectories of a list of
 %               variables in two different simulations. One plot is drawn
 %               for each variable. The trajectories must have been previously
 %               saved by the instruction DYNASAVE. The simulation in file1
 %               is refered to as the base simulation.
 
-% Copyright (C) 2001-2010 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -50,6 +50,3 @@ end
 
 % 06/18/01 MJ corrected treatment of options_.smpl
 % 06/24/01 MJ removed color specification
-
-
-
diff --git a/matlab/gensylv/gensylv.m b/matlab/gensylv/gensylv.m
index 26624fea741d87645c77f2398edb56a5b44cd04a..2920aca4d2bd8d3f6f6cfb0842618cf669e75673 100644
--- a/matlab/gensylv/gensylv.m
+++ b/matlab/gensylv/gensylv.m
@@ -3,23 +3,23 @@ function [err, E] = gensylv(kron_prod,A,B,C0,D)
 % Solves a Sylvester equation.
 %
 % INPUTS
-%   kron_prod     
+%   kron_prod
 %   A
 %   B
 %   C
 %   D
-%    
+%
 % OUTPUTS
 %   err      [double] scalar: 1 indicates failure, 0 indicates success
 %   E
-%    
+%
 % ALGORITHM
 %   none.
 %
 % SPECIAL REQUIREMENTS
-%   none.  
+%   none.
 
-% Copyright (C) 1996-2011 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -36,9 +36,9 @@ function [err, E] = gensylv(kron_prod,A,B,C0,D)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 C = C0;
-for i=1:(kron_prod-1);
-    C  = kron(C0,C); 
-end;
+for i=1:(kron_prod-1)
+    C  = kron(C0,C);
+end
 
 x0 = sylvester3(A,B,C,D);
 E  = sylvester3a(x0,A,B,C,D);
diff --git a/matlab/gensylv/sylvester3.m b/matlab/gensylv/sylvester3.m
index be4d8c574f39ad28bcd1e3b94cb4e9d210398ff4..4e0ab85ee8df54dd728079985aae69275b55f0f0 100644
--- a/matlab/gensylv/sylvester3.m
+++ b/matlab/gensylv/sylvester3.m
@@ -1,7 +1,7 @@
 function x=sylvester3(a,b,c,d)
 % solves a*x+b*x*c=d where d is [n x m x p]
 
-% Copyright (C) 2005-2012 Dynare Team
+% Copyright (C) 2005-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -23,21 +23,21 @@ m = size(c,1);
 p = size(d,3);
 x=zeros(n,m,p);
 if n == 1
-    for j=1:p,
+    for j=1:p
         x(:,:,j)=d(:,:,j)./(a*ones(1,m)+b*c);
     end
     return
 end
 if m == 1
-    for j=1:p,
+    for j=1:p
         x(:,:,j) = (a+c*b)\d(:,:,j);
     end
-    return;
+    return
 end
 [u,t]=schur(c);
 if isoctave
     [aa,bb,qq,zz]=qz(full(a),full(b));
-    for j=1:p,
+    for j=1:p
         if octave_ver_less_than('3.4.0')
             d(:,:,j)=qq'*d(:,:,j)*u;
         else
@@ -46,7 +46,7 @@ if isoctave
     end
 else
     [aa,bb,qq,zz]=qz(full(a),full(b),'real'); % available in Matlab version 6.0
-    for j=1:p,
+    for j=1:p
         d(:,:,j)=qq*d(:,:,j)*u;
     end
 end
@@ -58,7 +58,7 @@ while i < m
         if i == 1
             c = zeros(n,1,p);
         else
-            for j=1:p,
+            for j=1:p
                 c(:,:,j) = bb*(x(:,1:i-1,j)*t(1:i-1,i));
             end
         end
@@ -69,7 +69,7 @@ while i < m
             c = zeros(n,1,p);
             c1 = zeros(n,1,p);
         else
-            for j=1:p,
+            for j=1:p
                 c(:,:,j) = bb*(x(:,1:i-1,j)*t(1:i-1,i));
                 c1(:,:,j) = bb*(x(:,1:i-1,j)*t(1:i-1,i+1));
             end
@@ -82,13 +82,13 @@ while i < m
     end
 end
 if i == m
-    for j=1:p,
+    for j=1:p
         c(:,:,j) = bb*(x(:,1:m-1,j)*t(1:m-1,m));
     end
     aabbt = (aa+bb*t(m,m));
     x(:,m,:)=aabbt\squeeze(d(:,m,:)-c);
 end
-for j=1:p,
+for j=1:p
     x(:,:,j)=zz*x(:,:,j)*u';
 end
 
diff --git a/matlab/gensylv/sylvester3a.m b/matlab/gensylv/sylvester3a.m
index 00724dc387bbfa5efd5d26e45ec7592526ab592e..f286c8bdfc90dff3e289a63af5374073a8bf289a 100644
--- a/matlab/gensylv/sylvester3a.m
+++ b/matlab/gensylv/sylvester3a.m
@@ -1,7 +1,7 @@
 function [x0, flag]=sylvester3a(x0,a,b,c,dd)
 % solves iteratively ax+bxc=d
 
-% Copyright (C) 2005-2012 Dynare Team
+% Copyright (C) 2005-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -21,7 +21,7 @@ function [x0, flag]=sylvester3a(x0,a,b,c,dd)
 a_1 = inv(a);
 b = a_1*b;
 flag=0;
-for j=1:size(dd,3),
+for j=1:size(dd,3)
     d = a_1*dd(:,:,j);
     e = 1;
     iter = 1;
diff --git a/matlab/gensylv_fp.m b/matlab/gensylv_fp.m
index 2e5c167b5ecf2e4fd9d876be43fc6e2b02612c5b..51c96fceb8c2e08ef179b3f5b5cb0683080105f6 100644
--- a/matlab/gensylv_fp.m
+++ b/matlab/gensylv_fp.m
@@ -7,23 +7,23 @@ function X = gensylv_fp(A, B, C, D, block, tol)
 %   B
 %   C
 %   D
-%   block : block number (for storage purpose) 
+%   block : block number (for storage purpose)
 %   tol : convergence criteria
 % OUTPUTS
 %   X solution
-%    
+%
 % ALGORITHM
 %   fixed point method
 %   MARLLINY MONSALVE (2008): "Block linear method for large scale
-%   Sylvester equations", Computational & Applied Mathematics, Vol 27, n�1,
+%   Sylvester equations", Computational & Applied Mathematics, Vol 27, n°1,
 %   p47-59
 %   ||A^-1||.||B||.||C|| < 1 is a suffisant condition:
 %    - to get a unique solution for the Sylvester equation
 %    - to get a convergent fixed-point algorithm
 %
 % SPECIAL REQUIREMENTS
-%   none.  
-% Copyright (C) 1996-2012 Dynare Team
+%   none.
+% Copyright (C) 1996-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -50,11 +50,11 @@ if isempty(hxo)
     X = zeros(size(B, 2), size(C, 1));
 else
     X = hxo;
-end;
+end
 it_fp = 0;
 maxit_fp = 1000;
 Z = - (B * X * C + D);
-while it_fp < maxit_fp && evol > tol;
+while it_fp < maxit_fp && evol > tol
     %X_old = X;
     %X = - A1 * ( B * X * C + D);
     %evol = max(max(abs(X - X_old)));
@@ -62,12 +62,12 @@ while it_fp < maxit_fp && evol > tol;
     Z_old = Z;
     Z = - (B * X * C + D);
     evol = max(sum(abs(Z - Z_old))); %norm_1
-    %evol = max(sum(abs(Z - Z_old)')); %norm_inf
+                                     %evol = max(sum(abs(Z - Z_old)')); %norm_inf
     it_fp = it_fp + 1;
-end;
+end
 %fprintf('sylvester it_fp=%d evol=%g | ',it_fp,evol);
 if evol < tol
     eval(['hxo_' int2str(block) ' = X;']);
 else
     error(['convergence not achieved in fixed point solution of Sylvester equation after ' int2str(it_fp) ' iterations']);
-end;
\ No newline at end of file
+end
\ No newline at end of file
diff --git a/matlab/getH.m b/matlab/getH.m
index 0db11d8e33ac31260a2cf2bd937573e732171e67..fcee9242e3cf19fb95f6fca712d2d4aee206320b 100644
--- a/matlab/getH.m
+++ b/matlab/getH.m
@@ -13,14 +13,14 @@ function [H, dA, dOm, Hss, gp, d2A, d2Om, H2ss] = getH(A, B, estim_params_,M_,oo
 %                   not (-1 or -2)
 %   indx:           Index of estimated parameters in M_.params
 %   indexo:         Index of estimated standard deviations in M_.exo_names
-%   iv:             Index of considered variables           
-% 
+%   iv:             Index of considered variables
+%
 % Outputs:
 %   H:              dTAU/dTHETA: Jacobian of TAU, vectorized form of
 %                   linearized reduced form state space model, given ys [steady state],
 %                   A [transition matrix], B [matrix of shocks], Sigma [covariance of shocks]
-%                   TAU = [ys; vec(A); dyn_vech(B*Sigma*B')]. 
-%   dA:             [endo_nbr by endo_nbr by (indx+indexo)] Jacobian of transition matrix A            
+%                   TAU = [ys; vec(A); dyn_vech(B*Sigma*B')].
+%   dA:             [endo_nbr by endo_nbr by (indx+indexo)] Jacobian of transition matrix A
 %   dOm:            [endo_nbr by endo_nbr by (indx+indexo)] Jacobian of Omega = (B*Sigma*B')
 %   Hss:            [endo_nbr by (indx)] Jacobian of steady state with respect to estimated
 %                   structural parameters only (indx)
@@ -32,7 +32,7 @@ function [H, dA, dOm, Hss, gp, d2A, d2Om, H2ss] = getH(A, B, estim_params_,M_,oo
 %   H2s:            Hessian of steady state with respect to estimated
 %                   structural parameters only (indx)
 
-% Copyright (C) 2010-2016 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -50,23 +50,23 @@ function [H, dA, dOm, Hss, gp, d2A, d2Om, H2ss] = getH(A, B, estim_params_,M_,oo
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 if nargin<7 || isempty(kronflag)
-    kronflag = 0; 
+    kronflag = 0;
 end
 if nargin<8 || isempty(indx)
-    indx = []; 
+    indx = [];
 end
 if nargin<9 || isempty(indexo)
-    indexo = []; 
+    indexo = [];
 end
 if nargin<10 || isempty(iv)
-    iv = (1:length(A))'; 
+    iv = (1:length(A))';
 end
 
 [I,J]=find(M_.lead_lag_incidence');
 yy0=oo_.dr.ys(I);
 param_nbr = length(indx);
 tot_param_nbr = param_nbr + length(indexo);
-if nargout>5,
+if nargout>5
     param_nbr_2 = param_nbr*(param_nbr+1)/2;
     tot_param_nbr_2 = tot_param_nbr*(tot_param_nbr+1)/2;
 end
@@ -75,18 +75,18 @@ m = size(A,1);
 m1=length(iv);
 n = size(B,2);
 
-if kronflag==-1, % perturbation
+if kronflag==-1 % perturbation
     gp=0;
     fun = 'thet2tau';
     params0 = M_.params;
     H = fjaco(fun,[sqrt(diag(M_.Sigma_e(indexo,indexo))); M_.params(indx)], M_, oo_, indx, indexo,0);
-    if nargout>1,
+    if nargout>1
         dOm = zeros(m1,m1,tot_param_nbr);
         dA=zeros(m1,m1,tot_param_nbr);
         Hss=H(iv,length(indexo)+1:end);
         da = H(m+1:m+m*m,:);
         dom = H(m+m*m+1:end,:);
-        for j=1:tot_param_nbr,
+        for j=1:tot_param_nbr
             tmp = dyn_unvech(dom(:,j));
             dOm(:,:,j) = tmp(iv,iv);
             tmp = reshape(da(:,j),m,m);
@@ -94,13 +94,13 @@ if kronflag==-1, % perturbation
         end
         clear da dom tmp
     end
-    if nargout>5,
+    if nargout>5
         H2 = hessian_sparse('thet2tau',[sqrt(diag(M_.Sigma_e(indexo,indexo))); M_.params(indx)], ...
-            options_.gstep,estim_params_,M_, oo_, indx,indexo,0,[],[],[],iv);
+                            options_.gstep,estim_params_,M_, oo_, indx,indexo,0,[],[],[],iv);
         H2ss = zeros(m1,tot_param_nbr,tot_param_nbr);
         iax=find(triu(rand(tot_param_nbr,tot_param_nbr)));
         H2 = H2(:,iax);
-        for j=1:m1,
+        for j=1:m1
             H2ss(j,:,:)=dyn_unvech(full(H2(j,:)));
         end
         H2ss=H2ss(:,length(indexo)+1:end,length(indexo)+1:end);
@@ -109,33 +109,33 @@ if kronflag==-1, % perturbation
         d2A(:,:) = H2(m1+1:m1+m1*m1,:);
         d2Om(:,:) = H2(m1+m1*m1+1:end,:);
         clear H2
-%         tmp0=zeros(m1,m1);
-%         tmp0(iv,iv)=1;
-%         iax=find(tmp0);
-%         d2A=d2a(iax,:);
-%         iax=find(dyn_vech(tmp0));
-%         d2Om=d2om(iax,:);
+        %         tmp0=zeros(m1,m1);
+        %         tmp0(iv,iv)=1;
+        %         iax=find(tmp0);
+        %         d2A=d2a(iax,:);
+        %         iax=find(dyn_vech(tmp0));
+        %         d2Om=d2om(iax,:);
 
     end
-%     assignin('base','M_', M_);
-%     assignin('base','oo_', oo_);
+    %     assignin('base','M_', M_);
+    %     assignin('base','oo_', oo_);
     return
 end
 
-if kronflag==-2,
-    if nargout>5,
+if kronflag==-2
+    if nargout>5
         [residual, g1, g2 ] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', ...
-            M_.params, oo_.dr.ys, 1);
+                                    M_.params, oo_.dr.ys, 1);
         g22 = hessian_sparse('thet2tau',[M_.params(indx)],options_.gstep,estim_params_,M_, oo_, indx,[],-1);
         H2ss=full(g22(1:M_.endo_nbr,:));
         H2ss = reshape(H2ss,[M_.endo_nbr param_nbr param_nbr]);
-        for j=1:M_.endo_nbr,
+        for j=1:M_.endo_nbr
             H2ss(j,:,:)=dyn_unvech(dyn_vech(H2ss(j,:,:)));
         end
         g22=g22(M_.endo_nbr+1:end,:);
         inx=find(g22);
         gx22=zeros(length(inx),5);
-        for j=1:length(inx),
+        for j=1:length(inx)
             [i1, i2] = ind2sub(size(g22),inx(j));
             [ig1, ig2] = ind2sub(size(g1),i1);
             [ip1, ip2] = ind2sub([param_nbr param_nbr],i2);
@@ -145,145 +145,135 @@ if kronflag==-2,
         clear gx22;
     else
         [residual, g1 ] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', ...
-            M_.params, oo_.dr.ys, 1);        
+                                M_.params, oo_.dr.ys, 1);
     end
     gp = fjaco('thet2tau',[M_.params(indx)],estim_params_,M_, oo_, indx,[],-1);
     Hss=gp(1:M_.endo_nbr,:);
     gp=gp(M_.endo_nbr+1:end,:);
     gp = reshape(gp,[size(g1) param_nbr]);
 else
-
-% yy0=[];
-% for j=1:size(M_.lead_lag_incidence,1);
-%     yy0 = [ yy0; oo_.dr.ys(find(M_.lead_lag_incidence(j,:)))];
-% end
-dyssdtheta=zeros(length(oo_.dr.ys),M_.param_nbr);
-d2yssdtheta=zeros(length(oo_.dr.ys),M_.param_nbr,M_.param_nbr);
-[residual, gg1] = feval([M_.fname,'_static'],oo_.dr.ys, oo_.exo_steady_state', M_.params);
-df = feval([M_.fname,'_static_params_derivs'],oo_.dr.ys, repmat(oo_.exo_steady_state',[M_.maximum_exo_lag+M_.maximum_exo_lead+1]), ...
-    M_.params);
-dyssdtheta = -gg1\df;
-if nargout>5,
-    [residual, gg1, gg2] = feval([M_.fname,'_static'],oo_.dr.ys, oo_.exo_steady_state', M_.params);
-    [residual, g1, g2, g3] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', ...
-        M_.params, oo_.dr.ys, 1);
-    [nr, nc]=size(gg2);
-
-    [df, gpx, d2f] = feval([M_.fname,'_static_params_derivs'],oo_.dr.ys, oo_.exo_steady_state', ...
-        M_.params);%, oo_.dr.ys, 1, dyssdtheta*0, d2yssdtheta);
-    d2f = get_all_resid_2nd_derivs(d2f,length(oo_.dr.ys),M_.param_nbr);
-
-    if isempty(find(gg2)),
-        for j=1:M_.param_nbr,
-        d2yssdtheta(:,:,j) = -gg1\d2f(:,:,j);
-        end
-    else
-        gam = d2f*0;
-        for j=1:nr,
-            tmp1 = (squeeze(gpx(j,:,:))'*dyssdtheta);
-            gam(j,:,:)=transpose(reshape(gg2(j,:),[nr nr])*dyssdtheta)*dyssdtheta ...
-                + tmp1 + tmp1';
-        end
-        for j=1:M_.param_nbr,
-        d2yssdtheta(:,:,j) = -gg1\(d2f(:,:,j)+gam(:,:,j));
-%         d2yssdtheta(:,:,j) = -gg1\(d2f(:,:,j)+gam(:,:,j)+ squeeze(gpx(:,:,j))*dyssdtheta);
+    dyssdtheta=zeros(length(oo_.dr.ys),M_.param_nbr);
+    d2yssdtheta=zeros(length(oo_.dr.ys),M_.param_nbr,M_.param_nbr);
+    [residual, gg1] = feval([M_.fname,'_static'],oo_.dr.ys, oo_.exo_steady_state', M_.params);
+    df = feval([M_.fname,'_static_params_derivs'],oo_.dr.ys, repmat(oo_.exo_steady_state',[M_.maximum_exo_lag+M_.maximum_exo_lead+1]), ...
+               M_.params);
+    dyssdtheta = -gg1\df;
+    if nargout>5
+        [residual, gg1, gg2] = feval([M_.fname,'_static'],oo_.dr.ys, oo_.exo_steady_state', M_.params);
+        [residual, g1, g2, g3] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', ...
+                                       M_.params, oo_.dr.ys, 1);
+        [nr, nc]=size(gg2);
+
+        [df, gpx, d2f] = feval([M_.fname,'_static_params_derivs'],oo_.dr.ys, oo_.exo_steady_state', ...
+                               M_.params);%, oo_.dr.ys, 1, dyssdtheta*0, d2yssdtheta);
+        d2f = get_all_resid_2nd_derivs(d2f,length(oo_.dr.ys),M_.param_nbr);
+        if isempty(find(gg2))
+            for j=1:M_.param_nbr
+                d2yssdtheta(:,:,j) = -gg1\d2f(:,:,j);
+            end
+        else
+            gam = d2f*0;
+            for j=1:nr
+                tmp1 = (squeeze(gpx(j,:,:))'*dyssdtheta);
+                gam(j,:,:)=transpose(reshape(gg2(j,:),[nr nr])*dyssdtheta)*dyssdtheta ...
+                    + tmp1 + tmp1';
+            end
+            for j=1:M_.param_nbr
+                d2yssdtheta(:,:,j) = -gg1\(d2f(:,:,j)+gam(:,:,j));
+            end
+            clear tmp1 gpx gam
         end
-        clear tmp1 gpx gam,
     end
-end
 
-if any(any(isnan(dyssdtheta))),    
-    [U,T] = schur(gg1);
-    qz_criterium=options_.qz_criterium;
-    e1 = abs(ordeig(T)) < qz_criterium-1;
-    k = sum(e1);       % Number non stationary variables.
-%     n = length(e1)-k;  % Number of stationary variables.
-    [U,T] = ordschur(U,T,e1);
-    T = T(k+1:end,k+1:end);
-    dyssdtheta = -U(:,k+1:end)*(T\U(:,k+1:end)')*df;
-    if nargout>5,
-        for j=1:length(indx),
-            d2yssdtheta(:,:,j) = -U(:,k+1:end)*(T\U(:,k+1:end)')*d2f(:,:,j);
+    if any(any(isnan(dyssdtheta)))
+        [U,T] = schur(gg1);
+        qz_criterium=options_.qz_criterium;
+        e1 = abs(ordeig(T)) < qz_criterium-1;
+        k = sum(e1);       % Number non stationary variables.
+                           %     n = length(e1)-k;  % Number of stationary variables.
+        [U,T] = ordschur(U,T,e1);
+        T = T(k+1:end,k+1:end);
+        dyssdtheta = -U(:,k+1:end)*(T\U(:,k+1:end)')*df;
+        if nargout>5
+            for j=1:length(indx)
+                d2yssdtheta(:,:,j) = -U(:,k+1:end)*(T\U(:,k+1:end)')*d2f(:,:,j);
+            end
         end
     end
-end
-if nargout>5,
-    [df, gp, d2f, gpp, hp] = feval([M_.fname,'_params_derivs'],yy0, oo_.exo_steady_state', ...
-        M_.params, oo_.dr.ys, 1, dyssdtheta, d2yssdtheta);
-    H2ss = d2yssdtheta(oo_.dr.order_var,indx,indx);
-%     nelem=size(g1,2);
-%     g22 = get_all_2nd_derivs(gpp,m,nelem,M_.param_nbr);
-%     g22 = g22(:,:,indx,indx);
-else
-    [df, gp] = feval([M_.fname,'_params_derivs'],yy0, repmat(oo_.exo_steady_state',[M_.maximum_exo_lag+M_.maximum_exo_lead+1,1]), ...
-        M_.params, oo_.dr.ys, 1, dyssdtheta,d2yssdtheta);
-    [residual, g1, g2 ] = feval([M_.fname,'_dynamic'],yy0, repmat(oo_.exo_steady_state',[M_.maximum_exo_lag+M_.maximum_exo_lead+1,1]), ...
-        M_.params, oo_.dr.ys, 1);
-end
+    if nargout>5
+        [df, gp, d2f, gpp, hp] = feval([M_.fname,'_params_derivs'],yy0, oo_.exo_steady_state', ...
+                                       M_.params, oo_.dr.ys, 1, dyssdtheta, d2yssdtheta);
+        H2ss = d2yssdtheta(oo_.dr.order_var,indx,indx);
+    else
+        [df, gp] = feval([M_.fname,'_params_derivs'],yy0, repmat(oo_.exo_steady_state',[M_.maximum_exo_lag+M_.maximum_exo_lead+1,1]), ...
+                         M_.params, oo_.dr.ys, 1, dyssdtheta,d2yssdtheta);
+        [residual, g1, g2 ] = feval([M_.fname,'_dynamic'],yy0, repmat(oo_.exo_steady_state',[M_.maximum_exo_lag+M_.maximum_exo_lead+1,1]), ...
+                                    M_.params, oo_.dr.ys, 1);
+    end
 
-[nr, nc]=size(g2);
-nc = sqrt(nc);
-Hss = dyssdtheta(oo_.dr.order_var,indx);
-dyssdtheta = dyssdtheta(I,:);
-ns = max(max(M_.lead_lag_incidence)); % retrieve the number of states excluding columns for shocks
-gp2 = gp*0;
-for j=1:nr,
-    [II JJ]=ind2sub([nc nc],find(g2(j,:)));
-    for i=1:nc,
-        is = find(II==i);
-        is = is(find(JJ(is)<=ns));
-        if ~isempty(is),
-            g20=full(g2(j,find(g2(j,:))));
-            gp2(j,i,:)=g20(is)*dyssdtheta(JJ(is),:);
+    [nr, nc]=size(g2);
+    nc = sqrt(nc);
+    Hss = dyssdtheta(oo_.dr.order_var,indx);
+    dyssdtheta = dyssdtheta(I,:);
+    ns = max(max(M_.lead_lag_incidence)); % retrieve the number of states excluding columns for shocks
+    gp2 = gp*0;
+    for j=1:nr
+        [II JJ]=ind2sub([nc nc],find(g2(j,:)));
+        for i=1:nc
+            is = find(II==i);
+            is = is(find(JJ(is)<=ns));
+            if ~isempty(is)
+                g20=full(g2(j,find(g2(j,:))));
+                gp2(j,i,:)=g20(is)*dyssdtheta(JJ(is),:);
+            end
         end
     end
-end
 
-gp = gp+gp2;
-gp = gp(:,:,indx);
-
-if nargout>5,
-%     h22 = get_all_hess_derivs(hp,nr,nc,M_.param_nbr);
-    g22 = gpp;
-    gp22 = sparse(nr*nc,param_nbr*param_nbr);
-    tmp1 = reshape(g3,[nr*nc*nc nc]);
-    tmp2=sparse(size(tmp1,1),M_.param_nbr);
-%     tmp2=tmp1*[dyssdtheta; zeros(nc-ns,M_.param_nbr)];
-    tmpa=[dyssdtheta; zeros(nc-ns,M_.param_nbr)];
-    tmpa=sparse(tmpa);
-    for j=1:M_.param_nbr,
-        tmp2(:,j)=tmp1*tmpa(:,j);
-    end
-%     tmp2=sparse(tmp2);
-%     [i1 i2]=ind2sub([nc M_.param_nbr],[1:nc*M_.param_nbr]');
-
-    for j=1:nr,
-        tmp0=reshape(g2(j,:),[nc nc]);   
-        tmp0 = tmp0(:,1:ns)*reshape(d2yssdtheta(I,:,:),[ns,M_.param_nbr*M_.param_nbr]);
-        for i=1:nc,
-            indo = sub2ind([nr nc nc], ones(nc,1)*j ,ones(nc,1)*i, (1:nc)');
-            tmpx = (tmp2(indo,:))'*[dyssdtheta; zeros(nc-ns,M_.param_nbr)];
-%             gp22(j,i,:,:)=squeeze(tmp1(j,i,:,:))'*[dyssdtheta; zeros(nc-ns,M_.param_nbr)];
-            tmpu = (get_hess_deriv(hp,j,i,nc,M_.param_nbr))'*[dyssdtheta; zeros(nc-ns,M_.param_nbr)];
-            tmpy = tmpx+tmpu+tmpu'+reshape(tmp0(i,:,:),[M_.param_nbr M_.param_nbr]);
-            tmpy = tmpy + get_2nd_deriv_mat(gpp,j,i,M_.param_nbr);
-            tmpy = tmpy(indx,indx);
-            if any(any(tmpy)),
-                ina = find(triu(tmpy));
-                gp22(sub2ind([nr nc],j,i),ina)=transpose(tmpy(ina));
-%             gp22(j,i,:,:)= reshape(tmpy,[1 1 M_.param_nbr M_.param_nbr]);
+    gp = gp+gp2;
+    gp = gp(:,:,indx);
+
+    if nargout>5
+        %     h22 = get_all_hess_derivs(hp,nr,nc,M_.param_nbr);
+        g22 = gpp;
+        gp22 = sparse(nr*nc,param_nbr*param_nbr);
+        tmp1 = reshape(g3,[nr*nc*nc nc]);
+        tmp2=sparse(size(tmp1,1),M_.param_nbr);
+        %     tmp2=tmp1*[dyssdtheta; zeros(nc-ns,M_.param_nbr)];
+        tmpa=[dyssdtheta; zeros(nc-ns,M_.param_nbr)];
+        tmpa=sparse(tmpa);
+        for j=1:M_.param_nbr
+            tmp2(:,j)=tmp1*tmpa(:,j);
+        end
+        %     tmp2=sparse(tmp2);
+        %     [i1 i2]=ind2sub([nc M_.param_nbr],[1:nc*M_.param_nbr]');
+
+        for j=1:nr
+            tmp0=reshape(g2(j,:),[nc nc]);
+            tmp0 = tmp0(:,1:ns)*reshape(d2yssdtheta(I,:,:),[ns,M_.param_nbr*M_.param_nbr]);
+            for i=1:nc
+                indo = sub2ind([nr nc nc], ones(nc,1)*j ,ones(nc,1)*i, (1:nc)');
+                tmpx = (tmp2(indo,:))'*[dyssdtheta; zeros(nc-ns,M_.param_nbr)];
+                %             gp22(j,i,:,:)=squeeze(tmp1(j,i,:,:))'*[dyssdtheta; zeros(nc-ns,M_.param_nbr)];
+                tmpu = (get_hess_deriv(hp,j,i,nc,M_.param_nbr))'*[dyssdtheta; zeros(nc-ns,M_.param_nbr)];
+                tmpy = tmpx+tmpu+tmpu'+reshape(tmp0(i,:,:),[M_.param_nbr M_.param_nbr]);
+                tmpy = tmpy + get_2nd_deriv_mat(gpp,j,i,M_.param_nbr);
+                tmpy = tmpy(indx,indx);
+                if any(any(tmpy))
+                    ina = find(triu(tmpy));
+                    gp22(sub2ind([nr nc],j,i),ina)=transpose(tmpy(ina));
+                    %             gp22(j,i,:,:)= reshape(tmpy,[1 1 M_.param_nbr M_.param_nbr]);
 
+                end
             end
+            %             gp22(j,:,:,:)=gp22(j,:,:,:)+reshape(tmp0(:,1:ns)*d2yssdtheta(I,:,:),[1 nc M_.param_nbr M_.param_nbr]);
         end
-%             gp22(j,:,:,:)=gp22(j,:,:,:)+reshape(tmp0(:,1:ns)*d2yssdtheta(I,:,:),[1 nc M_.param_nbr M_.param_nbr]);
-    end
 
-%     g22 = g22+gp22;
-%     g22 = g22(:,:,indx,indx);
-    clear tmp0 tmp1 tmp2 tmpu tmpx tmpy,
+        %     g22 = g22+gp22;
+        %     g22 = g22(:,:,indx,indx);
+        clear tmp0 tmp1 tmp2 tmpu tmpx tmpy
         inx=find(gp22);
         gx22=zeros(length(inx),5);
-        for j=1:length(inx),
+        for j=1:length(inx)
             [i1, i2] = ind2sub(size(gp22),inx(j));
             [ig1, ig2] = ind2sub(size(g1),i1);
             [ip1, ip2] = ind2sub([param_nbr param_nbr],i2);
@@ -292,7 +282,7 @@ if nargout>5,
         g22 = gx22;
         clear gx22 gp22;
 
-end
+    end
 end
 
 
@@ -301,15 +291,14 @@ klen = M_.maximum_endo_lag + M_.maximum_endo_lead + 1;
 k11 = M_.lead_lag_incidence(find([1:klen] ~= M_.maximum_endo_lag+1),:);
 a = g1(:,nonzeros(k11'));
 da = gp(:,nonzeros(k11'),:);
-if nargout > 5,
+if nargout > 5
     indind = ismember(g22(:,2),nonzeros(k11'));
     tmp = g22(indind,:);
     d2a=tmp;
-    for j=1:size(tmp,1),
+    for j=1:size(tmp,1)
         inxinx = find(nonzeros(k11')==tmp(j,2));
         d2a(j,2) = inxinx;
     end
-%     d2a = g22(:,nonzeros(k11'),:,:);
 end
 kstate = oo_.dr.kstate;
 
@@ -319,12 +308,12 @@ Dg1 = zeros(M_.endo_nbr,M_.endo_nbr,param_nbr);
 k1 = find(kstate(:,2) == M_.maximum_endo_lag+2 & kstate(:,3));
 GAM1(:, kstate(k1,1)) = -a(:,kstate(k1,3));
 Dg1(:, kstate(k1,1), :) = -da(:,kstate(k1,3),:);
-if nargout > 5,
+if nargout > 5
     indind = ismember(d2a(:,2),kstate(k1,3));
     tmp = d2a(indind,:);
     tmp(:,end)=-tmp(:,end);
     D2g1 = tmp;
-    for j=1:size(tmp,1),
+    for j=1:size(tmp,1)
         inxinx = (kstate(k1,3)==tmp(j,2));
         D2g1(j,2) = kstate(k1(inxinx),1);
     end
@@ -336,11 +325,11 @@ GAM0 = zeros(M_.endo_nbr,M_.endo_nbr);
 Dg0 = zeros(M_.endo_nbr,M_.endo_nbr,param_nbr);
 GAM0(:,cols_b) = g1(:,cols_j);
 Dg0(:,cols_b,:) = gp(:,cols_j,:);
-if nargout > 5,
+if nargout > 5
     indind = ismember(g22(:,2),cols_j);
     tmp = g22(indind,:);
     D2g0=tmp;
-    for j=1:size(tmp,1),
+    for j=1:size(tmp,1)
         inxinx = (cols_j==tmp(j,2));
         D2g0(j,2) = cols_b(inxinx);
     end
@@ -352,12 +341,12 @@ GAM2 = zeros(M_.endo_nbr,M_.endo_nbr);
 Dg2 = zeros(M_.endo_nbr,M_.endo_nbr,param_nbr);
 GAM2(:, kstate(k2,1)) = -a(:,kstate(k2,4));
 Dg2(:, kstate(k2,1), :) = -da(:,kstate(k2,4),:);
-if nargout > 5,
+if nargout > 5
     indind = ismember(d2a(:,2),kstate(k2,4));
     tmp = d2a(indind,:);
     tmp(:,end)=-tmp(:,end);
     D2g2 = tmp;
-    for j=1:size(tmp,1),
+    for j=1:size(tmp,1)
         inxinx = (kstate(k2,4)==tmp(j,2));
         D2g2(j,2) = kstate(k2(inxinx),1);
     end
@@ -365,13 +354,13 @@ end
 
 GAM3 = -g1(:,length(yy0)+1:end);
 Dg3 = -gp(:,length(yy0)+1:end,:);
-if nargout>5,
+if nargout>5
     cols_ex = [length(yy0)+1:size(g1,2)];
     indind = ismember(g22(:,2),cols_ex);
     tmp = g22(indind,:);
     tmp(:,end)=-tmp(:,end);
     D2g3=tmp;
-    for j=1:size(tmp,1),
+    for j=1:size(tmp,1)
         inxinx = find(cols_ex==tmp(j,2));
         D2g3(j,2) = inxinx;
     end
@@ -380,11 +369,11 @@ end
 
 clear g1 g2 g3 df d2f gpp hp residual gg1 gg2 gp2 dyssdtheta d2yssdtheta
 
-if kronflag==1, % kronecker products
+if kronflag==1 % kronecker products
     Dg0=reshape(Dg0,m^2,param_nbr);
     Dg1=reshape(Dg1,m^2,param_nbr);
     Dg2=reshape(Dg2,m^2,param_nbr);
-    for j=1:param_nbr,
+    for j=1:param_nbr
         Dg3(:,:,j)=Dg3(:,:,j)*M_.Sigma_e;
     end
     Dg3=reshape(Dg3,m*n,param_nbr);
@@ -427,7 +416,7 @@ if kronflag==1, % kronecker products
     H(m*m+1:end,:) = tmpH(Index,:);
 
     Hx = [];
-    if ~isempty(indexo),
+    if ~isempty(indexo)
         dSig = zeros(M_.exo_nbr,M_.exo_nbr);
         dOm = cat(3,zeros(size(dOm,1),size(dOm,1),length(indexo)),dOm);
         for j=1:length(indexo)
@@ -435,7 +424,7 @@ if kronflag==1, % kronecker products
             y = B*dSig*B';
             y = y(nauxe+1:end,nauxe+1:end);
             Hx(:,j) = [zeros((m-nauxe)^2,1); dyn_vech(y)];
-            if nargout>1,
+            if nargout>1
                 dOm(:,:,j) = y;
             end
             dSig(indexo(j),indexo(j)) = 0;
@@ -452,47 +441,47 @@ else % generalized sylvester equation
     c = A;
     elem = zeros(m,m,param_nbr);
     d = elem;
-    for j=1:param_nbr,
+    for j=1:param_nbr
         elem(:,:,j) = (Dg0(:,:,j)-Dg1(:,:,j)*A);
         d(:,:,j) = Dg2(:,:,j)-elem(:,:,j)*A;
     end
     xx=sylvester3(a,b,c,d);
     flag=1;
     icount=0;
-    while flag && icount<4,
+    while flag && icount<4
         [xx, flag]=sylvester3a(xx,a,b,c,d);
         icount=icount+1;
     end
     H=zeros(m1*m1+m1*(m1+1)/2,param_nbr+length(indexo));
-    if nargout>1,
+    if nargout>1
         dOm = zeros(m1,m1,param_nbr+length(indexo));
         dA=zeros(m1,m1,param_nbr+length(indexo));
         dB=zeros(m,n,param_nbr);
     end
-    if ~isempty(indexo),
+    if ~isempty(indexo)
         dSig = zeros(M_.exo_nbr,M_.exo_nbr,length(indexo));
         for j=1:length(indexo)
             dSig(indexo(j),indexo(j),j) = 2*sqrt(M_.Sigma_e(indexo(j),indexo(j)));
             y = B*dSig(:,:,j)*B';
-%             y = y(nauxe+1:end,nauxe+1:end);
-%             H(:,j) = [zeros((m-nauxe)^2,1); dyn_vech(y)];
+            %             y = y(nauxe+1:end,nauxe+1:end);
+            %             H(:,j) = [zeros((m-nauxe)^2,1); dyn_vech(y)];
             H(:,j) = [zeros(m1^2,1); dyn_vech(y(iv,iv))];
-            if nargout>1,
+            if nargout>1
                 dOm(:,:,j) = y(iv,iv);
             end
-%             dSig(indexo(j),indexo(j)) = 0;
+            %             dSig(indexo(j),indexo(j)) = 0;
         end
     end
-    for j=1:param_nbr,
+    for j=1:param_nbr
         x = xx(:,:,j);
         y = inva * (Dg3(:,:,j)-(elem(:,:,j)-GAM1*x)*B);
-        if nargout>1,
+        if nargout>1
             dB(:,:,j) = y;
         end
         y = y*M_.Sigma_e*B'+B*M_.Sigma_e*y';
-%         x = x(nauxe+1:end,nauxe+1:end);
-%         y = y(nauxe+1:end,nauxe+1:end);
-        if nargout>1,
+        %         x = x(nauxe+1:end,nauxe+1:end);
+        %         y = y(nauxe+1:end,nauxe+1:end);
+        if nargout>1
             dA(:,:,j+length(indexo)) = x(iv,iv);
             dOm(:,:,j+length(indexo)) = y(iv,iv);
         end
@@ -515,7 +504,7 @@ else % generalized sylvester equation
 
 end
 
-if nargout > 5,
+if nargout > 5
     H2ss = H2ss(iv,:,:);
     d = zeros(m,m,floor(sqrt(param_nbr_2)));
     %     d2A = zeros(m,m,tot_param_nbr,tot_param_nbr);
@@ -532,9 +521,9 @@ if nargout > 5,
     cumjcount=0;
     jinx = [];
     x2x=sparse(m*m,param_nbr_2);
-%     x2x=[];
-    for i=1:param_nbr,
-        for j=1:i,
+    %     x2x=[];
+    for i=1:param_nbr
+        for j=1:i
             elem1 = (get_2nd_deriv(D2g0,m,m,j,i)-get_2nd_deriv(D2g1,m,m,j,i)*A);
             elem1 = get_2nd_deriv(D2g2,m,m,j,i)-elem1*A;
             elemj0 = Dg0(:,:,j)-Dg1(:,:,j)*A;
@@ -545,24 +534,24 @@ if nargout > 5,
             jcount=jcount+1;
             jinx = [jinx; [j i]];
             d(:,:,jcount) = elem1+elem2;
-            if jcount==floor(sqrt(param_nbr_2)) || (j*i)==param_nbr^2,
-                if (j*i)==param_nbr^2,
+            if jcount==floor(sqrt(param_nbr_2)) || (j*i)==param_nbr^2
+                if (j*i)==param_nbr^2
                     d = d(:,:,1:jcount);
                 end
-%                 d(find(abs(d)<1.e-12))=0;
+                %                 d(find(abs(d)<1.e-12))=0;
                 xx2=sylvester3(a,b,c,d);
                 flag=1;
                 icount=0;
-                while flag && icount<4,
+                while flag && icount<4
                     [xx2, flag]=sylvester3a(xx2,a,b,c,d);
                     icount = icount + 1;
                 end
-%                 inx = find(abs(xx2)>1.e-12);
-%                 xx2(find(abs(xx2)<1.e-12))=0;
+                %                 inx = find(abs(xx2)>1.e-12);
+                %                 xx2(find(abs(xx2)<1.e-12))=0;
                 x2x(:,cumjcount+1:cumjcount+jcount)=reshape(xx2,[m*m jcount]);
                 cumjcount=cumjcount+jcount;
-%                 [i1 i2 i3]=ind2sub(size(xx2),inx);
-%                 x2x = [x2x; [i1 i2 jinx(i3,:) xx2(inx)]];
+                %                 [i1 i2 i3]=ind2sub(size(xx2),inx);
+                %                 x2x = [x2x; [i1 i2 jinx(i3,:) xx2(inx)]];
                 jcount = 0;
                 jinx = [];
             end
@@ -583,27 +572,27 @@ if nargout > 5,
     offset = length(indexo);
     %     d2B = zeros(m,n,tot_param_nbr,tot_param_nbr);
     d2Sig = zeros(M_.exo_nbr,M_.exo_nbr,length(indexo));
-    for j=1:tot_param_nbr,
-        for i=1:j,
+    for j=1:tot_param_nbr
+        for i=1:j
             jcount=jcount+1;
-            if j<=offset,
-                if i==j,
+            if j<=offset
+                if i==j
                     d2Sig(indexo(j),indexo(j),j) = 2;
                     y = B*d2Sig(:,:,j)*B';
-%                     y(abs(y)<1.e-8)=0;
+                    %                     y(abs(y)<1.e-8)=0;
                     d2Om_tmp(:,jcount) = dyn_vech(y(iv,iv));
                 end
             else
                 jind = j-offset;
                 iind = i-offset;
-                if i<=offset,
+                if i<=offset
                     y = dB(:,:,jind)*dSig(:,:,i)*B'+B*dSig(:,:,i)*dB(:,:,jind)';
-%                     y(abs(y)<1.e-8)=0;
+                    %                     y(abs(y)<1.e-8)=0;
                     d2Om_tmp(:,jcount) = dyn_vech(y(iv,iv));
                 else
                     icount=icount+1;
                     x = reshape(x2x(:,icount),[m m]);
-%                     x = get_2nd_deriv(x2x,m,m,iind,jind);%xx2(:,:,jcount);
+                    %                     x = get_2nd_deriv(x2x,m,m,iind,jind);%xx2(:,:,jcount);
                     elem1 = (get_2nd_deriv(D2g0,m,m,iind,jind)-get_2nd_deriv(D2g1,m,m,iind,jind)*A);
                     elem1 = elem1 -( Dg1(:,:,jind)*xx(:,:,iind) + Dg1(:,:,iind)*xx(:,:,jind) );
                     elemj0 = Dg0(:,:,jind)-Dg1(:,:,jind)*A-GAM1*xx(:,:,jind);
@@ -614,13 +603,13 @@ if nargout > 5,
                     %         d2B(:,:,i+length(indexo),j+length(indexo)) = y;
                     y = y*M_.Sigma_e*B'+B*M_.Sigma_e*y'+ ...
                         dB(:,:,jind)*M_.Sigma_e*dB(:,:,iind)'+dB(:,:,iind)*M_.Sigma_e*dB(:,:,jind)';
-%                     x(abs(x)<1.e-8)=0;
+                    %                     x(abs(x)<1.e-8)=0;
                     d2A_tmp(:,jcount) = vec(x(iv,iv));
-%                     y(abs(y)<1.e-8)=0;
+                    %                     y(abs(y)<1.e-8)=0;
                     d2Om_tmp(:,jcount) = dyn_vech(y(iv,iv));
                 end
             end
-            if jcount==ncol || i*j==tot_param_nbr^2,
+            if jcount==ncol || i*j==tot_param_nbr^2
                 d2A(:,cumjcount+1:cumjcount+jcount) = d2A_tmp(:,1:jcount);
                 %         d2A(:,:,j+length(indexo),i+length(indexo)) = x;
                 %         d2A(:,:,i+length(indexo),j+length(indexo)) = x;
@@ -635,7 +624,7 @@ if nargout > 5,
                 %         d2Om = sparse(m1*(m1+1)/2,tot_param_nbr*(tot_param_nbr+1)/2);
                 d2A_tmp = zeros(m1*m1,ncol);
                 d2Om_tmp = zeros(m1*(m1+1)/2,ncol);
-                
+
             end
         end
     end
@@ -643,100 +632,100 @@ end
 
 return
 
-function g22 = get_2nd_deriv(gpp,m,n,i,j),
+function g22 = get_2nd_deriv(gpp,m,n,i,j)
 
 g22=zeros(m,n);
 is=find(gpp(:,3)==i);
 is=is(find(gpp(is,4)==j));
 
-if ~isempty(is),
+if ~isempty(is)
     g22(sub2ind([m,n],gpp(is,1),gpp(is,2)))=gpp(is,5)';
 end
 return
 
-function g22 = get_2nd_deriv_mat(gpp,i,j,n),
+function g22 = get_2nd_deriv_mat(gpp,i,j,n)
 
 g22=zeros(n,n);
 is=find(gpp(:,1)==i);
 is=is(find(gpp(is,2)==j));
 
-if ~isempty(is),
+if ~isempty(is)
     g22(sub2ind([n,n],gpp(is,3),gpp(is,4)))=gpp(is,5)';
     g22(sub2ind([n,n],gpp(is,4),gpp(is,3)))=gpp(is,5)';
 end
 return
 
-function g22 = get_all_2nd_derivs(gpp,m,n,npar,fsparse),
+function g22 = get_all_2nd_derivs(gpp,m,n,npar,fsparse)
 
-if nargin==4 || isempty(fsparse),
+if nargin==4 || isempty(fsparse)
     fsparse=0;
 end
-if fsparse,
+if fsparse
     g22=sparse(m*n,npar*npar);
 else
-g22=zeros(m,n,npar,npar);
+    g22=zeros(m,n,npar,npar);
 end
 % c=ones(npar,npar);
 % c=triu(c);
 % ic=find(c);
 
-for is=1:length(gpp),
-%     d=zeros(npar,npar);
-%     d(gpp(is,3),gpp(is,4))=1;
-%     indx = find(ic==find(d));
-    if fsparse,
+for is=1:length(gpp)
+    %     d=zeros(npar,npar);
+    %     d(gpp(is,3),gpp(is,4))=1;
+    %     indx = find(ic==find(d));
+    if fsparse
         g22(sub2ind([m,n],gpp(is,1),gpp(is,2)),sub2ind([npar,npar],gpp(is,3),gpp(is,4)))=gpp(is,5);
         g22(sub2ind([m,n],gpp(is,1),gpp(is,2)),sub2ind([npar,npar],gpp(is,4),gpp(is,3)))=gpp(is,5);
     else
-    g22(gpp(is,1),gpp(is,2),gpp(is,3),gpp(is,4))=gpp(is,5);
-    g22(gpp(is,1),gpp(is,2),gpp(is,4),gpp(is,3))=gpp(is,5);
-end
+        g22(gpp(is,1),gpp(is,2),gpp(is,3),gpp(is,4))=gpp(is,5);
+        g22(gpp(is,1),gpp(is,2),gpp(is,4),gpp(is,3))=gpp(is,5);
+    end
 end
 
 return
 
-function r22 = get_all_resid_2nd_derivs(rpp,m,npar),
+function r22 = get_all_resid_2nd_derivs(rpp,m,npar)
 
 r22=zeros(m,npar,npar);
 % c=ones(npar,npar);
 % c=triu(c);
 % ic=find(c);
 
-for is=1:length(rpp),
-%     d=zeros(npar,npar);
-%     d(rpp(is,2),rpp(is,3))=1;
-%     indx = find(ic==find(d));
+for is=1:length(rpp)
+    %     d=zeros(npar,npar);
+    %     d(rpp(is,2),rpp(is,3))=1;
+    %     indx = find(ic==find(d));
     r22(rpp(is,1),rpp(is,2),rpp(is,3))=rpp(is,4);
     r22(rpp(is,1),rpp(is,3),rpp(is,2))=rpp(is,4);
 end
 
 return
 
-function h2 = get_all_hess_derivs(hp,r,m,npar),
+function h2 = get_all_hess_derivs(hp,r,m,npar)
 
 h2=zeros(r,m,m,npar);
 
-for is=1:length(hp),
+for is=1:length(hp)
     h2(hp(is,1),hp(is,2),hp(is,3),hp(is,4))=hp(is,5);
     h2(hp(is,1),hp(is,3),hp(is,2),hp(is,4))=hp(is,5);
 end
 
 return
 
-function h2 = get_hess_deriv(hp,i,j,m,npar),
+function h2 = get_hess_deriv(hp,i,j,m,npar)
 
 h2=zeros(m,npar);
 is1=find(hp(:,1)==i);
 is=is1(find(hp(is1,2)==j));
 
-if ~isempty(is),
+if ~isempty(is)
     h2(sub2ind([m,npar],hp(is,3),hp(is,4)))=hp(is,5)';
 end
 
 is=is1(find(hp(is1,3)==j));
 
-if ~isempty(is),
+if ~isempty(is)
     h2(sub2ind([m,npar],hp(is,2),hp(is,4)))=hp(is,5)';
 end
 
-return
+return
\ No newline at end of file
diff --git a/matlab/getIrfShocksIndx.m b/matlab/getIrfShocksIndx.m
index 737bfcfb1db036b9655afcb01f5069e3c22209e5..788d58cd1ff42cb7167d5e89495d2cf96031965c 100644
--- a/matlab/getIrfShocksIndx.m
+++ b/matlab/getIrfShocksIndx.m
@@ -8,7 +8,7 @@ function irf_shocks_indx=getIrfShocksIndx()
 % Outputs:
 %   irf_shocks_indx: [1 by n_irf_shocks] vector storing the indices
 %
-% Copyright (C) 2011-13 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -34,7 +34,7 @@ else
     for i=1:size(options_.irf_shocks,1)
         irf_shocks_indx(i) = find(strcmp(deblank(options_.irf_shocks(i,:)), cellstr(M_.exo_names)));
     end
-    irf_shocks_indx_unique=unique(irf_shocks_indx);    
+    irf_shocks_indx_unique=unique(irf_shocks_indx);
     if options_.debug && (length(irf_shocks_indx_unique) ~= length(irf_shocks_indx))
         fprintf('\nSTOCH_SIMUL: Warning: The IRFs for some shocks have been requested twice.\n')
         fprintf('STOCH_SIMUL: The redundant entries will be ignored.\n')
diff --git a/matlab/getJJ.m b/matlab/getJJ.m
index b7686a03599f8161d1171efec9792ac2130f6157..7f934b81aedaaa8f084c26b00404e13701a24d63 100644
--- a/matlab/getJJ.m
+++ b/matlab/getJJ.m
@@ -2,7 +2,7 @@ function [JJ, H, gam, gp, dA, dOm, dYss] = getJJ(A, B, estim_params_, M_,oo_,opt
 % function [JJ, H, gam, gp, dA, dOm, dYss] = getJJ(A, B, estim_params_, M_,oo_,options_,kronflag,indx,indexo,mf,nlags,useautocorr)
 % computes derivatives of 1st and 2nd order moments of observables with
 % respect to estimated parameters
-% 
+%
 % Inputs:
 %   A:              Transition matrix of lagged states from Kalman filter
 %   B:              Matrix in state transition equation mapping shocks today to
@@ -19,25 +19,25 @@ function [JJ, H, gam, gp, dA, dOm, dYss] = getJJ(A, B, estim_params_, M_,oo_,opt
 %                   correlations
 %   useautocorr:    Indicator on whether to use correlations (1) instead of
 %                   covariances (0)
-% 
+%
 % Outputs:
-%   JJ:             Jacobian of 1st and 2nd order moments of observables, i.e.  dgam/dTHETA 
+%   JJ:             Jacobian of 1st and 2nd order moments of observables, i.e.  dgam/dTHETA
 %                   (see below for definition of gam)
 %   H:              dTAU/dTHETA: Jacobian of TAU, vectorized form of
 %                   linearized reduced form state space model, given ys [steady state],
 %                   A [transition matrix], B [matrix of shocks], Sigma [covariance of shocks]
 %                   TAU = [ys; vec(A); dyn_vech(B*Sigma*B')].
-%   gam:            vector of theoretical moments of observed variables mf [JJ is the Jacobian of gam]. 
-%                   gam = [ys(mf); dyn_vech(GAM{1}); vec(GAM{j+1})]; for j=1:ar and where 
+%   gam:            vector of theoretical moments of observed variables mf [JJ is the Jacobian of gam].
+%                   gam = [ys(mf); dyn_vech(GAM{1}); vec(GAM{j+1})]; for j=1:ar and where
 %                   GAM is the first output of th_autocovariances
 %   gp:             Jacobian of linear rational expectation matrices [i.e.
 %                   Jacobian of dynamic model] with respect to estimated
 %                   structural parameters only (indx)
-%   dA:             [endo_nbr by endo_nbr by (indx+indexo)] Jacobian of transition matrix A           
+%   dA:             [endo_nbr by endo_nbr by (indx+indexo)] Jacobian of transition matrix A
 %   dOm:            Jacobian of Omega = (B*Sigma*B')
 %   dYss            Jacobian of steady state with respect to estimated structural parameters only (indx)
 
-% Copyright (C) 2010-2016 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -55,22 +55,22 @@ function [JJ, H, gam, gp, dA, dOm, dYss] = getJJ(A, B, estim_params_, M_,oo_,opt
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 if nargin<8 || isempty(indx)
-%     indx = [1:M_.param_nbr];
-end,
+    %     indx = [1:M_.param_nbr];
+end
 if nargin<9 || isempty(indexo)
     indexo = [];
-end,
+end
 if nargin<11 || isempty(nlags)
-    nlags=3; 
+    nlags=3;
 end
 if nargin<12 || isempty(useautocorr)
-    useautocorr=0; 
+    useautocorr=0;
 end
 
 %   if useautocorr,
 warning('off','MATLAB:divideByZero')
 %   end
-if kronflag == -1,
+if kronflag == -1
     fun = 'thet2tau';
     params0 = M_.params;
     para0 = get_all_parameters(estim_params_, M_);
@@ -87,7 +87,7 @@ if kronflag == -1,
     dYss = H(1:M_.endo_nbr,offset+1:end);
     dA = reshape(H(M_.orig_endo_nbr+[1:numel(A)],:),[size(A),size(H,2)]);
     dOm = dA*0;
-    for j=1:size(H,2),
+    for j=1:size(H,2)
         dOm(:,:,j) = dyn_unvech(H(M_.endo_nbr+numel(A)+1:end,j));
     end
     assignin('base','M_', M_);
@@ -109,13 +109,13 @@ else
     sdy = sqrt(diag(GAM));
     sy = sdy*sdy';
     %   end
-    
+
     %   BB = dOm*0;
     %   for j=1:length(indx),
     %     BB(:,:,j)= dA(:,:,j)*GAM*A'+A*GAM*dA(:,:,j)'+dOm(:,:,j);
     %   end
     %   XX =  lyapunov_symm_mr(A,BB,options_.qz_criterium,options_.lyapunov_complex_threshold,0);
-    for j=1:length(indexo),
+    for j=1:length(indexo)
         dum =  lyapunov_symm(A,dOm(:,:,j),options_.lyapunov_fixed_point_tol,options_.qz_criterium,options_.lyapunov_complex_threshold,2,options_.debug);
         %     dum =  XX(:,:,j);
         k = find(abs(dum) < 1e-12);
@@ -130,7 +130,7 @@ else
         else
             dumm = dyn_vech(dum(mf,mf));
         end
-        for i=1:nlags,
+        for i=1:nlags
             dum1 = A^i*dum;
             if useautocorr
                 dum1 = (dum1.*sy-dsy.*(A^i*GAM))./(sy.*sy);
@@ -140,7 +140,7 @@ else
         JJ(:,j) = dumm;
     end
     nexo = length(indexo);
-    for j=1:length(indx),
+    for j=1:length(indx)
         dum =  lyapunov_symm(A,dA(:,:,j+nexo)*GAM*A'+A*GAM*dA(:,:,j+nexo)'+dOm(:,:,j+nexo),options_.lyapunov_fixed_point_tol,options_.qz_criterium,options_.lyapunov_complex_threshold,2,options_.debug);
         %     dum =  XX(:,:,j);
         k = find(abs(dum) < 1e-12);
@@ -155,9 +155,9 @@ else
         else
             dumm = dyn_vech(dum(mf,mf));
         end
-        for i=1:nlags,
+        for i=1:nlags
             dum1 = A^i*dum;
-            for ii=1:i,
+            for ii=1:i
                 dum1 = dum1 + A^(ii-1)*dA(:,:,j+nexo)*A^(i-ii)*GAM;
             end
             if useautocorr
@@ -167,27 +167,27 @@ else
         end
         JJ(:,j+nexo) = dumm;
     end
-    
+
     JJ = [ [zeros(length(mf),nexo) dYss(mf,:)]; JJ];
-    
+
 end
-if nargout >2,
+if nargout >2
     %     sy=sy(mf,mf);
     options_.ar=nlags;
     nodecomposition = 1;
     [GAM,stationary_vars] = th_autocovariances(oo_.dr,oo_.dr.order_var(mf),M_,options_,nodecomposition);
     sy=sqrt(diag(GAM{1}));
     sy=sy*sy';
-    if useautocorr,
+    if useautocorr
         sy=sy-diag(diag(sy))+eye(length(mf));
         GAM{1}=GAM{1}./sy;
     else
-        for j=1:nlags,
+        for j=1:nlags
             GAM{j+1}=GAM{j+1}.*sy;
         end
     end
     gam = dyn_vech(GAM{1});
-    for j=1:nlags,
+    for j=1:nlags
         gam = [gam; vec(GAM{j+1})];
     end
 end
diff --git a/matlab/get_Hessian.m b/matlab/get_Hessian.m
index a42b3c81250b89ad85163dcfa46eff7f40094fe3..fe74848dd683157a67215289b1d278e4ec53211b 100644
--- a/matlab/get_Hessian.m
+++ b/matlab/get_Hessian.m
@@ -10,7 +10,7 @@ function [Hess] = get_Hessian(T,R,Q,H,P,Y,DT,DYss,DOm,DH,DP,D2T,D2Yss,D2Om,D2H,D
 % NOTE: the derivative matrices (D2T,D2Om ...) are 4-dim. arrays with last
 % two dimensions equal to the number of structural parameters
 
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -28,146 +28,146 @@ function [Hess] = get_Hessian(T,R,Q,H,P,Y,DT,DYss,DOm,DH,DP,D2T,D2Yss,D2Om,D2H,D
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 
-    k = size(DT,3);                                 % number of structural parameters
-    smpl = size(Y,2);                               % Sample size.
-    pp   = size(Y,1);                               % Maximum number of observed variables.
-    mm   = size(T,2);                               % Number of state variables.
-    a    = zeros(mm,1);                             % State vector.
-    Om   = R*Q*transpose(R);                        % Variance of R times the vector of structural innovations.
-    t    = 0;                                       % Initialization of the time index.
-    oldK = 0;
-    notsteady   = 1;                                % Steady state flag.
-    F_singular  = 1;
-
-    Hess  = zeros(k,k);                             % Initialization of the Hessian
-    Da    = zeros(mm,k);                             % State vector.
-    Dv = zeros(length(mf),k);
-    D2a    = zeros(mm,k,k);                             % State vector.
-    D2v = zeros(length(mf),k,k);
-
-    C = zeros(length(mf),mm);
-    for ii=1:length(mf); C(ii,mf(ii))=1;end         % SELECTION MATRIX IN MEASUREMENT EQ. (FOR WHEN IT IS NOT CONSTANT)
-    dC = zeros(length(mf),mm,k);
-    d2C = zeros(length(mf),mm,k,k);
-    
-    s   = zeros(pp,1);                      % CONSTANT TERM IN MEASUREMENT EQ. (FOR WHEN IT IS NOT CONSTANT)
-    ds  = zeros(pp,1,k);
-    d2s = zeros(pp,1,k,k);
-    
+k = size(DT,3);                                 % number of structural parameters
+smpl = size(Y,2);                               % Sample size.
+pp   = size(Y,1);                               % Maximum number of observed variables.
+mm   = size(T,2);                               % Number of state variables.
+a    = zeros(mm,1);                             % State vector.
+Om   = R*Q*transpose(R);                        % Variance of R times the vector of structural innovations.
+t    = 0;                                       % Initialization of the time index.
+oldK = 0;
+notsteady   = 1;                                % Steady state flag.
+F_singular  = 1;
+
+Hess  = zeros(k,k);                             % Initialization of the Hessian
+Da    = zeros(mm,k);                             % State vector.
+Dv = zeros(length(mf),k);
+D2a    = zeros(mm,k,k);                             % State vector.
+D2v = zeros(length(mf),k,k);
+
+C = zeros(length(mf),mm);
+for ii=1:length(mf); C(ii,mf(ii))=1;end         % SELECTION MATRIX IN MEASUREMENT EQ. (FOR WHEN IT IS NOT CONSTANT)
+dC = zeros(length(mf),mm,k);
+d2C = zeros(length(mf),mm,k,k);
+
+s   = zeros(pp,1);                      % CONSTANT TERM IN MEASUREMENT EQ. (FOR WHEN IT IS NOT CONSTANT)
+ds  = zeros(pp,1,k);
+d2s = zeros(pp,1,k,k);
+
 %     for ii = 1:k
-%         DOm = DR(:,:,ii)*Q*transpose(R) + R*DQ(:,:,ii)*transpose(R) + R*Q*transpose(DR(:,:,ii)); 
+%         DOm = DR(:,:,ii)*Q*transpose(R) + R*DQ(:,:,ii)*transpose(R) + R*Q*transpose(DR(:,:,ii));
 %     end
-    
-    while notsteady & t<smpl
-        t  = t+1;
-        v  = Y(:,t)-a(mf);
-        F  = P(mf,mf) + H;
-        if rcond(F) < kalman_tol
-            if ~all(abs(F(:))<kalman_tol)
-                return
-            else
-                a = T*a;
-                P = T*P*transpose(T)+Om;
-            end
+
+while notsteady & t<smpl
+    t  = t+1;
+    v  = Y(:,t)-a(mf);
+    F  = P(mf,mf) + H;
+    if rcond(F) < kalman_tol
+        if ~all(abs(F(:))<kalman_tol)
+            return
         else
-            F_singular = 0;
-            iF     = inv(F);
-            K      = P(:,mf)*iF;
-
-            [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K);
-            [D2K,D2F,D2P1] = computeD2Kalman(T,DT,D2T,D2Om,P,DP,D2P,DH,mf,iF,K,DK);
-            tmp = (a+K*v);
-
-    for ii = 1:k
-        Dv(:,ii)   = -Da(mf,ii) - DYss(mf,ii);
-      %  dai = da(:,:,ii);
-        dKi  = DK(:,:,ii);
-        diFi = -iF*DF(:,:,ii)*iF;
-        dtmpi = Da(:,ii)+dKi*v+K*Dv(:,ii);
-            
-        
-        for jj = 1:ii
-            dFj    = DF(:,:,jj);
-            diFj   = -iF*DF(:,:,jj)*iF;
-            dKj  = DK(:,:,jj);
-            d2Kij  = D2K(:,:,jj,ii);
-            d2Fij  = D2F(:,:,jj,ii);
-            d2iFij = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi;
-            dtmpj = Da(:,jj)+dKj*v+K*Dv(:,jj);
-
-            d2vij  = -D2Yss(mf,jj,ii)  - D2a(mf,jj,ii); 
-            d2tmpij = D2a(:,jj,ii) + d2Kij*v + dKj*Dv(:,ii) + dKi*Dv(:,jj) + K*d2vij;
-            D2a(:,jj,ii) = D2T(:,:,jj,ii)*tmp + DT(:,:,jj)*dtmpi + DT(:,:,ii)*dtmpj + T*d2tmpij;            
-
-            Hesst(ii,jj) = getHesst_ij(v,Dv(:,ii),Dv(:,jj),d2vij,iF,diFi,diFj,d2iFij,dFj,d2Fij);
+            a = T*a;
+            P = T*P*transpose(T)+Om;
         end
-        Da(:,ii)   = DT(:,:,ii)*tmp + T*dtmpi;
-    end
-%                     vecDPmf = reshape(DP(mf,mf,:),[],k);
-%                     iPmf = inv(P(mf,mf));
-                    if t>=start
-                        Hess = Hess + Hesst;
-                    end
-            a      = T*(a+K*v);                   
-            P      = T*(P-K*P(mf,:))*transpose(T)+Om;
-            DP     = DP1;
-            D2P     = D2P1;
+    else
+        F_singular = 0;
+        iF     = inv(F);
+        K      = P(:,mf)*iF;
+
+        [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K);
+        [D2K,D2F,D2P1] = computeD2Kalman(T,DT,D2T,D2Om,P,DP,D2P,DH,mf,iF,K,DK);
+        tmp = (a+K*v);
+
+        for ii = 1:k
+            Dv(:,ii)   = -Da(mf,ii) - DYss(mf,ii);
+            %  dai = da(:,:,ii);
+            dKi  = DK(:,:,ii);
+            diFi = -iF*DF(:,:,ii)*iF;
+            dtmpi = Da(:,ii)+dKi*v+K*Dv(:,ii);
+
+
+            for jj = 1:ii
+                dFj    = DF(:,:,jj);
+                diFj   = -iF*DF(:,:,jj)*iF;
+                dKj  = DK(:,:,jj);
+                d2Kij  = D2K(:,:,jj,ii);
+                d2Fij  = D2F(:,:,jj,ii);
+                d2iFij = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi;
+                dtmpj = Da(:,jj)+dKj*v+K*Dv(:,jj);
+
+                d2vij  = -D2Yss(mf,jj,ii)  - D2a(mf,jj,ii);
+                d2tmpij = D2a(:,jj,ii) + d2Kij*v + dKj*Dv(:,ii) + dKi*Dv(:,jj) + K*d2vij;
+                D2a(:,jj,ii) = D2T(:,:,jj,ii)*tmp + DT(:,:,jj)*dtmpi + DT(:,:,ii)*dtmpj + T*d2tmpij;
+
+                Hesst(ii,jj) = getHesst_ij(v,Dv(:,ii),Dv(:,jj),d2vij,iF,diFi,diFj,d2iFij,dFj,d2Fij);
+            end
+            Da(:,ii)   = DT(:,:,ii)*tmp + T*dtmpi;
+        end
+        %                     vecDPmf = reshape(DP(mf,mf,:),[],k);
+        %                     iPmf = inv(P(mf,mf));
+        if t>=start
+            Hess = Hess + Hesst;
         end
-        notsteady = max(max(abs(K-oldK))) > riccati_tol;
-        oldK = K;
+        a      = T*(a+K*v);
+        P      = T*(P-K*P(mf,:))*transpose(T)+Om;
+        DP     = DP1;
+        D2P     = D2P1;
     end
+    notsteady = max(max(abs(K-oldK))) > riccati_tol;
+    oldK = K;
+end
 
-    if F_singular
-        error('The variance of the forecast error remains singular until the end of the sample')
-    end
+if F_singular
+    error('The variance of the forecast error remains singular until the end of the sample')
+end
 
-    
-    if t < smpl
-        t0 = t+1;
-        while t < smpl
-            t = t+1;
-            v = Y(:,t)-a(mf);
-            tmp = (a+K*v);
-            for ii = 1:k,
-                Dv(:,ii)   = -Da(mf,ii)-DYss(mf,ii);
-                dKi  = DK(:,:,ii);
-                diFi = -iF*DF(:,:,ii)*iF;
-                dtmpi = Da(:,ii)+dKi*v+K*Dv(:,ii);
-                
-                for jj = 1:ii,
-                    dFj    = DF(:,:,jj);
-                    diFj   = -iF*DF(:,:,jj)*iF;
-                    dKj  = DK(:,:,jj);
-                    d2Kij  = D2K(:,:,jj,ii);
-                    d2Fij  = D2F(:,:,jj,ii);
-                    d2iFij = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi;
-                    dtmpj = Da(:,jj)+dKj*v+K*Dv(:,jj);
-                    
-                    d2vij  = -D2Yss(mf,jj,ii)  - D2a(mf,jj,ii);
-                    d2tmpij = D2a(:,jj,ii) + d2Kij*v + dKj*Dv(:,ii) + dKi*Dv(:,jj) + K*d2vij;
-                    D2a(:,jj,ii) = D2T(:,:,jj,ii)*tmp + DT(:,:,jj)*dtmpi + DT(:,:,ii)*dtmpj + T*d2tmpij;            
-                    
-                    Hesst(ii,jj) = getHesst_ij(v,Dv(:,ii),Dv(:,jj),d2vij,iF,diFi,diFj,d2iFij,dFj,d2Fij);
-                end
-                Da(:,ii)   = DT(:,:,ii)*tmp + T*dtmpi;
-            end
-            if t>=start
-                Hess = Hess + Hesst;
+
+if t < smpl
+    t0 = t+1;
+    while t < smpl
+        t = t+1;
+        v = Y(:,t)-a(mf);
+        tmp = (a+K*v);
+        for ii = 1:k
+            Dv(:,ii)   = -Da(mf,ii)-DYss(mf,ii);
+            dKi  = DK(:,:,ii);
+            diFi = -iF*DF(:,:,ii)*iF;
+            dtmpi = Da(:,ii)+dKi*v+K*Dv(:,ii);
+
+            for jj = 1:ii
+                dFj    = DF(:,:,jj);
+                diFj   = -iF*DF(:,:,jj)*iF;
+                dKj  = DK(:,:,jj);
+                d2Kij  = D2K(:,:,jj,ii);
+                d2Fij  = D2F(:,:,jj,ii);
+                d2iFij = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi;
+                dtmpj = Da(:,jj)+dKj*v+K*Dv(:,jj);
+
+                d2vij  = -D2Yss(mf,jj,ii)  - D2a(mf,jj,ii);
+                d2tmpij = D2a(:,jj,ii) + d2Kij*v + dKj*Dv(:,ii) + dKi*Dv(:,jj) + K*d2vij;
+                D2a(:,jj,ii) = D2T(:,:,jj,ii)*tmp + DT(:,:,jj)*dtmpi + DT(:,:,ii)*dtmpj + T*d2tmpij;
+
+                Hesst(ii,jj) = getHesst_ij(v,Dv(:,ii),Dv(:,jj),d2vij,iF,diFi,diFj,d2iFij,dFj,d2Fij);
             end
-            a = T*(a+K*v);
+            Da(:,ii)   = DT(:,:,ii)*tmp + T*dtmpi;
+        end
+        if t>=start
+            Hess = Hess + Hesst;
         end
-%         Hess = Hess + .5*(smpl+t0-1)*(vecDPmf' * kron(iPmf,iPmf) * vecDPmf);
-        %         for ii = 1:k;
-        %             for jj = 1:ii
-        %              H(ii,jj) = trace(iPmf*(.5*DP(mf,mf,ii)*iPmf*DP(mf,mf,jj) + Dv(:,ii)*Dv(:,jj)'));
-        %             end
-        %         end
+        a = T*(a+K*v);
     end
-    
+    %         Hess = Hess + .5*(smpl+t0-1)*(vecDPmf' * kron(iPmf,iPmf) * vecDPmf);
+    %         for ii = 1:k;
+    %             for jj = 1:ii
+    %              H(ii,jj) = trace(iPmf*(.5*DP(mf,mf,ii)*iPmf*DP(mf,mf,jj) + Dv(:,ii)*Dv(:,jj)'));
+    %             end
+    %         end
+end
+
 Hess = Hess + tril(Hess,-1)';
 
-Hess = -Hess/2;  
-% end of main function    
+Hess = -Hess/2;
+% end of main function
 
 function Hesst_ij = getHesst_ij(e,dei,dej,d2eij,iS,diSi,diSj,d2iSij,dSj,d2Sij);
 % computes (i,j) term in the Hessian
@@ -178,11 +178,11 @@ Hesst_ij = trace(diSi*dSj + iS*d2Sij) + e'*d2iSij*e + 2*(dei'*diSj*e + dei'*iS*d
 
 function [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K)
 
-            k      = size(DT,3);
-            tmp    = P-K*P(mf,:);
+k      = size(DT,3);
+tmp    = P-K*P(mf,:);
 
 for ii = 1:k
-    DF(:,:,ii)  = DP(mf,mf,ii) + DH(:,:,ii); 
+    DF(:,:,ii)  = DP(mf,mf,ii) + DH(:,:,ii);
     DiF(:,:,ii) = -iF*DF(:,:,ii)*iF;
     DK(:,:,ii)  = DP(:,mf,ii)*iF + P(:,mf)*DiF(:,:,ii);
     Dtmp        = DP(:,:,ii) - DK(:,:,ii)*P(mf,:) - K*DP(mf,:,ii);
@@ -191,12 +191,12 @@ end
 
 % end of computeDKalman
 
-function [d2K,d2S,d2P1] = computeD2Kalman(A,dA,d2A,d2Om,P0,dP0,d2P0,DH,mf,iF,K0,dK0);
+function [d2K,d2S,d2P1] = computeD2Kalman(A,dA,d2A,d2Om,P0,dP0,d2P0,DH,mf,iF,K0,dK0)
 % computes the second derivatives of the Kalman matrices
 % note: A=T in main func.
-        
-            k      = size(dA,3);
-            tmp    = P0-K0*P0(mf,:);
+
+k      = size(dA,3);
+tmp    = P0-K0*P0(mf,:);
 [ns,no] = size(K0);
 
 % CPC = C*P0*C'; CPC = .5*(CPC+CPC');iF = inv(CPC);
@@ -225,34 +225,31 @@ for ii = 1:k
         d2Aij = d2A(:,:,jj,ii);
         d2Pij = d2P0(:,:,jj,ii);
         d2Omij = d2Om(:,:,jj,ii);
-       
-    % second order
-    
-    d2Fij = d2Pij(mf,mf) ;
-    
-%     d2APC = d2Aij*P0*C' + A*d2Pij*C' + A*P0*d2Cij' + dAi*dPj*C' + dAj*dPi*C' + A*dPj*dCi' + A*dPi*dCj' + dAi*P0*dCj' + dAj*P0*dCi';
-    d2APC = d2Pij(:,mf);
-    
-    d2iF = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi;
-    
-    d2Kij= d2Pij(:,mf)*iF + P0(:,mf)*d2iF + dP0(:,mf,jj)*diFi + dP0(:,mf,ii)*diFj;
-        
-    d2KCP = d2Kij*P0(mf,:) + K0*d2Pij(mf,:) + dKi*dP0(mf,:,jj) + dKj*dP0(mf,:,ii) ;
-    
-    dtmpi        = dP0(:,:,ii) - dK0(:,:,ii)*P0(mf,:) - K0*dP0(mf,:,ii);
-    dtmpj        = dP0(:,:,jj) - dK0(:,:,jj)*P0(mf,:) - K0*dP0(mf,:,jj);
-    d2tmp = d2Pij - d2KCP;
-
-    d2AtmpA = d2Aij*tmp*A' + A*d2tmp*A' + A*tmp*d2Aij' + dAi*dtmpj*A' + dAj*dtmpi*A' + A*dtmpj*dAi' + A*dtmpi*dAj' + dAi*tmp*dAj' + dAj*tmp*dAi';
-
-    d2K(:,:,ii,jj)  = d2Kij; %#ok<NASGU>
-    d2P1(:,:,ii,jj) = d2AtmpA  + d2Omij;  %#ok<*NASGU>
-    d2S(:,:,ii,jj)  = d2Fij;
-%     d2iS(:,:,ii,jj) = d2iF;
+
+        % second order
+
+        d2Fij = d2Pij(mf,mf) ;
+
+        %     d2APC = d2Aij*P0*C' + A*d2Pij*C' + A*P0*d2Cij' + dAi*dPj*C' + dAj*dPi*C' + A*dPj*dCi' + A*dPi*dCj' + dAi*P0*dCj' + dAj*P0*dCi';
+        d2APC = d2Pij(:,mf);
+
+        d2iF = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi;
+
+        d2Kij= d2Pij(:,mf)*iF + P0(:,mf)*d2iF + dP0(:,mf,jj)*diFi + dP0(:,mf,ii)*diFj;
+
+        d2KCP = d2Kij*P0(mf,:) + K0*d2Pij(mf,:) + dKi*dP0(mf,:,jj) + dKj*dP0(mf,:,ii) ;
+
+        dtmpi        = dP0(:,:,ii) - dK0(:,:,ii)*P0(mf,:) - K0*dP0(mf,:,ii);
+        dtmpj        = dP0(:,:,jj) - dK0(:,:,jj)*P0(mf,:) - K0*dP0(mf,:,jj);
+        d2tmp = d2Pij - d2KCP;
+
+        d2AtmpA = d2Aij*tmp*A' + A*d2tmp*A' + A*tmp*d2Aij' + dAi*dtmpj*A' + dAj*dtmpi*A' + A*dtmpj*dAi' + A*dtmpi*dAj' + dAi*tmp*dAj' + dAj*tmp*dAi';
+
+        d2K(:,:,ii,jj)  = d2Kij; %#ok<NASGU>
+        d2P1(:,:,ii,jj) = d2AtmpA  + d2Omij;  %#ok<*NASGU>
+        d2S(:,:,ii,jj)  = d2Fij;
+        %     d2iS(:,:,ii,jj) = d2iF;
     end
 end
 
 % end of computeD2Kalman
-
-
-            
\ No newline at end of file
diff --git a/matlab/get_all_parameters.m b/matlab/get_all_parameters.m
index f924157705de918ae8917e2329c003a2eb8fd061..289b6a67994a50007c44085e80e429787ccac3ac 100644
--- a/matlab/get_all_parameters.m
+++ b/matlab/get_all_parameters.m
@@ -4,18 +4,18 @@ function xparam1=get_all_parameters(estim_params_,M_)
 % gets parameters values from M_.params into xparam1 (inverse mapping to set_all_parameters)
 % This is called if a model was calibrated before estimation to back out
 % parameter values
-% 
+%
 % INPUTS
-%	 estim_params_:  Dynare structure describing the estimated parameters.
-%    M_:             Dynare structure describing the model. 
+%        estim_params_:  Dynare structure describing the estimated parameters.
+%    M_:             Dynare structure describing the model.
 %
 % OUTPUTS
 %    xparam1:       N*1 double vector of parameters from calibrated model that are to be estimated
-%        
+%
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -100,5 +100,5 @@ offset = nvx+ncx+nvn+ncn;
 
 % structural parameters
 if np
-     xparam1(offset+1:end)=M_.params(estim_params_.param_vals(:,1));
+    xparam1(offset+1:end)=M_.params(estim_params_.param_vals(:,1));
 end
\ No newline at end of file
diff --git a/matlab/get_dynare_random_generator_state.m b/matlab/get_dynare_random_generator_state.m
index 513919c220ff7de3f5a3d364cefd6637381d08e0..b2789b054d083ee4a6e6d962b73523cd3cbfee53 100644
--- a/matlab/get_dynare_random_generator_state.m
+++ b/matlab/get_dynare_random_generator_state.m
@@ -1,12 +1,12 @@
 function [state_u,state_n] = get_dynare_random_generator_state()
 % Get state of Matlab/Octave random generator depending on matlab
-% (octave) version. 
+% (octave) version.
 % In older versions, Matlab kept one generator for uniformly distributed numbers and
-% one for normally distributed numbers. 
+% one for normally distributed numbers.
 % For backward compatibility, we return two vectors, but, in recent
 % versions of Matlab and in Octave, we return two identical vectors.
 
-% Copyright (C) 2010-2013 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -23,22 +23,22 @@ function [state_u,state_n] = get_dynare_random_generator_state()
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-    matlab_random_streams = ~(isoctave || matlab_ver_less_than('7.7'));
+matlab_random_streams = ~(isoctave || matlab_ver_less_than('7.7'));
 
-    if matlab_random_streams% Use new matlab interface.
-        if matlab_ver_less_than('7.12')
-            s = RandStream.getDefaultStream();
-        else
-            s = RandStream.getGlobalStream();
-        end
-        if isequal(s.Type,'legacy')
-            state_u = rand('state');
-            state_n = randn('state');
-        else            
-            state_u = s.State;
-            state_n = state_u;
-        end
-    else% Use old matlab interface.
+if matlab_random_streams% Use new matlab interface.
+    if matlab_ver_less_than('7.12')
+        s = RandStream.getDefaultStream();
+    else
+        s = RandStream.getGlobalStream();
+    end
+    if isequal(s.Type,'legacy')
         state_u = rand('state');
         state_n = randn('state');
-    end
\ No newline at end of file
+    else
+        state_u = s.State;
+        state_n = state_u;
+    end
+else% Use old matlab interface.
+    state_u = rand('state');
+    state_n = randn('state');
+end
\ No newline at end of file
diff --git a/matlab/get_file_extension.m b/matlab/get_file_extension.m
index d922b36ac50150c4a8e925ad4446df03ad166ded..dad9ee0ac9157fbcde933064970cc98ae0e9a9bd 100644
--- a/matlab/get_file_extension.m
+++ b/matlab/get_file_extension.m
@@ -2,16 +2,16 @@ function ext = get_file_extension(file)
 
 % returns the extension of a file.
 %
-% INPUTS 
+% INPUTS
 %  o file      string, name of the file
 %
-% OUTPUTS 
+% OUTPUTS
 %  o ext       string, extension.
 %
-% REMARKS 
+% REMARKS
 %  If the provided file name has no extension, the routine will return an empty array.
-    
-% Copyright (C) 2013-2015 Dynare Team
+
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/get_moments_size.m b/matlab/get_moments_size.m
index aa8087c025500e342c8bfa5848765113ef9cf146..6515c39b8a3e127f752d2a8bc523f4771c8b98a6 100644
--- a/matlab/get_moments_size.m
+++ b/matlab/get_moments_size.m
@@ -4,14 +4,14 @@ function s=get_moments_size(options)
 %
 % INPUTS
 %    options: structure of Dynare options
-%    
+%
 % OUTPUTS
 %    s: size of moments for a given model and options
-%        
+%
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2008-2011 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/get_name_of_the_last_mh_file.m b/matlab/get_name_of_the_last_mh_file.m
index 7634351251eb65c36fee1a16438fe2d8e1273c0b..e6732a2ef4ca62647ddda2cd1cb76f7fce982dbd 100644
--- a/matlab/get_name_of_the_last_mh_file.m
+++ b/matlab/get_name_of_the_last_mh_file.m
@@ -1,17 +1,17 @@
 function [mhname,info] = get_name_of_the_last_mh_file(M_)
 % This function returns the name of the last mh file and test if the metropolis was completed.
 %
-% INPUTS 
-%   M_       [structure]   Dynare structure specifying the model.     
+% INPUTS
+%   M_       [structure]   Dynare structure specifying the model.
 %
-% OUTPUTS 
-%  mhname    [string]      Name of the last mh file (with complete path).  
+% OUTPUTS
+%  mhname    [string]      Name of the last mh file (with complete path).
 %  info      [integer]     Scalar. If info is equal to 1 then the predicted name of the last
-%                          metropolis hastings matches the name of the name of the last mh 
-%                          file. Otherwise info is equal to zero (a likely reason for this is 
+%                          metropolis hastings matches the name of the name of the last mh
+%                          file. Otherwise info is equal to zero (a likely reason for this is
 %                          that the mcmc simulations were not completed).
 
-% Copyright (C) 2008-2013 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/get_new_or_existing_ei_index.m b/matlab/get_new_or_existing_ei_index.m
index 39bec99a329ed9aa6c195102d935d4e482501370..a6b3b85e19924e58806e9cacdcc8168dcd314250 100644
--- a/matlab/get_new_or_existing_ei_index.m
+++ b/matlab/get_new_or_existing_ei_index.m
@@ -17,7 +17,7 @@ function indx = get_new_or_existing_ei_index(substructure_name, name1, name2)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -38,7 +38,7 @@ global estimation_info
 
 if eval(['isempty(estimation_info.' substructure_name ')'])
     indx = 1;
-    return;
+    return
 end
 
 if isempty(name2) % parameter or std() statement
diff --git a/matlab/get_optimal_policy_discount_factor.m b/matlab/get_optimal_policy_discount_factor.m
index 67931b8ab1eb51fd7552c4288acd3b9c2023d657..89b605b3b55fe379cd74a921850904f2ec9a3b22 100644
--- a/matlab/get_optimal_policy_discount_factor.m
+++ b/matlab/get_optimal_policy_discount_factor.m
@@ -2,18 +2,18 @@ function discount_factor=get_optimal_policy_discount_factor(params,param_names)
 
 %function discount_factor=get_optimal_policy_discount_factor(M)
 %  get the value of Ramsey policy discount factor
-% 
+%
 % INPUTS
-%   params:             (vector) value of parameters    
+%   params:             (vector) value of parameters
 %   param_names:        (char array) list of parameter names
-%    
+%
 % OUTPUTS
 %   discount_factor     (double) discount factor
 %
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2007-2011 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -30,4 +30,4 @@ function discount_factor=get_optimal_policy_discount_factor(params,param_names)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-    discount_factor = params(find(strcmp('optimal_policy_discount_factor',cellstr(param_names))));
+discount_factor = params(find(strcmp('optimal_policy_discount_factor',cellstr(param_names))));
diff --git a/matlab/get_param_by_name.m b/matlab/get_param_by_name.m
index 795ac88dff1c450d3f26735fc140c77dfa0926b5..b06ab5f0740a978a4a3c9b82a24ee104ead24654 100644
--- a/matlab/get_param_by_name.m
+++ b/matlab/get_param_by_name.m
@@ -1,7 +1,7 @@
 function x = get_param_by_name(pname)
 % function x = get_param_by_name(pname)
 % returns the value of a parameter identified by its name
-%  
+%
 % INPUTS:
 %   pname:  parameter name
 %
@@ -11,7 +11,7 @@ function x = get_param_by_name(pname)
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2006-2009 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/get_posterior_parameters.m b/matlab/get_posterior_parameters.m
index 495f365657623b228f78fef688607bf34e192a6f..e10616d2078e964ff6f47aa16a5f0ccfb947f775 100644
--- a/matlab/get_posterior_parameters.m
+++ b/matlab/get_posterior_parameters.m
@@ -2,18 +2,18 @@ function xparam = get_posterior_parameters(type,field1)
 
 % function xparam = get_posterior_parameters(type)
 % Selects (estimated) parameters (posterior mode or posterior mean).
-% 
-% INPUTS 
+%
+% INPUTS
 %   o type       [char]     = 'mode' or 'mean'.
 %   o field_1    [char]     optional field like 'mle_'.
-%  
-% OUTPUTS 
-%   o xparam     vector of estimated parameters  
+%
+% OUTPUTS
+%   o xparam     vector of estimated parameters
 %
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2006-2016 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -30,7 +30,7 @@ function xparam = get_posterior_parameters(type,field1)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-global estim_params_ oo_ options_ M_ 
+global estim_params_ oo_ options_ M_
 
 if nargin<2
     field1='posterior_';
diff --git a/matlab/get_subsamples_range_indx.m b/matlab/get_subsamples_range_indx.m
index 1d114c6869d38b01258bf262d60567f7055b53dd..56c87f286ad02b6a50075d7ed451eff8e74ebbf9 100644
--- a/matlab/get_subsamples_range_indx.m
+++ b/matlab/get_subsamples_range_indx.m
@@ -16,7 +16,7 @@ function range_indx = get_subsamples_range_indx(subsamples_indx, range_label)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -39,5 +39,5 @@ range_indx = find(strcmp(range_label, estimation_info.subsamples(subsamples_indx
 
 if size(range_indx,2) ~= 1
     error(['Error: Index not found in estimation_info.subsamples(' ...
-        num2str(subsamples_indx) ').range_index for label ' range_label]);
+           num2str(subsamples_indx) ').range_index for label ' range_label]);
 end
diff --git a/matlab/get_variables_list.m b/matlab/get_variables_list.m
index 5d6a93c84f17e42913eee8d244a2f6e900828cbd..b72479b37c891f9f5b3b0175c64a303b34713e14 100644
--- a/matlab/get_variables_list.m
+++ b/matlab/get_variables_list.m
@@ -1,22 +1,22 @@
 function [ivar,vartan,options_] = get_variables_list(options_,M_)
 % This function builds a vector of indices in varlist or varobs.
-% 
-% INPUTS 
-%   o options_   [structure]  Describes global options. 
+%
+% INPUTS
+%   o options_   [structure]  Describes global options.
 %   o M_         [structure]  Describes the model.
-% OUTPUTS 
+% OUTPUTS
 %   o ivar       [integer]    nvar*1 vector of indices (nvar is the number
 %                             of variables).
 %   o vartan     [char]       array of characters (with nvar rows).
 %   o options_   [structure]  Describes global options.
-% 
-% ALGORITHM 
-%   None.       
+%
+% ALGORITHM
+%   None.
 %
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2007-2012 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/get_variance_of_endogenous_variables.m b/matlab/get_variance_of_endogenous_variables.m
index 005ceb8e08db837c6c07ab73e5411a99d2c3e676..965319b1bdadf8960309f849c305f3b883be58fc 100644
--- a/matlab/get_variance_of_endogenous_variables.m
+++ b/matlab/get_variance_of_endogenous_variables.m
@@ -6,14 +6,14 @@ function vx1 = get_variance_of_endogenous_variables(dr,i_var)
 % INPUTS
 %    dr:        structure of decisions rules for stochastic simulations
 %    i_var:     indices of a variables list
-%        
+%
 % OUTPUTS
 %    vx1:       variance-covariance matrix
-%        
+%
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2012 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -48,7 +48,7 @@ n = length(i_var);
 [vx,u] = lyapunov_symm(A,B*Sigma_e*B',options_.lyapunov_fixed_point_tol,options_.qz_criterium,options_.lyapunov_complex_threshold, [], options_.debug);
 
 if size(u,2) > 0
-    i_stat = find(any(abs(ghx*u) < options_.Schur_vec_tol,2)); %only set those variances of objective function for which variance is finite     
+    i_stat = find(any(abs(ghx*u) < options_.Schur_vec_tol,2)); %only set those variances of objective function for which variance is finite
     ghx = ghx(i_stat,:);
     ghu = ghu(i_stat,:);
 else
@@ -57,4 +57,3 @@ end
 
 vx1 = Inf*ones(n,n);
 vx1(i_stat,i_stat) = ghx*vx*ghx'+ghu*Sigma_e*ghu';
-
diff --git a/matlab/global_initialization.m b/matlab/global_initialization.m
index e8d1627e26cd41e2d7caba99ae7043bc0d1971fd..d26b488c840b2e01750c340acef14bcde18cae99 100644
--- a/matlab/global_initialization.m
+++ b/matlab/global_initialization.m
@@ -11,7 +11,7 @@ function global_initialization()
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2016 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -165,9 +165,9 @@ options_.nocorr = 0;
 options_.periods = 0;
 options_.noprint = 0;
 options_.SpectralDensity.trigger = 0;
-options_.SpectralDensity.plot  = 1; 
-options_.SpectralDensity.cutoff  = 150; 
-options_.SpectralDensity.sdl = 0.01; 
+options_.SpectralDensity.plot  = 1;
+options_.SpectralDensity.cutoff  = 150;
+options_.SpectralDensity.sdl = 0.01;
 options_.nofunctions = false;
 
 options_.bandpass.indicator = 0;
@@ -282,7 +282,7 @@ particle.resampling.number_of_partitions = 200;
 particle.mixture_state_variables = 5 ;
 particle.mixture_structural_shocks = 1 ;
 particle.mixture_measurement_shocks = 1 ;
-% Online approach 
+% Online approach
 particle.liu_west_delta = 0.99 ;
 particle.liu_west_chol_sigma_bar = .01 ;
 % Options for setting the weights in conditional particle filters.
@@ -471,7 +471,7 @@ options_.sub_draws = [];
 options_.gradient_method = 2; %used by csminwel and newrat
 options_.gradient_epsilon = 1e-6; %used by csminwel and newrat
 options_.posterior_sampler_options.sampling_opt = []; %extended set of options for individual posterior samplers
-% Random Walk Metropolis-Hastings
+                                                      % Random Walk Metropolis-Hastings
 options_.posterior_sampler_options.posterior_sampling_method = 'random_walk_metropolis_hastings';
 options_.posterior_sampler_options.rwmh.proposal_distribution = 'rand_multivariate_normal';
 options_.posterior_sampler_options.rwmh.student_degrees_of_freedom = 3;
@@ -525,8 +525,8 @@ options_.estimation.moments_posterior_density.indicator = 1;
 options_.estimation.moments_posterior_density.gridpoints = 2^9;
 options_.estimation.moments_posterior_density.bandwidth = 0; % Rule of thumb optimal bandwidth parameter.
 options_.estimation.moments_posterior_density.kernel_function = 'gaussian'; % Gaussian kernel for Fast Fourrier Transform approximaton.
-% Misc
-% options_.conf_sig = 0.6;
+                                                                            % Misc
+                                                                            % options_.conf_sig = 0.6;
 oo_.exo_simul = [];
 oo_.endo_simul = [];
 ys0_ = [];
@@ -568,6 +568,9 @@ options_.homotopy_force_continue = 0;
 % numerical hessian
 hessian.use_penalized_objective = false;
 
+% Robust prediction error covariance (kalman filter)
+options_.rescale_prediction_error_covariance = false;
+
 options_.hessian = hessian;
 
 %csminwel optimization routine
@@ -629,7 +632,7 @@ 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.TolFun=1e-6; %accuracy of function
 solveopt.MaxIter=15000;
 solveopt.verbosity=1;
 solveopt.TolXConstraint=1.e-8;
@@ -722,7 +725,14 @@ options_.discretionary_tol = 1e-7;
 % Shock decomposition
 options_.parameter_set = [];
 options_.use_shock_groups = '';
-options_.colormap = '';
+options_.shock_decomp.colormap = '';
+options_.shock_decomp.init_state = 0;
+
+% Shock decomposition realtime
+options_.shock_decomp.forecast = 0;
+options_.shock_decomp.presample = NaN;
+options_.shock_decomp.save_realtime = 0; % saves memory
+options_ = set_default_plot_shock_decomposition_options(options_);
 
 % Nonlinearfilters
 options_.nonlinear_filter = [];
@@ -831,4 +841,3 @@ set_dynare_seed('default');
 if isfield(options_, 'global_init_file')
     run(options_.global_init_file);
 end
-
diff --git a/matlab/graph_decomp.m b/matlab/graph_decomp.m
index 2edd40ef547045b1d8cacb04ad276104c827478f..f2c6705490602085d01b30e82b1292b36d462ef3 100644
--- a/matlab/graph_decomp.m
+++ b/matlab/graph_decomp.m
@@ -1,7 +1,7 @@
 function []=graph_decomp(z,shock_names,endo_names,i_var,initial_date,DynareModel,DynareOptions)
 %function []=graph_decomp(z,shock_names,endo_names,i_var,initial_date,DynareModel,DynareOptions)
 % Plots the results from the shock_decomposition command
-% 
+%
 % Inputs
 %   z               [n_var*(nshock+2)*nperiods]     shock decomposition array, see shock_decomposition.m for details
 %   shock_names     [endo_nbr*string length]        shock names from M_.exo_names
@@ -11,7 +11,7 @@ function []=graph_decomp(z,shock_names,endo_names,i_var,initial_date,DynareModel
 %   DynareModel     [structure]                     Dynare model structure
 %   DynareOptions   [structure]                     Dynare options structure
 
-% Copyright (C) 2010-2016 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -28,46 +28,111 @@ function []=graph_decomp(z,shock_names,endo_names,i_var,initial_date,DynareModel
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-new_colormap = DynareOptions.colormap;
+GraphDirectoryName = CheckPath('graphs',DynareModel.dname);
+new_colormap = DynareOptions.plot_shock_decomp.colormap;
 
 % number of components equals number of shocks + 1 (initial conditions)
 comp_nbr = size(z,2)-1;
 
+SteadyState=[];
+fig_mode='';
+fig_mode1='';
+% fig_name='';
+% screen_shocks=0;
+opts_decomp = DynareOptions.plot_shock_decomp;
+if isfield(opts_decomp,'steady_state')
+    SteadyState = opts_decomp.steady_state;
+end
+if ~isempty(opts_decomp.type)
+    fig_mode = opts_decomp.type;
+    fig_mode1 = ['_' fig_mode];
+    fig_mode = [fig_mode '_'];
+end
+fig_name_long = opts_decomp.fig_name;
+
+use_shock_groups = DynareOptions.plot_shock_decomp.use_shock_groups;
+screen_shocks = opts_decomp.screen_shocks;
+if use_shock_groups | comp_nbr<=18
+    screen_shocks=0;
+end
+if use_shock_groups
+    shock_groups = DynareModel.shock_groups.(use_shock_groups);
+    shock_ind = fieldnames(shock_groups);
+end
+if screen_shocks
+    fig_name_long = [fig_name_long ' SCREEN'];
+end
+
+fig_name=strrep(fig_name_long, '(given ', '');
+fig_name=strrep(fig_name, '(vintage ', '');
+fig_name=regexprep(fig_name, ' ', '_');
+fig_name=strrep(fig_name, '.', '');
+fig_name=strrep(fig_name, '-', '');
+fig_name=strrep(fig_name, ')', '');
+fig_name=strrep(fig_name, '(', '');
+
+interactive = opts_decomp.interactive;
+
+
 gend = size(z,3);
 if isempty(initial_date)
     x = 0:gend;
+    freq = 1;
 else
     freq = initial_date.freq;
-    initial_period = initial_date.time(1) + initial_date.time(2)/freq;
+    initial_period = initial_date.time(1) + (initial_date.time(2)-1)/freq;
     x = initial_period-1/freq:(1/freq):initial_period+(gend-1)/freq;
 end
 
 nvar = length(i_var);
 
 %% write LaTeX-Header
-if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
-    fidTeX = fopen([DynareModel.fname '_shock_decomp.tex'],'w');
+if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.plot_shock_decomp.graph_format)))
+    fidTeX = fopen([GraphDirectoryName, filesep, DynareModel.fname '_shock_decomp' fig_mode1 fig_name '.tex'],'w');
     fprintf(fidTeX,'%% TeX eps-loader file generated by Dynare''s graph_decomp.m.\n');
     fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
     fprintf(fidTeX,' \n');
 end
 
+if opts_decomp.vintage && opts_decomp.realtime>1
+    preamble_txt = 'Shock decomposition';
+else
+    preamble_txt = 'Historical shock decomposition';
+end
+
+if ~(screen_shocks && comp_nbr>18)
+    screen_shocks=0;
+end
+comp_nbr0=comp_nbr;
 %%plot decomposition
 for j=1:nvar
     z1 = squeeze(z(i_var(j),:,:));
+    if screen_shocks
+        [junk, isort] = sort(mean(abs(z1(1:end-2,:)')), 'descend');
+        labels = char(char(shock_names(isort(1:16),:)),'Others', 'Initial values');
+        zres = sum(z1(isort(17:end),:),1);
+        z1 = [z1(isort(1:16),:); zres; z1(comp_nbr0:end,:)];
+        comp_nbr=18;
+        func = @(x) colorspace('RGB->Lab',x);
+        new_colormap = distinguishable_colors(size(z1,1)-1,'w',func);
+        new_colormap(end,:) = [0.7 0.7 0.7];
+    else
+        labels = char(char(shock_names),'Initial values');
+    end
     xmin = x(1);
-    xmax = x(end);
-    ix = z1 > 0;
-    ymax = max(sum(z1.*ix));
-    ix = z1 < 0;
-    ymin = min(sum(z1.*ix));
+    xmax = x(end)+1/freq;
+    ix = z1(1:comp_nbr,:) > 0;
+    ymax = max(sum(z1(1:comp_nbr,:).*ix))*1.1;
+    ix = z1(1:comp_nbr,:) < 0;
+    ymin = min(sum(z1(1:comp_nbr,:).*ix))*1.1;
     if ymax-ymin < 1e-6
         continue
     end
-    fhandle = dyn_figure(DynareOptions,'Name',['Shock decomposition: ',endo_names(i_var(j),:)]);
-    ax=axes('Position',[0.1 0.1 0.6 0.8]);
-    plot(ax,x(2:end),z1(end,:),'k-','LineWidth',2)
-    axis(ax,[xmin xmax ymin ymax]);
+    fhandle = dyn_figure(DynareOptions.plot_shock_decomp.nodisplay,'Name',[preamble_txt fig_name_long strrep(fig_mode1, '_', ' ') ': ' deblank(endo_names(i_var(j),:)) '.'], 'PaperPositionMode', 'auto','PaperOrientation','landscape','renderermode','auto');
+    set(fhandle,'position' ,[50 50 1500 750])
+    ax=axes('Position',[0.1 0.1 0.6 0.8],'box','on');
+    %     plot(ax,x(2:end),z1(end,:),'k-','LineWidth',2)
+    %     axis(ax,[xmin xmax ymin ymax]);
     hold on;
     for i=1:gend
         i_1 = i-1;
@@ -76,16 +141,39 @@ for j=1:nvar
         for k = 1:comp_nbr
             zz = z1(k,i);
             if zz > 0
-                fill([x(i) x(i) x(i+1) x(i+1)],[yp yp+zz yp+zz yp],k);
+                fill([x(i) x(i) x(i+1) x(i+1)]+(1/freq/2),[yp yp+zz yp+zz yp],k);
                 yp = yp+zz;
             else
-                fill([x(i) x(i) x(i+1) x(i+1)],[ym ym+zz ym+zz ym],k);
+                fill([x(i) x(i) x(i+1) x(i+1)]+(1/freq/2),[ym ym+zz ym+zz ym],k);
                 ym = ym+zz;
             end
             hold on;
         end
     end
     plot(ax,x(2:end),z1(end,:),'k-','LineWidth',2)
+    if ~isempty(SteadyState)
+        plot(ax,[xmin xmax],[0 0],'--','linewidth',1,'color',[0.7 0.7 0.7])
+        if ymin+SteadyState(i_var(j))<0 && ymax+SteadyState(i_var(j))>0
+            plot(ax,[xmin xmax],SteadyState(i_var(j))*[-1 -1],'k--','linewidth',1)
+            ytick=get(ax,'ytick');
+            ytick1=ytick-SteadyState(i_var(j));
+            ind1=min(find(ytick1>=ymin));
+            ind2=max(find(ytick1<=ymax));
+            dytick=ytick(2)-ytick(1);
+            if ind1>1
+                ytick1  = [ytick1(ind1:end) ytick1(end)+dytick:dytick:ymax];
+            elseif ind2<length(ytick)
+                ytick1= [sort(ytick1(1)-dytick:-dytick:ymin) ytick1(1:ind2)];
+            end
+            set(ax,'ytick',ytick1),
+        else
+            ytick1=get(ax,'ytick');
+        end
+        ylabel = ytick1'+SteadyState(i_var(j));
+        ylabel(abs(ylabel)<eps)=0;
+        set(ax,'yticklabel',num2str(ylabel,'%4.2g'))
+    end
+    set(ax,'xlim',[xmin xmax]);
     hold off;
 
     axes('Position',[0.75 0.1 0.2 0.8]);
@@ -94,34 +182,51 @@ for j=1:nvar
     hold on;
     y1 = 0;
     height = 1/comp_nbr;
-    labels = char(char(shock_names),'Initial values');
 
-    for i=1:comp_nbr
-        fill([0 0 0.2 0.2],[y1 y1+0.7*height y1+0.7*height y1],i);
+    for i=comp_nbr:-1:1
+        %     for i=1:comp_nbr
+        hl = fill([0 0 0.2 0.2],[y1 y1+0.7*height y1+0.7*height y1],i);
         hold on
-        text(0.3,y1+0.3*height,labels(i,:),'Interpreter','none');
+        ht = text(0.3,y1+0.3*height,labels(i,:),'Interpreter','none');
         hold on
+        if interactive & (~isoctave & use_shock_groups)
+            mydata.fig_name = DynareOptions.plot_shock_decomp.fig_name(2:end);
+            mydata.use_shock_groups = DynareOptions.plot_shock_decomp.use_shock_groups;
+            mydata.shock_group = shock_groups.(shock_ind{i});
+            mydata.shock_decomp = DynareOptions.plot_shock_decomp;
+            if ~isempty(mydata.shock_group.shocks{1})
+                c = uicontextmenu;
+                hl.UIContextMenu=c;
+                browse_menu = uimenu(c,'Label','Browse group');
+                expand_menu = uimenu(c,'Label','Expand group','Callback',['expand_group(''' mydata.use_shock_groups ''',''' deblank(mydata.shock_decomp.orig_varlist(j,:)) ''',' int2str(i) ')']);
+                set(expand_menu,'UserData',mydata,'Tag',['group' int2str(i)]);
+                for jmember = mydata.shock_group.shocks
+                    uimenu('parent',browse_menu,'Label',char(jmember))
+                end
+                ht.UIContextMenu=c;
+            end
+        end
         y1 = y1 + height;
     end
 
     if ~isempty(new_colormap)
         colormap(new_colormap)
     end
-    dyn_saveas(fhandle,[DynareModel.fname,'_shock_decomposition_',deblank(endo_names(i_var(j),:))],DynareOptions);
     hold off
-    if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
+    dyn_saveas(fhandle,[GraphDirectoryName, filesep, DynareModel.fname,'_shock_decomposition_',deblank(endo_names(i_var(j),:)),fig_mode1,fig_name],DynareOptions.plot_shock_decomp.nodisplay,DynareOptions.plot_shock_decomp.graph_format);
+    if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.plot_shock_decomp.graph_format)))
         fprintf(fidTeX,'\\begin{figure}[H]\n');
         fprintf(fidTeX,'\\centering \n');
-        fprintf(fidTeX,['\\includegraphics[width=0.8\\textwidth]{%s_shock_decomposition_%s}\n'],DynareModel.fname,deblank(endo_names(i_var(j),:)));
-        fprintf(fidTeX,'\\label{Fig:shock_decomp:%s}\n',deblank(endo_names(i_var(j),:)));
-        fprintf(fidTeX,'\\caption{Historical shock decomposition: $ %s $}\n',deblank(DynareModel.endo_names_tex(i_var(j),:)));
+        fprintf(fidTeX,'\\includegraphics[width=0.8\\textwidth]{%s/graphs/%s_shock_decomposition_%s}\n',DynareModel.fname,DynareModel.fname,[deblank(endo_names(i_var(j),:)) fig_mode1 fig_name]);
+        fprintf(fidTeX,'\\label{Fig:shock_decomp:%s}\n',[fig_mode deblank(endo_names(i_var(j),:)) fig_name]);
+        fprintf(fidTeX,['\\caption{' preamble_txt fig_name_long strrep(fig_mode1, '_',  ' ') ': $ %s $.}\n'],deblank(DynareModel.endo_names_tex(i_var(j),:)));
         fprintf(fidTeX,'\\end{figure}\n');
         fprintf(fidTeX,' \n');
-    end    
+    end
 end
 
 %% write LaTeX-Footer
-if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
+if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.plot_shock_decomp.graph_format)))
     fprintf(fidTeX,' \n');
     fprintf(fidTeX,'%% End of TeX file.\n');
     fclose(fidTeX);
diff --git a/matlab/graph_decomp_detail.m b/matlab/graph_decomp_detail.m
new file mode 100644
index 0000000000000000000000000000000000000000..75951a41135b97718454053b752727a2813fc357
--- /dev/null
+++ b/matlab/graph_decomp_detail.m
@@ -0,0 +1,245 @@
+function []=graph_decomp_detail(z,shock_names,endo_names,i_var,initial_date,DynareModel,DynareOptions)
+%function []=graph_decomp_detail(z,shock_names,endo_names,i_var,initial_date,DynareModel,DynareOptions)
+% Plots the results from the shock_decomposition command
+%
+% Inputs
+%   z               [n_var*(nshock+2)*nperiods]     shock decomposition array, see shock_decomposition.m for details
+%   shock_names     [endo_nbr*string length]        shock names from M_.exo_names
+%   endo_names      [exo_nbr*string length]         variable names from M_.endo_names
+%   i_var           [n_var*1]                       vector indices of requested variables in M_.endo_names and z
+%   initial_date    [dseries object]                first period of decomposition to plot
+%   DynareModel     [structure]                     Dynare model structure
+%   DynareOptions   [structure]                     Dynare options structure
+
+% Copyright (C) 2010-2017 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/>.
+
+GraphDirectoryName = CheckPath('graphs',DynareModel.dname);
+% interactive = 0;
+fig_mode='';
+fig_mode1='';
+% fig_name='';
+% screen_shocks=0;
+use_shock_groups = DynareOptions.plot_shock_decomp.use_shock_groups;
+if use_shock_groups
+    shock_groups = DynareModel.shock_groups.(use_shock_groups);
+    shock_ind = fieldnames(shock_groups);
+end
+
+% number of components equals number of shocks + 1 (initial conditions)
+comp_nbr = size(z,2)-1;
+
+opts_decomp = DynareOptions.plot_shock_decomp;
+
+interactive = opts_decomp.interactive;
+if ~isempty(opts_decomp.type)
+    fig_mode = opts_decomp.type;
+    fig_mode1 = ['_' fig_mode];
+    fig_mode = [fig_mode '_'];
+end
+screen_shocks = opts_decomp.screen_shocks;
+if DynareOptions.plot_shock_decomp.use_shock_groups | comp_nbr<=18
+    screen_shocks=0;
+end
+fig_name_long = opts_decomp.fig_name;
+%         fig_name = ['_' fig_name];
+
+if screen_shocks
+    %     fig_name1 = [fig_name1 '_screen'];
+    fig_name_long = [fig_name_long ' SCREEN'];
+end
+
+fig_name=strrep(fig_name_long, '(given ', '');
+fig_name=strrep(fig_name, '(vintage ', '');
+fig_name=regexprep(fig_name, ' ', '_');
+fig_name=strrep(fig_name, '.', '');
+fig_name=strrep(fig_name, '-', '');
+fig_name=strrep(fig_name, ')', '');
+fig_name=strrep(fig_name, '(', '');
+% fig_name1 = [fig_name];
+% fig_name = [fig_name '_'];
+
+gend = size(z,3);
+if isempty(initial_date)
+    x = 0:gend;
+    freq = 1;
+else
+    freq = initial_date.freq;
+    initial_period = initial_date.time(1) + (initial_date.time(2)-1)/freq;
+    x = initial_period-1/freq:(1/freq):initial_period+(gend-1)/freq;
+end
+
+ind_yrs = find(floor(x)==x);
+dind_tick = 1;
+if floor(length(ind_yrs)/3)
+    dind_tick = floor(length(ind_yrs)/3);
+    xind_tick = x(ind_yrs(1)):dind_tick:x(ind_yrs(end))+(length(ind_yrs)-(dind_tick*3+1));
+else
+    xind_tick = x(ind_yrs(1)):dind_tick:x(ind_yrs(end))+(length(ind_yrs)-(dind_tick+1));
+end
+% xind_tick = floor(x(1))-floor(dind_tick/2):dind_tick:ceil(x(end))+ceil(dind_tick/2);
+if abs(floor(x(1))-xind_tick(1))-abs(ceil(x(end))-xind_tick(end))>1
+    xind_tick = xind_tick-1;
+end
+if abs(floor(x(1))-xind_tick(1))-abs(ceil(x(end))-xind_tick(end))<-1
+    xind_tick = xind_tick+1;
+end
+% xind_tick = [x(ind_yrs(1))-floor(dind_tick/2):dind_tick:x(ind_yrs(end))+floor(dind_tick/2)]+1;
+% xind_tick = x(ind_yrs(1))-1:dind_tick:x(ind_yrs(end))+1;
+% xind_tick = x(ind_yrs(1))-1:dind_tick:x(ind_yrs(end))+dind_tick;
+
+nvar = length(i_var);
+
+%% write LaTeX-Header
+if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.plot_shock_decomp.graph_format)))
+    fidTeX = fopen([GraphDirectoryName, filesep, DynareModel.fname '_shock_decomp' fig_mode1 fig_name '_detail.tex'],'w');
+    fprintf(fidTeX,'%% TeX eps-loader file generated by Dynare''s graph_decomp_detail.m.\n');
+    fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
+    fprintf(fidTeX,' \n');
+end
+
+if opts_decomp.vintage && opts_decomp.realtime>1
+    preamble_txt = 'Shock decomposition';
+else
+    preamble_txt = 'Historical shock decomposition';
+end
+
+ncol=3;
+nrow=ceil(comp_nbr/ncol);
+ntotrow = nrow;
+nrow = min(ntotrow, 6);
+nfigs = ceil(ntotrow/nrow);
+labels = char(char(shock_names),'Initial values');
+if ~(screen_shocks && comp_nbr>18)
+    screen_shocks=0;
+end
+comp_nbr0=comp_nbr;
+%%plot decomposition
+for j=1:nvar
+    z1 = squeeze(z(i_var(j),:,:));
+    if screen_shocks,
+        [junk, isort] = sort(mean(abs(z1(1:end-2,:)')), 'descend');
+        labels = char(char(shock_names(isort(1:16),:)),'Others', 'Initial values');
+        zres = sum(z1(isort(17:end),:),1);
+        z1 = [z1(isort(1:16),:); zres; z1(comp_nbr0:end,:)];
+        comp_nbr=18;
+        nfigs=1;
+    end
+    xmin = x(1);
+    xmin = min(xmin, xind_tick(1));
+    xmax = x(end)+1/freq;
+    xmax = max(xmax, xind_tick(end));
+    ix = z1(1:comp_nbr,:) > 0;
+    ymax = max(sum(z1(1:comp_nbr,:).*ix))*1.1;
+    ix = z1(1:comp_nbr,:) < 0;
+    ymin = min(sum(z1(1:comp_nbr,:).*ix))*1.1;
+    if ymax-ymin < 1e-6
+        continue
+    end
+    for jf = 1:nfigs
+        fhandle = dyn_figure(DynareOptions.plot_shock_decomp.nodisplay,'Name',[preamble_txt fig_name_long strrep(fig_mode1, '_', ' ') ': ' deblank(endo_names(i_var(j),:)) ' (detail).'],'position',[200 100 650 850], 'PaperPositionMode', 'auto','PaperOrientation','portrait','renderermode','auto');
+        a0=zeros(1,4);
+        a0(3)=inf;
+        a0(4)=-inf;
+        for ic=1+nrow*ncol*(jf-1):min(nrow*ncol*jf,comp_nbr)
+            i = ic-nrow*ncol*(jf-1);
+            zz = z1(ic,:);
+            zz(2,:)=z1(end,:)-zz;
+            ipos=zz>0;
+            ineg=zz<0;
+            hax = subplot(nrow,ncol,i); set(gca,'box','on')
+            hbar = bar(x(2:end),(zz.*ipos)','stacked');
+            colormap([0.15 0.15 0.15;0.85 0.85 0.85]),
+            set(hbar,'edgecolor','flat');
+            hold on,
+            hbar = bar(x(2:end),(zz.*ineg)','stacked');
+            colormap([0.15 0.15 0.15;0.85 0.85 0.85]),
+            set(hbar,'edgecolor','flat');
+            title(deblank(labels(ic,:)),'Interpreter','none'),
+            axis tight;
+            a=axis;
+            set(gca,'Xtick',xind_tick)
+            set(gca,'xlim',[xmin xmax])
+            a0(3)=min(a(3),a0(3));
+            a0(4)=max(a(4),a0(4));
+            set(gca,'ylim',a0(3:4))
+            hold on, h1=plot(x(2:end),z1(end,:),'k-','LineWidth',2);
+            if interactive & (~isoctave & use_shock_groups)
+                mydata.fig_name = DynareOptions.plot_shock_decomp.fig_name(2:end);
+                mydata.use_shock_groups = DynareOptions.plot_shock_decomp.use_shock_groups;
+                mydata.shock_group = shock_groups.(shock_ind{ic});
+                mydata.shock_decomp = DynareOptions.plot_shock_decomp;
+                if ~isempty(mydata.shock_group.shocks{1})
+                    c = uicontextmenu;
+                    hax.UIContextMenu=c;
+                    browse_menu = uimenu(c,'Label','Browse group');
+                    expand_menu = uimenu(c,'Label','Expand group','Callback',['expand_group(''' mydata.use_shock_groups ''',''' deblank(mydata.shock_decomp.orig_varlist(j,:)) ''',' int2str(ic) ')']);
+                    set(expand_menu,'UserData',mydata,'Tag',['group' int2str(ic)]);
+                    for jmember = mydata.shock_group.shocks
+                        uimenu('parent',browse_menu,'Label',char(jmember))
+                    end
+                end
+            end
+        end
+        for isub=1:i
+            subplot(nrow,ncol,isub),
+            set(gca,'ylim',a0(3:4))
+        end
+
+        % make legend
+        axes('Position',[0.1 0.01 0.8 0.02],'units','normalized');
+        axis([0 1 0 1]);
+        axis off;
+        hold on;
+        x1 = 0;
+        width = 1/2;
+        mylabels = {'Individual contrib.','Residual contrib.'};
+
+        for i=1:2
+            %     for i=1:comp_nbr
+            hl = fill([x1 x1 x1+0.3*width x1+0.3*width],[0 1 1 0],i);
+            hold on
+            ht = text(x1+0.4*width,0.3,mylabels{i},'Interpreter','none');
+            hold on
+            x1 = x1 + width;
+        end
+
+
+        if nfigs>1
+            suffix = ['_detail_' int2str(jf)];
+        else
+            suffix = ['_detail'];
+        end
+        dyn_saveas(fhandle,[GraphDirectoryName, filesep, DynareModel.fname,'_shock_decomposition_',deblank(endo_names(i_var(j),:)),fig_mode1,fig_name suffix],DynareOptions.plot_shock_decomp.nodisplay,DynareOptions.plot_shock_decomp.graph_format);
+        if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.plot_shock_decomp.graph_format)))
+            fprintf(fidTeX,'\\begin{figure}[H]\n');
+            fprintf(fidTeX,'\\centering \n');
+            fprintf(fidTeX,'\\includegraphics[width=0.8\\textwidth]{%s/graphs/%s_shock_decomposition_%s}\n',DynareModel.fname,DynareModel.fname,[deblank(endo_names(i_var(j),:)) fig_mode1 fig_name suffix]);
+            fprintf(fidTeX,'\\label{Fig:shock_decomp_detail:%s}\n',[fig_mode deblank(endo_names(i_var(j),:)) fig_name suffix]);
+            fprintf(fidTeX,['\\caption{' preamble_txt fig_name_long strrep(fig_mode1, '_',  ' ') ': $ %s $ (detail).}\n'],deblank(DynareModel.endo_names_tex(i_var(j),:)));
+            fprintf(fidTeX,'\\end{figure}\n');
+            fprintf(fidTeX,' \n');
+        end
+    end
+end
+
+%% write LaTeX-Footer
+if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.plot_shock_decomp.graph_format)))
+    fprintf(fidTeX,' \n');
+    fprintf(fidTeX,'%% End of TeX file.\n');
+    fclose(fidTeX);
+end
diff --git a/matlab/gsa/Morris_Measure_Groups.m b/matlab/gsa/Morris_Measure_Groups.m
index 5b6c30720b8fb6871133093167dc073885f10735..1271ed1b6858a8ee677e91d92ccebd1df70653a6 100644
--- a/matlab/gsa/Morris_Measure_Groups.m
+++ b/matlab/gsa/Morris_Measure_Groups.m
@@ -5,24 +5,29 @@ function [SAmeas, OutMatrix] = Morris_Measure_Groups(NumFact, Sample, Output, p,
 % -------------------------------------------------------------------------
 % INPUTS
 % -------------------------------------------------------------------------
-% Group [NumFactor, NumGroups] := Matrix describing the groups. 
-% Each column represents one group. 
+% Group [NumFactor, NumGroups] := Matrix describing the groups.
+% Each column represents one group.
 % The element of each column are zero if the factor is not in the
 % group. Otherwise it is 1.
 %
-% Sample := Matrix of the Morris sampled trajectories 
+% Sample := Matrix of the Morris sampled trajectories
 %
 % Output := Matrix of the output(s) values in correspondence of each point
 % of each trajectory
 %
 % k = Number of factors
 % -------------------------------------------------------------------------
-% OUTPUTS 
+% OUTPUTS
 % OutMatrix (NumFactor*NumOutputs, 3)= [Mu*, Mu, StDev]
 % for each output it gives the three measures of each factor
 % -------------------------------------------------------------------------
+%
+% Written by Jessica Cariboni and Francesca Campolongo
+% Joint Research Centre, The European Commission,
+%
 
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2005 European Commission
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -39,17 +44,17 @@ function [SAmeas, OutMatrix] = Morris_Measure_Groups(NumFact, Sample, Output, p,
 % 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==0,
-  skipline()
-  disp('[SAmeas, OutMatrix] = Morris_Measure_Groups(NumFact, Sample, Output, p, Group);')
-  return
+if nargin==0
+    skipline()
+    disp('[SAmeas, OutMatrix] = Morris_Measure_Groups(NumFact, Sample, Output, p, Group);')
+    return
 end
 
 OutMatrix=[];
 if nargin < 5, Group=[]; end
 
 NumGroups = size(Group,2);
-if nargin < 4 | isempty(p),
+if nargin < 4 | isempty(p)
     p = 4;
 end
 Delt = p/(2*p-2);
@@ -58,45 +63,45 @@ if NumGroups ~ 0
     sizea = NumGroups;      % Number of groups
     GroupMat=Group;
     GroupMat = GroupMat';
-else 
-    sizea = NumFact; 
+else
+    sizea = NumFact;
 end
 r=size(Sample,1)/(sizea+1);     % Number of trajectories
 
 % For Each Output
 for k=1:size(Output,2)
-    
+
     OutValues=Output(:,k);
-  
+
     % For each r trajectory
     for i=1:r
-    
+
         % For each step j in the trajectory
         % Read the orientation matrix fact for the r-th sampling
         % Read the corresponding output values
-        Single_Sample = Sample(i+(i-1)*sizea:i+(i-1)*sizea+sizea,:); 
-        Single_OutValues = OutValues(i+(i-1)*sizea:i+(i-1)*sizea+sizea,:); 
+        Single_Sample = Sample(i+(i-1)*sizea:i+(i-1)*sizea+sizea,:);
+        Single_OutValues = OutValues(i+(i-1)*sizea:i+(i-1)*sizea+sizea,:);
         A = (Single_Sample(2:sizea+1,:)-Single_Sample(1:sizea,:))';
         Delta = A(find(A));
 
         % For each point of the fixed trajectory compute the values of the Morris function. The function
         % is partitioned in four parts, from order zero to order 4th.
-        for j=1:sizea   % For each point in the trajectory i.e for each factor   
-            % matrix of factor which changes
-            if NumGroups ~ 0;
+        for j=1:sizea   % For each point in the trajectory i.e for each factor
+                        % matrix of factor which changes
+            if NumGroups ~ 0
                 AuxFind (:,1) = A(:,j);
-%                 AuxFind(find(A(:,j)),1)=1;
-%                 Pippo = sum((Group - repmat(AuxFind,1,NumGroups)),1);
-%                 Change_factor(j,i) = find(Pippo==0);   
-                Change_factor = find(abs(AuxFind)>1e-010); 
+                %                 AuxFind(find(A(:,j)),1)=1;
+                %                 Pippo = sum((Group - repmat(AuxFind,1,NumGroups)),1);
+                %                 Change_factor(j,i) = find(Pippo==0);
+                Change_factor = find(abs(AuxFind)>1e-010);
                 % If we deal with groups we can only estimate the new mu*
                 % measure since factors in the same groups can move in
                 % opposite direction and the definition of the standard
-                % Morris mu cannopt be applied. 
+                % Morris mu cannopt be applied.
                 % In the new version the elementary effect is defined with
                 % the absolute value.
-                %SAmeas(find(GroupMat(Change_factor(j,i),:)),i) = abs((Single_OutValues(j) - Single_OutValues(j+1) )/Delt); %(2/3));   
-                SAmeas(i,Change_factor') = abs((Single_OutValues(j) - Single_OutValues(j+1) )/Delt);   
+                %SAmeas(find(GroupMat(Change_factor(j,i),:)),i) = abs((Single_OutValues(j) - Single_OutValues(j+1) )/Delt); %(2/3));
+                SAmeas(i,Change_factor') = abs((Single_OutValues(j) - Single_OutValues(j+1) )/Delt);
             else
                 Change_factor(j,i) = find(Single_Sample(j+1,:)-Single_Sample(j,:));
                 % If no groups --> we compute both the original and
@@ -105,41 +110,41 @@ for k=1:size(Output,2)
                     SAmeas(Change_factor(j,i),i) = (Single_OutValues(j+1) - Single_OutValues(j) )/Delt; %(2/3);
                 else                                         %=> -Delta
                     SAmeas(Change_factor(j,i),i) = (Single_OutValues(j) - Single_OutValues(j+1) )/Delt; %(2/3);
-                end 
+                end
             end
         end   %for j=1:sizea
-    
+
     end     %for i=1:r
-   
+
     if NumGroups ~ 0
         SAmeas = SAmeas';
     end
 
     % Compute Mu AbsMu and StDev
     if any(any(isnan(SAmeas)))
-      for j=1:NumFact,
-        SAm = SAmeas(j,:);
-        SAm = SAm(find(~isnan(SAm)));
-        rr=length(SAm);
-        AbsMu(j,1) = sum(abs(SAm),2)/rr;
-      if NumGroups == 0
-        Mu(j,1) = sum(SAm,2)/rr;
-        StDev(j,1) = sum((SAm - repmat(Mu(j),1,rr)).^2/(rr*(rr-1)),2).^0.5;
-      end
-      end
+        for j=1:NumFact
+            SAm = SAmeas(j,:);
+            SAm = SAm(find(~isnan(SAm)));
+            rr=length(SAm);
+            AbsMu(j,1) = sum(abs(SAm),2)/rr;
+            if NumGroups == 0
+                Mu(j,1) = sum(SAm,2)/rr;
+                StDev(j,1) = sum((SAm - repmat(Mu(j),1,rr)).^2/(rr*(rr-1)),2).^0.5;
+            end
+        end
     else
-      AbsMu = sum(abs(SAmeas),2)/r;
-      if NumGroups == 0
-        Mu = sum(SAmeas,2)/r;
-        StDev = sum((SAmeas - repmat(Mu,1,r)).^2/(r*(r-1)),2).^0.5;
-      end
+        AbsMu = sum(abs(SAmeas),2)/r;
+        if NumGroups == 0
+            Mu = sum(SAmeas,2)/r;
+            StDev = sum((SAmeas - repmat(Mu,1,r)).^2/(r*(r-1)),2).^0.5;
+        end
     end
 
     % Define the output Matrix - if we have groups we cannot define the old
     % measure mu, only mu* makes sense
     if NumGroups > 0
-        OutMatrix = [OutMatrix; AbsMu];   
+        OutMatrix = [OutMatrix; AbsMu];
     else
-        OutMatrix = [OutMatrix; AbsMu, Mu, StDev];   
+        OutMatrix = [OutMatrix; AbsMu, Mu, StDev];
     end
 end     % For Each Output
diff --git a/matlab/gsa/Sampling_Function_2.m b/matlab/gsa/Sampling_Function_2.m
index 9c3fea877c52e4deb019ccffff03b543843ab74b..48a8187df08eacad91724698670c03d7fde44ff6 100644
--- a/matlab/gsa/Sampling_Function_2.m
+++ b/matlab/gsa/Sampling_Function_2.m
@@ -1,42 +1,42 @@
 function [Outmatrix, OutFact] = Sampling_Function_2(p, k, r, UB, LB, GroupMat)
 %[Outmatrix, OutFact] = Sampling_Function_2(p, k, r, UB, LB, GroupMat)
-%	Inputs: k (1,1)                      := number of factors examined or number of groups examined.
+%       Inputs: k (1,1)                      := number of factors examined or number of groups examined.
 %                                           In case the groups are chosen the number of factors is stores in NumFact and
-%                                           sizea becomes the number of created groups. 
+%                                           sizea becomes the number of created groups.
 %           NumFact (1,1)                := number of factors examined in the case when groups are chosen
-%	    	r (1,1)                      := sample size  
+%               r (1,1)                      := sample size
 %           p (1,1)                      := number of intervals considered in [0, 1]
-%           UB(sizea,1)                  := Upper Bound for each factor 
-%           LB(sizea,1)                  := Lower Bound for each factor 
+%           UB(sizea,1)                  := Upper Bound for each factor
+%           LB(sizea,1)                  := Lower Bound for each factor
 %           GroupNumber(1,1)             := Number of groups (eventually 0)
-%           GroupMat(NumFact,GroupNumber):= Matrix which describes the chosen groups. Each column represents a group and its elements 
+%           GroupMat(NumFact,GroupNumber):= Matrix which describes the chosen groups. Each column represents a group and its elements
 %                                           are set to 1 in correspondence of the factors that belong to the fixed group. All
 %                                           the other elements are zero.
-%   Local Variables:  
-%	    	sizeb (1,1)         := sizea+1
+%   Local Variables:
+%               sizeb (1,1)         := sizea+1
 %           sizec (1,1)         := 1
-%           randmult (sizea,1)  := vector of random +1 and -1  
-%           perm_e(1,sizea)     := vector of sizea random permutated indeces    
+%           randmult (sizea,1)  := vector of random +1 and -1
+%           perm_e(1,sizea)     := vector of sizea random permutated indeces
 %           fact(sizea)         := vector containing the factor varied within each traj
-% 	        DDo(sizea,sizea)    := D*       in Morris, 1991   
-%	        A(sizeb,sizea)      := Jk+1,k   in Morris, 1991
-%	        B(sizeb,sizea)      := B        in Morris, 1991
-%	        Po(sizea,sizea)     := P*       in Morris, 1991
+%               DDo(sizea,sizea)    := D*       in Morris, 1991
+%               A(sizeb,sizea)      := Jk+1,k   in Morris, 1991
+%               B(sizeb,sizea)      := B        in Morris, 1991
+%               Po(sizea,sizea)     := P*       in Morris, 1991
 %           Bo(sizeb,sizea)     := B*       in Morris, 1991
-%	        Ao(sizeb,sizec)     := Jk+1,1   in Morris, 1991
-%	        xo(sizec,sizea)     := x*       in Morris, 1991 (starting point for the trajectory)
+%               Ao(sizeb,sizec)     := Jk+1,1   in Morris, 1991
+%               xo(sizec,sizea)     := x*       in Morris, 1991 (starting point for the trajectory)
 %           In(sizeb,sizea)     := for each loop orientation matrix. It corresponds to a trajectory
 %                                  of k step in the parameter space and it provides a single elementary
-%                                  effect per factor 
+%                                  effect per factor
 %           MyInt()
-%           Fact(sizea,1)       := for each loop vector indicating which factor or group of factors has been changed 
+%           Fact(sizea,1)       := for each loop vector indicating which factor or group of factors has been changed
 %                                  in each step of the trajectory
 %           AuxMat(sizeb,sizea) := Delta*0.5*((2*B - A) * DD0 + A) in Morris, 1991. The AuxMat is used as in Morris design
 %                                  for single factor analysis, while it constitutes an intermediate step for the group analysis.
 %
-%	Output: Outmatrix(sizeb*r, sizea) := for the entire sample size computed In(i,j) matrices
+%       Output: Outmatrix(sizeb*r, sizea) := for the entire sample size computed In(i,j) matrices
 %           OutFact(sizea*r,1)        := for the entire sample size computed Fact(i,1) vectors
-%           
+%
 %   Note: B0 is constructed as in Morris design when groups are not considered. When groups are considered the routine
 %         follows the following steps:
 %           1- Creation of P0 and DD0 matrices defined in Morris for the groups. This means that the dimensions of these
@@ -44,14 +44,19 @@ function [Outmatrix, OutFact] = Sampling_Function_2(p, k, r, UB, LB, GroupMat)
 %           2- Creation of AuxMat matrix with (GroupNumber+1,GroupNumber) elements.
 %           3- Definition of GroupB0 starting from AuxMat, GroupMat and P0.
 %           4- The final B0 for groups is obtained as [ones(sizeb,1)*x0' + GroupB0]. The P0 permutation is present in GroupB0
-%              and it's not necessary to permute the matrix (ones(sizeb,1)*x0') because it's already randomly created. 
+%              and it's not necessary to permute the matrix (ones(sizeb,1)*x0') because it's already randomly created.
 %   Reference:
 %   A. Saltelli, K. Chan, E.M. Scott, "Sensitivity Analysis" on page 68 ss
 %
 %   F. Campolongo, J. Cariboni, JRC - IPSC Ispra, Varese, IT
 %   Last Update: 15 November 2005 by J.Cariboni
+%
+% Written by Jessica Cariboni and Francesca Campolongo
+% Joint Research Centre, The European Commission,
+%
 
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2005 European Commission
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -77,76 +82,76 @@ GroupNumber = size(GroupMat,2);
 
 if GroupNumber ~ 0;
     sizea = size(GroupMat,2);
-end    
+end
 
 sizeb = sizea + 1;
 sizec = 1;
 Outmatrix = [];
 OutFact = [];
 
-% For each i generate a trajectory  
+% For each i generate a trajectory
 for i=1:r
-    
+
     % Construct DD0 - OLD VERSION - it does not need communication toolbox
     % RAND(N,M) is an NXM matrix with random entries, chosen from a uniform distribution on the interval (0.0,1.0).
     % Note that DD0 tells if the factor have to be increased or ddecreased
     % by Delta.
-    randmult = ones(k,1);           
-    v = rand(k,1);                  
+    randmult = ones(k,1);
+    v = rand(k,1);
     randmult (find(v < 0.5))=-1;
     randmult = repmat(randmult,1,k);
     DD0 = randmult .* eye(k);
-    
+
     % Construct DD0 - NEW VERSION - it needs communication toolbox
     % randsrc(m) generates an m-by-m matrix, each of whose entries independently takes the value -1 with probability 1/2,
     % and 1 with probability 1/2.
-    % DD0 = randsrc(NumFact) .* eye(NumFact);      
-    
+    % DD0 = randsrc(NumFact) .* eye(NumFact);
+
     % Construct B (lower triangular)
     B = ones(sizeb,sizea);
     for j = 1:sizea
-       B(1:j,j)=0;    
+        B(1:j,j)=0;
     end
-    
+
     % Construct A0, A
     A0 = ones(sizeb,1);
     A = ones(sizeb,NumFact);
 
     % Construct the permutation matrix P0. In each column of P0 one randomly chosen element equals 1
-    % while all the others equal zero. 
+    % while all the others equal zero.
     % P0 tells the order in which order factors are changed in each
     % trajectory. P0 is created as it follows:
     % 1) All the elements of P0 are set equal to zero ==> P0 = zeros (sizea, sizea);
-    % 2) The function randperm create a random permutation of integer 1:sizea, without repetitions ==> perm_e; 
-    % 3) In each column of P0 the element indicated in perm_e is set equal to one.    
-    % Note that P0 is then used reading it by rows. 
+    % 2) The function randperm create a random permutation of integer 1:sizea, without repetitions ==> perm_e;
+    % 3) In each column of P0 the element indicated in perm_e is set equal to one.
+    % Note that P0 is then used reading it by rows.
     P0 = zeros (sizea, sizea);
     perm_e = randperm(sizea);               % RANDPERM(n) is a random permutation of the integers from 1 to n.
     for j = 1:sizea
-        P0(perm_e(j),j) = 1;    
-    end    
-    
-    % When groups are present the random permutation is done only on B. The effect is the same since 
-    % the added part (A0*x0') is completely random. 
+        P0(perm_e(j),j) = 1;
+    end
+
+    % When groups are present the random permutation is done only on B. The effect is the same since
+    % the added part (A0*x0') is completely random.
     if GroupNumber ~ 0
         B = B * (GroupMat*P0')';
     end
-    
+
     % Compute AuxMat both for single factors and groups analysis. For Single factors analysis
     % AuxMat is added to (A0*X0) and then permutated through P0. When groups are active AuxMat is
     % used to build GroupB0. AuxMat is created considering DD0. If the element on DD0 diagonal
-    % is 1 then AuxMat will start with zero and add Delta. If the element on DD0 diagonal is -1 
+    % is 1 then AuxMat will start with zero and add Delta. If the element on DD0 diagonal is -1
     % then DD0 will start Delta and goes to zero.
     AuxMat = Delta*0.5*((2*B - A) * DD0 + A);
-    
+
     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
     % a --> Define the random vector x0 for the factors. Note that x0 takes value in the hypercube
-    % [0,...,1-Delta]*[0,...,1-Delta]*[0,...,1-Delta]*[0,...,1-Delta] 
+    % [0,...,1-Delta]*[0,...,1-Delta]*[0,...,1-Delta]*[0,...,1-Delta]
     MyInt = repmat([0:(1/(p-1)):(1-Delta)],NumFact,1);     % Construct all possible values of the factors
-    
+
     % OLD VERSION - it needs communication toolbox
-    % w = randint(NumFact,1,[1,size(MyInt,2)]);              
-    
+    % w = randint(NumFact,1,[1,size(MyInt,2)]);
+
     % NEW VERSION - construct a version of random integers
     % 1) create a vector of random integers
     % 2) divide [0,1] into the needed steps
@@ -155,21 +160,21 @@ for i=1:r
     v = repmat(rand(NumFact,1),1,size(MyInt,2)+1);     % 1)
     IntUsed = repmat([0:1/size(MyInt,2):1],NumFact,1); % 2)
     DiffAuxVec = IntUsed - v;                          % 3)
-    
+
     for ii = 1:size(DiffAuxVec,1)
         w(1,ii) = max(find(DiffAuxVec(ii,:)<0));       % 4)
     end
-    x0 = MyInt(1,w)';                                  % Define x0    
-    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
+    x0 = MyInt(1,w)';                                  % Define x0
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
     % b --> Compute the matrix B*, here indicated as B0. Each row in B0 is a
-    % trajectory for Morris Calculations. The dimension of B0 is (Numfactors+1,Numfactors) 
+    % trajectory for Morris Calculations. The dimension of B0 is (Numfactors+1,Numfactors)
     if GroupNumber ~ 0
         B0 = (A0*x0' + AuxMat);
     else
         B0 = (A0*x0' + AuxMat)*P0;
     end
-    
-    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
+
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
     % c --> Compute values in the original intervals
     % B0 has values x(i,j) in [0, 1/(p -1), 2/(p -1), ... , 1].
     % To obtain values in the original intervals [LB, UB] we compute
@@ -182,8 +187,8 @@ for i=1:r
         Fact(1,j) = find(P0(j,:));
     end
     Fact(1,sizea+1) = 0;
-    
+
     Outmatrix = [Outmatrix; In];
     OutFact = [OutFact; Fact'];
-    
+
 end
\ No newline at end of file
diff --git a/matlab/gsa/cumplot.m b/matlab/gsa/cumplot.m
index 79aae60df9762a1a38281d8a384f727c7837df74..70fe1f47593538d93bef58dedcdf1b6620abeb92 100644
--- a/matlab/gsa/cumplot.m
+++ b/matlab/gsa/cumplot.m
@@ -1,7 +1,12 @@
-function h = cumplot(x);
+function h = cumplot(x)
 %function h =cumplot(x)
 
-% Copyright (C) 2012 Dynare Team
+% Written by Marco Ratto
+% Joint Research Centre, The European Commission,
+% marco.ratto@ec.europa.eu
+
+% Copyright (C) 2012 European Commission
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -24,6 +29,6 @@ y=[0:n n]./n;
 h0 = stairs(x,y);
 grid on,
 
-if nargout,
+if nargout
     h=h0;
 end
diff --git a/matlab/gsa/filt_mc_.m b/matlab/gsa/filt_mc_.m
index 3c79676d8fbd6544c1517bc80d4ec29d878c4c3f..b2dfb04117ed2ec29c3acb73644552ada46a349f 100644
--- a/matlab/gsa/filt_mc_.m
+++ b/matlab/gsa/filt_mc_.m
@@ -11,12 +11,10 @@ function [rmse_MC, ixx] = filt_mc_(OutDir,options_gsa_,dataset_,dataset_info)
 %
 % Written by Marco Ratto
 % Joint Research Centre, The European Commission,
-% (http://eemc.jrc.ec.europa.eu/),
-% marco.ratto@jrc.it
-% Reference:
-% M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006.
+% marco.ratto@ec.europa.eu
 
-% Copyright (C) 2012-2016 Dynare Team
+% Copyright (C) 2012-2016 European Commission
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -39,6 +37,8 @@ global bayestopt_ estim_params_ M_ options_ oo_
 vvarvecm = options_gsa_.var_rmse;
 if options_.TeX
     vvarvecm_tex = options_gsa_.var_rmse_tex;
+else
+    vvarvecm_tex = [];
 end
 loadSA   = options_gsa_.load_rmse;
 pfilt    = options_gsa_.pfilt_rmse;
@@ -57,51 +57,52 @@ skipline(2)
 disp('Starting sensitivity analysis')
 disp('for the fit of EACH observed series ...')
 skipline()
-disp('Deleting old SA figures...')
-a=dir([OutDir,filesep,'*.*']);
-tmp1='0';
-if options_.opt_gsa.ppost,
-    tmp=['_rmse_post'];
-else
-    if options_.opt_gsa.pprior
-        tmp=['_rmse_prior'];
+if ~options_.nograph
+    disp('Deleting old SA figures...')
+    a=dir([OutDir,filesep,'*.*']);
+    tmp1='0';
+    if options_.opt_gsa.ppost
+        tmp=['_rmse_post'];
     else
-        tmp=['_rmse_mc'];
+        if options_.opt_gsa.pprior
+            tmp=['_rmse_prior'];
+        else
+            tmp=['_rmse_mc'];
+        end
+        if options_gsa_.lik_only
+            tmp1 = [tmp,'_post_SA'];
+            tmp = [tmp,'_lik_SA'];
+        end
     end
-    if options_gsa_.lik_only,
-        tmp1 = [tmp,'_post_SA'];
-        tmp = [tmp,'_lik_SA'];
+    for j=1:length(a)
+        if strmatch([fname_,tmp],a(j).name)
+            disp(a(j).name)
+            delete([OutDir,filesep,a(j).name])
+        end
+        if strmatch([fname_,tmp1],a(j).name)
+            disp(a(j).name)
+            delete([OutDir,filesep,a(j).name])
+        end
     end
+    disp('done !')
 end
-for j=1:length(a),
-    if strmatch([fname_,tmp],a(j).name),
-        disp(a(j).name)
-        delete([OutDir,filesep,a(j).name])
-    end,
-    if strmatch([fname_,tmp1],a(j).name),
-        disp(a(j).name)
-        delete([OutDir,filesep,a(j).name])
-    end,
-end
-disp('done !')
-
 
 nshock=estim_params_.nvx + estim_params_.nvn + estim_params_.ncx + estim_params_.ncn;
 npar=estim_params_.np;
-if ~isempty(options_.mode_file),
-    load(options_.mode_file,'xparam1'),
+if ~isempty(options_.mode_file)
+    load(options_.mode_file,'xparam1')
 end
-if options_.opt_gsa.ppost,
+if options_.opt_gsa.ppost
     c=load([fname_,'_mean.mat'],'xparam1');
     xparam1_mean=c.xparam1;
     clear c
-elseif ~isempty(options_.mode_file) && exist([fname_,'_mean.mat'])==2,
+elseif ~isempty(options_.mode_file) && exist([fname_,'_mean.mat'])==2
     c=load([fname_,'_mean.mat'],'xparam1');
     xparam1_mean=c.xparam1;
     clear c
 end
 
-if options_.opt_gsa.ppost,
+if options_.opt_gsa.ppost
     fnamtmp=[fname_,'_post'];
     DirectoryName = CheckPath('metropolis',M_.dname);
 else
@@ -113,7 +114,17 @@ else
         DirectoryName = CheckPath(['gsa' filesep 'mc'],M_.dname);
     end
 end
-if ~loadSA,
+if loadSA
+    tmplist =load([OutDir,filesep,fnamtmp, '.mat'],'vvarvecm');
+    if isempty(fieldnames(tmplist))
+        disp('WARNING: cannot load results since the list of variables used is not present in the mat file')
+        loadSA=0;
+    elseif ~isequal(tmplist.vvarvecm,vvarvecm)
+        disp('WARNING: cannot load results since the list of variables in the mat file differs from the one requested.')
+        loadSA=0;
+    end
+end
+if ~loadSA
     if exist('xparam1','var')
         M_ = set_all_parameters(xparam1,estim_params_,M_);
         ys_mode=steady_(M_,options_,oo_);
@@ -128,19 +139,26 @@ if ~loadSA,
     data_index = dataset_info.missing.aindex;
     missing_value = dataset_info.missing.state;
     for jx=1:gend
-        data_indx(jx,data_index{jx})=true; 
+        data_indx(jx,data_index{jx})=true;
     end
     %stock_gend=data_info.gend;
     %stock_data = data_info.data;
     load([DirectoryName filesep M_.fname '_data.mat']);
     filfilt = dir([DirectoryName filesep M_.fname '_filter_step_ahead*.mat']);
-    filsmooth = dir([DirectoryName filesep M_.fname '_smooth*.mat']);
+    temp_smooth_file_list = dir([DirectoryName filesep M_.fname '_smooth*.mat']);
+    jfile=0;
+    for j=1:length(temp_smooth_file_list)
+        if isempty(strfind(temp_smooth_file_list(j).name,'smoothed')),
+            jfile=jfile+1;
+            filsmooth(jfile)=temp_smooth_file_list(j);
+        end
+    end
     filupdate = dir([DirectoryName filesep M_.fname '_update*.mat']);
     filparam = dir([DirectoryName filesep M_.fname '_param*.mat']);
     x=[];
     logpo2=[];
     sto_ys=[];
-    for j=1:length(filparam),
+    for j=1:length(filparam)
         %load([DirectoryName filesep M_.fname '_param',int2str(j),'.mat']);
         if isempty(strmatch([M_.fname '_param_irf'],filparam(j).name))
             load([DirectoryName filesep filparam(j).name]);
@@ -155,63 +173,63 @@ if ~loadSA,
     if options_.opt_gsa.ppost || (options_.opt_gsa.ppost==0 && options_.opt_gsa.lik_only==0)
         skipline()
         disp('Computing RMSE''s...')
-        for i=1:size(vvarvecm,1),
+        for i=1:size(vvarvecm,1)
             vj=deblank(vvarvecm(i,:));
-            
+
             jxj(i) = strmatch(vj,lgy_(dr_.order_var,:),'exact');
             js(i) = strmatch(vj,lgy_,'exact');
             yss(i,:,:)=repmat(sto_ys(:,js(i))',[gend,1]);
         end
         if exist('xparam1','var')
             [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK] = DsgeSmoother(xparam1,gend,Y,data_index,missing_value,M_,oo_,options_,bayestopt_,estim_params_);
-            y0 = transpose( squeeze(aK(1,jxj,1:gend)));% + kron(ys_mode(js),ones(1,gend)));
+            y0 = reshape( squeeze(aK(1,jxj,1:gend)),[gend length(jxj)]);% + kron(ys_mode(js),ones(1,gend)));
             yobs = transpose( ahat(jxj,:));% + kron(ys_mode(js),ones(1,gend)));
             rmse_mode = sqrt(mean((yobs(istart:end,:)-y0(istart:end,:)).^2));
             r2_mode = 1-sum((yobs(istart:end,:)-y0(istart:end,:)).^2)./sum(yobs(istart:end,:).^2);
         end
         y0=-yss;
         nbb=0;
-        for j=1:length(filfilt),
+        for j=1:length(filfilt)
             load([DirectoryName filesep M_.fname '_filter_step_ahead',num2str(j),'.mat']);
             nb = size(stock,4);
-            y0(:,:,nbb+1:nbb+nb)=y0(:,:,nbb+1:nbb+nb)+squeeze(stock(1,js,1:gend,:));
+            y0(:,:,nbb+1:nbb+nb)=y0(:,:,nbb+1:nbb+nb)+reshape(stock(1,js,1:gend,:),[length(js) gend nb]);
             nbb=nbb+nb;
             clear stock;
         end
         yobs=-yss;
         nbb=0;
-        for j=1:length(filupdate),
+        for j=1:length(filupdate)
             load([DirectoryName filesep M_.fname '_update',num2str(j),'.mat']);
             nb = size(stock,3);
-            yobs(:,:,nbb+1:nbb+nb)=yobs(:,:,nbb+1:nbb+nb)+squeeze(stock(js,1:gend,:));
+            yobs(:,:,nbb+1:nbb+nb)=yobs(:,:,nbb+1:nbb+nb)+reshape(stock(js,1:gend,:),[length(js) gend nb]);
             nbb=nbb+nb;
             clear stock;
         end
         y0M=mean(y0,2);
         rmse_MC=zeros(nruns,length(js));
         r2_MC=zeros(nruns,length(js));
-        for j=1:nruns,
+        for j=1:nruns
             rmse_MC(j,:) = sqrt(mean((yobs(:,istart:end,j)'-y0(:,istart:end,j)').^2));
             r2_MC(j,:) = 1-mean((yobs(:,istart:end,j)'-y0(:,istart:end,j)').^2)./mean((yobs(:,istart:end,j)').^2);
         end
         if exist('xparam1_mean','var')
             %eval(['rmse_pmean(i) = sqrt(mean((',vj,'(fobs-1+istart:fobs-1+nobs)-y0M(istart:end-1)).^2));'])
             [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK] = DsgeSmoother(xparam1_mean,gend,Y,data_index,missing_value,M_,oo_,options_,bayestopt_,estim_params_);
-            y0 = transpose( squeeze(aK(1,jxj,1:gend)));% + kron(ys_mean(js),ones(1,gend)));
+            y0 = reshape( squeeze(aK(1,jxj,1:gend)),[gend length(jxj)]);% + kron(ys_mean(js),ones(1,gend)));
             yobs = transpose( ahat(jxj,:));% + kron(ys_mean(js),ones(1,gend)));
             rmse_pmean = sqrt(mean((yobs(istart:end,:)-y0(istart:end,:)).^2));
             r2_pmean = 1-mean((yobs(istart:end,:)-y0(istart:end,:)).^2)./mean(yobs(istart:end,:).^2);
         end
         clear stock_filter;
     end
-    for j=1:nruns,
+    for j=1:nruns
         lnprior(j,1) = priordens(x(j,:)',bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4);
     end
     likelihood=logpo2(:)-lnprior(:);
     disp('... done!')
-    
+
     if options_.opt_gsa.ppost
-        save([OutDir,filesep,fnamtmp,'.mat'], 'x', 'logpo2', 'likelihood', 'rmse_MC', 'r2_MC')
+        save([OutDir,filesep,fnamtmp,'.mat'], 'x', 'logpo2', 'likelihood', 'rmse_MC', 'r2_MC', 'vvarvecm')
         if exist('xparam1_mean','var')
             save([OutDir,filesep,fnamtmp, '.mat'], 'rmse_pmean', 'r2_pmean','-append')
         end
@@ -222,7 +240,7 @@ if ~loadSA,
         if options_.opt_gsa.lik_only
             save([OutDir,filesep,fnamtmp, '.mat'], 'x', 'logpo2','likelihood', '-append')
         else
-            save([OutDir,filesep,fnamtmp, '.mat'], 'x', 'logpo2','likelihood', 'rmse_MC', 'r2_MC','-append')
+            save([OutDir,filesep,fnamtmp, '.mat'], 'x', 'logpo2','likelihood', 'rmse_MC', 'r2_MC', 'vvarvecm','-append')
             if exist('xparam1_mean','var')
                 save([OutDir,filesep,fnamtmp, '.mat'], 'rmse_pmean', 'r2_pmean','-append')
             end
@@ -235,7 +253,7 @@ else
     if options_.opt_gsa.lik_only && options_.opt_gsa.ppost==0
         load([OutDir,filesep,fnamtmp, '.mat'],'x','logpo2','likelihood');
     else
-        load([OutDir,filesep,fnamtmp, '.mat'],'x','logpo2','likelihood','rmse_MC','rmse_mode','rmse_pmean', 'r2_MC', 'r2_mode','r2_pmean');
+        load([OutDir,filesep,fnamtmp, '.mat'],'x','logpo2','likelihood','rmse_MC','rmse_mode','rmse_pmean', 'r2_MC', 'vvarvecm', 'r2_mode','r2_pmean');
     end
     lnprior=logpo2(:)-likelihood(:);
     nruns=size(x,1);
@@ -248,6 +266,34 @@ if ~options_.opt_gsa.ppost
     [dum, ipost]=sort(-logpo2);
     [dum, ilik]=sort(-likelihood);
 end
+
+%% visual scatter analysis!
+if options_.opt_gsa.ppost
+    tmp_title='R2 Posterior:';
+    atitle='R2 Posterior:';
+    asname='r2_post';
+else
+    if options_.opt_gsa.pprior
+        tmp_title='R2 Prior:';
+        atitle='R2 Prior:';
+        asname='r2_prior';
+    else
+        tmp_title='R2 MC:';
+        atitle='R2 MC:';
+        asname='r2_mc';
+    end
+end
+options_scatter.param_names = vvarvecm;
+options_scatter.param_names_tex = vvarvecm_tex;
+options_scatter.fname_ = fname_;
+options_scatter.OutputDirectoryName = OutDir;
+options_scatter.amcf_name = asname;
+options_scatter.amcf_title = atitle;
+options_scatter.title = tmp_title;
+scatter_analysis(r2_MC, x,options_scatter, options_);
+%% end of visual scatter analysis
+
+
 if ~options_.opt_gsa.ppost && options_.opt_gsa.lik_only
     if options_.opt_gsa.pprior
         anam='rmse_prior_post';
@@ -266,6 +312,7 @@ if ~options_.opt_gsa.ppost && options_.opt_gsa.lik_only
     else
         [pnames]=get_LaTeX_parameter_names(M_,options_,estim_params_,bayestopt_);
         options_mcf.param_names = char(pnames);
+        options_mcf.param_names_tex = [];
     end
     options_mcf.fname_ = fname_;
     options_mcf.OutputDirectoryName = OutDir;
@@ -275,7 +322,7 @@ if ~options_.opt_gsa.ppost && options_.opt_gsa.lik_only
     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';
         atitle = 'RMSE prior: Log Likelihood Kernel';
@@ -289,14 +336,14 @@ if ~options_.opt_gsa.ppost && options_.opt_gsa.lik_only
     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
-    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'),
+        if options_.opt_gsa.pprior || ~exist('rmse_pmean')
+            if exist('rmse_mode')
                 rmse_txt=rmse_mode;
                 r2_txt=r2_mode;
             else
@@ -309,28 +356,28 @@ else
             r2_txt=r2_pmean;
         end
     end
-    for i=1:size(vvarvecm,1),
+    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),
+    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);
-            if H1 & H2==0,
+            if H1 & H2==0
                 SS(j,i)=1;
-            elseif H1==0,
+            elseif H1==0
                 SS(j,i)=-1;
             else
                 SS(j,i)=0;
             end
             PP(j,i)=P;
         end
-        for i=1:size(vvarvecm,1),
-            for l=1:size(vvarvecm,1),
+        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);
@@ -346,9 +393,9 @@ else
             end
         end
     end
-    if ~options_.nograph,
+    if ~options_.nograph
         ifig=0;
-        for i=1:size(vvarvecm,1),
+        for i=1:size(vvarvecm,1)
             if options_.opt_gsa.ppost
                 temp_name='RMSE Posterior: Log Prior';
             else
@@ -358,9 +405,9 @@ else
                     temp_name='RMSE MC: Log Prior';
                 end
             end
-            if mod(i,9)==1,
+            if mod(i,9)==1
                 ifig=ifig+1;
-                hh=dyn_figure(options_,'name',[temp_name,' ',int2str(ifig)]);
+                hh=dyn_figure(options_.nodisplay,'name',[temp_name,' ',int2str(ifig)]);
             end
             subplot(3,3,i-9*(ifig-1))
             h=cumplot(lnprior(ixx(1:nfilt0(i),i)));
@@ -376,21 +423,27 @@ else
                     annotation('textbox', [0.55,0,0.35,0.05],'String', 'Log-prior for WORSE R2', 'Color','Red','horizontalalignment','center');
                 end
                 if options_.opt_gsa.ppost
-                    dyn_saveas(hh,[OutDir filesep fname_ '_rmse_post_lnprior',int2str(ifig)],options_);
-                    create_TeX_loader(options_,[OutDir '/' fname_ '_rmse_post_lnprior',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_post_lnprior',options_.figures.textwidth*min((i-9*(ifig-1))/3,1))
+                    dyn_saveas(hh,[OutDir filesep fname_ '_rmse_post_lnprior',int2str(ifig)],options_.nodisplay,options_.graph_format);
+                    if options_.TeX
+                        create_TeX_loader(options_,[OutDir '/' fname_ '_rmse_post_lnprior',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_post_lnprior',options_.figures.textwidth*min((i-9*(ifig-1))/3,1))
+                    end
                 else
                     if options_.opt_gsa.pprior
-                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_lnprior',int2str(ifig) ],options_);
-                        create_TeX_loader(options_,[OutDir '/' fname_ '_rmse_prior_lnprior',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_prior_lnprior',options_.figures.textwidth*min((i-9*(ifig-1))/3,1))
+                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_lnprior',int2str(ifig) ],options_.nodisplay,options_.graph_format);
+                        if options_.TeX
+                            create_TeX_loader(options_,[OutDir '/' fname_ '_rmse_prior_lnprior',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_prior_lnprior',options_.figures.textwidth*min((i-9*(ifig-1))/3,1))
+                        end
                     else
-                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_lnprior',int2str(ifig) ],options_);
-                        create_TeX_loader(options_,[OutDir '/' fname_ '_rmse_mc_lnprior',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_mc_lnprior',options_.figures.textwidth*min((i-9*(ifig-1))/3,1))
+                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_lnprior',int2str(ifig) ],options_.nodisplay,options_.graph_format);
+                        if options_.TeX
+                            create_TeX_loader(options_,[OutDir '/' fname_ '_rmse_mc_lnprior',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_mc_lnprior',options_.figures.textwidth*min((i-9*(ifig-1))/3,1))
+                        end
                     end
                 end
             end
         end
         ifig=0;
-        for i=1:size(vvarvecm,1),
+        for i=1:size(vvarvecm,1)
             if options_.opt_gsa.ppost
                 temp_name='RMSE Posterior: Log Likelihood';
             else
@@ -400,9 +453,9 @@ else
                     temp_name='RMSE MC: Log Likelihood';
                 end
             end
-            if mod(i,9)==1,
+            if mod(i,9)==1
                 ifig=ifig+1;
-                hh = dyn_figure(options_,'Name',[temp_name,' ',int2str(ifig)]);
+                hh = dyn_figure(options_.nodisplay,'Name',[temp_name,' ',int2str(ifig)]);
             end
             subplot(3,3,i-9*(ifig-1))
             h=cumplot(likelihood(ixx(1:nfilt0(i),i)));
@@ -412,7 +465,7 @@ else
             h=cumplot(likelihood(ixx(nfilt0(i)+1:end,i)));
             set(h,'color','red','linewidth',2)
             title(vvarvecm(i,:),'interpreter','none')
-            if options_.opt_gsa.ppost==0,
+            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)
@@ -421,21 +474,27 @@ else
                     annotation('textbox', [0.55,0,0.35,0.05],'String', 'Log-likelihood for WORSE R2', 'Color','Red','horizontalalignment','center');
                 end
                 if options_.opt_gsa.ppost
-                    dyn_saveas(hh,[OutDir filesep fname_ '_rmse_post_lnlik',int2str(ifig) ],options_);
-                    create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_post_lnprior',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_post_lnprior',options_.figures.textwidth*min((i-9*(ifig-1))/3,1));
+                    dyn_saveas(hh,[OutDir filesep fname_ '_rmse_post_lnlik',int2str(ifig) ],options_.nodisplay,options_.graph_format);
+                    if options_.TeX
+                        create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_post_lnprior',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_post_lnprior',options_.figures.textwidth*min((i-9*(ifig-1))/3,1));
+                    end
                 else
                     if options_.opt_gsa.pprior
-                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_lnlik',int2str(ifig)],options_);
-                        create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_prior_lnlik',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_prior_lnlik',options_.figures.textwidth*min((i-9*(ifig-1))/3,1));
+                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_lnlik',int2str(ifig)],options_.nodisplay,options_.graph_format);
+                        if options_.TeX
+                            create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_prior_lnlik',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_prior_lnlik',options_.figures.textwidth*min((i-9*(ifig-1))/3,1));
+                        end
                     else
-                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_lnlik',int2str(ifig) ],options_);
-                        create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_mc_lnlik',int2str(ifig) ],ifig,[temp_name,' ',int2str(ifig)],'rmse_mc_lnlik',options_.figures.textwidth*min((i-9*(ifig-1))/3,1));
+                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_lnlik',int2str(ifig) ],options_.nodisplay,options_.graph_format);
+                        if options_.TeX
+                            create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_mc_lnlik',int2str(ifig) ],ifig,[temp_name,' ',int2str(ifig)],'rmse_mc_lnlik',options_.figures.textwidth*min((i-9*(ifig-1))/3,1));
+                        end
                     end
                 end
             end
         end
         ifig=0;
-        for i=1:size(vvarvecm,1),
+        for i=1:size(vvarvecm,1)
             if options_.opt_gsa.ppost
                 temp_name='RMSE Posterior: Log Posterior';
             else
@@ -445,9 +504,9 @@ else
                     temp_name='RMSE MC: Log Posterior';
                 end
             end
-            if mod(i,9)==1,
+            if mod(i,9)==1
                 ifig=ifig+1;
-                hh = dyn_figure(options_,'Name',[temp_name,' ',int2str(ifig)]);
+                hh = dyn_figure(options_.nodisplay,'Name',[temp_name,' ',int2str(ifig)]);
             end
             subplot(3,3,i-9*(ifig-1))
             h=cumplot(logpo2(ixx(1:nfilt0(i),i)));
@@ -457,7 +516,7 @@ else
             h=cumplot(logpo2(ixx(nfilt0(i)+1:end,i)));
             set(h,'color','red','linewidth',2)
             title(vvarvecm(i,:),'interpreter','none')
-            if options_.opt_gsa.ppost==0,
+            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)
@@ -466,21 +525,27 @@ else
                     annotation('textbox', [0.55,0,0.35,0.05],'String', 'Log-posterior for WORSE R2', 'Color','Red','horizontalalignment','center');
                 end
                 if options_.opt_gsa.ppost
-                    dyn_saveas(hh,[OutDir filesep fname_ '_rmse_post_lnpost',int2str(ifig) ],options_);
-                    create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_post_lnpost',int2str(ifig) ],ifig,[temp_name,' ',int2str(ifig)],'rmse_post_lnpost',options_.figures.textwidth*min((i-9*(ifig-1))/3,1));
+                    dyn_saveas(hh,[OutDir filesep fname_ '_rmse_post_lnpost',int2str(ifig) ],options_.nodisplay,options_.graph_format);
+                    if options_.TeX
+                        create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_post_lnpost',int2str(ifig) ],ifig,[temp_name,' ',int2str(ifig)],'rmse_post_lnpost',options_.figures.textwidth*min((i-9*(ifig-1))/3,1));
+                    end
                 else
                     if options_.opt_gsa.pprior
-                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_lnpost',int2str(ifig)],options_);
-                        create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_prior_lnpost',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_prior_lnpost',options_.figures.textwidth*min((i-9*(ifig-1))/3,1));
+                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_lnpost',int2str(ifig)],options_.nodisplay,options_.graph_format);
+                        if options_.TeX
+                            create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_prior_lnpost',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_prior_lnpost',options_.figures.textwidth*min((i-9*(ifig-1))/3,1));
+                        end
                     else
-                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_lnpost',int2str(ifig)],options_);
-                        create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_mc_lnpost',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_mc_lnpost',options_.figures.textwidth*min((i-9*(ifig-1))/3,1));
+                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_lnpost',int2str(ifig)],options_.nodisplay,options_.graph_format);
+                        if options_.TeX
+                            create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_mc_lnpost',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_mc_lnpost',options_.figures.textwidth*min((i-9*(ifig-1))/3,1));
+                        end
                     end
                 end
             end
         end
     end
-    
+
     if options_.TeX
         [pnames,pnames_tex]=get_LaTeX_parameter_names(M_,options_,estim_params_,bayestopt_);
         param_names = char(pnames);
@@ -488,9 +553,10 @@ else
     else
         [pnames]=get_LaTeX_parameter_names(M_,options_,estim_params_,bayestopt_);
         param_names = char(pnames);
+        param_names_tex = [];
     end
 
-    
+
     skipline()
     title_string='RMSE over the MC sample:';
     data_mat=[min(rmse_MC)' max(rmse_MC)'];
@@ -500,7 +566,7 @@ else
         headers_tex=strvcat('\text{Variable}','\text{min yr RMSE}','\text{max yr RMSE}');
         dyn_latex_table(M_,options_,title_string,'RMSE_MC',headers_tex,vvarvecm_tex,data_mat,0,15,5);
     end
-    
+
     invar = find( std(rmse_MC)./mean(rmse_MC)<=0.0001 );
     if ~isempty(invar)
         skipline(2)
@@ -509,10 +575,12 @@ else
         disp('These variables are excluded from SA')
         disp('[Unless you treat these series as exogenous, there is something wrong in your estimation !]')
     end
+    vvarvecm0=vvarvecm;
+
     ivar = find( std(rmse_MC)./mean(rmse_MC)>0.0001 );
     vvarvecm=vvarvecm(ivar,:);
     rmse_MC=rmse_MC(:,ivar);
-    
+
     skipline()
     % if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior,
     disp(['Sample filtered the ',num2str(pfilt*100),'% best RMSE''s for each observed series ...' ])
@@ -522,11 +590,11 @@ else
     % figure, boxplot(rmse_MC)
     % set(gca,'xticklabel',vvarvecm)
     % saveas(gcf,[fname_,'_SA_RMSE'])
-    
+
     skipline(2)
     disp('RMSE ranges after filtering:')
     title_string='RMSE ranges after filtering:';
-    if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior,
+    if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior
         headers=strvcat('Variable','min','max','min','max','posterior mode');
         headers_tex=strvcat('\text{Variable}','\text{min}','\text{max}','\text{min}','\text{max}','\text{posterior mode}');
     else
@@ -534,12 +602,12 @@ else
         headers_tex=strvcat('\text{Variable}','\text{min}','\text{max}','\text{min}','\text{max}','\text{posterior mean}');
     end
     data_mat=NaN(size(vvarvecm,1),5);
-    for j=1:size(vvarvecm,1),
+    for j=1:size(vvarvecm,1)
         data_mat(j,:)=[min(rmse_MC(ixx(1:nfilt0(j),j),j)) ...
-            max(rmse_MC(ixx(1:nfilt0(j),j),j))  ...
-            min(rmse_MC(ixx(nfilt0(j)+1:end,j),j)) ...
-            max(rmse_MC(ixx(nfilt0(j)+1:end,j),j)) ...
-            rmse_txt(j)];
+                       max(rmse_MC(ixx(1:nfilt0(j),j),j))  ...
+                       min(rmse_MC(ixx(nfilt0(j)+1:end,j),j)) ...
+                       max(rmse_MC(ixx(nfilt0(j)+1:end,j),j)) ...
+                       rmse_txt(j)];
     end
     %get formatting for additional header line
     val_width=15;
@@ -554,7 +622,7 @@ else
     if any(data_mat) < 0 %add one character for minus sign
         values_length = values_length+1;
     end
-    
+
     headers_length = max(size(deblank(headers(2:end,:)),2));
     if ~isempty(val_width)
         val_width = max(max(headers_length,values_length)+2,val_width);
@@ -563,24 +631,24 @@ else
     end
     value_format  = sprintf('%%%d.%df',val_width,val_precis);
     header_string_format  = sprintf('%%%ds',val_width);
-    
-    if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior,
+
+    if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior
         optional_header=sprintf([label_format_leftbound,header_string_format,header_string_format,header_string_format,header_string_format],'','',['best ',num2str(pfilt*100),'% filtered'],'','remaining 90%');
     else
         optional_header=sprintf([label_format_leftbound,header_string_format,header_string_format,header_string_format,header_string_format],'','','best  filtered','','remaining');
     end
     dyntable(options_,title_string,headers,vvarvecm,data_mat, 0, val_width, val_precis,optional_header);
     if options_.TeX
-        if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior,
+        if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior
             optional_header={[' & \multicolumn{2}{c}{best ',num2str(pfilt*100),' filtered} & \multicolumn{2}{c}{remaining 90\%}\\']};
         else
             optional_header={[' & \multicolumn{2}{c}{best filtered} & \multicolumn{2}{c}{remaining}\\']};
         end
         dyn_latex_table(M_,options_,title_string,'RMSE_ranges_after_filtering',headers_tex,vvarvecm_tex,data_mat,0,val_width,val_precis,optional_header);
     end
-    
+
     %%%%% R2 table
-    
+    vvarvecm=vvarvecm0;
     skipline()
     title_string='R2 over the MC sample:';
     data_mat=[min(r2_MC)' max(r2_MC)'];
@@ -590,16 +658,17 @@ else
         headers_tex=strvcat('\text{Variable}','\text{min yr R2}','\text{max yr R2}');
         dyn_latex_table(M_,options_,title_string,'R2_MC',headers_tex,vvarvecm_tex,data_mat,0,15,5);
     end
-    
+
     r2_MC=r2_MC(:,ivar);
-    
+    vvarvecm=vvarvecm(ivar,:);
+
     skipline()
     disp(['Sample filtered the ',num2str(pfilt*100),'% best R2''s for each observed series ...' ])
-    
+
     skipline()
     disp('R2 ranges after filtering:')
     title_string='R2 ranges after filtering:';
-    if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior,
+    if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior
         headers=strvcat('Variable','min','max','min','max','posterior mode');
         headers_tex=strvcat('\text{Variable}','\text{min}','\text{max}','\text{min}','\text{max}','\text{posterior mode}');
     else
@@ -607,12 +676,12 @@ else
         headers_tex=strvcat('\text{Variable}','\text{min}','\text{max}','\text{min}','\text{max}','\text{posterior mean}');
     end
     data_mat=NaN(size(vvarvecm,1),5);
-    for j=1:size(vvarvecm,1),
+    for j=1:size(vvarvecm,1)
         data_mat(j,:)=[min(r2_MC(ixx(1:nfilt0(j),j),j)) ...
-            max(r2_MC(ixx(1:nfilt0(j),j),j))  ...
-            min(r2_MC(ixx(nfilt0(j)+1:end,j),j)) ...
-            max(r2_MC(ixx(nfilt0(j)+1:end,j),j)) ...
-            r2_txt(j)];
+                       max(r2_MC(ixx(1:nfilt0(j),j),j))  ...
+                       min(r2_MC(ixx(nfilt0(j)+1:end,j),j)) ...
+                       max(r2_MC(ixx(nfilt0(j)+1:end,j),j)) ...
+                       r2_txt(j)];
     end
     %get formatting for additional header line
     val_width=15;
@@ -627,7 +696,7 @@ else
     if any(data_mat) < 0 %add one character for minus sign
         values_length = values_length+1;
     end
-    
+
     headers_length = max(size(deblank(headers(2:end,:)),2));
     if ~isempty(val_width)
         val_width = max(max(headers_length,values_length)+2,val_width);
@@ -636,32 +705,32 @@ else
     end
     value_format  = sprintf('%%%d.%df',val_width,val_precis);
     header_string_format  = sprintf('%%%ds',val_width);
-    
-    if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior,
+
+    if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior
         optional_header=sprintf([label_format_leftbound,header_string_format,header_string_format,header_string_format,header_string_format],'','',['best ',num2str(pfilt*100),'% filtered'],'','remaining 90%');
     else
         optional_header=sprintf([label_format_leftbound,header_string_format,header_string_format,header_string_format,header_string_format],'','','best  filtered','','remaining');
     end
     dyntable(options_,title_string,headers,vvarvecm,data_mat, 0, val_width, val_precis,optional_header);
     if options_.TeX
-        if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior,
+        if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior
             optional_header={[' & \multicolumn{2}{c}{best ',num2str(pfilt*100),' filtered} & \multicolumn{2}{c}{remaining 90\%}\\']};
         else
             optional_header={[' & \multicolumn{2}{c}{best filtered} & \multicolumn{2}{c}{remaining}\\']};
         end
         dyn_latex_table(M_,options_,title_string,'R2_ranges_after_filtering',headers_tex,vvarvecm_tex,data_mat,0,val_width,val_precis,optional_header);
     end
-    
-    
+
+
     %%%%  R2 table
     SP=zeros(npar+nshock,size(vvarvecm,1));
-    for j=1:size(vvarvecm,1),
+    for j=1:size(vvarvecm,1)
         ns=find(PP(:,j)<alpha);
         SP(ns,j)=ones(size(ns));
         SS(:,j)=SS(:,j).*SP(:,j);
     end
-    
-    for j=1:npar+nshock, %estim_params_.np,
+
+    for j=1:npar+nshock %estim_params_.np,
         nsp(j)=length(find(SP(j,:)));
     end
     snam0=param_names(find(nsp==0),:);
@@ -673,7 +742,7 @@ else
     % snam2=bayestopt_.name(find(nsp>1));
     % snam=bayestopt_.name(find(nsp>0));
     nsnam=(find(nsp>1));
-    
+
     skipline(2)
     disp('These parameters do not affect significantly the fit of ANY observed series:')
     disp(snam0)
@@ -683,11 +752,11 @@ else
     skipline()
     disp('These parameters affect MORE THAN ONE observed series: trade off exists!')
     disp(snam2)
-    
-    
+
+
     %pnam=bayestopt_.name(end-estim_params_.np+1:end);
     pnam=bayestopt_.name;
-    
+
     % plot trade-offs
     if ~options_.nograph
         a00=jet(size(vvarvecm,1));
@@ -714,7 +783,7 @@ else
         options_mcf.param_names_tex = param_names_tex;
         options_mcf.fname_ = fname_;
         options_mcf.OutputDirectoryName = OutDir;
-        for iy=1:size(vvarvecm,1),
+        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,:))];
@@ -722,21 +791,21 @@ else
             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),
+        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),
+            for ix=1:ceil(length(ipar)/5)
+                hh = dyn_figure(options_.nodisplay,'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),
+                    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,
+                        if any(iobs==i) || i==iy
                             h0=cumplot(x(ixx(1:nfilt0(i),i),ipar(j)));
                             if ~isoctave
                                 hcmenu = uicontextmenu;
@@ -768,24 +837,30 @@ 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_' deblank(vvarvecm(iy,:)) '_' int2str(ix)],options_);
-                    create_TeX_loader(options_,[ OutDir filesep fname_ '_rmse_post_' deblank(vvarvecm(iy,:)) '_' int2str(ix)],ix,[temp_name,' observed variable $',deblank(vvarvecm_tex(iy,:)) '$'],['rmse_post_' deblank(vvarvecm(iy,:))],1)
+                    dyn_saveas(hh,[ OutDir filesep fname_ '_rmse_post_' deblank(vvarvecm(iy,:)) '_' int2str(ix)],options_.nodisplay,options_.graph_format);
+                    if options_.TeX
+                        create_TeX_loader(options_,[ OutDir filesep fname_ '_rmse_post_' deblank(vvarvecm(iy,:)) '_' int2str(ix)],ix,[temp_name,' observed variable $',deblank(vvarvecm_tex(iy,:)) '$'],['rmse_post_' deblank(vvarvecm(iy,:))],1)
+                    end
                 else
                     if options_.opt_gsa.pprior
-                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_' deblank(vvarvecm(iy,:)) '_' int2str(ix) ],options_);
-                        create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_prior_' deblank(vvarvecm(iy,:)) '_' int2str(ix) ],ix,[temp_name,' observed variable $',deblank(vvarvecm_tex(iy,:)) '$'],['rmse_prior_' deblank(vvarvecm(iy,:))],1)
+                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_' deblank(vvarvecm(iy,:)) '_' int2str(ix) ],options_.nodisplay,options_.graph_format);
+                        if options_.TeX
+                            create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_prior_' deblank(vvarvecm(iy,:)) '_' int2str(ix) ],ix,[temp_name,' observed variable $',deblank(vvarvecm_tex(iy,:)) '$'],['rmse_prior_' deblank(vvarvecm(iy,:))],1)
+                        end
                     else
-                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_' deblank(vvarvecm(iy,:)) '_' int2str(ix)],options_);
-                        create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_mc_' deblank(vvarvecm(iy,:)) '_' int2str(ix)],ix,[temp_name,' observed variable $',deblank(vvarvecm_tex(iy,:)) '$'],['rmse_mc_' deblank(vvarvecm(iy,:))],1)
+                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_' deblank(vvarvecm(iy,:)) '_' int2str(ix)],options_.nodisplay,options_.graph_format);
+                        if options_.TeX
+                            create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_mc_' deblank(vvarvecm(iy,:)) '_' int2str(ix)],ix,[temp_name,' observed variable $',deblank(vvarvecm_tex(iy,:)) '$'],['rmse_mc_' deblank(vvarvecm(iy,:))],1)
+                        end
                     end
                 end
             end
         end
-        
+
         % now I plot by individual parameters
-        for ix=1:ceil(length(nsnam)/5),
-            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),
+        for ix=1:ceil(length(nsnam)/5)
+            hh = dyn_figure(options_.nodisplay,'name',[temp_name,' estimated params and shocks ',int2str(ix)]);
+            for j=1+5*(ix-1):min(size(snam2,1),5*ix)
                 subplot(2,3,j-5*(ix-1))
                 %h0=cumplot(x(:,nsnam(j)+nshock));
                 h0=cumplot(x(:,nsnam(j)));
@@ -794,10 +869,10 @@ else
                 npx=find(SP(nsnam(j),:)==0);
                 %a0=jet(nsp(nsnam(j)));
                 %             a0=a00(np,:);
-                for i=1:size(vvarvecm,1),
+                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(npx==i),
+                    if any(npx==i)
                         h0=cumplot(x(ixx(1:nfilt0(i),i),nsnam(j))*NaN);
                     else
                         h0=cumplot(x(ixx(1:nfilt0(i),i),nsnam(j)));
@@ -829,79 +904,85 @@ 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_params_' int2str(ix)],options_);
-                create_TeX_loader(options_,[ OutDir filesep fname_ '_rmse_post_params_' int2str(ix)],ix,[temp_name,' estimated params and shocks ',int2str(ix)],'rmse_post_params',1)
+                dyn_saveas(hh,[ OutDir filesep fname_ '_rmse_post_params_' int2str(ix)],options_.nodisplay,options_.graph_format);
+                if options_.TeX
+                    create_TeX_loader(options_,[ OutDir filesep fname_ '_rmse_post_params_' int2str(ix)],ix,[temp_name,' estimated params and shocks ',int2str(ix)],'rmse_post_params',1)
+                end
             else
                 if options_.opt_gsa.pprior
-                    dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_params_' int2str(ix) ],options_);
-                    create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_prior_params_' int2str(ix) ],ix,[temp_name,' estimated params and shocks ',int2str(ix)],'rmse_prior_params',1)
+                    dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_params_' int2str(ix) ],options_.nodisplay,options_.graph_format);
+                    if options_.TeX
+                        create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_prior_params_' int2str(ix) ],ix,[temp_name,' estimated params and shocks ',int2str(ix)],'rmse_prior_params',1)
+                    end
                 else
-                    dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_params_' int2str(ix)],options_);
-                    create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_mc_params_' int2str(ix)],ix,[temp_name,' estimated params and shocks ',int2str(ix)],'rmse_mc_params',1)
+                    dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_params_' int2str(ix)],options_.nodisplay,options_.graph_format);
+                    if options_.TeX
+                        create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_mc_params_' int2str(ix)],ix,[temp_name,' estimated params and shocks ',int2str(ix)],'rmse_mc_params',1)
+                    end
                 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
-    
-    
-%     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
-    
+
+    %     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
+
 end
 
 function []=create_TeX_loader(options_,figpath,label_number,caption,label_name,scale_factor)
@@ -925,7 +1006,7 @@ end
 function [pnames,pnames_tex]=get_LaTeX_parameter_names(M_,options_,estim_params_,bayestopt_)
 np=size(bayestopt_.name,1);
 pnames=cell(np,1);
-pnames_tex=cell(np,1);    
+pnames_tex=cell(np,1);
 for ii=1:length(bayestopt_.name)
     if options_.TeX
         [param_name_temp, param_name_tex_temp]= get_the_name(ii,options_.TeX,M_,estim_params_,options_);
@@ -936,4 +1017,3 @@ for ii=1:length(bayestopt_.name)
         pnames{ii,1} = param_name_temp;
     end
 end
-
diff --git a/matlab/gsa/ghx2transition.m b/matlab/gsa/ghx2transition.m
index 46b463e36e8847f268eb1efe334328174bbbe98f..df404577a9cee5141cef2116cccab0233efe2ac5 100644
--- a/matlab/gsa/ghx2transition.m
+++ b/matlab/gsa/ghx2transition.m
@@ -3,13 +3,10 @@ function [A,B] = ghx2transition(mm,iv,ic,aux)
 %
 % Adapted by M. Ratto (from kalman_transition_matrix.m)
 % Joint Research Centre, The European Commission,
-% (http://eemc.jrc.ec.europa.eu/),
-% marco.ratto@jrc.it 
+% marco.ratto@ec.europa.eu
 %
-% Reference:
-% M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006.
 
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -28,10 +25,10 @@ function [A,B] = ghx2transition(mm,iv,ic,aux)
 
 global oo_ M_
 
-  [nr1, nc1] = size(mm);
-  ghx = mm(:, [1:(nc1-M_.exo_nbr)]);
-  ghu = mm(:, [(nc1-M_.exo_nbr+1):end] );
-  if nargin == 1
+[nr1, nc1] = size(mm);
+ghx = mm(:, [1:(nc1-M_.exo_nbr)]);
+ghu = mm(:, [(nc1-M_.exo_nbr+1):end] );
+if nargin == 1
     oo_.dr.ghx = ghx;
     oo_.dr.ghu = ghu;
     endo_nbr = M_.endo_nbr;
@@ -43,18 +40,18 @@ global oo_ M_
     k = find(aux(:,2) > nspred);
     aux(:,2) = aux(:,2) + nstatic;
     aux(k,2) = aux(k,2) + M_.nfwrd;
-  end
-  n_iv = length(iv);
-  n_ir1 = size(aux,1);
-  nr = n_iv + n_ir1;
-  
-  A = zeros(nr,nr);
-  B = zeros(nr,M_.exo_nbr);
-  
-  i_n_iv = 1:n_iv;
-  A(i_n_iv,ic) = ghx(iv,:);
-  if n_ir1 > 0
+end
+n_iv = length(iv);
+n_ir1 = size(aux,1);
+nr = n_iv + n_ir1;
+
+A = zeros(nr,nr);
+B = zeros(nr,M_.exo_nbr);
+
+i_n_iv = 1:n_iv;
+A(i_n_iv,ic) = ghx(iv,:);
+if n_ir1 > 0
     A(n_iv+1:end,:) = sparse(aux(:,1),aux(:,2),ones(n_ir1,1),n_ir1,nr);
-  end
-  
-  B(i_n_iv,:) = ghu(iv,:);
+end
+
+B(i_n_iv,:) = ghu(iv,:);
diff --git a/matlab/gsa/gsa_plotmatrix.m b/matlab/gsa/gsa_plotmatrix.m
index 4caadf40705928edaa8511ea94610f7a8347948c..1a12a7e8b803cfb15a8fee3cc4ba0bfe2b8b32a1 100644
--- a/matlab/gsa/gsa_plotmatrix.m
+++ b/matlab/gsa/gsa_plotmatrix.m
@@ -1,8 +1,13 @@
 function gsa_plotmatrix(type,varargin)
 % function gsa_plotmatrix(type,varargin)
-% extended version of the standard MATLAB plotmatrix 
+% extended version of the standard MATLAB plotmatrix
+%
+% Written by Marco Ratto
+% Joint Research Centre, The European Commission,
+% marco.ratto@ec.europa.eu
 
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2012 European Commission
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -33,45 +38,45 @@ end
 iexplosive = iunstable(~ismember(iunstable,[iindeterm;iwrong]));
 
 switch type
-    case 'all'
-        x=[lpmat0 lpmat];
-        NumberOfDraws=size(x,1);
-        B=NumberOfDraws;
-    case 'stable'
-        x=[lpmat0(istable,:) lpmat(istable,:)];
-        NumberOfDraws=size(x,1);
-        B=NumberOfDraws;
-    case 'nosolution'
-        x=[lpmat0(iunstable,:) lpmat(iunstable,:)];
-        NumberOfDraws=size(x,1);
-        B=NumberOfDraws;
-    case 'unstable'
-        x=[lpmat0(iexplosive,:) lpmat(iexplosive,:)];
-        NumberOfDraws=size(x,1);
-        B=NumberOfDraws;
-    case 'indeterm'
-        x=[lpmat0(iindeterm,:) lpmat(iindeterm,:)];
-        NumberOfDraws=size(x,1);
-        B=NumberOfDraws;
-    case 'wrong'
-        x=[lpmat0(iwrong,:) lpmat(iwrong,:)];
-        NumberOfDraws=size(x,1);
-        B=NumberOfDraws;
-        
+  case 'all'
+    x=[lpmat0 lpmat];
+    NumberOfDraws=size(x,1);
+    B=NumberOfDraws;
+  case 'stable'
+    x=[lpmat0(istable,:) lpmat(istable,:)];
+    NumberOfDraws=size(x,1);
+    B=NumberOfDraws;
+  case 'nosolution'
+    x=[lpmat0(iunstable,:) lpmat(iunstable,:)];
+    NumberOfDraws=size(x,1);
+    B=NumberOfDraws;
+  case 'unstable'
+    x=[lpmat0(iexplosive,:) lpmat(iexplosive,:)];
+    NumberOfDraws=size(x,1);
+    B=NumberOfDraws;
+  case 'indeterm'
+    x=[lpmat0(iindeterm,:) lpmat(iindeterm,:)];
+    NumberOfDraws=size(x,1);
+    B=NumberOfDraws;
+  case 'wrong'
+    x=[lpmat0(iwrong,:) lpmat(iwrong,:)];
+    NumberOfDraws=size(x,1);
+    B=NumberOfDraws;
+
 end
 
-if isempty(x),
+if isempty(x)
     disp('Empty parameter set!')
     return
 end
 
-for j=1:length(varargin),
+for j=1:length(varargin)
     jcol(j)=strmatch(varargin{j},bayestopt_.name,'exact');
 end
 
 [H,AX,BigA,P,PAx]=plotmatrix(x(:,jcol));
 
-for j=1:length(varargin),
+for j=1:length(varargin)
     %      axes(AX(1,j)), title(varargin{j})
     %      axes(AX(j,1)), ylabel(varargin{j})
     %      set(AX(1,j),'title',varargin{j}),
@@ -79,15 +84,15 @@ for j=1:length(varargin),
     set(get(AX(end,j),'xlabel'),'string',varargin{j})
 end
 
-if options_.opt_gsa.pprior==0,
+if options_.opt_gsa.pprior==0
     xparam1=xparam1(jcol);
-    for j=1:length(varargin),
-        for i=1:j-1,
-            axes(AX(j,i)),
+    for j=1:length(varargin)
+        for i=1:j-1
+            axes(AX(j,i))
             hold on, plot(xparam1(i),xparam1(j),'*r')
         end
-        for i=j+1:length(varargin),
-            axes(AX(j,i)),
+        for i=j+1:length(varargin)
+            axes(AX(j,i))
             hold on, plot(xparam1(i),xparam1(j),'*r')
         end
     end
diff --git a/matlab/gsa/gsa_skewness.m b/matlab/gsa/gsa_skewness.m
index 01c8186a6a76143803442f2ccc022984fab80e26..dfb6ccfb92047a58a5b81afcfef69c85fb114ed4 100644
--- a/matlab/gsa/gsa_skewness.m
+++ b/matlab/gsa/gsa_skewness.m
@@ -1,6 +1,11 @@
-function s=gsa_skewness(y),
+function s=gsa_skewness(y)
 
-% Copyright (C) 2012 Dynare Team
+% Written by Marco Ratto
+% Joint Research Centre, The European Commission,
+% marco.ratto@ec.europa.eu
+
+% Copyright (C) 2012 European Commission
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -19,6 +24,6 @@ function s=gsa_skewness(y),
 
 % y=stand_(y);
 % s=mean(y.^3);
-    m2=mean((y-mean(y)).^2);
-    m3=mean((y-mean(y)).^3);
-    s=m3/m2^1.5;
\ No newline at end of file
+m2=mean((y-mean(y)).^2);
+m3=mean((y-mean(y)).^3);
+s=m3/m2^1.5;
\ No newline at end of file
diff --git a/matlab/gsa/gsa_speed.m b/matlab/gsa/gsa_speed.m
index d0845c57f8b3de6ed76ab9b7d03cfe6969f05911..135036ad2ee18eaaa3278c384f82c524e2054aa1 100644
--- a/matlab/gsa/gsa_speed.m
+++ b/matlab/gsa/gsa_speed.m
@@ -1,15 +1,12 @@
-function [tadj, iff] = gsa_speed(A,B,mf,p),
+function [tadj, iff] = gsa_speed(A,B,mf,p)
 % [tadj, iff] = gsa_speed(A,B,mf,p),
 %
 % Written by Marco Ratto
 % Joint Research Centre, The European Commission,
-% (http://eemc.jrc.ec.europa.eu/),
-% marco.ratto@jrc.it 
-%
-% Reference:
-% M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006.
+% marco.ratto@ec.europa.eu
 
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012 European Commission
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -36,25 +33,25 @@ tadj=iff;
 disp('Computing speed of adjustement ...')
 h = dyn_waitbar(0,'Speed of adjustement...');
 
-for i=1:nrun,
-  irf=zeros(nvar,nshock);
-  a=squeeze(A(:,:,i));
-  b=squeeze(B(:,:,i));
-  IFF=inv(eye(nstate)-a)*b;
-  iff(:,:,i)=IFF(mf,:);
-  IF=IFF-b;
-  
-  t=0;
-  while any(any(irf<0.5))
-    t=t+1;
-    IFT=((eye(nstate)-a^(t+1))*inv(eye(nstate)-a))*b-b;
-    irf=IFT(mf,:)./(IF(mf,:)+eps);
-    irf = irf.*(abs(IF(mf,:))>1.e-7)+(abs(IF(mf,:))<=1.e-7);
-    %irf=ft(mf,:);
-    tt=(irf>0.5).*t;
-    tadj(:,:,i)=((tt-tadj(:,:,i))==tt).*tt+tadj(:,:,i);
-  end
-  dyn_waitbar(i/nrun,h)
+for i=1:nrun
+    irf=zeros(nvar,nshock);
+    a=squeeze(A(:,:,i));
+    b=squeeze(B(:,:,i));
+    IFF=inv(eye(nstate)-a)*b;
+    iff(:,:,i)=IFF(mf,:);
+    IF=IFF-b;
+
+    t=0;
+    while any(any(irf<0.5))
+        t=t+1;
+        IFT=((eye(nstate)-a^(t+1))*inv(eye(nstate)-a))*b-b;
+        irf=IFT(mf,:)./(IF(mf,:)+eps);
+        irf = irf.*(abs(IF(mf,:))>1.e-7)+(abs(IF(mf,:))<=1.e-7);
+        %irf=ft(mf,:);
+        tt=(irf>0.5).*t;
+        tadj(:,:,i)=((tt-tadj(:,:,i))==tt).*tt+tadj(:,:,i);
+    end
+    dyn_waitbar(i/nrun,h)
 end
 skipline()
 disp('.. done !')
diff --git a/matlab/gsa/log_trans_.m b/matlab/gsa/log_trans_.m
index da34bd4808e4db5f95be70f9311662953e113932..c6011979317ce55e43ec8836437ba37d4e6ae93c 100644
--- a/matlab/gsa/log_trans_.m
+++ b/matlab/gsa/log_trans_.m
@@ -1,6 +1,11 @@
 function [yy, xdir, isig, lam]=log_trans_(y0,xdir0,isig,lam)
 
-% Copyright (C) 2012 Dynare Team
+% Written by Marco Ratto
+% Joint Research Centre, The European Commission,
+% marco.ratto@ec.europa.eu
+
+% Copyright (C) 2012 European Commission
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -17,62 +22,64 @@ function [yy, xdir, isig, lam]=log_trans_(y0,xdir0,isig,lam)
 % 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,
+if nargin==4
     % inverse transformation
     yy = (exp(y0)-lam)*isig;
     return
 end
 
-if nargin==1,
-  xdir0='';
+if nargin==1
+    xdir0='';
 end
 f=@(lam,y)gsa_skewness(log(y+lam));
 isig=1;
 if ~(max(y0)<0 | min(y0)>0)
-  if gsa_skewness(y0)<0,
-    isig=-1;
-    y0=-y0;
-  end
-  n=hist(y0,10);
-  if n(1)>20*n(end),
-    try lam=fzero(f,[-min(y0)+10*eps -min(y0)+abs(median(y0))],[],y0);
-    catch
-      yl(1)=f(-min(y0)+10*eps,y0);
-      yl(2)=f(-min(y0)+abs(median(y0)),y0);
-      if abs(yl(1))<abs(yl(2))
-        lam=-min(y0)+eps;
-      else
-        lam = -min(y0)+abs(median(y0)); %abs(100*(1+min(y0)));
-      end
+    if gsa_skewness(y0)<0,
+        isig=-1;
+        y0=-y0;
     end
-    yy = log(y0+lam);
-    xdir=[xdir0,'_logskew'];
-  else
-    isig=0;
-    lam=0;
-    yy = log(y0.^2);
-    xdir=[xdir0,'_logsquared'];
-  end
-else
-  if max(y0)<0
-    isig=-1;    
-    y0=-y0;
-    %yy=log(-y0);
-    xdir=[xdir0,'_minuslog'];
-  elseif min(y0)>0
-    %yy=log(y0);
-    xdir=[xdir0,'_log'];
-  end
-  try lam=fzero(f,[-min(y0)+10*eps -min(y0)+median(y0)],[],y0);
-  catch
-    yl(1)=f(-min(y0)+10*eps,y0);
-      yl(2)=f(-min(y0)+abs(median(y0)),y0);
-    if abs(yl(1))<abs(yl(2))
-      lam=-min(y0)+eps;
+    n=hist(y0,10);
+    if n(1)>20*n(end)
+        try
+            lam=fzero(f,[-min(y0)+10*eps -min(y0)+abs(median(y0))],[],y0);
+        catch
+            yl(1)=f(-min(y0)+10*eps,y0);
+            yl(2)=f(-min(y0)+abs(median(y0)),y0);
+            if abs(yl(1))<abs(yl(2))
+                lam=-min(y0)+eps;
+            else
+                lam = -min(y0)+abs(median(y0)); %abs(100*(1+min(y0)));
+            end
+        end
+        yy = log(y0+lam);
+        xdir=[xdir0,'_logskew'];
     else
-        lam = -min(y0)+abs(median(y0)); %abs(100*(1+min(y0)));
+        isig=0;
+        lam=0;
+        yy = log(y0.^2);
+        xdir=[xdir0,'_logsquared'];
     end
-  end
-  lam = max(lam,0);
-  yy = log(y0+lam);
+else
+    if max(y0)<0
+        isig=-1;
+        y0=-y0;
+        %yy=log(-y0);
+        xdir=[xdir0,'_minuslog'];
+    elseif min(y0)>0
+        %yy=log(y0);
+        xdir=[xdir0,'_log'];
+    end
+    try
+        lam=fzero(f,[-min(y0)+10*eps -min(y0)+median(y0)],[],y0);
+    catch
+        yl(1)=f(-min(y0)+10*eps,y0);
+        yl(2)=f(-min(y0)+abs(median(y0)),y0);
+        if abs(yl(1))<abs(yl(2))
+            lam=-min(y0)+eps;
+        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 c9d95c4ce5dec768ba7039195005a8700a8c3679..c7f707d4920f35ff5b3faec078255414d9278deb 100644
--- a/matlab/gsa/map_calibration.m
+++ b/matlab/gsa/map_calibration.m
@@ -1,6 +1,11 @@
 function map_calibration(OutputDirectoryName, Model, DynareOptions, DynareResults, EstimatedParameters, BayesInfo)
 
-% Copyright (C) 2014-2016 Dynare Team
+% Written by Marco Ratto
+% Joint Research Centre, The European Commission,
+% marco.ratto@ec.europa.eu
+
+% Copyright (C) 2014-2016 European Commission
+% Copyright (C) 2014-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -23,7 +28,7 @@ np = EstimatedParameters.np;
 nshock = EstimatedParameters.nvx + EstimatedParameters.nvn + EstimatedParameters.ncx + EstimatedParameters.ncn;
 pnames=cell(np,1);
 pnames_tex=cell(np,1);
-for jj=1:np        
+for jj=1:np
     if DynareOptions.TeX
         [param_name_temp, param_name_tex_temp]= get_the_name(nshock+jj, DynareOptions.TeX, Model, EstimatedParameters, DynareOptions);
         pnames_tex{jj,1} = strrep(param_name_tex_temp,'$','');
@@ -53,10 +58,10 @@ options_mcf.OutputDirectoryName = OutputDirectoryName;
 skipline()
 disp('Sensitivity analysis for calibration criteria')
 
-if DynareOptions.opt_gsa.ppost,
+if DynareOptions.opt_gsa.ppost
     filetoload=dir([Model.dname filesep 'metropolis' filesep fname_ '_param_irf*.mat']);
     lpmat=[];
-    for j=1:length(filetoload),
+    for j=1:length(filetoload)
         load([Model.dname filesep 'metropolis' filesep fname_ '_param_irf',int2str(j),'.mat'])
         lpmat = [lpmat; stock];
         clear stock
@@ -84,34 +89,34 @@ nbr_moment_restrictions = size(DynareOptions.endogenous_prior_restrictions.momen
 
 if init
     mat_irf=cell(nbr_irf_restrictions,1);
-    for ij=1:nbr_irf_restrictions,
+    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,
+    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,
+    for j=1:Nsam
         Model = set_all_parameters(lpmat(j,:)',EstimatedParameters,Model);
-        if nbr_moment_restrictions,
+        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 info(1)==0,
+        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,
+                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,
+                for ij=1:nbr_moment_restrictions
                     mat_moment{ij}(j,:)=data_moment{ij}(:,2)';
                 end
                 indx_moment(j,:)=info_moment(:,1);
@@ -122,7 +127,7 @@ if init
         dyn_waitbar(j/Nsam,h,['MC iteration ',int2str(j),'/',int2str(Nsam)])
     end
     dyn_waitbar_close(h);
-    
+
     irestrictions=irestrictions(find(irestrictions));
     xmat=lpmat(irestrictions,:);
     skipline()
@@ -131,36 +136,36 @@ if init
 else
     load([OutputDirectoryName,filesep,fname_,'_',type,'_restrictions'],'xmat','mat_irf','mat_moment','irestrictions','indx_irf','indx_moment','endo_prior_restrictions');
 end
-if ~isempty(indx_irf),
+if ~isempty(indx_irf)
     skipline()
     disp('Deleting old IRF calibration plots ...')
     a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_irf_calib*.eps']);
-    for j=1:length(a),
+    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),
+    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),
+    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),
+    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),
+    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),
+    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);
@@ -183,21 +188,21 @@ if ~isempty(indx_irf),
         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,:);
-    if ~DynareOptions.nograph,
-        h1=dyn_figure(DynareOptions,'name',[type ' evaluation of irf restrictions']);
+    if ~DynareOptions.nograph
+        h1=dyn_figure(DynareOptions.nodisplay,'name',[type ' evaluation of irf restrictions']);
         nrow=ceil(sqrt(nbr_irf_couples));
         ncol=nrow;
-        if nrow*(nrow-1)>nbr_irf_couples,
+        if nrow*(nrow-1)>nbr_irf_couples
             ncol=nrow-1;
         end
     end
-    for ij=1:nbr_irf_restrictions,
+    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),
+        for ik=1:size(mat_irf{ij},2)
             [Mean,Median,Var,HPD,Distrib] = ...
                 posterior_moments(mat_irf{ij}(:,ik),0,DynareOptions.mh_conf_sig);
             irf_mean{plot_indx(ij)} = [irf_mean{plot_indx(ij)}; Mean];
@@ -208,12 +213,12 @@ if ~isempty(indx_irf),
         end
         leg = num2str(endo_prior_restrictions.irf{ij,3}(1));
         aleg = num2str(endo_prior_restrictions.irf{ij,3}(1));
-        if size(mat_irf{ij},2)>1,
+        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))];
             iplot_indx(ij)=0;
         end
-        if ~DynareOptions.nograph && length(time_matrix{plot_indx(ij)})==1,
+        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));
@@ -255,16 +260,16 @@ if ~isempty(indx_irf),
         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
     end
-    for ij=1:nbr_irf_couples,
-        if length(time_matrix{ij})>1,
-            if ~DynareOptions.nograph,
+    for ij=1:nbr_irf_couples
+        if length(time_matrix{ij})>1
+            if ~DynareOptions.nograph
                 set(0,'currentfigure',h1);
                 subplot(nrow,ncol, ij)
                 itmp = (find(plot_indx==ij));
@@ -272,7 +277,7 @@ if ~isempty(indx_irf),
                 a=axis;
                 delete(htmp);
                 tmp=[];
-                for ir=1:length(itmp),
+                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};
@@ -288,14 +293,14 @@ if ~isempty(indx_irf),
                 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,
+                hold off
                 axis([max(1,a(1)) a(2:4)])
-                box on,
+                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),
+            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);
@@ -319,8 +324,8 @@ if ~isempty(indx_irf),
             end
         end
     end
-    if ~DynareOptions.nograph,
-        dyn_saveas(h1,[OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions'],DynareOptions);
+    if ~DynareOptions.nograph
+        dyn_saveas(h1,[OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions'],DynareOptions.nodisplay,DynareOptions.graph_format);
         create_TeX_loader(DynareOptions,[OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions'],[type ' evaluation of irf restrictions'],'irf_restrictions',type,DynareOptions.figures.textwidth*min(ij/ncol,1))
     end
     skipline()
@@ -330,32 +335,32 @@ 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),
+    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),
+    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),
+    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),
+    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),
+    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),
+    for j=1:length(a)
         delete([OutputDirectoryName,filesep,a(j).name]);
     end
     disp('done !')
     skipline()
-    
+
     %get parameter names including standard deviations
     np=size(BayesInfo.name,1);
     name=cell(np,1);
@@ -397,22 +402,22 @@ if ~isempty(indx_moment)
         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,:);
-    if ~DynareOptions.nograph,
-        h2=dyn_figure(DynareOptions,'name',[type ' evaluation of moment restrictions']);
+    if ~DynareOptions.nograph
+        h2=dyn_figure(DynareOptions.nodisplay,'name',[type ' evaluation of moment restrictions']);
         nrow=ceil(sqrt(nbr_moment_couples));
         ncol=nrow;
-        if nrow*(nrow-1)>nbr_moment_couples,
+        if nrow*(nrow-1)>nbr_moment_couples
             ncol=nrow-1;
         end
     end
-    
-    for ij=1:nbr_moment_restrictions,
+
+    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),
+        for ik=1:size(mat_moment{ij},2)
             [Mean,Median,Var,HPD,Distrib] = ...
                 posterior_moments(mat_moment{ij}(:,ik),0,DynareOptions.mh_conf_sig);
             moment_mean{plot_indx(ij)} = [moment_mean{plot_indx(ij)}; Mean];
@@ -423,12 +428,12 @@ if ~isempty(indx_moment)
         end
         leg = num2str(endo_prior_restrictions.moment{ij,3}(1));
         aleg = num2str(endo_prior_restrictions.moment{ij,3}(1));
-        if size(mat_moment{ij},2)>1,
+        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 ~DynareOptions.nograph && length(time_matrix{plot_indx(ij)})==1,
+        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));
@@ -438,10 +443,10 @@ if ~isempty(indx_moment)
             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,'FaceColor', [0.7 0.8 1])
-            hold all,
+            hold all
             hc = cumplot(mat_moment{ij}(:,ik));
             set(hc,'color','k','linewidth',2)
-            hold off,
+            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}(:));
@@ -465,15 +470,15 @@ if ~isempty(indx_moment)
         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
     end
-    for ij=1:nbr_moment_couples,
-        if length(time_matrix{ij})>1,
+    for ij=1:nbr_moment_couples
+        if length(time_matrix{ij})>1
             if ~DynareOptions.nograph
                 itmp = (find(plot_indx==ij));
                 set(0,'currentfigure',h2);
@@ -482,7 +487,7 @@ if ~isempty(indx_moment)
                 a=axis;
                 delete(htmp);
                 tmp=[];
-                for ir=1:length(itmp),
+                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};
@@ -493,19 +498,19 @@ if ~isempty(indx_moment)
                 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,
+                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,
+                hold off
                 axis(a)
-                box on,
+                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),
+            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);
@@ -529,11 +534,11 @@ if ~isempty(indx_moment)
             end
         end
     end
-    if ~DynareOptions.nograph,
-        dyn_saveas(h2,[OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions'],DynareOptions);
+    if ~DynareOptions.nograph
+        dyn_saveas(h2,[OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions'],DynareOptions.nodisplay,DynareOptions.graph_format);
         create_TeX_loader(DynareOptions,[OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions'],[type ' evaluation of moment restrictions'],'moment_restrictions',type,DynareOptions.figures.textwidth*min(ij/ncol,1))
     end
-    
+
     skipline()
 end
 return
diff --git a/matlab/gsa/map_ident_.m b/matlab/gsa/map_ident_.m
index 535f4bf33ee27d8e42d4f25daaac88898bea6375..fa23574dd2cc99925e97050e12642cafb779090f 100644
--- a/matlab/gsa/map_ident_.m
+++ b/matlab/gsa/map_ident_.m
@@ -1,6 +1,11 @@
 function map_ident_(OutputDirectoryName,opt_gsa)
 
-% Copyright (C) 2012-2016 Dynare Team
+% Written by Marco Ratto
+% Joint Research Centre, The European Commission,
+% marco.ratto@ec.europa.eu
+
+% Copyright (C) 2012-2016 European Commission
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -26,24 +31,24 @@ ntra   = opt_gsa.morris_ntra;
 itrans = opt_gsa.trans_ident;
 
 np = estim_params_.np;
-if opt_gsa.load_ident_files,
-  gsa_flag=0;
+if opt_gsa.load_ident_files
+    gsa_flag=0;
 else
-  gsa_flag=-2;
+    gsa_flag=-2;
 end
 
 pnames = M_.param_names(estim_params_.param_vals(:,1),:);
-    if opt_gsa.pprior,
+if opt_gsa.pprior
 
-filetoload=[OutputDirectoryName '/' fname_ '_prior'];
-    else
-filetoload=[OutputDirectoryName '/' fname_ '_mc'];
-    end
+    filetoload=[OutputDirectoryName '/' fname_ '_prior'];
+else
+    filetoload=[OutputDirectoryName '/' fname_ '_mc'];
+end
 load(filetoload,'lpmat','lpmat0','istable','T','yys','nspred','nboth','nfwrd')
-if ~isempty(lpmat0),
-  lpmatx=lpmat0(istable,:);
+if ~isempty(lpmat0)
+    lpmatx=lpmat0(istable,:);
 else
-  lpmatx=[];
+    lpmatx=[];
 end
 Nsam = size(lpmat,1);
 nshock = size(lpmat0,2);
@@ -51,140 +56,140 @@ npT = np+nshock;
 
 fname_ = M_.fname;
 
-if opt_gsa.load_ident_files==0,
-  % th moments
-%     options_.ar = min(3,options_.ar);
-
-  mss = yys(bayestopt_.mfys,:);
-  mss = teff(mss(:,istable),Nsam,istable);
-  yys = teff(yys(oo_.dr.order_var,istable),Nsam,istable);
-  if exist('T'),
-      [vdec, cc, ac] = mc_moments(T, lpmatx, oo_.dr);
-  else
-      return,
-  end
-
-
-  if opt_gsa.morris==2,
-   pdraws = dynare_identification(options_.options_ident,[lpmatx lpmat(istable,:)]);
-%    [pdraws, TAU, GAM] = dynare_identification(options_.options_ident,[lpmatx lpmat(istable,:)]);
-    if ~isempty(pdraws) && max(max(abs(pdraws-[lpmatx lpmat(istable,:)])))==0,
-      disp(['Sample check OK ', num2str(max(max(abs(pdraws-[lpmatx lpmat(istable,:)]))))]),
-      clear pdraws;
+if opt_gsa.load_ident_files==0
+    % th moments
+    %     options_.ar = min(3,options_.ar);
+
+    mss = yys(bayestopt_.mfys,:);
+    mss = teff(mss(:,istable),Nsam,istable);
+    yys = teff(yys(oo_.dr.order_var,istable),Nsam,istable);
+    if exist('T')
+        [vdec, cc, ac] = mc_moments(T, lpmatx, oo_.dr);
+    else
+        return
     end
-%     for j=1:length(istable), gas(:,j)=[vech(cc(:,:,j)); vec(ac(:,:,j))];  end
-%     if ~isempty(mss),
-%     gas = [mss(istable,:)'; gas];
-%     end
-%     if max(max(abs(GAM-gas)))<=1.e-8,
-%       disp(['Moments check OK ',num2str(max(max(abs(GAM-gas))))]),
-      clear GAM gas
-%     end
-  end
-  if opt_gsa.morris~=1 & M_.exo_nbr>1,
-    ifig=0;
-    for j=1:M_.exo_nbr,
-      if mod(j,6)==1
-        hh=dyn_figure(options_,'name',['Variance decomposition shocks']);
-        ifig=ifig+1;
-        iplo=0;
-      end
-      iplo=iplo+1;
-      subplot(2,3,iplo)
-      myboxplot(squeeze(vdec(:,j,:))',[],'.',[],10)
-      %     boxplot(squeeze(vdec(:,j,:))','whis',10,'symbol','.r')
-      set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:size(options_.varobs,1)])
-      set(gca,'xlim',[0.5 size(options_.varobs,1)+0.5])
-      set(gca,'ylim',[-2 102])
-      for ip=1:size(options_.varobs,1),
-        text(ip,-4,deblank(options_.varobs(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-      end
-      xlabel(' ')
-      ylabel(' ')
-      title(M_.exo_names(j,:),'interpreter','none')
-      if mod(j,6)==0 | j==M_.exo_nbr,
-        dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_vdec_exo_',int2str(ifig)],options_);  
-        create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_vdec_exo_',int2str(ifig)],ifig,['Variance decomposition shocks'],'vdec_exo',options_.figures.textwidth*min(iplo/3,1))
-      end
+
+
+    if opt_gsa.morris==2
+        pdraws = dynare_identification(options_.options_ident,[lpmatx lpmat(istable,:)]);
+        %    [pdraws, TAU, GAM] = dynare_identification(options_.options_ident,[lpmatx lpmat(istable,:)]);
+        if ~isempty(pdraws) && max(max(abs(pdraws-[lpmatx lpmat(istable,:)])))==0
+            disp(['Sample check OK ', num2str(max(max(abs(pdraws-[lpmatx lpmat(istable,:)]))))]),
+            clear pdraws;
+        end
+        %     for j=1:length(istable), gas(:,j)=[vech(cc(:,:,j)); vec(ac(:,:,j))];  end
+        %     if ~isempty(mss),
+        %     gas = [mss(istable,:)'; gas];
+        %     end
+        %     if max(max(abs(GAM-gas)))<=1.e-8,
+        %       disp(['Moments check OK ',num2str(max(max(abs(GAM-gas))))]),
+        clear GAM gas
+        %     end
+    end
+    if opt_gsa.morris~=1 & M_.exo_nbr>1
+        ifig=0;
+        for j=1:M_.exo_nbr
+            if mod(j,6)==1
+                hh=dyn_figure(options_.nodisplay,'name',['Variance decomposition shocks']);
+                ifig=ifig+1;
+                iplo=0;
+            end
+            iplo=iplo+1;
+            subplot(2,3,iplo)
+            myboxplot(squeeze(vdec(:,j,:))',[],'.',[],10)
+            %     boxplot(squeeze(vdec(:,j,:))','whis',10,'symbol','.r')
+            set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:size(options_.varobs,1)])
+            set(gca,'xlim',[0.5 size(options_.varobs,1)+0.5])
+            set(gca,'ylim',[-2 102])
+            for ip=1:size(options_.varobs,1)
+                text(ip,-4,deblank(options_.varobs(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+            end
+            xlabel(' ')
+            ylabel(' ')
+            title(M_.exo_names(j,:),'interpreter','none')
+            if mod(j,6)==0 | j==M_.exo_nbr
+                dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_vdec_exo_',int2str(ifig)],options_.nodisplay,options_.graph_format);
+                create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_vdec_exo_',int2str(ifig)],ifig,['Variance decomposition shocks'],'vdec_exo',options_.figures.textwidth*min(iplo/3,1))
+            end
+        end
     end
-  end
-  for j=1:size(cc,1)
-    cc(j,j,:)=stand_(squeeze(log(cc(j,j,:))))./2;
-  end
-  [vdec, j0, ir_vdec, ic_vdec] = teff(vdec,Nsam,istable);
-  [cc, j0, ir_cc, ic_cc] = teff(cc,Nsam,istable);
-  [ac, j0, ir_ac, ic_ac] = teff(ac,Nsam,istable);
-
-  [nr1, nc1, nnn] = size(T);
+    for j=1:size(cc,1)
+        cc(j,j,:)=stand_(squeeze(log(cc(j,j,:))))./2;
+    end
+    [vdec, j0, ir_vdec, ic_vdec] = teff(vdec,Nsam,istable);
+    [cc, j0, ir_cc, ic_cc] = teff(cc,Nsam,istable);
+    [ac, j0, ir_ac, ic_ac] = teff(ac,Nsam,istable);
+
+    [nr1, nc1, nnn] = size(T);
     endo_nbr = M_.endo_nbr;
     nstatic = M_.nstatic;
     nspred = M_.nspred;
     iv = (1:endo_nbr)';
     ic = [ nstatic+(1:nspred) endo_nbr+(1:size(oo_.dr.ghx,2)-nspred) ]';
-  
+
     dr.ghx = T(:, [1:(nc1-M_.exo_nbr)],1);
     dr.ghu = T(:, [(nc1-M_.exo_nbr+1):end], 1);
     [Aa,Bb] = kalman_transition_matrix(dr,iv,ic,M_.exo_nbr);
-%     bayestopt_.restrict_var_list, ...
-%     bayestopt_.restrict_columns, ...
-%     bayestopt_.restrict_aux, M_.exo_nbr);
-  A = zeros(size(Aa,1),size(Aa,2)+size(Aa,1),length(istable));
-  % Sig(estim_params_.var_exo(:,1))=lpmatx(1,:).^2;
-  if ~isempty(lpmatx),
-      set_shocks_param(lpmatx(1,:));
-  end
-  A(:,:,1)=[Aa, triu(Bb*M_.Sigma_e*Bb')];
-  for j=2:length(istable),
-    dr.ghx = T(:, [1:(nc1-M_.exo_nbr)],j);
-    dr.ghu = T(:, [(nc1-M_.exo_nbr+1):end], j);
-    [Aa,Bb] = kalman_transition_matrix(dr, iv, ic, M_.exo_nbr);
-%       bayestopt_.restrict_var_list, ...
-%       bayestopt_.restrict_columns, ...
-%       bayestopt_.restrict_aux, M_.exo_nbr);
-    if ~isempty(lpmatx),
-        set_shocks_param(lpmatx(j,:));
+    %     bayestopt_.restrict_var_list, ...
+    %     bayestopt_.restrict_columns, ...
+    %     bayestopt_.restrict_aux, M_.exo_nbr);
+    A = zeros(size(Aa,1),size(Aa,2)+size(Aa,1),length(istable));
+    % Sig(estim_params_.var_exo(:,1))=lpmatx(1,:).^2;
+    if ~isempty(lpmatx)
+        set_shocks_param(lpmatx(1,:));
     end
-    A(:,:,j)=[Aa, triu(Bb*M_.Sigma_e*Bb')];
-  end
-  clear T;
-  clear lpmatx;
-
-  [nr,nc,nn]=size(A);
-  io=bayestopt_.mf2;
-  % T1=A(io,1:nr,:);
-  % ino=find(~ismember([1:nr],io));
-  % T2=A(ino,1:nr,:);
-  R=A(:,nr+1:nc,:);
-%   [tadj, iff] = gsa_speed(A(1:nr,1:nr,:),R,io,0.5);
-%   [tadj, j0, ir_tadj, ic_tadj] = teff(tadj,Nsam,istable);
-%   [iff, j0, ir_if, ic_if] = teff(iff,Nsam,istable);
-
-
-  [yt, j0]=teff(A,Nsam,istable);
-  yt = [yys yt];
-  if opt_gsa.morris==2,
-%     iii=find(std(yt(istable,:))>1.e-8);
-%     if max(max(abs(TAU-yt(istable,iii)')))<= 1.e-8,
-%       err = max(max(abs(TAU-yt(istable,iii)')));
-%       disp(['Model check OK ',num2str(err)]),
-      clear TAU A
-%     end
-  else
-    clear A,
-  end
-  % [yt1, j01]=teff(T1,Nsam,istable);
-  % [yt2, j02]=teff(T2,Nsam,istable);
-  % [ytr, j0r]=teff(R,Nsam,istable);
-  %
-  % yt=[yt1 yt2 ytr];
-  save([OutputDirectoryName,'/',fname_,'_main_eff.mat'],'ac','cc','vdec','yt','mss')
+    A(:,:,1)=[Aa, triu(Bb*M_.Sigma_e*Bb')];
+    for j=2:length(istable)
+        dr.ghx = T(:, [1:(nc1-M_.exo_nbr)],j);
+        dr.ghu = T(:, [(nc1-M_.exo_nbr+1):end], j);
+        [Aa,Bb] = kalman_transition_matrix(dr, iv, ic, M_.exo_nbr);
+        %       bayestopt_.restrict_var_list, ...
+        %       bayestopt_.restrict_columns, ...
+        %       bayestopt_.restrict_aux, M_.exo_nbr);
+        if ~isempty(lpmatx)
+            set_shocks_param(lpmatx(j,:));
+        end
+        A(:,:,j)=[Aa, triu(Bb*M_.Sigma_e*Bb')];
+    end
+    clear T
+    clear lpmatx
+
+    [nr,nc,nn]=size(A);
+    io=bayestopt_.mf2;
+    % T1=A(io,1:nr,:);
+    % ino=find(~ismember([1:nr],io));
+    % T2=A(ino,1:nr,:);
+    R=A(:,nr+1:nc,:);
+    %   [tadj, iff] = gsa_speed(A(1:nr,1:nr,:),R,io,0.5);
+    %   [tadj, j0, ir_tadj, ic_tadj] = teff(tadj,Nsam,istable);
+    %   [iff, j0, ir_if, ic_if] = teff(iff,Nsam,istable);
+
+
+    [yt, j0]=teff(A,Nsam,istable);
+    yt = [yys yt];
+    if opt_gsa.morris==2
+        %     iii=find(std(yt(istable,:))>1.e-8);
+        %     if max(max(abs(TAU-yt(istable,iii)')))<= 1.e-8,
+        %       err = max(max(abs(TAU-yt(istable,iii)')));
+        %       disp(['Model check OK ',num2str(err)]),
+        clear TAU A
+        %     end
+    else
+        clear A
+    end
+    % [yt1, j01]=teff(T1,Nsam,istable);
+    % [yt2, j02]=teff(T2,Nsam,istable);
+    % [ytr, j0r]=teff(R,Nsam,istable);
+    %
+    % yt=[yt1 yt2 ytr];
+    save([OutputDirectoryName,'/',fname_,'_main_eff.mat'],'ac','cc','vdec','yt','mss')
 else
-  if opt_gsa.morris==2,
-%    [pdraws, TAU, GAM] = dynare_identification([1:npT]); %,[lpmatx lpmat(istable,:)]);
-%    [pdraws, TAU, GAM] = dynare_identification(options_.options_ident);
-   pdraws = dynare_identification(options_.options_ident);
-  end
-  load([OutputDirectoryName,'/',fname_,'_main_eff.mat'],'ac','cc','vdec','yt','mss')
+    if opt_gsa.morris==2
+        %    [pdraws, TAU, GAM] = dynare_identification([1:npT]); %,[lpmatx lpmat(istable,:)]);
+        %    [pdraws, TAU, GAM] = dynare_identification(options_.options_ident);
+        pdraws = dynare_identification(options_.options_ident);
+    end
+    load([OutputDirectoryName,'/',fname_,'_main_eff.mat'],'ac','cc','vdec','yt','mss')
 end
 
 %   for j=1:nr,
@@ -200,1354 +205,1353 @@ end
 %   end
 %   yt = yt(:,j0);
 
-if opt_gsa.morris==1,
-  %OutputDir = CheckPath('gsa/screen');
-  if ~isempty(vdec),
-  if opt_gsa.load_ident_files==0,
-  SAMorris = [];
-  for i=1:size(vdec,2),
-    [SAmeas, SAMorris(:,:,i)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], vdec(:,i),nliv);
-  end
-  SAvdec = squeeze(SAMorris(:,1,:))';
-  save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'SAvdec','vdec','ir_vdec','ic_vdec')
-  else
-    load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAvdec','vdec','ir_vdec','ic_vdec')
-  end
-  
-  hh = dyn_figure(options_,'name','Screening identification: variance decomposition');
-%   boxplot(SAvdec,'whis',10,'symbol','r.')
-  myboxplot(SAvdec,[],'.',[],10)
-  set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
-  set(gca,'xlim',[0.5 npT+0.5])
-  ydum = get(gca,'ylim');
-  set(gca,'ylim',[0 ydum(2)])
-  set(gca,'position',[0.13 0.2 0.775 0.7])
-  for ip=1:npT,
-    text(ip,-2,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
-  end
-  xlabel(' ')
-  title('Elementary effects variance decomposition')
-  dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morris_vdec'],options_);
-  create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_vdec'],1,'Screening identification: variance decomposition','morris_vdec',1)
-  else
-  save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'vdec')
-    
-  end
-
-%   ifig = 0;
-%   for j=1:size(options_.varobs,1)
-%     if mod(j,6)==1
-%       figure('name',['EET variance decomposition observed variables']);
-%       ifig=ifig+1;
-%       iplo=0;
-%     end
-%     iplo=iplo+1;
-%     subplot(3,2,iplo)
-%     iv = find(ir_vdec==j);
-%     if ~isempty(iv)
-%       if length(iv)>1
-% %         boxplot(SAvdec(iv,:),'whis',3,'symbol','r.');
-%         myboxplot(SAvdec(iv,:),[],'.',[],3)
-%       else
-%         plot(SAvdec(iv,:),'r.');
-%       end
-%       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
-%       set(gca,'xlim',[0.5 npT+0.5])
-%       ydum = get(gca,'ylim');
-%       set(gca,'ylim',[0 ydum(2)])
-%       for ip=1:npT,
-%         text(ip,-2,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%       end
-%       xlabel(' ')
-%     end
-%     title(options_.varobs(j,:),'interpreter','none')
-%     if mod(j,6)==0 | j==size(options_.varobs,1)
-%       saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_vdec_varobs_',int2str(ifig)])
-%       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_vdec_varobs_',int2str(ifig)]);
-%       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_vdec_varobs_',int2str(ifig)]);
-%       close(gcf)
-%     end
-%   end
-% 
-%   ifig = 0;
-%   for j=1:M_.exo_nbr,
-%     if mod(j,6)==1
-%       figure('name',['EET variance decomposition shocks']);
-%       ifig=ifig+1;
-%       iplo=0;
-%     end
-%     iplo=iplo+1;
-%     subplot(3,2,iplo)
-%     iv = find(ic_vdec==j);
-%     if ~isempty(iv)
-%       if length(iv)>1
-% %         boxplot(SAvdec(iv,:),'whis',3,'symbol','r.');
-%         myboxplot(SAvdec(iv,:),[],'.',[],3)
-%       else
-%         plot(SAvdec(iv,:),'r.');
-%       end
-%       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
-%       set(gca,'xlim',[0.5 npT+0.5])
-%       ydum = get(gca,'ylim');
-%       set(gca,'ylim',[0 ydum(2)])
-%       for ip=1:npT,
-%         text(ip,-2,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%       end
-%       xlabel(' ')
-%     end
-%     title(M_.exo_names(j,:),'interpreter','none')
-%     if mod(j,6)==0 | j==M_.exo_nbr,
-%       saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_vdec_exo_',int2str(ifig)])
-%       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_vdec_exo_',int2str(ifig)]);
-%       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_vdec_exo_',int2str(ifig)]);
-%       close(gcf),
-%     end
-%   end
+if opt_gsa.morris==1
+    %OutputDir = CheckPath('gsa/screen');
+    if ~isempty(vdec)
+        if opt_gsa.load_ident_files==0
+            SAMorris = [];
+            for i=1:size(vdec,2)
+                [SAmeas, SAMorris(:,:,i)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], vdec(:,i),nliv);
+            end
+            SAvdec = squeeze(SAMorris(:,1,:))';
+            save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'SAvdec','vdec','ir_vdec','ic_vdec')
+        else
+            load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAvdec','vdec','ir_vdec','ic_vdec')
+        end
 
+        hh = dyn_figure(options_.nodisplay,'name','Screening identification: variance decomposition');
+        %   boxplot(SAvdec,'whis',10,'symbol','r.')
+        myboxplot(SAvdec,[],'.',[],10)
+        set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
+        set(gca,'xlim',[0.5 npT+0.5])
+        ydum = get(gca,'ylim');
+        set(gca,'ylim',[0 ydum(2)])
+        set(gca,'position',[0.13 0.2 0.775 0.7])
+        for ip=1:npT
+            text(ip,-2,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
+        end
+        xlabel(' ')
+        title('Elementary effects variance decomposition')
+        dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morris_vdec'],options_.nodisplay,options_.graph_format);
+        create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_vdec'],1,'Screening identification: variance decomposition','morris_vdec',1)
+    else
+        save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'vdec')
 
-  if opt_gsa.load_ident_files==0,
-  SAMorris = [];
-  ccac = [mss cc ac];
-  for i=1:size(ccac,2),
-    [SAmeas, SAMorris(:,:,i)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], [ccac(:,i)],nliv);
-  end
-  SAcc = squeeze(SAMorris(:,1,:))';
-  SAcc = SAcc./(max(SAcc')'*ones(1,npT));
-  save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'SAcc','cc','ir_cc','ic_cc','-append')
-  save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'ac','ir_ac','ic_ac','-append')
-  else
-    load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAcc','cc','ir_cc','ic_cc')
-    load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'ac','ir_ac','ic_ac')
-  end
-  
-  hh=dyn_figure(options_,'name','Screening identification: theoretical moments');
-%   boxplot(SAcc,'whis',10,'symbol','r.')
-  myboxplot(SAcc,[],'.',[],10)
-  set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
-  set(gca,'xlim',[0.5 npT+0.5])
-  ydum = get(gca,'ylim');
-  set(gca,'ylim',[0 1])
-  set(gca,'position',[0.13 0.2 0.775 0.7])
-  for ip=1:npT,
-    text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
-  end
-  xlabel(' ')
-  title('Elementary effects in the moments')
-  dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morris_moments'],options_);
-  create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_moments'],1,'Screening identification: theoretical moments','morris_moments',1)
-
-%   close(gcf),
-
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-% MORRIS FOR DERIVATIVES  
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-
-% if opt_gsa.load_ident_files==0,
-%     for j=1:npT,
-%   SAMorris = [];
-%   ddd=NaN(size(lpmat,1),size(JJ,1));
-%   ddd(istable,:) = squeeze(JJ(:,j,:))';
-%   for i=1:size(ddd,2),
-%     [SAmeas, SAMorris(:,:,i)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], [ddd(:,i)],nliv);
-%   end
-%   SAddd(:,:,j) = squeeze(SAMorris(:,1,:))';
-%   SAddd(:,:,j) = SAddd(:,:,j)./(max(SAddd(:,:,j)')'*ones(1,npT));
-%   sad(:,j) = median(SAddd(find(~isnan(squeeze(SAddd(:,1,j)))),:,j))'; 
-%     end
-%   save([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAddd','sad','-append')
-%   else
-%     load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAddd','sad')
-%   end
-%   figure,
-%   contourf(sad,10), colorbar
-%   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
-%   set(gca,'yticklabel',' ','fontsize',10,'ytick',[1:npT])
-%   for ip=1:npT,
-%     text(ip,0.9,['D(',bayestopt_.name{ip},')'],'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%     text(0.9,ip,[bayestopt_.name{ip}],'rotation',0,'HorizontalAlignment','right','interpreter','none')
-%   end
-%   [m,im]=max(sad);
-%   iii = find((im-[1:npT])==0);
-%   disp('Most identified params')
-%   disp(bayestopt_.name(iii))
-  
-  
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-% END OF MORRIS FOR DERIVATIVES  
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-  
-%   ifig = 0;
-%   for j=1:size(options_.varobs,1)
-%     if mod(j,6)==1
-%       figure('name',['EET cross-correlations']);
-%       ifig=ifig+1;
-%       iplo=0;
-%     end
-%     iplo=iplo+1;
-%     subplot(3,2,iplo)
-%     iv = find(ir_cc==j);
-%     iv = [iv; find(ic_cc==j)];
-%     if ~isempty(iv)
-%       if length(iv)>1
-% %         boxplot(SAcc(iv,:),'whis',3,'symbol','r.');
-%         myboxplot(SAcc(iv,:),[],'.',[],3)
-%       else
-%         plot(SAcc(iv,:),'r.');
-%       end
-%       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
-%       set(gca,'xlim',[0.5 npT+0.5])
-%       ydum = get(gca,'ylim');
-%       set(gca,'ylim',[0 ydum(2)])
-%       for ip=1:npT,
-%         text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%       end
-%       xlabel(' ')
-%     end
-%     title(options_.varobs(j,:),'interpreter','none')
-%     if mod(j,6)==0 | j==size(options_.varobs,1)
-%       saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_cc_',int2str(ifig)])
-%       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_cc_',int2str(ifig)]);
-%       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_cc_',int2str(ifig)]);
-%       close(gcf),
-%     end
-%   end
+    end
 
+    %   ifig = 0;
+    %   for j=1:size(options_.varobs,1)
+    %     if mod(j,6)==1
+    %       figure('name',['EET variance decomposition observed variables']);
+    %       ifig=ifig+1;
+    %       iplo=0;
+    %     end
+    %     iplo=iplo+1;
+    %     subplot(3,2,iplo)
+    %     iv = find(ir_vdec==j);
+    %     if ~isempty(iv)
+    %       if length(iv)>1
+    % %         boxplot(SAvdec(iv,:),'whis',3,'symbol','r.');
+    %         myboxplot(SAvdec(iv,:),[],'.',[],3)
+    %       else
+    %         plot(SAvdec(iv,:),'r.');
+    %       end
+    %       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
+    %       set(gca,'xlim',[0.5 npT+0.5])
+    %       ydum = get(gca,'ylim');
+    %       set(gca,'ylim',[0 ydum(2)])
+    %       for ip=1:npT,
+    %         text(ip,-2,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %       end
+    %       xlabel(' ')
+    %     end
+    %     title(options_.varobs(j,:),'interpreter','none')
+    %     if mod(j,6)==0 | j==size(options_.varobs,1)
+    %       saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_vdec_varobs_',int2str(ifig)])
+    %       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_vdec_varobs_',int2str(ifig)]);
+    %       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_vdec_varobs_',int2str(ifig)]);
+    %       close(gcf)
+    %     end
+    %   end
+    %
+    %   ifig = 0;
+    %   for j=1:M_.exo_nbr,
+    %     if mod(j,6)==1
+    %       figure('name',['EET variance decomposition shocks']);
+    %       ifig=ifig+1;
+    %       iplo=0;
+    %     end
+    %     iplo=iplo+1;
+    %     subplot(3,2,iplo)
+    %     iv = find(ic_vdec==j);
+    %     if ~isempty(iv)
+    %       if length(iv)>1
+    % %         boxplot(SAvdec(iv,:),'whis',3,'symbol','r.');
+    %         myboxplot(SAvdec(iv,:),[],'.',[],3)
+    %       else
+    %         plot(SAvdec(iv,:),'r.');
+    %       end
+    %       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
+    %       set(gca,'xlim',[0.5 npT+0.5])
+    %       ydum = get(gca,'ylim');
+    %       set(gca,'ylim',[0 ydum(2)])
+    %       for ip=1:npT,
+    %         text(ip,-2,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %       end
+    %       xlabel(' ')
+    %     end
+    %     title(M_.exo_names(j,:),'interpreter','none')
+    %     if mod(j,6)==0 | j==M_.exo_nbr,
+    %       saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_vdec_exo_',int2str(ifig)])
+    %       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_vdec_exo_',int2str(ifig)]);
+    %       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_vdec_exo_',int2str(ifig)]);
+    %       close(gcf),
+    %     end
+    %   end
 
-%   if opt_gsa.load_ident_files==0,
-%   SAMorris = [];
-%   for i=1:size(ac,2),
-%     [SAmeas, SAMorris(:,:,i)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], ac(:,i),nliv);
-%   end
-%   %end
-%   SAac = squeeze(SAMorris(:,1,:))';
-%   save([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAac','ac','ir_ac','ic_ac','-append')
-%   else
-%     load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAac','ac','ir_ac','ic_ac')
-%   end
-%   figure,
-% %   boxplot(SAac,'whis',10,'symbol','r.')
-%   myboxplot(SAac,[],'.',[],10)
-%   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
-%   set(gca,'xlim',[0.5 npT+0.5])
-%   ydum = get(gca,'ylim');
-%   set(gca,'ylim',[0 ydum(2)])
-%   set(gca,'position',[0.13 0.2 0.775 0.7])
-%   for ip=1:npT,
-%     text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%   end
-%   xlabel(' ')
-%   title('EET All auto-correlations')
-%   saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_ac'])
-%   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_ac']);
-%   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_ac']);
-%   close(gcf),
-
-%   ifig = 0;
-%   for j=1:size(options_.varobs,1)
-%     if mod(j,6)==1
-%       figure('name',['EET auto-correlations']);
-%       ifig=ifig+1;
-%       iplo=0;
-%     end
-%     iplo=iplo+1;
-%     subplot(3,2,iplo)
-%     iv = find(ir_ac==j);
-%     if ~isempty(iv)
-%       if length(iv)>1
-% %         boxplot(SAac(iv,:),'whis',3,'symbol','r.');
-%         myboxplot(SAac(iv,:),[],'.',[],3)
-%       else
-%         plot(SAac(iv,:),'r.');
-%       end
-%       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
-%       set(gca,'xlim',[0.5 npT+0.5])
-%       ydum = get(gca,'ylim');
-%       set(gca,'ylim',[0 ydum(2)])
-%       for ip=1:npT,
-%         text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%       end
-%       xlabel(' ')
-%     end
-%     title(options_.varobs(j,:),'interpreter','none')
-%     if mod(j,6)==0 | j==size(options_.varobs,1)
-%       saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_ac_',int2str(ifig)])
-%       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_ac_',int2str(ifig)]);
-%       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_ac_',int2str(ifig)]);
-%       close(gcf),
-%     end
-%   end
 
-%   if opt_gsa.load_ident_files==0,
-%   js=0;
-%   %for j=1:size(tadj,1),
-%   SAMorris = [];
-%   for i=1:size(tadj,2),
-%     js=js+1;
-%     [SAmeas, SAMorris(:,:,js)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], tadj(:,i),nliv);
-%   end
-%   %end
-%   SAM = squeeze(SAMorris(nshock+1:end,1,:));
-%   for j=1:js,
-%     SAtadj(:,j)=SAM(:,j)./(max(SAM(:,j))+eps);
-%   end
-%   SAtadj = SAtadj';
-%   save([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAtadj','tadj','ir_tadj','ic_tadj','-append')
-%   else
-%     load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAtadj','tadj','ir_tadj','ic_tadj')
-%   end
-%   if opt_gsa.load_ident_files==0,
-%   js=0;
-%   SAMorris = [];
-%   for i=1:size(iff,2),
-%     js=js+1;
-%     [SAmeas, SAMorriss(:,:,js)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], iff(:,i),nliv);
-%   end
-%   SAM = squeeze(SAMorriss(nshock+1:end,1,:));
-%   for j=1:js,
-%     SAIF(:,j)=SAM(:,j)./(max(SAM(:,j))+eps);
-%   end
-%   SAIF = SAIF';
-%   save([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAIF','iff','ir_if','ic_if','-append')
-%   else
-%     load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAIF','iff','ir_if','ic_if')
-%   end
-%   figure,
-%   %bar(SAtadj),
-% %   boxplot(SAtadj,'whis',10,'symbol','r.')
-%   myboxplot(SAtadj,[],'.',[],10)
-%   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
-%   set(gca,'xlim',[0.5 np+0.5])
-%   set(gca,'ylim',[0 1])
-%   set(gca,'position',[0.13 0.2 0.775 0.7])
-%   for ip=1:np,
-%     text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%   end
-%   xlabel(' ')
-%   title('All half-life')
-%   saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_tadj'])
-%   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_tadj']);
-%   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_tadj']);
-%   close(gcf),
-
-%   ifig = 0;
-%   for j=1:size(options_.varobs,1)
-%     if mod(j,6)==1
-%       figure('name',['EET speed of adjustment observed variables']);
-%       ifig=ifig+1;
-%       iplo=0;
-%     end
-%     iplo=iplo+1;
-%     subplot(3,2,iplo)
-%     iv = find(ir_tadj==j);
-%     if ~isempty(iv)
-%       if length(iv)>1
-% %         boxplot(SAtadj(iv,:),'whis',3,'symbol','r.');
-%         myboxplot(SAtadj(iv,:),[],'.',[],3)
-%       else
-%         plot(SAtadj(iv,:),'r.');
-%       end
-%       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
-%       set(gca,'xlim',[0.5 np+0.5])
-%       ydum = get(gca,'ylim');
-%       set(gca,'ylim',[0 ydum(2)])
-%       for ip=1:np,
-%         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%       end
-%       xlabel(' ')
-%     end
-%     title(options_.varobs(j,:),'interpreter','none')
-%     if mod(j,6)==0 | j==size(options_.varobs,1)
-%       saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_tadj_varobs_',int2str(ifig)])
-%       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_tadj_varobs_',int2str(ifig)]);
-%       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_tadj_varobs_',int2str(ifig)]);
-%       close(gcf),
-%     end
-%   end
+    if opt_gsa.load_ident_files==0
+        SAMorris = [];
+        ccac = [mss cc ac];
+        for i=1:size(ccac,2)
+            [SAmeas, SAMorris(:,:,i)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], [ccac(:,i)],nliv);
+        end
+        SAcc = squeeze(SAMorris(:,1,:))';
+        SAcc = SAcc./(max(SAcc')'*ones(1,npT));
+        save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'SAcc','cc','ir_cc','ic_cc','-append')
+        save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'ac','ir_ac','ic_ac','-append')
+    else
+        load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAcc','cc','ir_cc','ic_cc')
+        load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'ac','ir_ac','ic_ac')
+    end
 
-%   ifig = 0;
-%   for j=1:M_.exo_nbr,
-%     if mod(j,6)==1
-%       figure('name',['EET speed of adjustment shocks']);
-%       ifig=ifig+1;
-%       iplo=0;
-%     end
-%     iplo=iplo+1;
-%     subplot(3,2,iplo)
-%     iv = find(ic_tadj==j);
-%     if ~isempty(iv)
-%       if length(iv)>1
-% %         boxplot(SAtadj(iv,:),'whis',3,'symbol','r.');
-%         myboxplot(SAtadj(iv,:),[],'.',[],3)
-%       else
-%         plot(SAtadj(iv,:),'r.');
-%       end
-%       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
-%       set(gca,'xlim',[0.5 np+0.5])
-%       ydum = get(gca,'ylim');
-%       set(gca,'ylim',[0 ydum(2)])
-%       for ip=1:np,
-%         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%       end
-%       xlabel(' ')
-%     end
-%     title(M_.exo_names(j,:),'interpreter','none')
-%     if mod(j,6)==0 | j==M_.exo_nbr,
-%       saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_tadj_exo_',int2str(ifig)])
-%       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_tadj_exo_',int2str(ifig)]);
-%       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_tadj_exo_',int2str(ifig)]);
-%       close(gcf),
-%     end
-%   end
+    hh=dyn_figure(options_.nodisplay,'name','Screening identification: theoretical moments');
+    %   boxplot(SAcc,'whis',10,'symbol','r.')
+    myboxplot(SAcc,[],'.',[],10)
+    set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
+    set(gca,'xlim',[0.5 npT+0.5])
+    ydum = get(gca,'ylim');
+    set(gca,'ylim',[0 1])
+    set(gca,'position',[0.13 0.2 0.775 0.7])
+    for ip=1:npT
+        text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    end
+    xlabel(' ')
+    title('Elementary effects in the moments')
+    dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morris_moments'],options_.nodisplay,options_.graph_format);
+    create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_moments'],1,'Screening identification: theoretical moments','morris_moments',1)
 
-%   figure,
-%   %bar(SAIF),
-% %   boxplot(SAIF,'whis',10,'symbol','r.')
-%   myboxplot(SAIF,[],'.',[],10)
-%   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
-%   set(gca,'xlim',[0.5 np+0.5])
-%   set(gca,'ylim',[0 1])
-%   set(gca,'position',[0.13 0.2 0.775 0.7])
-%   for ip=1:np,
-%     text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%   end
-%   xlabel(' ')
-%   ylabel('Elementary Effects')
-%   title('Steady state gains (impact factors)')
-%   saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_gain'])
-%   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_gain']);
-%   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_gain']);
-%   close(gcf),
-  %figure, bar(SAIF'), title('All Gain Relationships')
-%   ifig = 0;
-%   for j=1:size(options_.varobs,1)
-%     if mod(j,6)==1
-%       figure('name',['EET steady state gain observed series']);
-%       ifig=ifig+1;
-%       iplo=0;
-%     end
-%     iplo=iplo+1;
-%     subplot(3,2,iplo)
-%     iv = find(ir_if==j);
-%     if ~isempty(iv)
-%       if length(iv)>1
-% %         boxplot(SAIF(iv,:),'whis',10,'symbol','r.');
-%         myboxplot(SAIF(iv,:),[],'.',[],10)
-%       else
-%         plot(SAIF(iv,:),'r.');
-%       end
-%       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
-%       set(gca,'xlim',[0.5 np+0.5])
-%       ydum = get(gca,'ylim');
-%       set(gca,'ylim',[0 ydum(2)])
-%       for ip=1:np,
-%         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%       end
-%       xlabel(' ')
-%     end
-%     title(options_.varobs(j,:),'interpreter','none')
-%     if mod(j,6)==0 | j==size(options_.varobs,1)
-%       saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_gain_varobs_',int2str(ifig)])
-%       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_gain_varobs_',int2str(ifig)]);
-%       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_gain_varobs_',int2str(ifig)]);
-%       close(gcf),
-%     end
-%   end
-% 
-%   ifig = 0;
-%   for j=1:M_.exo_nbr,
-%     if mod(j,6)==1
-%       figure('name',['EET steady state gain shocks']);
-%       ifig=ifig+1;
-%       iplo=0;
-%     end
-%     iplo=iplo+1;
-%     subplot(3,2,iplo)
-%     iv = find(ic_if==j);
-%     if ~isempty(iv)
-%       if length(iv)>1
-% %         boxplot(SAIF(iv,:),'whis',3,'symbol','r.');
-%         myboxplot(SAIF(iv,:),[],'.',[],3)
-%       else
-%         plot(SAIF(iv,:),'r.');
-%       end
-%       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
-%       set(gca,'xlim',[0.5 np+0.5])
-%       ydum = get(gca,'ylim');
-%       set(gca,'ylim',[0 ydum(2)])
-%       for ip=1:np,
-%         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%       end
-%       xlabel(' ')
-%     end
-%     title(M_.exo_names(j,:),'interpreter','none')
-%     if mod(j,6)==0 | j==M_.exo_nbr,
-%       saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_gain_exo_',int2str(ifig)])
-%       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_gain_exo_',int2str(ifig)]);
-%       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_gain_exo_',int2str(ifig)]);
-%       close(gcf),
-%     end
-%   end
+    %   close(gcf),
 
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % MORRIS FOR DERIVATIVES
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 
-  if opt_gsa.load_ident_files==0,
-  SAMorris = [];
-  for j=1:j0,
-    [SAmeas, SAMorris(:,:,j)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], yt(:,j),nliv);
-  end
-
-%   SAM = squeeze(SAMorris(nshock+1:end,1,:));
-  SAM = squeeze(SAMorris(1:end,1,:));
-  for j=1:j0
-    SAnorm(:,j)=SAM(:,j)./max(SAM(:,j));
-    irex(j)=length(find(SAnorm(:,j)>0.01));
-  end
-  [dum, irel]=sort(irex);
-
-%   SAMmu = squeeze(SAMorris(nshock+1:end,2,:));
-  SAMmu = squeeze(SAMorris(1:end,2,:));
-  for j=1:j0
-    SAmunorm(:,j)=SAMmu(:,j)./max(SAM(:,j));  % normalised w.r.t. mu*
-  end
-%   SAMsig = squeeze(SAMorris(nshock+1:end,3,:));
-  SAMsig = squeeze(SAMorris(1:end,3,:));
-  for j=1:j0
-    SAsignorm(:,j)=SAMsig(:,j)./max(SAMsig(:,j));
-  end
-    save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'SAnorm','SAmunorm','SAsignorm','-append')
-  else
-    load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAnorm','SAmunorm','SAsignorm')
-  end
-  hh=dyn_figure(options_,'name','Screening identification: model'); %bar(SAnorm(:,irel))
-%   boxplot(SAnorm','whis',10,'symbol','r.')
-  myboxplot(SAnorm',[],'.',[],10)
-  set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
-  set(gca,'xlim',[0.5 npT+0.5])
-  set(gca,'ylim',[0 1])
-  set(gca,'position',[0.13 0.2 0.775 0.7])
-  xlabel(' ')
-  for ip=1:npT,
-%     text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-    text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
-  end
-  xlabel(' ')
-  title('Elementary effects in the model')
-  dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morris_par'],options_);
-  create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_par'],1,'Screening identification: model','morris_par',1)
-
-%   hh=dyn_figure(options_); %bar(SAmunorm(:,irel))
-% %   boxplot(SAmunorm','whis',10,'symbol','r.')
-%   myboxplot(SAmunorm',[],'.',[],10)
-%   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
-%   set(gca,'xlim',[0.5 npT+0.5])
-%   set(gca,'ylim',[-1 1])
-%   set(gca,'position',[0.13 0.2 0.775 0.7])
-%   xlabel(' ')
-%   for ip=1:npT,
-%     text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%   end
-%   xlabel(' ')
-%   title('\mu in the model')
-%   dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morrismu_par'],options_);
-% 
-%   hh=dyn_figure(options_); %bar(SAsignorm(:,irel))
-% %   boxplot(SAsignorm','whis',10,'symbol','r.')
-%   myboxplot(SAsignorm',[],'.',[],10)
-%   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
-%   set(gca,'xlim',[0.5 npT+0.5])
-%   set(gca,'ylim',[0 1])
-%   set(gca,'position',[0.13 0.2 0.775 0.7])
-%   xlabel(' ')
-%   for ip=1:npT,
-%     text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%   end
-%   xlabel(' ')
-%   title('\sigma in the model')
-%   dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morrissig_par'],options_);
-
-  %     figure, bar(SAnorm(:,irel)')
-  %     set(gca,'xtick',[1:j0])
-  %     set(gca,'xlim',[0.5 j0+0.5])
-  %     title('Elementary effects relationships')
-  %     saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_redform'])
-  %     eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_redform']);
-  %     eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_redform']);
-
-elseif opt_gsa.morris==3,
+    % if opt_gsa.load_ident_files==0,
+    %     for j=1:npT,
+    %   SAMorris = [];
+    %   ddd=NaN(size(lpmat,1),size(JJ,1));
+    %   ddd(istable,:) = squeeze(JJ(:,j,:))';
+    %   for i=1:size(ddd,2),
+    %     [SAmeas, SAMorris(:,:,i)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], [ddd(:,i)],nliv);
+    %   end
+    %   SAddd(:,:,j) = squeeze(SAMorris(:,1,:))';
+    %   SAddd(:,:,j) = SAddd(:,:,j)./(max(SAddd(:,:,j)')'*ones(1,npT));
+    %   sad(:,j) = median(SAddd(find(~isnan(squeeze(SAddd(:,1,j)))),:,j))';
+    %     end
+    %   save([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAddd','sad','-append')
+    %   else
+    %     load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAddd','sad')
+    %   end
+    %   figure,
+    %   contourf(sad,10), colorbar
+    %   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
+    %   set(gca,'yticklabel',' ','fontsize',10,'ytick',[1:npT])
+    %   for ip=1:npT,
+    %     text(ip,0.9,['D(',bayestopt_.name{ip},')'],'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %     text(0.9,ip,[bayestopt_.name{ip}],'rotation',0,'HorizontalAlignment','right','interpreter','none')
+    %   end
+    %   [m,im]=max(sad);
+    %   iii = find((im-[1:npT])==0);
+    %   disp('Most identified params')
+    %   disp(bayestopt_.name(iii))
+
+
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    % END OF MORRIS FOR DERIVATIVES
+    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+    %   ifig = 0;
+    %   for j=1:size(options_.varobs,1)
+    %     if mod(j,6)==1
+    %       figure('name',['EET cross-correlations']);
+    %       ifig=ifig+1;
+    %       iplo=0;
+    %     end
+    %     iplo=iplo+1;
+    %     subplot(3,2,iplo)
+    %     iv = find(ir_cc==j);
+    %     iv = [iv; find(ic_cc==j)];
+    %     if ~isempty(iv)
+    %       if length(iv)>1
+    % %         boxplot(SAcc(iv,:),'whis',3,'symbol','r.');
+    %         myboxplot(SAcc(iv,:),[],'.',[],3)
+    %       else
+    %         plot(SAcc(iv,:),'r.');
+    %       end
+    %       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
+    %       set(gca,'xlim',[0.5 npT+0.5])
+    %       ydum = get(gca,'ylim');
+    %       set(gca,'ylim',[0 ydum(2)])
+    %       for ip=1:npT,
+    %         text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %       end
+    %       xlabel(' ')
+    %     end
+    %     title(options_.varobs(j,:),'interpreter','none')
+    %     if mod(j,6)==0 | j==size(options_.varobs,1)
+    %       saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_cc_',int2str(ifig)])
+    %       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_cc_',int2str(ifig)]);
+    %       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_cc_',int2str(ifig)]);
+    %       close(gcf),
+    %     end
+    %   end
+
+
+    %   if opt_gsa.load_ident_files==0,
+    %   SAMorris = [];
+    %   for i=1:size(ac,2),
+    %     [SAmeas, SAMorris(:,:,i)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], ac(:,i),nliv);
+    %   end
+    %   %end
+    %   SAac = squeeze(SAMorris(:,1,:))';
+    %   save([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAac','ac','ir_ac','ic_ac','-append')
+    %   else
+    %     load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAac','ac','ir_ac','ic_ac')
+    %   end
+    %   figure,
+    % %   boxplot(SAac,'whis',10,'symbol','r.')
+    %   myboxplot(SAac,[],'.',[],10)
+    %   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
+    %   set(gca,'xlim',[0.5 npT+0.5])
+    %   ydum = get(gca,'ylim');
+    %   set(gca,'ylim',[0 ydum(2)])
+    %   set(gca,'position',[0.13 0.2 0.775 0.7])
+    %   for ip=1:npT,
+    %     text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %   end
+    %   xlabel(' ')
+    %   title('EET All auto-correlations')
+    %   saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_ac'])
+    %   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_ac']);
+    %   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_ac']);
+    %   close(gcf),
+
+    %   ifig = 0;
+    %   for j=1:size(options_.varobs,1)
+    %     if mod(j,6)==1
+    %       figure('name',['EET auto-correlations']);
+    %       ifig=ifig+1;
+    %       iplo=0;
+    %     end
+    %     iplo=iplo+1;
+    %     subplot(3,2,iplo)
+    %     iv = find(ir_ac==j);
+    %     if ~isempty(iv)
+    %       if length(iv)>1
+    % %         boxplot(SAac(iv,:),'whis',3,'symbol','r.');
+    %         myboxplot(SAac(iv,:),[],'.',[],3)
+    %       else
+    %         plot(SAac(iv,:),'r.');
+    %       end
+    %       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
+    %       set(gca,'xlim',[0.5 npT+0.5])
+    %       ydum = get(gca,'ylim');
+    %       set(gca,'ylim',[0 ydum(2)])
+    %       for ip=1:npT,
+    %         text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %       end
+    %       xlabel(' ')
+    %     end
+    %     title(options_.varobs(j,:),'interpreter','none')
+    %     if mod(j,6)==0 | j==size(options_.varobs,1)
+    %       saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_ac_',int2str(ifig)])
+    %       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_ac_',int2str(ifig)]);
+    %       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_ac_',int2str(ifig)]);
+    %       close(gcf),
+    %     end
+    %   end
+
+    %   if opt_gsa.load_ident_files==0,
+    %   js=0;
+    %   %for j=1:size(tadj,1),
+    %   SAMorris = [];
+    %   for i=1:size(tadj,2),
+    %     js=js+1;
+    %     [SAmeas, SAMorris(:,:,js)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], tadj(:,i),nliv);
+    %   end
+    %   %end
+    %   SAM = squeeze(SAMorris(nshock+1:end,1,:));
+    %   for j=1:js,
+    %     SAtadj(:,j)=SAM(:,j)./(max(SAM(:,j))+eps);
+    %   end
+    %   SAtadj = SAtadj';
+    %   save([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAtadj','tadj','ir_tadj','ic_tadj','-append')
+    %   else
+    %     load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAtadj','tadj','ir_tadj','ic_tadj')
+    %   end
+    %   if opt_gsa.load_ident_files==0,
+    %   js=0;
+    %   SAMorris = [];
+    %   for i=1:size(iff,2),
+    %     js=js+1;
+    %     [SAmeas, SAMorriss(:,:,js)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], iff(:,i),nliv);
+    %   end
+    %   SAM = squeeze(SAMorriss(nshock+1:end,1,:));
+    %   for j=1:js,
+    %     SAIF(:,j)=SAM(:,j)./(max(SAM(:,j))+eps);
+    %   end
+    %   SAIF = SAIF';
+    %   save([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAIF','iff','ir_if','ic_if','-append')
+    %   else
+    %     load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAIF','iff','ir_if','ic_if')
+    %   end
+    %   figure,
+    %   %bar(SAtadj),
+    % %   boxplot(SAtadj,'whis',10,'symbol','r.')
+    %   myboxplot(SAtadj,[],'.',[],10)
+    %   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
+    %   set(gca,'xlim',[0.5 np+0.5])
+    %   set(gca,'ylim',[0 1])
+    %   set(gca,'position',[0.13 0.2 0.775 0.7])
+    %   for ip=1:np,
+    %     text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %   end
+    %   xlabel(' ')
+    %   title('All half-life')
+    %   saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_tadj'])
+    %   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_tadj']);
+    %   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_tadj']);
+    %   close(gcf),
+
+    %   ifig = 0;
+    %   for j=1:size(options_.varobs,1)
+    %     if mod(j,6)==1
+    %       figure('name',['EET speed of adjustment observed variables']);
+    %       ifig=ifig+1;
+    %       iplo=0;
+    %     end
+    %     iplo=iplo+1;
+    %     subplot(3,2,iplo)
+    %     iv = find(ir_tadj==j);
+    %     if ~isempty(iv)
+    %       if length(iv)>1
+    % %         boxplot(SAtadj(iv,:),'whis',3,'symbol','r.');
+    %         myboxplot(SAtadj(iv,:),[],'.',[],3)
+    %       else
+    %         plot(SAtadj(iv,:),'r.');
+    %       end
+    %       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
+    %       set(gca,'xlim',[0.5 np+0.5])
+    %       ydum = get(gca,'ylim');
+    %       set(gca,'ylim',[0 ydum(2)])
+    %       for ip=1:np,
+    %         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %       end
+    %       xlabel(' ')
+    %     end
+    %     title(options_.varobs(j,:),'interpreter','none')
+    %     if mod(j,6)==0 | j==size(options_.varobs,1)
+    %       saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_tadj_varobs_',int2str(ifig)])
+    %       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_tadj_varobs_',int2str(ifig)]);
+    %       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_tadj_varobs_',int2str(ifig)]);
+    %       close(gcf),
+    %     end
+    %   end
+
+    %   ifig = 0;
+    %   for j=1:M_.exo_nbr,
+    %     if mod(j,6)==1
+    %       figure('name',['EET speed of adjustment shocks']);
+    %       ifig=ifig+1;
+    %       iplo=0;
+    %     end
+    %     iplo=iplo+1;
+    %     subplot(3,2,iplo)
+    %     iv = find(ic_tadj==j);
+    %     if ~isempty(iv)
+    %       if length(iv)>1
+    % %         boxplot(SAtadj(iv,:),'whis',3,'symbol','r.');
+    %         myboxplot(SAtadj(iv,:),[],'.',[],3)
+    %       else
+    %         plot(SAtadj(iv,:),'r.');
+    %       end
+    %       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
+    %       set(gca,'xlim',[0.5 np+0.5])
+    %       ydum = get(gca,'ylim');
+    %       set(gca,'ylim',[0 ydum(2)])
+    %       for ip=1:np,
+    %         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %       end
+    %       xlabel(' ')
+    %     end
+    %     title(M_.exo_names(j,:),'interpreter','none')
+    %     if mod(j,6)==0 | j==M_.exo_nbr,
+    %       saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_tadj_exo_',int2str(ifig)])
+    %       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_tadj_exo_',int2str(ifig)]);
+    %       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_tadj_exo_',int2str(ifig)]);
+    %       close(gcf),
+    %     end
+    %   end
+
+    %   figure,
+    %   %bar(SAIF),
+    % %   boxplot(SAIF,'whis',10,'symbol','r.')
+    %   myboxplot(SAIF,[],'.',[],10)
+    %   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
+    %   set(gca,'xlim',[0.5 np+0.5])
+    %   set(gca,'ylim',[0 1])
+    %   set(gca,'position',[0.13 0.2 0.775 0.7])
+    %   for ip=1:np,
+    %     text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %   end
+    %   xlabel(' ')
+    %   ylabel('Elementary Effects')
+    %   title('Steady state gains (impact factors)')
+    %   saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_gain'])
+    %   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_gain']);
+    %   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_gain']);
+    %   close(gcf),
+    %figure, bar(SAIF'), title('All Gain Relationships')
+    %   ifig = 0;
+    %   for j=1:size(options_.varobs,1)
+    %     if mod(j,6)==1
+    %       figure('name',['EET steady state gain observed series']);
+    %       ifig=ifig+1;
+    %       iplo=0;
+    %     end
+    %     iplo=iplo+1;
+    %     subplot(3,2,iplo)
+    %     iv = find(ir_if==j);
+    %     if ~isempty(iv)
+    %       if length(iv)>1
+    % %         boxplot(SAIF(iv,:),'whis',10,'symbol','r.');
+    %         myboxplot(SAIF(iv,:),[],'.',[],10)
+    %       else
+    %         plot(SAIF(iv,:),'r.');
+    %       end
+    %       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
+    %       set(gca,'xlim',[0.5 np+0.5])
+    %       ydum = get(gca,'ylim');
+    %       set(gca,'ylim',[0 ydum(2)])
+    %       for ip=1:np,
+    %         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %       end
+    %       xlabel(' ')
+    %     end
+    %     title(options_.varobs(j,:),'interpreter','none')
+    %     if mod(j,6)==0 | j==size(options_.varobs,1)
+    %       saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_gain_varobs_',int2str(ifig)])
+    %       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_gain_varobs_',int2str(ifig)]);
+    %       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_gain_varobs_',int2str(ifig)]);
+    %       close(gcf),
+    %     end
+    %   end
+    %
+    %   ifig = 0;
+    %   for j=1:M_.exo_nbr,
+    %     if mod(j,6)==1
+    %       figure('name',['EET steady state gain shocks']);
+    %       ifig=ifig+1;
+    %       iplo=0;
+    %     end
+    %     iplo=iplo+1;
+    %     subplot(3,2,iplo)
+    %     iv = find(ic_if==j);
+    %     if ~isempty(iv)
+    %       if length(iv)>1
+    % %         boxplot(SAIF(iv,:),'whis',3,'symbol','r.');
+    %         myboxplot(SAIF(iv,:),[],'.',[],3)
+    %       else
+    %         plot(SAIF(iv,:),'r.');
+    %       end
+    %       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
+    %       set(gca,'xlim',[0.5 np+0.5])
+    %       ydum = get(gca,'ylim');
+    %       set(gca,'ylim',[0 ydum(2)])
+    %       for ip=1:np,
+    %         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %       end
+    %       xlabel(' ')
+    %     end
+    %     title(M_.exo_names(j,:),'interpreter','none')
+    %     if mod(j,6)==0 | j==M_.exo_nbr,
+    %       saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_gain_exo_',int2str(ifig)])
+    %       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_gain_exo_',int2str(ifig)]);
+    %       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_gain_exo_',int2str(ifig)]);
+    %       close(gcf),
+    %     end
+    %   end
+
+
+    if opt_gsa.load_ident_files==0
+        SAMorris = [];
+        for j=1:j0
+            [SAmeas, SAMorris(:,:,j)] = Morris_Measure_Groups(npT, [lpmat0 lpmat], yt(:,j),nliv);
+        end
+
+        %   SAM = squeeze(SAMorris(nshock+1:end,1,:));
+        SAM = squeeze(SAMorris(1:end,1,:));
+        for j=1:j0
+            SAnorm(:,j)=SAM(:,j)./max(SAM(:,j));
+            irex(j)=length(find(SAnorm(:,j)>0.01));
+        end
+        [dum, irel]=sort(irex);
+
+        %   SAMmu = squeeze(SAMorris(nshock+1:end,2,:));
+        SAMmu = squeeze(SAMorris(1:end,2,:));
+        for j=1:j0
+            SAmunorm(:,j)=SAMmu(:,j)./max(SAM(:,j));  % normalised w.r.t. mu*
+        end
+        %   SAMsig = squeeze(SAMorris(nshock+1:end,3,:));
+        SAMsig = squeeze(SAMorris(1:end,3,:));
+        for j=1:j0
+            SAsignorm(:,j)=SAMsig(:,j)./max(SAMsig(:,j));
+        end
+        save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'SAnorm','SAmunorm','SAsignorm','-append')
+    else
+        load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAnorm','SAmunorm','SAsignorm')
+    end
+    hh=dyn_figure(options_.nodisplay,'name','Screening identification: model'); %bar(SAnorm(:,irel))
+                                                                                %   boxplot(SAnorm','whis',10,'symbol','r.')
+    myboxplot(SAnorm',[],'.',[],10)
+    set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
+    set(gca,'xlim',[0.5 npT+0.5])
+    set(gca,'ylim',[0 1])
+    set(gca,'position',[0.13 0.2 0.775 0.7])
+    xlabel(' ')
+    for ip=1:npT
+        %     text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+        text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    end
+    xlabel(' ')
+    title('Elementary effects in the model')
+    dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morris_par'],options_.nodisplay,options_.graph_format);
+    create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_par'],1,'Screening identification: model','morris_par',1)
+
+    %   hh=dyn_figure(options_.nodisplay); %bar(SAmunorm(:,irel))
+    % %   boxplot(SAmunorm','whis',10,'symbol','r.')
+    %   myboxplot(SAmunorm',[],'.',[],10)
+    %   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
+    %   set(gca,'xlim',[0.5 npT+0.5])
+    %   set(gca,'ylim',[-1 1])
+    %   set(gca,'position',[0.13 0.2 0.775 0.7])
+    %   xlabel(' ')
+    %   for ip=1:npT,
+    %     text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %   end
+    %   xlabel(' ')
+    %   title('\mu in the model')
+    %   dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morrismu_par'],options_.nodisplay,options_.graph_format);
+    %
+    %   hh=dyn_figure(options_.nodisplay); %bar(SAsignorm(:,irel))
+    % %   boxplot(SAsignorm','whis',10,'symbol','r.')
+    %   myboxplot(SAsignorm',[],'.',[],10)
+    %   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
+    %   set(gca,'xlim',[0.5 npT+0.5])
+    %   set(gca,'ylim',[0 1])
+    %   set(gca,'position',[0.13 0.2 0.775 0.7])
+    %   xlabel(' ')
+    %   for ip=1:npT,
+    %     text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %   end
+    %   xlabel(' ')
+    %   title('\sigma in the model')
+    %   dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morrissig_par'],options_.nodisplay,options_.graph_format);
+
+    %     figure, bar(SAnorm(:,irel)')
+    %     set(gca,'xtick',[1:j0])
+    %     set(gca,'xlim',[0.5 j0+0.5])
+    %     title('Elementary effects relationships')
+    %     saveas(gcf,[OutputDirectoryName,'/',fname_,'_morris_redform'])
+    %     eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_morris_redform']);
+    %     eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_redform']);
+
+elseif opt_gsa.morris==3
     return
-    
-  np=estim_params_.np;
-  na=(4*np+1)*opt_gsa.Nsam;
-  for j=1:j0,
-    [idex(j,:), yd(j,:)] = spop_ide(lpmat, yt(:,j), opt_gsa.Nsam, 5-1);
-  end
-  iok=find(~isnan(yt(1:opt_gsa.Nsam,1)));
-  yr=NaN*ones(size(lpmat,1),j0);
-  for j=1:j0,
-    ys(j,:)=yd(j,:)./max(yd(j,:));
-    [dum, is]=sort(yt(iok,j));
-    yr(iok(is),j)=[1:length(iok)]'./length(iok);
-    yr(istable(length(iok)+1:end),j) = interp1(yt(iok,j),yr(iok,j),yt(istable(length(iok)+1:end),j),'','extrap');
-    ineg=find(yr(:,j)<0);
-    if any(ineg),
-      [dum, is]=sort(yr(ineg,j));
-      yr(ineg(is),j)=-[length(ineg):-1:1]./length(iok);
 
+    np=estim_params_.np;
+    na=(4*np+1)*opt_gsa.Nsam;
+    for j=1:j0
+        [idex(j,:), yd(j,:)] = spop_ide(lpmat, yt(:,j), opt_gsa.Nsam, 5-1);
     end
-    [idex_r(j,:), yd_r(j,:)] = spop_ide(lpmat, yr(:,j), opt_gsa.Nsam, 5-1);
-    ys_r(j,:)=yd_r(j,:)./max(yd_r(j,:));
-
-  end,
-  figure, bar((idex.*ys)./opt_gsa.Nsam), title('Relationships')
-  figure, bar((idex.*ys)'./opt_gsa.Nsam), title('Parameters')
-  figure, bar((idex_r.*ys_r)./opt_gsa.Nsam), title('Relationships rank')
-  figure, bar((idex_r.*ys_r)'./opt_gsa.Nsam), title('Parameters rank')
-  [v0,d0]=eig(corrcoef(yt(iok,:)));
-  ee=diag(d0);
-  ee=ee([end:-1:1])./j0;
-  i0=length(find(ee>0.01));
-  v0=v0(:,[end:-1:1]);
-  for j=1:i0,
-    [idex_pc(j,:), yd_pc(j,:)] = spop_ide(lpmat, yt*v0(:,j), opt_gsa.Nsam, 5-1);
-  end
-  for j=1:i0,
-    ys_pc(j,:)=yd_pc(j,:)./max(yd_pc(j,:));
-  end,
-  figure, bar((idex_pc.*ys_pc)./opt_gsa.Nsam), title('Relationships PCA')
-  figure, bar((idex_pc.*ys_pc)'./opt_gsa.Nsam), title('Parameters PCA')
-
-  [vr,dr]=eig(corrcoef(yr(iok,:)));
-  er=diag(dr);
-  er=er([end:-1:1])./j0;
-  ir0=length(find(er>0.01));
-  vr=vr(:,[end:-1:1]);
-  for j=1:ir0,
-    [idex_pcr(j,:), yd_pcr(j,:)] = spop_ide(lpmat, yr*vr(:,j), opt_gsa.Nsam, 5-1);
-  end
-  for j=1:ir0,
-    ys_pcr(j,:)=yd_pcr(j,:)./max(yd_pcr(j,:));
-  end,
-  figure, bar((idex_pcr.*ys_pcr)./opt_gsa.Nsam), title('Relationships rank PCA')
-  figure, bar((idex_pcr.*ys_pcr)'./opt_gsa.Nsam), title('Parameters rank PCA')
-  
-elseif opt_gsa.morris==2,   % ISKREV staff
-  return,
-
-  
-else,  % main effects analysis
-  
-  if itrans==0,
-    fsuffix = '';
-  elseif itrans==1,
-    fsuffix = '_log';
-  else
-    fsuffix = '_rank';
-  end
-  
-  imap=[1:npT];
-
-  if isempty(lpmat0),
-      x0=lpmat(istable,:);
-  else
-      
-      x0=[lpmat0(istable,:), lpmat(istable,:)];
-  end
-  nrun=length(istable);
-  nest=min(250,nrun);
-  nfit=min(1000,nrun);
-  
-%   opt_gsa.load_ident_files=0;
-  
-%   if opt_gsa.load_ident_files==0,
-%   try 
-%     EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAvdec','vdec','ir_vdec','ic_vdec');
-%   catch
-%     EET=[];
-%   end
-%   SAvdec=zeros(size(vdec,2),npT);
-% 
-%   for j=1:size(vdec,2),
-%     if itrans==0,
-%       y0 = vdec(istable,j);
-%     elseif itrans==1,
-%       y0 = log_trans_(vdec(istable,j));
-%     else
-%       y0 = trank(vdec(istable,j));
-%     end
-%     if ~isempty(EET),
-% %       imap=find(EET.SAvdec(j,:));
-% %       [dum, isort]=sort(-EET.SAvdec(j,:));
-%       imap=find(EET.SAvdec(j,:) >= (0.1.*max(EET.SAvdec(j,:))) );
-%     end
-%   gsa_(j) = gsa_sdp(y0(1:nest), x0(1:nest,imap), ...
-%       2, [],[],[],0,[OutputDirectoryName,'/map_vdec',fsuffix,int2str(j)], pnames);
-%   if nfit>nest,
-%     gsa_(j) = gsa_sdp(y0(1:nfit), x0(1:nfit,imap), ...
-%         -2, gsa_(j).nvr*nest^3/nfit^3,[],[],0,[OutputDirectoryName,'/map_vdec',fsuffix,int2str(j)], pnames);
-%   end
-%     
-%     SAvdec(j,imap)=gsa_(j).si;
-%     imap_vdec{j}=imap;
-%   end
-%   save([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_vdec','SAvdec','vdec','ir_vdec','ic_vdec','-append')
-%   else
-%   load([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_vdec','SAvdec','vdec','ir_vdec','ic_vdec')
-%   end
-%   figure,
-% %   boxplot(SAvdec,'whis',10,'symbol','r.')
-%   myboxplot(SAvdec,[],'.',[],10)
-%   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
-%   set(gca,'xlim',[0.5 npT+0.5])
-%   ydum = get(gca,'ylim');
-%   set(gca,'ylim',[0 ydum(2)])
-%   set(gca,'position',[0.13 0.2 0.775 0.7])
-%   for ip=1:npT,
-%     text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
-% %     text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%   end
-%   xlabel(' ')
-%   title(['Main effects variance decomposition ',fsuffix],'interpreter','none')
-%   saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_vdec',fsuffix])
-%   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix]);
-%   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix]);
-%   close(gcf),
-% 
-%   ifig = 0;
-%   for j=1:size(options_.varobs,1)
-%     if mod(j,6)==1
-%       figure('name',['Main effects observed variance decomposition ',fsuffix]);
-%       ifig=ifig+1;
-%       iplo=0;
-%     end
-%     iplo=iplo+1;
-%     subplot(3,2,iplo)
-%     iv = find(ir_vdec==j);
-%     if ~isempty(iv)
-%       if length(iv)>1
-% %         boxplot(SAvdec(iv,:),'whis',10,'symbol','r.');
-%         myboxplot(SAvdec(iv,:),[],'.',[],10)
-%       else
-%         plot(SAvdec(iv,:),'r.');
-%       end
-%       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
-%       set(gca,'xlim',[0.5 npT+0.5])
-%       ydum = get(gca,'ylim');
-%       set(gca,'ylim',[0 ydum(2)])
-%       for ip=1:npT,
-%         text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
-% %         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%       end
-%       xlabel(' ')
-%     end
-%     title(options_.varobs(j,:),'interpreter','none')
-%     if mod(j,6)==0 | j==size(options_.varobs,1)
-%       saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_vdec',fsuffix,'_varobs_',int2str(ifig)])
-%       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix,'_varobs_',int2str(ifig)]);
-%       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix,'_varobs_',int2str(ifig)]);
-%       close(gcf),
-%     end
-%   end
-% 
-%   ifig = 0;
-%   for j=1:M_.exo_nbr,
-%     if mod(j,6)==1
-%       figure('name',['Main effects shocks variance decomposition ',fsuffix]);
-%       ifig=ifig+1;
-%       iplo=0;
-%     end
-%     iplo=iplo+1;
-%     subplot(3,2,iplo)
-%     iv = find(ic_vdec==j);
-%     if ~isempty(iv)
-%       if length(iv)>1
-% %         boxplot(SAvdec(iv,:),'whis',3,'symbol','r.');
-%         myboxplot(SAvdec(iv,:),[],'.',[],10)
-%       else
-%         plot(SAvdec(iv,:),'r.');
-%       end
-%       set(gca,'xticklabel',' ','fontsize',3,'xtick',[1:np])
-%       set(gca,'xlim',[0.5 npT+0.5])
-%       ydum = get(gca,'ylim');
-%       set(gca,'ylim',[0 ydum(2)])
-%       for ip=1:npT,
-%         text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
-% %         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%       end
-%       xlabel(' ')
-%       set(gca,'fontsize',10)
-%     end
-%     title(M_.exo_names(j,:),'interpreter','none','fontsize',10)
-%     if mod(j,6)==0 | j==M_.exo_nbr
-%       saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_vdec',fsuffix,'_exo_',int2str(ifig)])
-%       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix,'_exo_',int2str(ifig)]);
-%       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix,'_exo_',int2str(ifig)]);
-%       close(gcf),
-%     end
-%   end
+    iok=find(~isnan(yt(1:opt_gsa.Nsam,1)));
+    yr=NaN*ones(size(lpmat,1),j0);
+    for j=1:j0,
+        ys(j,:)=yd(j,:)./max(yd(j,:));
+        [dum, is]=sort(yt(iok,j));
+        yr(iok(is),j)=[1:length(iok)]'./length(iok);
+        yr(istable(length(iok)+1:end),j) = interp1(yt(iok,j),yr(iok,j),yt(istable(length(iok)+1:end),j),'','extrap');
+        ineg=find(yr(:,j)<0);
+        if any(ineg)
+            [dum, is]=sort(yr(ineg,j));
+            yr(ineg(is),j)=-[length(ineg):-1:1]./length(iok);
+        end
+        [idex_r(j,:), yd_r(j,:)] = spop_ide(lpmat, yr(:,j), opt_gsa.Nsam, 5-1);
+        ys_r(j,:)=yd_r(j,:)./max(yd_r(j,:));
+
+    end,
+    figure, bar((idex.*ys)./opt_gsa.Nsam), title('Relationships')
+    figure, bar((idex.*ys)'./opt_gsa.Nsam), title('Parameters')
+    figure, bar((idex_r.*ys_r)./opt_gsa.Nsam), title('Relationships rank')
+    figure, bar((idex_r.*ys_r)'./opt_gsa.Nsam), title('Parameters rank')
+    [v0,d0]=eig(corrcoef(yt(iok,:)));
+    ee=diag(d0);
+    ee=ee([end:-1:1])./j0;
+    i0=length(find(ee>0.01));
+    v0=v0(:,[end:-1:1]);
+    for j=1:i0
+        [idex_pc(j,:), yd_pc(j,:)] = spop_ide(lpmat, yt*v0(:,j), opt_gsa.Nsam, 5-1);
+    end
+    for j=1:i0
+        ys_pc(j,:)=yd_pc(j,:)./max(yd_pc(j,:));
+    end,
+    figure, bar((idex_pc.*ys_pc)./opt_gsa.Nsam), title('Relationships PCA')
+    figure, bar((idex_pc.*ys_pc)'./opt_gsa.Nsam), title('Parameters PCA')
+
+    [vr,dr]=eig(corrcoef(yr(iok,:)));
+    er=diag(dr);
+    er=er([end:-1:1])./j0;
+    ir0=length(find(er>0.01));
+    vr=vr(:,[end:-1:1]);
+    for j=1:ir0
+        [idex_pcr(j,:), yd_pcr(j,:)] = spop_ide(lpmat, yr*vr(:,j), opt_gsa.Nsam, 5-1);
+    end
+    for j=1:ir0
+        ys_pcr(j,:)=yd_pcr(j,:)./max(yd_pcr(j,:));
+    end
+    figure, bar((idex_pcr.*ys_pcr)./opt_gsa.Nsam), title('Relationships rank PCA')
+    figure, bar((idex_pcr.*ys_pcr)'./opt_gsa.Nsam), title('Parameters rank PCA')
+
+elseif opt_gsa.morris==2   % ISKREV staff
+    return
+
+
+else  % main effects analysis
 
-  if opt_gsa.load_ident_files==0,
-  try 
-    EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAcc','ir_cc','ic_cc');
-  catch
-    EET=[];
-  end
-  ccac = stand_([mss cc ac]);
-  [pcc, dd] = eig(cov(ccac(istable,:)));
-  [latent, isort] = sort(-diag(dd));
-  latent = -latent;
-  figure, bar(latent)
-  title('Eigenvalues in PCA')
-  pcc=pcc(:,isort);
-  ccac = ccac*pcc;
-%   npca = min(40, max(find(cumsum(latent)./length(latent)<0.99))+1);
-  npca = max(find(cumsum(latent)./length(latent)<0.99))+1;
-  siPCA = (EET.SAcc'*abs(pcc'))';
-%   siPCA = siPCA./(max(siPCA')'*ones(1,npT)).*(latent*ones(1,npT));
-  siPCA = siPCA./(max(siPCA')'*ones(1,npT));
-%   siPCA = sum(siPCA,1);
-%   siPCA = siPCA./max(siPCA);
-  SAcc=zeros(size(ccac,2),npT);
-  for j=1:npca, %size(ccac,2),
-    if itrans==0,
-      y0 = ccac(istable,j);
-    elseif itrans==1,
-      y0 = log_trans_(ccac(istable,j));
+    if itrans==0
+        fsuffix = '';
+    elseif itrans==1
+        fsuffix = '_log';
     else
-      y0 = trank(ccac(istable,j));
+        fsuffix = '_rank';
     end
-    if ~isempty(EET),
-%       imap=find(EET.SAvdec(j,:));
-%       [dum, isort]=sort(-EET.SAvdec(j,:));
-      imap=find(siPCA(j,:) >= (0.1.*max(siPCA(j,:))) );
-%       imap=find(EET.SAcc(j,:) >= (0.1.*max(EET.SAcc(j,:))) );
+
+    imap=[1:npT];
+
+    if isempty(lpmat0)
+        x0=lpmat(istable,:);
+    else
+
+        x0=[lpmat0(istable,:), lpmat(istable,:)];
     end
-  gsa_(j) = gsa_sdp(y0(1:nest), x0(1:nest,imap), ...
-      2, [],[],[],0,[OutputDirectoryName,'/map_cc',fsuffix,int2str(j)], pnames);
-%   if nfit>nest,
-%     gsa_(j) = gsa_sdp(y0(1:nfit), x0(1:nfit,imap), ...
-%         -2, gsa_(j).nvr*nest^3/nfit^3,[],[],0,[OutputDirectoryName,'/map_cc',fsuffix,int2str(j)], pnames);
-%   end
-    SAcc(j,imap)=gsa_(j).si;
-    imap_cc{j}=imap;
-
-  end
-  save([OutputDirectoryName,'/map_cc',fsuffix,'.mat'],'gsa_')
-  save([OutputDirectoryName,'/',fname_,'_main_eff.mat'],'imap_cc','SAcc','ccac','-append')
-  else
-    load([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_cc','SAcc','ccac')
-    
-  end
-%   figure,
-% %   boxplot(SAcc,'whis',10,'symbol','r.')
-%   myboxplot(SAcc,[],'.',[],10)
-%   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
-%   set(gca,'xlim',[0.5 npT+0.5])
-%   ydum = get(gca,'ylim');
-%   set(gca,'ylim',[0 ydum(2)])
-%   set(gca,'position',[0.13 0.2 0.775 0.7])
-%   for ip=1:npT,
-%     text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
-% %     text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%   end
-%   xlabel(' ')
-%   ylabel(' ')
-%   title(['Main effects moments''s PCA ',fsuffix],'interpreter','none')
-%   saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_cc',fsuffix])
-%   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_moments',fsuffix]);
-%   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_moments',fsuffix]);
-%   close(gcf),
-
-%   ifig = 0;
-%   for j=1:size(options_.varobs,1)
-%     if mod(j,6)==1
-%       figure('name',['Main effects cross-covariances ',fsuffix]);
-%       ifig=ifig+1;
-%       iplo=0;
-%     end
-%     iplo=iplo+1;
-%     subplot(3,2,iplo)
-%     iv = find(ir_cc==j);
-%     iv = [iv; find(ic_cc==j)];
-%     if ~isempty(iv)
-%       if length(iv)>1
-% %         boxplot(SAcc(iv,:),'whis',10,'symbol','r.');
-%         myboxplot(SAcc(iv,:),[],'.',[],10)
-%       else
-%         plot(SAcc(iv,:),'r.');
-%       end
-%       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
-%       set(gca,'xlim',[0.5 npT+0.5])
-%       ydum = get(gca,'ylim');
-%       set(gca,'ylim',[0 ydum(2)])
-%       for ip=1:npT,
-%         text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
-% %         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%       end
-%       xlabel(' ')
-%       set(gca,'fontsize',10)
-%     end
-%     title(options_.varobs(j,:),'interpreter','none','fontsize',10)
-%     if mod(j,6)==0 | j==size(options_.varobs,1)
-%       saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_cc',fsuffix,'_',int2str(ifig)])
-%       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_cc',fsuffix,'_',int2str(ifig)]);
-%       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_cc',fsuffix,'_',int2str(ifig)]);
-%       close(gcf),
-%     end
-%   end
-% 
-%   if opt_gsa.load_ident_files==0,
-%   try 
-%     EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAac','ir_ac','ic_ac');
-%   catch
-%     EET=[];
-%   end
-%   SAac=zeros(size(ac,2),npT);
-%   for j=1:size(ac,2),
-%     if itrans==0,
-%       y0 = ac(istable,j);
-%     elseif itrans==1,
-%       y0 = log_trans_(ac(istable,j));
-%     else
-%       y0 = trank(ac(istable,j));
-%     end
-%     if ~isempty(EET),
-%       imap=find(EET.SAac(j,:) >= (0.1.*max(EET.SAac(j,:))) );
-%     end
-% %     gsa_(j) = gsa_sdp_dyn( y0, lpmat(istable,:), ...
-% %       gsa_flag, [],[],[],0,[OutputDirectoryName,'/map_ac',fsuffix,int2str(j)], pnames);
-%   gsa_(j) = gsa_sdp(y0(1:nest), x0(1:nest,imap), ...
-%       2, [],[],[],0,[OutputDirectoryName,'/map_ac',fsuffix,int2str(j)], pnames);
-%   if nfit>nest,
-%     gsa_(j) = gsa_sdp(y0(1:nfit), x0(1:nfit,imap), ...
-%         -2, gsa_(j).nvr*nest^3/nfit^3,[],[],0,[OutputDirectoryName,'/map_ac',fsuffix,int2str(j)], pnames);
-%   end
-%     SAac(j,imap)=gsa_(j).si;
-%     imap_ac{j}=imap;
-% 
-%   end
-%   save([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_ac','SAac','ac','ir_ac','ic_ac','-append')
-%   else
-%   load([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_ac','SAac','ac','ir_ac','ic_ac')
-%   end
-% 
-%   figure,
-% %   boxplot(SAac,'whis',10,'symbol','r.')
-%   myboxplot(SAac,[],'.',[],10)
-%   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
-%   set(gca,'xlim',[0.5 npT+0.5])
-%   ydum = get(gca,'ylim');
-%   set(gca,'ylim',[0 ydum(2)])
-%   set(gca,'position',[0.13 0.2 0.775 0.7])
-%   for ip=1:np,
-%     text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%   end
-%   xlabel(' ')
-%   title(['Main effects 1 lag auto-covariances ',fsuffix],'interpreter','none')
-%   saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_ac',fsuffix])
-%   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_ac',fsuffix]);
-%   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_ac',fsuffix]);
-%   close(gcf),
-% 
-%   ifig = 0;
-%   for j=1:size(options_.varobs,1)
-%     if mod(j,6)==1
-%       figure('name',['Main effects auto-covariances ',fsuffix]);
-%       ifig=ifig+1;
-%       iplo = 0;
-%     end
-%     iplo=iplo+1;
-%     subplot(3,2,iplo)
-%     iv = find(ir_ac==j);
-%     %iv = [iv; find(ic_ac==j)];
-%     if ~isempty(iv)
-%       if length(iv)>1
-% %         boxplot(SAac(iv,:),'whis',10,'symbol','r.');
-%         myboxplot(SAac(iv,:),[],'.',[],10)
-%       else
-%         plot(SAac(iv,:),'r.');
-%       end
-%       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
-%       set(gca,'xlim',[0.5 npT+0.5])
-%       ydum = get(gca,'ylim');
-%       set(gca,'ylim',[0 ydum(2)])
-%       for ip=1:npT,
-%         text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
-% %         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%       end
-%       xlabel(' ')
-%       set(gca,'fontsize',10)
-%     end
-%     title(options_.varobs(j,:),'interpreter','none','fontsize',10)
-%     if mod(j,6)==0 | j==size(options_.varobs,1)
-%       saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_ac',fsuffix,'_',int2str(ifig)])
-%       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_ac',fsuffix,'_',int2str(ifig)]);
-%       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_ac',fsuffix,'_',int2str(ifig)]);
-%       close(gcf),
-%     end
-%   end
-  
-%   x0=x0(:,nshock+1:end);
-  imap=[1:npT];
-
-%   if opt_gsa.load_ident_files==0,
-%   try 
-%     EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAtadj','ir_tadj','ic_tadj');
-%     ny=size(EET.SAtadj,1);
-%   catch
-%     EET=[];
-%   end
-%   SAtadj=zeros(size(tadj,2),np);
-%   for j=1:size(tadj,2),
-%     if itrans==0,
-%       y0 = tadj(istable,j);
-%     elseif itrans==1,
-%       y0 = log_trans_(tadj(istable,j));
-%     else
-%       y0 = trank(tadj(istable,j));
-%     end
-%     if ~isempty(EET),
-%       if size(tadj,2)~=ny,
-%         jj=find(EET.ir_tadj==ir_tadj(j));
-%         jj=jj(find(EET.ic_tadj(jj)==ic_tadj(j)));
-%         if ~isempty(jj),
-%           imap=find(EET.SAtadj(jj,:) >= (0.1.*max(EET.SAtadj(jj,:))) );
-%         else
-%           imap=[1:np];
-%         end
-%       else
-%         imap=find(EET.SAtadj(j,:) >= (0.1.*max(EET.SAtadj(j,:))) );
-%       end
-%     end
-% %     gsa_(j) = gsa_sdp_dyn( y0, lpmat(istable,:), ...
-% %       gsa_flag, [],[],[],0,[OutputDirectoryName,'/map_tadj',fsuffix,int2str(j)], pnames);
-%   gsa_(j) = gsa_sdp(y0(1:nest), x0(1:nest,imap), ...
-%       2, [],[],[],0,[OutputDirectoryName,'/map_tadj',fsuffix,int2str(j)], pnames);
-%   if nfit>nest,
-%     gsa_(j) = gsa_sdp(y0(1:nfit), x0(1:nfit,imap), ...
-%         -2, gsa_(j).nvr*nest^3/nfit^3,[],[],0,[OutputDirectoryName,'/map_tadj',fsuffix,int2str(j)], pnames);
-%   end
-%     SAtadj(j,imap)=gsa_(j).si;
-%     imap_tadj{j}=imap;
-% 
-%   end
-%   save([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_tadj','SAtadj','tadj','ir_tadj','ic_tadj','-append')
-%   else
-%   load([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_tadj','SAtadj','tadj','ir_tadj','ic_tadj')
-%   end
-% 
-%   figure,
-% %   boxplot(SAtadj,'whis',10,'symbol','r.')
-%   myboxplot(SAtadj,[],'.',[],10)
-%   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
-%   set(gca,'xlim',[0.5 np+0.5])
-%   ydum = get(gca,'ylim');
-%   set(gca,'ylim',[0 ydum(2)])
-%   set(gca,'position',[0.13 0.2 0.775 0.7])
-%   for ip=1:np,
-%     text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%   end
-%   xlabel(' ')
-%   title(['Main effects speed of adjustment ',fsuffix],'interpreter','none')
-%   saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_tadj',fsuffix])
-%   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix]);
-%   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix]);
-%   close(gcf),
-% 
-%   ifig = 0;
-%   for j=1:size(options_.varobs,1)
-%     if mod(j,6)==1
-%       figure('name',['Main effects observed speed adjustment ',fsuffix]);
-%       ifig=ifig+1;
-%       iplo = 0;
-%     end
-%     iplo=iplo+1;
-%     subplot(3,2,iplo)
-%     iv = find(ir_tadj==j);
-%     if ~isempty(iv)
-%       if length(iv)>1
-% %         boxplot(SAtadj(iv,:),'whis',3,'symbol','r.');
-%         myboxplot(SAtadj(iv,:),[],'.',[],10)
-%       else
-%         plot(SAtadj(iv,:),'r.');
-%       end
-%       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
-%       set(gca,'xlim',[0.5 np+0.5])
-%       ydum = get(gca,'ylim');
-%       set(gca,'ylim',[0 ydum(2)])
-%       for ip=1:np,
-%         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%       end
-%       xlabel(' ')
-%     end
-%     title(options_.varobs(j,:),'interpreter','none')
-%     if mod(j,6)==0 | j==size(options_.varobs,1)
-%       saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_tadj',fsuffix,'_varobs_',int2str(ifig)])
-%       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix,'_varobs_',int2str(ifig)]);
-%       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix,'_varobs_',int2str(ifig)]);
-%       close(gcf),
-%     end
-%   end
-% 
-%   ifig = 0;
-%   for j=1:M_.exo_nbr,
-%     if mod(j,6)==1
-%       figure('name',['Main effects shocks speed of adjustment ',fsuffix]);
-%       ifig=ifig+1;
-%       iplo=0;
-%     end
-%     iplo=iplo+1;
-%     subplot(3,2,iplo)
-%     iv = find(ic_tadj==j);
-%     if ~isempty(iv)
-%       if length(iv)>1
-% %         boxplot(SAtadj(iv,:),'whis',3,'symbol','r.');
-%         myboxplot(SAtadj(iv,:),[],'.',[],10)
-%       else
-%         plot(SAtadj(iv,:),'r.');
-%       end
-%       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
-%       set(gca,'xlim',[0.5 np+0.5])
-%       ydum = get(gca,'ylim');
-%       set(gca,'ylim',[0 ydum(2)])
-%       for ip=1:np,
-%         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%       end
-%       xlabel(' ')
-%     end
-%     title(M_.exo_names(j,:),'interpreter','none')
-%     if mod(j,6)==0 | j==M_.exo_nbr,
-%       saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_tadj',fsuffix,'_exo_',int2str(ifig)])
-%       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix,'_exo_',int2str(ifig)]);
-%       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix,'_exo_',int2str(ifig)]);
-%       close(gcf),
-%     end
-%   end
-% 
-% 
-%   if opt_gsa.load_ident_files==0,
-%   try 
-%     EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAIF','ir_if','ic_if');
-%   catch
-%     EET=[];
-%   end
-%   SAif=zeros(size(iff,2),np);
-%   for j=1:size(iff,2),
-%     if itrans==0,
-%       y0 = iff(istable,j);
-%     elseif itrans==1,
-%       y0 = log_trans_(iff(istable,j));
-%     else
-%       y0 = trank(iff(istable,j));
-%     end
-%     if ~isempty(EET),
-%       imap=find(EET.SAIF(j,:) >= (0.1.*max(EET.SAIF(j,:))) );
-%     end
-% %     gsa_(j) = gsa_sdp_dyn( y0, lpmat(istable,:), ...
-% %       gsa_flag, [],[],[],0,[OutputDirectoryName,'/map_if',fsuffix,int2str(j)], pnames);
-%   gsa_(j) = gsa_sdp(y0(1:nest), x0(1:nest,imap), ...
-%       2, [],[],[],0,[OutputDirectoryName,'/map_if',fsuffix,int2str(j)], pnames);
-%   if nfit>nest,
-%     gsa_(j) = gsa_sdp(y0(1:nfit), x0(1:nfit,imap), ...
-%         -2, gsa_(j).nvr*nest^3/nfit^3,[],[],0,[OutputDirectoryName,'/map_if',fsuffix,int2str(j)], pnames);
-%   end
-%     SAif(j,imap)=gsa_(j).si;
-%     imap_if{j}=imap;
-%     
-%   end
-%   save([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_if','SAif','iff','ir_if','ic_if','-append')
-%   else
-%   load([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_if','SAif','iff','ir_if','ic_if')
-%   end
-% 
-%   figure,
-% %   boxplot(SAif,'whis',10,'symbol','r.')
-%   myboxplot(SAif,[],'.',[],10)
-%   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
-%   set(gca,'xlim',[0.5 np+0.5])
-%   ydum = get(gca,'ylim');
-%   set(gca,'ylim',[0 ydum(2)])
-%   set(gca,'position',[0.13 0.2 0.775 0.7])
-%   for ip=1:np,
-%     text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%   end
-%   xlabel(' ')
-%   title(['Main effects impact factors ',fsuffix],'interpreter','none')
-%   saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_if',fsuffix])
-%   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_if',fsuffix]);
-%   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_if',fsuffix]);
-%   close(gcf),
-% 
-%   ifig = 0;
-%   for j=1:size(options_.varobs,1)
-%     if mod(j,6)==1
-%       figure('name',['Main effects observed impact factors ',fsuffix]);
-%       ifig=ifig+1;
-%       iplo = 0;
-%     end
-%     iplo=iplo+1;
-%     subplot(3,2,iplo)
-%     iv = find(ir_if==j);
-%     if ~isempty(iv)
-%       if length(iv)>1
-% %         boxplot(SAif(iv,:),'whis',3,'symbol','r.');
-%         myboxplot(SAif(iv,:),[],'.',[],10)
-%       else
-%         plot(SAif(iv,:),'r.');
-%       end
-%       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
-%       set(gca,'xlim',[0.5 np+0.5])
-%       ydum = get(gca,'ylim');
-%       set(gca,'ylim',[0 ydum(2)])
-%       for ip=1:np,
-%         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%       end
-%       xlabel(' ')
-%     end
-%     title(options_.varobs(j,:),'interpreter','none')
-%     if mod(j,6)==0 | j==size(options_.varobs,1)
-%       saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_if',fsuffix,'_varobs_',int2str(ifig)])
-%       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_if',fsuffix,'_varobs_',int2str(ifig)]);
-%       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_if',fsuffix,'_varobs_',int2str(ifig)]);
-%       close(gcf),
-%     end
-%   end
-% 
-%   ifig = 0;
-%   for j=1:M_.exo_nbr,
-%     if mod(j,6)==1
-%       figure('name',['Main effects shocks impact factors ',fsuffix]);
-%       ifig=ifig+1;
-%       iplo=0;
-%     end
-%     iplo=iplo+1;
-%     subplot(3,2,iplo)
-%     iv = find(ic_if==j);
-%     if ~isempty(iv)
-%       if length(iv)>1
-% %         boxplot(SAif(iv,:),'whis',3,'symbol','r.');
-%         myboxplot(SAif(iv,:),[],'.',[],10)
-%       else
-%         plot(SAif(iv,:),'r.');
-%       end
-%       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
-%       set(gca,'xlim',[0.5 np+0.5])
-%       ydum = get(gca,'ylim');
-%       set(gca,'ylim',[0 ydum(2)])
-%       for ip=1:np,
-%         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%       end
-%       xlabel(' ')
-%     end
-%     title(M_.exo_names(j,:),'interpreter','none')
-%     if mod(j,6)==0 | j==M_.exo_nbr
-%       saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_if',fsuffix,'_exo_',int2str(ifig)])
-%       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_if',fsuffix,'_exo_',int2str(ifig)]);
-%       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_if',fsuffix,'_exo_',int2str(ifig)]);
-%       close(gcf),
-%     end
-%   end
-%   SAmom = [SAvdec' SAcc' SAac']';
-%   SAdyn = [SAtadj' SAif']';
-%   SAall = [SAmom(:,nshock+1:end)' SAdyn']';
-%   
-%   figure,
-%   %   boxplot(SAtadj,'whis',10,'symbol','r.')
-%   myboxplot(SAmom,[],'.',[],10)
-%   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
-%   set(gca,'xlim',[0.5 npT+0.5])
-%   ydum = get(gca,'ylim');
-%   set(gca,'ylim',[0 ydum(2)])
-%   set(gca,'position',[0.13 0.2 0.775 0.7])
-%   for ip=1:npT,
-%     %     text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%     text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%   end
-%   xlabel(' ')
-%   title(['Main effects theoretical moments ',fsuffix],'interpreter','none')
-%   saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_moments',fsuffix])
-%   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_moments',fsuffix]);
-%   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_moments',fsuffix]);
-% %   close(gcf),
-%   
-%   figure,
-%   %   boxplot(SAtadj,'whis',10,'symbol','r.')
-%   myboxplot(SAdyn,[],'.',[],10)
-%   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
-%   set(gca,'xlim',[0.5 np+0.5])
-%   ydum = get(gca,'ylim');
-%   set(gca,'ylim',[0 ydum(2)])
-%   set(gca,'position',[0.13 0.2 0.775 0.7])
-%   for ip=1:np,
-%     text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-% %     text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%   end
-%   xlabel(' ')
-%   title(['Main effects short-long term dynamics ',fsuffix],'interpreter','none')
-%   saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_dynamics',fsuffix])
-%   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_dynamics',fsuffix]);
-%   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_dynamics',fsuffix]);
-% %   close(gcf),
-% 
-%   figure,
-%   %   boxplot(SAtadj,'whis',10,'symbol','r.')
-%   myboxplot(SAall,[],'.',[],10)
-%   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
-%   set(gca,'xlim',[0.5 np+0.5])
-%   ydum = get(gca,'ylim');
-%   set(gca,'ylim',[0 ydum(2)])
-%   set(gca,'position',[0.13 0.2 0.775 0.7])
-%   for ip=1:np,
-%     text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-% %     text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%   end
-%   xlabel(' ')
-%   title(['Main effects all ',fsuffix],'interpreter','none')
-%   saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_ALL',fsuffix])
-%   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_ALL',fsuffix]);
-%   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_ALL',fsuffix]);
-% %   close(gcf),
-
-%   for j=1:size(SAall,1),
-%     SAallN(j,:)=SAall(j,:)./max(SAall(j,:));
-%   end
-%   SAmean=mean(SAallN);
-%   for j=1:size(SAmom,1),
-%     SAmomN(j,:)=SAmom(j,1:nshock)./max(SAmom(j,1:nshock));
-%   end
-%   SAmomN(find(isnan(SAmomN)))=0;
-%   SAmeanexo=mean(SAmomN(:,1:nshock));
-
-%   figure, bar(latent'*SAcc),
-  hh=dyn_figure(options_,'Name',['Identifiability indices in the ',fsuffix,' moments.']);
-  bar(sum(SAcc)),
-  set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
-  set(gca,'xlim',[0.5 npT+0.5])
-  ydum = get(gca,'ylim');
-  set(gca,'ylim',[0 ydum(2)])
-  set(gca,'position',[0.13 0.2 0.775 0.7])
-  for ip=1:npT,
-    text(ip,-0.02*(ydum(2)),bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    nrun=length(istable);
+    nest=min(250,nrun);
+    nfit=min(1000,nrun);
+
+    %   opt_gsa.load_ident_files=0;
+
+    %   if opt_gsa.load_ident_files==0,
+    %   try
+    %     EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAvdec','vdec','ir_vdec','ic_vdec');
+    %   catch
+    %     EET=[];
+    %   end
+    %   SAvdec=zeros(size(vdec,2),npT);
+    %
+    %   for j=1:size(vdec,2),
+    %     if itrans==0,
+    %       y0 = vdec(istable,j);
+    %     elseif itrans==1,
+    %       y0 = log_trans_(vdec(istable,j));
+    %     else
+    %       y0 = trank(vdec(istable,j));
+    %     end
+    %     if ~isempty(EET),
+    % %       imap=find(EET.SAvdec(j,:));
+    % %       [dum, isort]=sort(-EET.SAvdec(j,:));
+    %       imap=find(EET.SAvdec(j,:) >= (0.1.*max(EET.SAvdec(j,:))) );
+    %     end
+    %   gsa_(j) = gsa_sdp(y0(1:nest), x0(1:nest,imap), ...
+    %       2, [],[],[],0,[OutputDirectoryName,'/map_vdec',fsuffix,int2str(j)], pnames);
+    %   if nfit>nest,
+    %     gsa_(j) = gsa_sdp(y0(1:nfit), x0(1:nfit,imap), ...
+    %         -2, gsa_(j).nvr*nest^3/nfit^3,[],[],0,[OutputDirectoryName,'/map_vdec',fsuffix,int2str(j)], pnames);
+    %   end
+    %
+    %     SAvdec(j,imap)=gsa_(j).si;
+    %     imap_vdec{j}=imap;
+    %   end
+    %   save([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_vdec','SAvdec','vdec','ir_vdec','ic_vdec','-append')
+    %   else
+    %   load([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_vdec','SAvdec','vdec','ir_vdec','ic_vdec')
+    %   end
+    %   figure,
+    % %   boxplot(SAvdec,'whis',10,'symbol','r.')
+    %   myboxplot(SAvdec,[],'.',[],10)
+    %   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
+    %   set(gca,'xlim',[0.5 npT+0.5])
+    %   ydum = get(gca,'ylim');
+    %   set(gca,'ylim',[0 ydum(2)])
+    %   set(gca,'position',[0.13 0.2 0.775 0.7])
+    %   for ip=1:npT,
     %     text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
-  end
-  xlabel(' ')
-  title(['Identifiability indices in the ',fsuffix,' moments.'],'interpreter','none')
-  dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_ident_ALL',fsuffix],options_);
-  create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_ident_ALL',fsuffix],1,['Identifiability indices in the ',fsuffix,' moments.'],['ident_ALL',fsuffix]',1)
-
-%   figure, bar(SAmeanexo),
-%   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:nshock])
-%   set(gca,'xlim',[0.5 nshock+0.5])
-%   ydum = get(gca,'ylim');
-%   set(gca,'ylim',[0 ydum(2)])
-%   set(gca,'position',[0.13 0.2 0.775 0.7])
-%   for ip=1:nshock,
-%     %     text(ip,-0.02*(ydum(2)),deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%     text(ip,-0.02*(ydum(2)),bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
-%   end
-%   xlabel(' ')
-%   title(['Identifiability indices for shocks',fsuffix],'interpreter','none')
-%   saveas(gcf,[OutputDirectoryName,'/',fname_,'_ident_SHOCKS',fsuffix])
-%   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_ident_SHOCKS',fsuffix]);
-%   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_ident_SHOCKS',fsuffix]);
+    % %     text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %   end
+    %   xlabel(' ')
+    %   title(['Main effects variance decomposition ',fsuffix],'interpreter','none')
+    %   saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_vdec',fsuffix])
+    %   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix]);
+    %   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix]);
+    %   close(gcf),
+    %
+    %   ifig = 0;
+    %   for j=1:size(options_.varobs,1)
+    %     if mod(j,6)==1
+    %       figure('name',['Main effects observed variance decomposition ',fsuffix]);
+    %       ifig=ifig+1;
+    %       iplo=0;
+    %     end
+    %     iplo=iplo+1;
+    %     subplot(3,2,iplo)
+    %     iv = find(ir_vdec==j);
+    %     if ~isempty(iv)
+    %       if length(iv)>1
+    % %         boxplot(SAvdec(iv,:),'whis',10,'symbol','r.');
+    %         myboxplot(SAvdec(iv,:),[],'.',[],10)
+    %       else
+    %         plot(SAvdec(iv,:),'r.');
+    %       end
+    %       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
+    %       set(gca,'xlim',[0.5 npT+0.5])
+    %       ydum = get(gca,'ylim');
+    %       set(gca,'ylim',[0 ydum(2)])
+    %       for ip=1:npT,
+    %         text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    % %         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %       end
+    %       xlabel(' ')
+    %     end
+    %     title(options_.varobs(j,:),'interpreter','none')
+    %     if mod(j,6)==0 | j==size(options_.varobs,1)
+    %       saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_vdec',fsuffix,'_varobs_',int2str(ifig)])
+    %       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix,'_varobs_',int2str(ifig)]);
+    %       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix,'_varobs_',int2str(ifig)]);
+    %       close(gcf),
+    %     end
+    %   end
+    %
+    %   ifig = 0;
+    %   for j=1:M_.exo_nbr,
+    %     if mod(j,6)==1
+    %       figure('name',['Main effects shocks variance decomposition ',fsuffix]);
+    %       ifig=ifig+1;
+    %       iplo=0;
+    %     end
+    %     iplo=iplo+1;
+    %     subplot(3,2,iplo)
+    %     iv = find(ic_vdec==j);
+    %     if ~isempty(iv)
+    %       if length(iv)>1
+    % %         boxplot(SAvdec(iv,:),'whis',3,'symbol','r.');
+    %         myboxplot(SAvdec(iv,:),[],'.',[],10)
+    %       else
+    %         plot(SAvdec(iv,:),'r.');
+    %       end
+    %       set(gca,'xticklabel',' ','fontsize',3,'xtick',[1:np])
+    %       set(gca,'xlim',[0.5 npT+0.5])
+    %       ydum = get(gca,'ylim');
+    %       set(gca,'ylim',[0 ydum(2)])
+    %       for ip=1:npT,
+    %         text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    % %         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %       end
+    %       xlabel(' ')
+    %       set(gca,'fontsize',10)
+    %     end
+    %     title(M_.exo_names(j,:),'interpreter','none','fontsize',10)
+    %     if mod(j,6)==0 | j==M_.exo_nbr
+    %       saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_vdec',fsuffix,'_exo_',int2str(ifig)])
+    %       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix,'_exo_',int2str(ifig)]);
+    %       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_vdec',fsuffix,'_exo_',int2str(ifig)]);
+    %       close(gcf),
+    %     end
+    %   end
+
+    if opt_gsa.load_ident_files==0
+        try
+            EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAcc','ir_cc','ic_cc');
+        catch
+            EET=[];
+        end
+        ccac = stand_([mss cc ac]);
+        [pcc, dd] = eig(cov(ccac(istable,:)));
+        [latent, isort] = sort(-diag(dd));
+        latent = -latent;
+        figure, bar(latent)
+        title('Eigenvalues in PCA')
+        pcc=pcc(:,isort);
+        ccac = ccac*pcc;
+        %   npca = min(40, max(find(cumsum(latent)./length(latent)<0.99))+1);
+        npca = max(find(cumsum(latent)./length(latent)<0.99))+1;
+        siPCA = (EET.SAcc'*abs(pcc'))';
+        %   siPCA = siPCA./(max(siPCA')'*ones(1,npT)).*(latent*ones(1,npT));
+        siPCA = siPCA./(max(siPCA')'*ones(1,npT));
+        %   siPCA = sum(siPCA,1);
+        %   siPCA = siPCA./max(siPCA);
+        SAcc=zeros(size(ccac,2),npT);
+        for j=1:npca %size(ccac,2),
+            if itrans==0
+                y0 = ccac(istable,j);
+            elseif itrans==1
+                y0 = log_trans_(ccac(istable,j));
+            else
+                y0 = trank(ccac(istable,j));
+            end
+            if ~isempty(EET)
+                %       imap=find(EET.SAvdec(j,:));
+                %       [dum, isort]=sort(-EET.SAvdec(j,:));
+                imap=find(siPCA(j,:) >= (0.1.*max(siPCA(j,:))) );
+                %       imap=find(EET.SAcc(j,:) >= (0.1.*max(EET.SAcc(j,:))) );
+            end
+            gsa_(j) = gsa_sdp(y0(1:nest), x0(1:nest,imap), ...
+                              2, [],[],[],0,[OutputDirectoryName,'/map_cc',fsuffix,int2str(j)], pnames);
+            %   if nfit>nest,
+            %     gsa_(j) = gsa_sdp(y0(1:nfit), x0(1:nfit,imap), ...
+            %         -2, gsa_(j).nvr*nest^3/nfit^3,[],[],0,[OutputDirectoryName,'/map_cc',fsuffix,int2str(j)], pnames);
+            %   end
+            SAcc(j,imap)=gsa_(j).si;
+            imap_cc{j}=imap;
+
+        end
+        save([OutputDirectoryName,'/map_cc',fsuffix,'.mat'],'gsa_')
+        save([OutputDirectoryName,'/',fname_,'_main_eff.mat'],'imap_cc','SAcc','ccac','-append')
+    else
+        load([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_cc','SAcc','ccac')
+
+    end
+    %   figure,
+    % %   boxplot(SAcc,'whis',10,'symbol','r.')
+    %   myboxplot(SAcc,[],'.',[],10)
+    %   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
+    %   set(gca,'xlim',[0.5 npT+0.5])
+    %   ydum = get(gca,'ylim');
+    %   set(gca,'ylim',[0 ydum(2)])
+    %   set(gca,'position',[0.13 0.2 0.775 0.7])
+    %   for ip=1:npT,
+    %     text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    % %     text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %   end
+    %   xlabel(' ')
+    %   ylabel(' ')
+    %   title(['Main effects moments''s PCA ',fsuffix],'interpreter','none')
+    %   saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_cc',fsuffix])
+    %   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_moments',fsuffix]);
+    %   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_moments',fsuffix]);
+    %   close(gcf),
+
+    %   ifig = 0;
+    %   for j=1:size(options_.varobs,1)
+    %     if mod(j,6)==1
+    %       figure('name',['Main effects cross-covariances ',fsuffix]);
+    %       ifig=ifig+1;
+    %       iplo=0;
+    %     end
+    %     iplo=iplo+1;
+    %     subplot(3,2,iplo)
+    %     iv = find(ir_cc==j);
+    %     iv = [iv; find(ic_cc==j)];
+    %     if ~isempty(iv)
+    %       if length(iv)>1
+    % %         boxplot(SAcc(iv,:),'whis',10,'symbol','r.');
+    %         myboxplot(SAcc(iv,:),[],'.',[],10)
+    %       else
+    %         plot(SAcc(iv,:),'r.');
+    %       end
+    %       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
+    %       set(gca,'xlim',[0.5 npT+0.5])
+    %       ydum = get(gca,'ylim');
+    %       set(gca,'ylim',[0 ydum(2)])
+    %       for ip=1:npT,
+    %         text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    % %         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %       end
+    %       xlabel(' ')
+    %       set(gca,'fontsize',10)
+    %     end
+    %     title(options_.varobs(j,:),'interpreter','none','fontsize',10)
+    %     if mod(j,6)==0 | j==size(options_.varobs,1)
+    %       saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_cc',fsuffix,'_',int2str(ifig)])
+    %       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_cc',fsuffix,'_',int2str(ifig)]);
+    %       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_cc',fsuffix,'_',int2str(ifig)]);
+    %       close(gcf),
+    %     end
+    %   end
+    %
+    %   if opt_gsa.load_ident_files==0,
+    %   try
+    %     EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAac','ir_ac','ic_ac');
+    %   catch
+    %     EET=[];
+    %   end
+    %   SAac=zeros(size(ac,2),npT);
+    %   for j=1:size(ac,2),
+    %     if itrans==0,
+    %       y0 = ac(istable,j);
+    %     elseif itrans==1,
+    %       y0 = log_trans_(ac(istable,j));
+    %     else
+    %       y0 = trank(ac(istable,j));
+    %     end
+    %     if ~isempty(EET),
+    %       imap=find(EET.SAac(j,:) >= (0.1.*max(EET.SAac(j,:))) );
+    %     end
+    % %     gsa_(j) = gsa_sdp_dyn( y0, lpmat(istable,:), ...
+    % %       gsa_flag, [],[],[],0,[OutputDirectoryName,'/map_ac',fsuffix,int2str(j)], pnames);
+    %   gsa_(j) = gsa_sdp(y0(1:nest), x0(1:nest,imap), ...
+    %       2, [],[],[],0,[OutputDirectoryName,'/map_ac',fsuffix,int2str(j)], pnames);
+    %   if nfit>nest,
+    %     gsa_(j) = gsa_sdp(y0(1:nfit), x0(1:nfit,imap), ...
+    %         -2, gsa_(j).nvr*nest^3/nfit^3,[],[],0,[OutputDirectoryName,'/map_ac',fsuffix,int2str(j)], pnames);
+    %   end
+    %     SAac(j,imap)=gsa_(j).si;
+    %     imap_ac{j}=imap;
+    %
+    %   end
+    %   save([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_ac','SAac','ac','ir_ac','ic_ac','-append')
+    %   else
+    %   load([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_ac','SAac','ac','ir_ac','ic_ac')
+    %   end
+    %
+    %   figure,
+    % %   boxplot(SAac,'whis',10,'symbol','r.')
+    %   myboxplot(SAac,[],'.',[],10)
+    %   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
+    %   set(gca,'xlim',[0.5 npT+0.5])
+    %   ydum = get(gca,'ylim');
+    %   set(gca,'ylim',[0 ydum(2)])
+    %   set(gca,'position',[0.13 0.2 0.775 0.7])
+    %   for ip=1:np,
+    %     text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %   end
+    %   xlabel(' ')
+    %   title(['Main effects 1 lag auto-covariances ',fsuffix],'interpreter','none')
+    %   saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_ac',fsuffix])
+    %   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_ac',fsuffix]);
+    %   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_ac',fsuffix]);
+    %   close(gcf),
+    %
+    %   ifig = 0;
+    %   for j=1:size(options_.varobs,1)
+    %     if mod(j,6)==1
+    %       figure('name',['Main effects auto-covariances ',fsuffix]);
+    %       ifig=ifig+1;
+    %       iplo = 0;
+    %     end
+    %     iplo=iplo+1;
+    %     subplot(3,2,iplo)
+    %     iv = find(ir_ac==j);
+    %     %iv = [iv; find(ic_ac==j)];
+    %     if ~isempty(iv)
+    %       if length(iv)>1
+    % %         boxplot(SAac(iv,:),'whis',10,'symbol','r.');
+    %         myboxplot(SAac(iv,:),[],'.',[],10)
+    %       else
+    %         plot(SAac(iv,:),'r.');
+    %       end
+    %       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
+    %       set(gca,'xlim',[0.5 npT+0.5])
+    %       ydum = get(gca,'ylim');
+    %       set(gca,'ylim',[0 ydum(2)])
+    %       for ip=1:npT,
+    %         text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    % %         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %       end
+    %       xlabel(' ')
+    %       set(gca,'fontsize',10)
+    %     end
+    %     title(options_.varobs(j,:),'interpreter','none','fontsize',10)
+    %     if mod(j,6)==0 | j==size(options_.varobs,1)
+    %       saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_ac',fsuffix,'_',int2str(ifig)])
+    %       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_ac',fsuffix,'_',int2str(ifig)]);
+    %       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_ac',fsuffix,'_',int2str(ifig)]);
+    %       close(gcf),
+    %     end
+    %   end
+
+    %   x0=x0(:,nshock+1:end);
+    imap=[1:npT];
+
+    %   if opt_gsa.load_ident_files==0,
+    %   try
+    %     EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAtadj','ir_tadj','ic_tadj');
+    %     ny=size(EET.SAtadj,1);
+    %   catch
+    %     EET=[];
+    %   end
+    %   SAtadj=zeros(size(tadj,2),np);
+    %   for j=1:size(tadj,2),
+    %     if itrans==0,
+    %       y0 = tadj(istable,j);
+    %     elseif itrans==1,
+    %       y0 = log_trans_(tadj(istable,j));
+    %     else
+    %       y0 = trank(tadj(istable,j));
+    %     end
+    %     if ~isempty(EET),
+    %       if size(tadj,2)~=ny,
+    %         jj=find(EET.ir_tadj==ir_tadj(j));
+    %         jj=jj(find(EET.ic_tadj(jj)==ic_tadj(j)));
+    %         if ~isempty(jj),
+    %           imap=find(EET.SAtadj(jj,:) >= (0.1.*max(EET.SAtadj(jj,:))) );
+    %         else
+    %           imap=[1:np];
+    %         end
+    %       else
+    %         imap=find(EET.SAtadj(j,:) >= (0.1.*max(EET.SAtadj(j,:))) );
+    %       end
+    %     end
+    % %     gsa_(j) = gsa_sdp_dyn( y0, lpmat(istable,:), ...
+    % %       gsa_flag, [],[],[],0,[OutputDirectoryName,'/map_tadj',fsuffix,int2str(j)], pnames);
+    %   gsa_(j) = gsa_sdp(y0(1:nest), x0(1:nest,imap), ...
+    %       2, [],[],[],0,[OutputDirectoryName,'/map_tadj',fsuffix,int2str(j)], pnames);
+    %   if nfit>nest,
+    %     gsa_(j) = gsa_sdp(y0(1:nfit), x0(1:nfit,imap), ...
+    %         -2, gsa_(j).nvr*nest^3/nfit^3,[],[],0,[OutputDirectoryName,'/map_tadj',fsuffix,int2str(j)], pnames);
+    %   end
+    %     SAtadj(j,imap)=gsa_(j).si;
+    %     imap_tadj{j}=imap;
+    %
+    %   end
+    %   save([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_tadj','SAtadj','tadj','ir_tadj','ic_tadj','-append')
+    %   else
+    %   load([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_tadj','SAtadj','tadj','ir_tadj','ic_tadj')
+    %   end
+    %
+    %   figure,
+    % %   boxplot(SAtadj,'whis',10,'symbol','r.')
+    %   myboxplot(SAtadj,[],'.',[],10)
+    %   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
+    %   set(gca,'xlim',[0.5 np+0.5])
+    %   ydum = get(gca,'ylim');
+    %   set(gca,'ylim',[0 ydum(2)])
+    %   set(gca,'position',[0.13 0.2 0.775 0.7])
+    %   for ip=1:np,
+    %     text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %   end
+    %   xlabel(' ')
+    %   title(['Main effects speed of adjustment ',fsuffix],'interpreter','none')
+    %   saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_tadj',fsuffix])
+    %   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix]);
+    %   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix]);
+    %   close(gcf),
+    %
+    %   ifig = 0;
+    %   for j=1:size(options_.varobs,1)
+    %     if mod(j,6)==1
+    %       figure('name',['Main effects observed speed adjustment ',fsuffix]);
+    %       ifig=ifig+1;
+    %       iplo = 0;
+    %     end
+    %     iplo=iplo+1;
+    %     subplot(3,2,iplo)
+    %     iv = find(ir_tadj==j);
+    %     if ~isempty(iv)
+    %       if length(iv)>1
+    % %         boxplot(SAtadj(iv,:),'whis',3,'symbol','r.');
+    %         myboxplot(SAtadj(iv,:),[],'.',[],10)
+    %       else
+    %         plot(SAtadj(iv,:),'r.');
+    %       end
+    %       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
+    %       set(gca,'xlim',[0.5 np+0.5])
+    %       ydum = get(gca,'ylim');
+    %       set(gca,'ylim',[0 ydum(2)])
+    %       for ip=1:np,
+    %         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %       end
+    %       xlabel(' ')
+    %     end
+    %     title(options_.varobs(j,:),'interpreter','none')
+    %     if mod(j,6)==0 | j==size(options_.varobs,1)
+    %       saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_tadj',fsuffix,'_varobs_',int2str(ifig)])
+    %       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix,'_varobs_',int2str(ifig)]);
+    %       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix,'_varobs_',int2str(ifig)]);
+    %       close(gcf),
+    %     end
+    %   end
+    %
+    %   ifig = 0;
+    %   for j=1:M_.exo_nbr,
+    %     if mod(j,6)==1
+    %       figure('name',['Main effects shocks speed of adjustment ',fsuffix]);
+    %       ifig=ifig+1;
+    %       iplo=0;
+    %     end
+    %     iplo=iplo+1;
+    %     subplot(3,2,iplo)
+    %     iv = find(ic_tadj==j);
+    %     if ~isempty(iv)
+    %       if length(iv)>1
+    % %         boxplot(SAtadj(iv,:),'whis',3,'symbol','r.');
+    %         myboxplot(SAtadj(iv,:),[],'.',[],10)
+    %       else
+    %         plot(SAtadj(iv,:),'r.');
+    %       end
+    %       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
+    %       set(gca,'xlim',[0.5 np+0.5])
+    %       ydum = get(gca,'ylim');
+    %       set(gca,'ylim',[0 ydum(2)])
+    %       for ip=1:np,
+    %         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %       end
+    %       xlabel(' ')
+    %     end
+    %     title(M_.exo_names(j,:),'interpreter','none')
+    %     if mod(j,6)==0 | j==M_.exo_nbr,
+    %       saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_tadj',fsuffix,'_exo_',int2str(ifig)])
+    %       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix,'_exo_',int2str(ifig)]);
+    %       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_tadj',fsuffix,'_exo_',int2str(ifig)]);
+    %       close(gcf),
+    %     end
+    %   end
+    %
+    %
+    %   if opt_gsa.load_ident_files==0,
+    %   try
+    %     EET=load([OutputDirectoryName,'/SCREEN/',fname_,'_morris_IDE'],'SAIF','ir_if','ic_if');
+    %   catch
+    %     EET=[];
+    %   end
+    %   SAif=zeros(size(iff,2),np);
+    %   for j=1:size(iff,2),
+    %     if itrans==0,
+    %       y0 = iff(istable,j);
+    %     elseif itrans==1,
+    %       y0 = log_trans_(iff(istable,j));
+    %     else
+    %       y0 = trank(iff(istable,j));
+    %     end
+    %     if ~isempty(EET),
+    %       imap=find(EET.SAIF(j,:) >= (0.1.*max(EET.SAIF(j,:))) );
+    %     end
+    % %     gsa_(j) = gsa_sdp_dyn( y0, lpmat(istable,:), ...
+    % %       gsa_flag, [],[],[],0,[OutputDirectoryName,'/map_if',fsuffix,int2str(j)], pnames);
+    %   gsa_(j) = gsa_sdp(y0(1:nest), x0(1:nest,imap), ...
+    %       2, [],[],[],0,[OutputDirectoryName,'/map_if',fsuffix,int2str(j)], pnames);
+    %   if nfit>nest,
+    %     gsa_(j) = gsa_sdp(y0(1:nfit), x0(1:nfit,imap), ...
+    %         -2, gsa_(j).nvr*nest^3/nfit^3,[],[],0,[OutputDirectoryName,'/map_if',fsuffix,int2str(j)], pnames);
+    %   end
+    %     SAif(j,imap)=gsa_(j).si;
+    %     imap_if{j}=imap;
+    %
+    %   end
+    %   save([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_if','SAif','iff','ir_if','ic_if','-append')
+    %   else
+    %   load([OutputDirectoryName,'/',fname_,'_main_eff'],'imap_if','SAif','iff','ir_if','ic_if')
+    %   end
+    %
+    %   figure,
+    % %   boxplot(SAif,'whis',10,'symbol','r.')
+    %   myboxplot(SAif,[],'.',[],10)
+    %   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
+    %   set(gca,'xlim',[0.5 np+0.5])
+    %   ydum = get(gca,'ylim');
+    %   set(gca,'ylim',[0 ydum(2)])
+    %   set(gca,'position',[0.13 0.2 0.775 0.7])
+    %   for ip=1:np,
+    %     text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %   end
+    %   xlabel(' ')
+    %   title(['Main effects impact factors ',fsuffix],'interpreter','none')
+    %   saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_if',fsuffix])
+    %   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_if',fsuffix]);
+    %   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_if',fsuffix]);
+    %   close(gcf),
+    %
+    %   ifig = 0;
+    %   for j=1:size(options_.varobs,1)
+    %     if mod(j,6)==1
+    %       figure('name',['Main effects observed impact factors ',fsuffix]);
+    %       ifig=ifig+1;
+    %       iplo = 0;
+    %     end
+    %     iplo=iplo+1;
+    %     subplot(3,2,iplo)
+    %     iv = find(ir_if==j);
+    %     if ~isempty(iv)
+    %       if length(iv)>1
+    % %         boxplot(SAif(iv,:),'whis',3,'symbol','r.');
+    %         myboxplot(SAif(iv,:),[],'.',[],10)
+    %       else
+    %         plot(SAif(iv,:),'r.');
+    %       end
+    %       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
+    %       set(gca,'xlim',[0.5 np+0.5])
+    %       ydum = get(gca,'ylim');
+    %       set(gca,'ylim',[0 ydum(2)])
+    %       for ip=1:np,
+    %         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %       end
+    %       xlabel(' ')
+    %     end
+    %     title(options_.varobs(j,:),'interpreter','none')
+    %     if mod(j,6)==0 | j==size(options_.varobs,1)
+    %       saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_if',fsuffix,'_varobs_',int2str(ifig)])
+    %       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_if',fsuffix,'_varobs_',int2str(ifig)]);
+    %       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_if',fsuffix,'_varobs_',int2str(ifig)]);
+    %       close(gcf),
+    %     end
+    %   end
+    %
+    %   ifig = 0;
+    %   for j=1:M_.exo_nbr,
+    %     if mod(j,6)==1
+    %       figure('name',['Main effects shocks impact factors ',fsuffix]);
+    %       ifig=ifig+1;
+    %       iplo=0;
+    %     end
+    %     iplo=iplo+1;
+    %     subplot(3,2,iplo)
+    %     iv = find(ic_if==j);
+    %     if ~isempty(iv)
+    %       if length(iv)>1
+    % %         boxplot(SAif(iv,:),'whis',3,'symbol','r.');
+    %         myboxplot(SAif(iv,:),[],'.',[],10)
+    %       else
+    %         plot(SAif(iv,:),'r.');
+    %       end
+    %       set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
+    %       set(gca,'xlim',[0.5 np+0.5])
+    %       ydum = get(gca,'ylim');
+    %       set(gca,'ylim',[0 ydum(2)])
+    %       for ip=1:np,
+    %         text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %       end
+    %       xlabel(' ')
+    %     end
+    %     title(M_.exo_names(j,:),'interpreter','none')
+    %     if mod(j,6)==0 | j==M_.exo_nbr
+    %       saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_if',fsuffix,'_exo_',int2str(ifig)])
+    %       eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_if',fsuffix,'_exo_',int2str(ifig)]);
+    %       eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_if',fsuffix,'_exo_',int2str(ifig)]);
+    %       close(gcf),
+    %     end
+    %   end
+    %   SAmom = [SAvdec' SAcc' SAac']';
+    %   SAdyn = [SAtadj' SAif']';
+    %   SAall = [SAmom(:,nshock+1:end)' SAdyn']';
+    %
+    %   figure,
+    %   %   boxplot(SAtadj,'whis',10,'symbol','r.')
+    %   myboxplot(SAmom,[],'.',[],10)
+    %   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
+    %   set(gca,'xlim',[0.5 npT+0.5])
+    %   ydum = get(gca,'ylim');
+    %   set(gca,'ylim',[0 ydum(2)])
+    %   set(gca,'position',[0.13 0.2 0.775 0.7])
+    %   for ip=1:npT,
+    %     %     text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %     text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %   end
+    %   xlabel(' ')
+    %   title(['Main effects theoretical moments ',fsuffix],'interpreter','none')
+    %   saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_moments',fsuffix])
+    %   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_moments',fsuffix]);
+    %   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_moments',fsuffix]);
+    % %   close(gcf),
+    %
+    %   figure,
+    %   %   boxplot(SAtadj,'whis',10,'symbol','r.')
+    %   myboxplot(SAdyn,[],'.',[],10)
+    %   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
+    %   set(gca,'xlim',[0.5 np+0.5])
+    %   ydum = get(gca,'ylim');
+    %   set(gca,'ylim',[0 ydum(2)])
+    %   set(gca,'position',[0.13 0.2 0.775 0.7])
+    %   for ip=1:np,
+    %     text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    % %     text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %   end
+    %   xlabel(' ')
+    %   title(['Main effects short-long term dynamics ',fsuffix],'interpreter','none')
+    %   saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_dynamics',fsuffix])
+    %   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_dynamics',fsuffix]);
+    %   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_dynamics',fsuffix]);
+    % %   close(gcf),
+    %
+    %   figure,
+    %   %   boxplot(SAtadj,'whis',10,'symbol','r.')
+    %   myboxplot(SAall,[],'.',[],10)
+    %   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
+    %   set(gca,'xlim',[0.5 np+0.5])
+    %   ydum = get(gca,'ylim');
+    %   set(gca,'ylim',[0 ydum(2)])
+    %   set(gca,'position',[0.13 0.2 0.775 0.7])
+    %   for ip=1:np,
+    %     text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    % %     text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %   end
+    %   xlabel(' ')
+    %   title(['Main effects all ',fsuffix],'interpreter','none')
+    %   saveas(gcf,[OutputDirectoryName,'/',fname_,'_map_ALL',fsuffix])
+    %   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_map_ALL',fsuffix]);
+    %   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_map_ALL',fsuffix]);
+    % %   close(gcf),
+
+    %   for j=1:size(SAall,1),
+    %     SAallN(j,:)=SAall(j,:)./max(SAall(j,:));
+    %   end
+    %   SAmean=mean(SAallN);
+    %   for j=1:size(SAmom,1),
+    %     SAmomN(j,:)=SAmom(j,1:nshock)./max(SAmom(j,1:nshock));
+    %   end
+    %   SAmomN(find(isnan(SAmomN)))=0;
+    %   SAmeanexo=mean(SAmomN(:,1:nshock));
+
+    %   figure, bar(latent'*SAcc),
+    hh=dyn_figure(options_.nodisplay,'Name',['Identifiability indices in the ',fsuffix,' moments.']);
+    bar(sum(SAcc))
+    set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
+    set(gca,'xlim',[0.5 npT+0.5])
+    ydum = get(gca,'ylim');
+    set(gca,'ylim',[0 ydum(2)])
+    set(gca,'position',[0.13 0.2 0.775 0.7])
+    for ip=1:npT
+        text(ip,-0.02*(ydum(2)),bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
+        %     text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    end
+    xlabel(' ')
+    title(['Identifiability indices in the ',fsuffix,' moments.'],'interpreter','none')
+    dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_ident_ALL',fsuffix],options_.nodisplay,options_.graph_format);
+    create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_ident_ALL',fsuffix],1,['Identifiability indices in the ',fsuffix,' moments.'],['ident_ALL',fsuffix]',1)
+
+    %   figure, bar(SAmeanexo),
+    %   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:nshock])
+    %   set(gca,'xlim',[0.5 nshock+0.5])
+    %   ydum = get(gca,'ylim');
+    %   set(gca,'ylim',[0 ydum(2)])
+    %   set(gca,'position',[0.13 0.2 0.775 0.7])
+    %   for ip=1:nshock,
+    %     %     text(ip,-0.02*(ydum(2)),deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %     text(ip,-0.02*(ydum(2)),bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
+    %   end
+    %   xlabel(' ')
+    %   title(['Identifiability indices for shocks',fsuffix],'interpreter','none')
+    %   saveas(gcf,[OutputDirectoryName,'/',fname_,'_ident_SHOCKS',fsuffix])
+    %   eval(['print -depsc2 ' OutputDirectoryName '/' fname_ '_ident_SHOCKS',fsuffix]);
+    %   eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_ident_SHOCKS',fsuffix]);
 end
 
 return
diff --git a/matlab/gsa/mc_moments.m b/matlab/gsa/mc_moments.m
index b2ea935385a7fd79363496d8b5f6f6b9c7a15f56..b7464a7e0d4a85404041278bbaede3090670018e 100644
--- a/matlab/gsa/mc_moments.m
+++ b/matlab/gsa/mc_moments.m
@@ -1,6 +1,6 @@
 function [vdec, cc, ac] = mc_moments(mm, ss, dr)
 
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -19,19 +19,19 @@ function [vdec, cc, ac] = mc_moments(mm, ss, dr)
 
 global options_ M_ estim_params_ oo_
 
-  [nr1, nc1, nsam] = size(mm);
-  nobs=size(options_.varobs,2);
-  disp('Computing theoretical moments ...')
-  h = dyn_waitbar(0,'Theoretical moments ...');
-  vdec = zeros(nobs,M_.exo_nbr,nsam);
-  cc = zeros(nobs,nobs,nsam);
-  ac = zeros(nobs,nobs*options_.ar,nsam);
-  
-  for j=1:nsam,
+[nr1, nc1, nsam] = size(mm);
+nobs=size(options_.varobs,2);
+disp('Computing theoretical moments ...')
+h = dyn_waitbar(0,'Theoretical moments ...');
+vdec = zeros(nobs,M_.exo_nbr,nsam);
+cc = zeros(nobs,nobs,nsam);
+ac = zeros(nobs,nobs*options_.ar,nsam);
+
+for j=1:nsam
     oo_.dr.ghx = mm(:, [1:(nc1-M_.exo_nbr)],j);
     oo_.dr.ghu = mm(:, [(nc1-M_.exo_nbr+1):end], j);
-    if ~isempty(ss),
-      set_shocks_param(ss(j,:));
+    if ~isempty(ss)
+        set_shocks_param(ss(j,:));
     end
     [vdec(:,:,j), corr, autocorr, z, zz] = th_moments(oo_.dr,options_.varobs);
     cc(:,:,j)=triu(corr);
@@ -41,7 +41,7 @@ global options_ M_ estim_params_ oo_
     end
     ac(:,:,j)=dum;
     dyn_waitbar(j/nsam,h)
-  end
-  dyn_waitbar_close(h)
-  skipline()
-  disp('... done !')
+end
+dyn_waitbar_close(h)
+skipline()
+disp('... done !')
diff --git a/matlab/gsa/mcf_analysis.m b/matlab/gsa/mcf_analysis.m
index b01ba58e0ec186808b3d7cbd19082f66334ba05f..c4de17b8feffdeeeed607d7caf92f75c8ce4c06f 100644
--- a/matlab/gsa/mcf_analysis.m
+++ b/matlab/gsa/mcf_analysis.m
@@ -1,85 +1,84 @@
-function indmcf = mcf_analysis(lpmat, ibeha, inobeha, options_mcf, DynareOptions)
-%
-% Written by Marco Ratto
-% Joint Research Centre, The European Commission,
-% marco.ratto@jrc.ec.europa.eu
-%
-
-% Copyright (C) 2014 European Commission
-% Copyright (C) 2016 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/>.
-
-pvalue_ks = options_mcf.pvalue_ks;
-pvalue_corr = options_mcf.pvalue_corr;
-alpha2 = options_mcf.alpha2;
-param_names = options_mcf.param_names;
-
-if DynareOptions.TeX
-    if ~isfield(options_mcf,'param_names_tex')
-        param_names_tex = options_mcf.param_names;
-    else
-        param_names_tex = options_mcf.param_names_tex;
-    end
-end
-amcf_name = options_mcf.amcf_name;
-amcf_title = options_mcf.amcf_title;
-beha_title = options_mcf.beha_title;
-nobeha_title = options_mcf.nobeha_title;
-title = options_mcf.title;
-fname_ = options_mcf.fname_;
-xparam1=[];
-if isfield(options_mcf,'xparam1'),
-    xparam1=options_mcf.xparam1;
-end    
-OutputDirectoryName = options_mcf.OutputDirectoryName;
-
-[proba, dproba] = stab_map_1(lpmat, ibeha, inobeha, [],0);
-%         indindet=find(dproba>ksstat);
-indmcf=find(proba<pvalue_ks);
-[tmp,jtmp] = sort(proba(indmcf),2,'ascend');
-indmcf = indmcf(jtmp);
-if ~isempty(indmcf)
-    skipline()
-    headers=char('Parameter','d-stat','p-value');
-    labels=char(param_names(indmcf,:));
-    data_mat=[dproba(indmcf)' proba(indmcf)'];
-    options_temp.noprint=0;
-    dyntable(options_temp,['Smirnov statistics in driving ', title],headers,labels,data_mat,size(labels,2)+2,16,3);
-    if DynareOptions.TeX
-        labels_TeX=param_names_tex(indmcf,:);
-        M_temp.dname=OutputDirectoryName ;
-        M_temp.fname=fname_;
-        dyn_latex_table(M_temp,options_temp,['Smirnov statistics in driving ', strrep(title,'_','\\_')],amcf_name,headers,labels_TeX,data_mat,size(labels,2)+2,16,6);
-    end
-end
-    
-
-if length(ibeha)>10 && length(inobeha)>10,
-    indcorr1 = stab_map_2(lpmat(ibeha,:),alpha2, pvalue_corr, beha_title);
-    indcorr2 = stab_map_2(lpmat(inobeha,:),alpha2, pvalue_corr, nobeha_title);
-    indcorr = union(indcorr1(:), indcorr2(:));
-    indcorr = indcorr(~ismember(indcorr(:),indmcf));
-    indmcf = [indmcf(:); indcorr(:)];
-end
-if ~isempty(indmcf) && ~DynareOptions.nograph,
-    skipline()
-    xx=[];
-    if ~ isempty(xparam1), xx=xparam1(indmcf); end
-    scatter_mcf(lpmat(ibeha,indmcf),lpmat(inobeha,indmcf), param_names(indmcf,:), ...
-        '.', [fname_,'_',amcf_name], OutputDirectoryName, amcf_title,xx, DynareOptions, ...
-        beha_title, nobeha_title)
-end
+function indmcf = mcf_analysis(lpmat, ibeha, inobeha, options_mcf, DynareOptions)
+%
+% Written by Marco Ratto
+% Joint Research Centre, The European Commission,
+% marco.ratto@ec.europa.eu
+%
+
+% Copyright (C) 2014 European Commission
+% Copyright (C) 2016-2017 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/>.
+
+pvalue_ks = options_mcf.pvalue_ks;
+pvalue_corr = options_mcf.pvalue_corr;
+alpha2 = options_mcf.alpha2;
+param_names = options_mcf.param_names;
+
+if DynareOptions.TeX
+    if ~isfield(options_mcf,'param_names_tex')
+        param_names_tex = options_mcf.param_names;
+    else
+        param_names_tex = options_mcf.param_names_tex;
+    end
+end
+amcf_name = options_mcf.amcf_name;
+amcf_title = options_mcf.amcf_title;
+beha_title = options_mcf.beha_title;
+nobeha_title = options_mcf.nobeha_title;
+title = options_mcf.title;
+fname_ = options_mcf.fname_;
+xparam1=[];
+if isfield(options_mcf,'xparam1')
+    xparam1=options_mcf.xparam1;
+end
+OutputDirectoryName = options_mcf.OutputDirectoryName;
+
+[proba, dproba] = stab_map_1(lpmat, ibeha, inobeha, [],0);
+indmcf=find(proba<pvalue_ks);
+[tmp,jtmp] = sort(proba(indmcf),2,'ascend');
+indmcf = indmcf(jtmp);
+if ~isempty(indmcf)
+    skipline()
+    headers=char('Parameter','d-stat','p-value');
+    labels=char(param_names(indmcf,:));
+    data_mat=[dproba(indmcf)' proba(indmcf)'];
+    options_temp.noprint=0;
+    dyntable(options_temp,['Smirnov statistics in driving ', title],headers,labels,data_mat,size(labels,2)+2,16,3);
+    if DynareOptions.TeX
+        labels_TeX=param_names_tex(indmcf,:);
+        M_temp.dname=OutputDirectoryName ;
+        M_temp.fname=fname_;
+        dyn_latex_table(M_temp,options_temp,['Smirnov statistics in driving ', strrep(title,'_','\\_')],amcf_name,headers,labels_TeX,data_mat,size(labels,2)+2,16,6);
+    end
+end
+
+
+if length(ibeha)>10 && length(inobeha)>10
+    indcorr1 = stab_map_2(lpmat(ibeha,:),alpha2, pvalue_corr, beha_title);
+    indcorr2 = stab_map_2(lpmat(inobeha,:),alpha2, pvalue_corr, nobeha_title);
+    indcorr = union(indcorr1(:), indcorr2(:));
+    indcorr = indcorr(~ismember(indcorr(:),indmcf));
+    indmcf = [indmcf(:); indcorr(:)];
+end
+if ~isempty(indmcf) && ~DynareOptions.nograph
+    skipline()
+    xx=[];
+    if ~ isempty(xparam1), xx=xparam1(indmcf); end
+    scatter_mcf(lpmat(ibeha,indmcf),lpmat(inobeha,indmcf), param_names(indmcf,:), ...
+                '.', [fname_,'_',amcf_name], OutputDirectoryName, amcf_title,xx, DynareOptions, ...
+                beha_title, nobeha_title)
+end
diff --git a/matlab/gsa/myboxplot.m b/matlab/gsa/myboxplot.m
index b83e5af1321e04695af9ec92a81aa3df114617f1..a83ca922c7970cd91d9414085823574cb11555f7 100644
--- a/matlab/gsa/myboxplot.m
+++ b/matlab/gsa/myboxplot.m
@@ -1,7 +1,12 @@
 function sout = myboxplot (data,notched,symbol,vertical,maxwhisker)
 %  sout = myboxplot (data,notched,symbol,vertical,maxwhisker)
 
-% Copyright (C) 2012 Dynare Team
+% Written by Marco Ratto
+% Joint Research Centre, The European Commission,
+% marco.ratto@ec.europa.eu
+
+% Copyright (C) 2012 European Commission
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -30,11 +35,11 @@ if notched==1, notched=0.25; end
 a=1-notched;
 
 % ## figure out how many data sets we have
-if iscell(data), 
-  nc = length(data);
+if iscell(data)
+    nc = length(data);
 else
-%   if isvector(data), data = data(:); end
-  nc = size(data,2);
+    %   if isvector(data), data = data(:); end
+    nc = size(data,2);
 end
 
 % ## compute statistics
@@ -58,60 +63,60 @@ for i=1:nc
     else
         col = data(:,i);
     end
-%   ## Skip missing data
-% % % % % % %   col(isnan(col) | isna (col)) = [];
-  col(isnan(col)) = [];
-
-  %   ## Remember the data length
-  nd = length(col);
-  box(i) = nd;
-  if (nd > 1)
-%     ## min,max and quartiles
-%     s(1:5,i) = statistics(col)(1:5);
-s(1,i)=min(col);
-s(5,i)=max(col);
-s(2,i)=myprctilecol(col,25);
-s(3,i)=myprctilecol(col,50);
-s(4,i)=myprctilecol(col,75);
-
-
-
-
-
-
-
-
-%     ## confidence interval for the median
-    est = 1.57*(s(4,i)-s(2,i))/sqrt(nd);
-    s(6,i) = max([s(3,i)-est, s(2,i)]);
-    s(7,i) = min([s(3,i)+est, s(4,i)]);
-%     ## whiskers out to the last point within the desired inter-quartile range
-    IQR = maxwhisker*(s(4,i)-s(2,i));
-    whisker_y(:,i) = [min(col(col >= s(2,i)-IQR)); s(2,i)];
-    whisker_y(:,nc+i) = [max(col(col <= s(4,i)+IQR)); s(4,i)];
-%     ## outliers beyond 1 and 2 inter-quartile ranges
-    outliers = col((col < s(2,i)-IQR & col >= s(2,i)-2*IQR) | (col > s(4,i)+IQR & col <= s(4,i)+2*IQR));
-    outliers2 = col(col < s(2,i)-2*IQR | col > s(4,i)+2*IQR);
-    outliers_x = [outliers_x; i*ones(size(outliers))];
-    outliers_y = [outliers_y; outliers];
-    outliers2_x = [outliers2_x; i*ones(size(outliers2))];
-    outliers2_y = [outliers2_y; outliers2];
-  elseif (nd == 1)
-%     ## all statistics collapse to the value of the point
-    s(:,i) = col;
-%     ## single point data sets are plotted as outliers.
-    outliers_x = [outliers_x; i];
-    outliers_y = [outliers_y; col];
-  else
-%     ## no statistics if no points
-    s(:,i) = NaN;
-  end
+    %   ## Skip missing data
+    % % % % % % %   col(isnan(col) | isna (col)) = [];
+    col(isnan(col)) = [];
+
+    %   ## Remember the data length
+    nd = length(col);
+    box(i) = nd;
+    if (nd > 1)
+        %     ## min,max and quartiles
+        %     s(1:5,i) = statistics(col)(1:5);
+        s(1,i)=min(col);
+        s(5,i)=max(col);
+        s(2,i)=myprctilecol(col,25);
+        s(3,i)=myprctilecol(col,50);
+        s(4,i)=myprctilecol(col,75);
+
+
+
+
+
+
+
+
+        %     ## confidence interval for the median
+        est = 1.57*(s(4,i)-s(2,i))/sqrt(nd);
+        s(6,i) = max([s(3,i)-est, s(2,i)]);
+        s(7,i) = min([s(3,i)+est, s(4,i)]);
+        %     ## whiskers out to the last point within the desired inter-quartile range
+        IQR = maxwhisker*(s(4,i)-s(2,i));
+        whisker_y(:,i) = [min(col(col >= s(2,i)-IQR)); s(2,i)];
+        whisker_y(:,nc+i) = [max(col(col <= s(4,i)+IQR)); s(4,i)];
+        %     ## outliers beyond 1 and 2 inter-quartile ranges
+        outliers = col((col < s(2,i)-IQR & col >= s(2,i)-2*IQR) | (col > s(4,i)+IQR & col <= s(4,i)+2*IQR));
+        outliers2 = col(col < s(2,i)-2*IQR | col > s(4,i)+2*IQR);
+        outliers_x = [outliers_x; i*ones(size(outliers))];
+        outliers_y = [outliers_y; outliers];
+        outliers2_x = [outliers2_x; i*ones(size(outliers2))];
+        outliers2_y = [outliers2_y; outliers2];
+    elseif (nd == 1)
+        %     ## all statistics collapse to the value of the point
+        s(:,i) = col;
+        %     ## single point data sets are plotted as outliers.
+        outliers_x = [outliers_x; i];
+        outliers_y = [outliers_y; col];
+    else
+        %     ## no statistics if no points
+        s(:,i) = NaN;
+    end
 end
 % % % % if isempty(outliers2_y)
 % % % %     outliers2_y=
 % ## Note which boxes don't have enough stats
 chop = find(box <= 1);
-    
+
 % ## Draw a box around the quartiles, with width proportional to the number of
 % ## items in the box. Draw notches if desired.
 box = box*0.23/max(box);
@@ -130,7 +135,7 @@ whisker_x(:,[chop,chop+nc]) = [];
 whisker_y(:,[chop,chop+nc]) = [];
 median_x(:,chop) = [];
 median_y(:,chop) = [];
-% % % % 
+% % % %
 % ## Add caps to the remaining whiskers
 cap_x = whisker_x;
 cap_x(1,:) =cap_x(1,:)- 0.05;
@@ -141,7 +146,7 @@ cap_y = whisker_y([1,1],:);
 % #whisker_x,whisker_y
 % #median_x,median_y
 % #cap_x,cap_y
-% 
+%
 % ## Do the plot
 
 mm=min(min(data));
@@ -149,25 +154,25 @@ MM=max(max(data));
 
 if vertical
     plot (quartile_x, quartile_y, 'b',  ...
-        whisker_x, whisker_y, 'b--',   ...
-        cap_x, cap_y, 'k',   ...
-        median_x, median_y, 'r',  ...
-        outliers_x, outliers_y, [symbol(1),'r'],   ...
-        outliers2_x, outliers2_y, [symbol(2),'r']);
-        set(gca,'XTick',1:nc);
-        set(gca, 'XLim', [0.5, nc+0.5]);
-        set(gca, 'YLim', [mm-(MM-mm)*0.05-eps, MM+(MM-mm)*0.05+eps]);
+          whisker_x, whisker_y, 'b--',   ...
+          cap_x, cap_y, 'k',   ...
+          median_x, median_y, 'r',  ...
+          outliers_x, outliers_y, [symbol(1),'r'],   ...
+          outliers2_x, outliers2_y, [symbol(2),'r']);
+    set(gca,'XTick',1:nc);
+    set(gca, 'XLim', [0.5, nc+0.5]);
+    set(gca, 'YLim', [mm-(MM-mm)*0.05-eps, MM+(MM-mm)*0.05+eps]);
 
 else
-% % % % %     plot (quartile_y, quartile_x, "b;;",
-% % % % %     whisker_y, whisker_x, "b;;",
-% % % % %     cap_y, cap_x, "b;;",
-% % % % %     median_y, median_x, "r;;",
-% % % % %     outliers_y, outliers_x, [symbol(1),"r;;"],
-% % % % %     outliers2_y, outliers2_x, [symbol(2),"r;;"]);
+    % % % % %     plot (quartile_y, quartile_x, "b;;",
+    % % % % %     whisker_y, whisker_x, "b;;",
+    % % % % %     cap_y, cap_x, "b;;",
+    % % % % %     median_y, median_x, "r;;",
+    % % % % %     outliers_y, outliers_x, [symbol(1),"r;;"],
+    % % % % %     outliers2_y, outliers2_x, [symbol(2),"r;;"]);
 end
 
-if nargout,
-  sout=s;
+if nargout
+    sout=s;
 end
 % % % endfunction
\ No newline at end of file
diff --git a/matlab/gsa/myprctilecol.m b/matlab/gsa/myprctilecol.m
index 1037a43e707ff6465b16953d90aac4342136d3f4..15ddcfcd44ce9cfb705e7128e23ae95f96dbe1ce 100644
--- a/matlab/gsa/myprctilecol.m
+++ b/matlab/gsa/myprctilecol.m
@@ -1,6 +1,11 @@
-function y = myprctilecol(x,p);
+function y = myprctilecol(x,p)
 
-% Copyright (C) 2012 Dynare Team
+% Written by Marco Ratto
+% Joint Research Centre, The European Commission,
+% marco.ratto@ec.europa.eu
+
+% Copyright (C) 2012 European Commission
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -22,10 +27,10 @@ xx = sort(x);
 
 if m==1 | n==1
     m = max(m,n);
-	if m == 1,
-	   y = x*ones(length(p),1);
-	   return;
-	end
+    if m == 1
+        y = x*ones(length(p),1);
+        return
+    end
     n = 1;
     q = 100*(0.5:m - 0.5)./m;
     xx = [min(x); xx(:); max(x)];
diff --git a/matlab/gsa/pick.m b/matlab/gsa/pick.m
new file mode 100644
index 0000000000000000000000000000000000000000..ed50f60cfe706953ef418216b16d107377f95929
--- /dev/null
+++ b/matlab/gsa/pick.m
@@ -0,0 +1,91 @@
+function pick
+%
+% Copyright (C) 2001-2017 European Commission
+% Copyright (C) 2017 DynareTeam
+    
+% This file is part of GLUEWIN
+% GLUEWIN is a MATLAB code designed for analysing the output
+% of Monte Carlo runs when empirical observations of the model output are available
+% and implements the GSA-GLUE methodology by Ratto et al. [1], based on a combination
+% of GLUE (Generalised Likelihood Uncertainty Estimation) by K. Beven [2] and GSA
+% Global Sensitivity Analysis) [3].']
+% The program has been developed by M. Ratto, European Commission, Joint Research Centre,
+% Institute for the Protection and Security of The Citizen, Technological and Economic Risk Management,
+% Applied Statistics, as a deliverable of the IMPACT project
+% (EC Fifth Framework Programme, SCA Project, IST-1999-11313, DG-INFSO).
+%
+% The graphical layout of the code is inspired by the freeware GLUE package by K. Beven,
+% vailable at the Lancaster University web site on the page [4]:
+% http://www.es.lancs.ac.uk/hfdg/glue.html
+% to which the GLUEWIN code introduces several extensions and additional options.
+% Thanks are due to R. Girardi, A. Rossi, A. Saltelli, S. Tarantola and U. Callies for numerous
+% comments and suggestions.
+% For more information, please contact marco.ratto@ec.europa.eu
+%
+% Disclaimer: This software has been developed at the Joint Research Centre of European Commission
+% by officers in the course of their official duties. This software is not subject to copyright
+% protection and is in the public domain. It is an experimental system. The Joint Research Centre
+% of European Commission assumes no responsibility whatsoever for its use by other parties
+% and makes no guarantees, expressed or implied, about its quality, reliability, or any other
+% characteristic. We would appreciate acknowledgement if the software is used.
+%
+% [1] Ratto, M., Tarantola, S., A. Saltelli, Sensitivity analysis in model calibration: GSA-GLUE approach.
+%                'Computer Physics Communications, 136, 2001, 212-224
+% [2] Beven K.J., Binley A., The Future of Distributed Models: Model Calibration and Uncertainty
+%                'Prediction, Hydrological Processes, 6, 279-298, 1992
+% [3] Saltelli, A., K. Chan, M. Scott, Editors, (2000), Sensitivity analysis, John Wiley & Sons
+%                'publishers, Probability and Statistics series.
+% [4] Beven K., GLUE for Windows User manual, 1998.
+
+
+
+pmenu=findobj(gcf,'type','uicontextmenu','Tag','Run viewer');
+button1=findobj(gcf,'type','uimenu','Tag','save params');
+button2=findobj(gcf,'type','uimenu','Tag','eval params');
+%button=get(pmenu,'children');
+gg=gco;
+ax0=gca;
+set(gg,'buttondownfcn',[]);
+c=get(gca,'currentpoint');
+x=c(1,1);
+y=c(1,2);
+X=get(gco,'xdata');
+Y=get(gco,'ydata');
+dx=get(gca,'xlim');
+dy=get(gca,'ylim');
+pos=get(gca,'position');
+scalex=dx(2)-dx(1);
+scaley=dy(2)-dy(1);
+if length(X)>1
+    K = dsearchn([(Y./scaley)' (X./scalex)'],[y/scaley x/scalex]);
+else
+    az=get(gca,'children');
+    T =get(az(end),'ydata');
+    [dum K]=max(T);
+end
+
+KK=K;
+
+set(button1,'Label',['Save ',num2str(K)],'Callback',['scatter_callback(',num2str(KK),',''save'')']);
+set(button2,'Label',['Eval ',num2str(K)],'Callback',['scatter_callback(',num2str(KK),',''eval'')']);
+hh=findobj(gcf,'type','axes','Tag','scatter');
+for k=1:length(hh)
+    axes(hh(k));
+    dum=get(gca,'children');
+    dumx=get(dum(end),'xdata');
+    dumy=get(dum(end),'ydata');
+    xmid=min(dumx) + 0.5*(max(dumx)-min(dumx));
+    hold on
+    plot(dumx(KK),dumy(KK),'or');
+    if dumx(KK) < xmid
+        text(dumx(KK),dumy(KK),['  ',num2str(K)], ...
+             'FontWeight','Bold',...
+             'Color','r');
+    else
+        text(dumx(KK),dumy(KK),[num2str(K),'  '], ...
+             'HorizontalAlignment','right', ...
+             'FontWeight','Bold',...
+             'Color','r');
+    end
+    hold off
+end
\ No newline at end of file
diff --git a/matlab/gsa/prior_draw_gsa.m b/matlab/gsa/prior_draw_gsa.m
index 1e66720500afab8b9bfe8bd529f27edffb2cbd88..c3c92d40d402d2ef2cf404f6569863ab6091cf4f 100644
--- a/matlab/gsa/prior_draw_gsa.m
+++ b/matlab/gsa/prior_draw_gsa.m
@@ -1,28 +1,25 @@
 function pdraw = prior_draw_gsa(init,rdraw)
 % Draws from the prior distributions for use with Sensitivity Toolbox for DYNARE
-% 
+%
 % INPUTS
 %   o init           [integer]  scalar equal to 1 (first call) or 0.
-%   o rdraw          
-%    
-% OUTPUTS 
-%   o pdraw          [double]   draw from the joint prior density. 
+%   o rdraw
+%
+% OUTPUTS
+%   o pdraw          [double]   draw from the joint prior density.
 %
-% ALGORITHM 
-%   ...       
+% ALGORITHM
+%   ...
 %
 % SPECIAL REQUIREMENTS
 %   MATLAB Statistics Toolbox
-%  
+%
 % Written by Marco Ratto
 % Joint Research Centre, The European Commission,
-% (http://eemc.jrc.ec.europa.eu/),
-% marco.ratto@jrc.it 
-%
-% Reference:
-% M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006.
+% marco.ratto@ec.europa.eu
 
-% Copyright (C) 2012-2015 Dynare Team
+% Copyright (C) 2012-2015 European Commission
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -41,7 +38,7 @@ function pdraw = prior_draw_gsa(init,rdraw)
 
 global bayestopt_ options_ estim_params_ M_
 persistent npar pshape p6 p7 p3 p4 lbcum ubcum
-  
+
 if init
     pshape = bayestopt_.pshape;
     p6 = bayestopt_.p6;
@@ -59,40 +56,40 @@ if init
         bounds.lb = max(bounds.lb,lb);
         bounds.ub = min(bounds.ub,ub);
     else  % estimated parameters but no declared priors
-        % No priors are declared so Dynare will estimate the model by
-        % maximum likelihood with inequality constraints for the parameters.
+          % No priors are declared so Dynare will estimate the model by
+          % maximum likelihood with inequality constraints for the parameters.
         bounds.lb = lb;
         bounds.ub = ub;
     end
     % set bounds for cumulative probabilities
     for i = 1:npar
-      switch pshape(i)
-        case 5% Uniform prior.
-          p4(i) = min(p4(i),bounds.ub(i));
-          p3(i) = max(p3(i),bounds.lb(i));
-        case 3% Gaussian prior.
-          lbcum(i) = 0.5 * erfc(-(bounds.lb(i)-p6(i))/p7(i) ./ sqrt(2));
-          ubcum(i) = 0.5 * erfc(-(bounds.ub(i)-p6(i))/p7(i) ./ sqrt(2));
-        case 2% Gamma prior.
-          lbcum(i) = gamcdf(bounds.lb(i)-p3(i),p6(i),p7(i));
-          ubcum(i) = gamcdf(bounds.ub(i)-p3(i),p6(i),p7(i));
-        case 1% Beta distribution (TODO: generalized beta distribution)
-          lbcum(i) = betainc((bounds.lb(i)-p3(i))./(p4(i)-p3(i)),p6(i),p7(i));
-          ubcum(i) = betainc((bounds.ub(i)-p3(i))./(p4(i)-p3(i)),p6(i),p7(i));
-        case 4% INV-GAMMA1 distribution
-          % TO BE CHECKED
-          lbcum(i) = gamcdf(1/(bounds.ub(i)-p3(i))^2,p7(i)/2,2/p6(i));
-          ubcum(i) = gamcdf(1/(bounds.lb(i)-p3(i))^2,p7(i)/2,2/p6(i));
-        case 6% INV-GAMMA2 distribution
-          % TO BE CHECKED
-          lbcum(i) = gamcdf(1/(bounds.ub(i)-p3(i)),p7(i)/2,2/p6(i));
-          ubcum(i) = gamcdf(1/(bounds.lb(i)-p3(i)),p7(i)/2,2/p6(i));
-        case 8
-          lbcum(i) = weibcdf(bounds.lb(i)-p3(i),p6(i),p7(i));
-          ubcum(i) = weibcdf(bounds.ub(i)-p3(i),p6(i),p7(i));
-        otherwise
-          % Nothing to do here.
-      end
+        switch pshape(i)
+          case 5% Uniform prior.
+            p4(i) = min(p4(i),bounds.ub(i));
+            p3(i) = max(p3(i),bounds.lb(i));
+          case 3% Gaussian prior.
+            lbcum(i) = 0.5 * erfc(-(bounds.lb(i)-p6(i))/p7(i) ./ sqrt(2));
+            ubcum(i) = 0.5 * erfc(-(bounds.ub(i)-p6(i))/p7(i) ./ sqrt(2));
+          case 2% Gamma prior.
+            lbcum(i) = gamcdf(bounds.lb(i)-p3(i),p6(i),p7(i));
+            ubcum(i) = gamcdf(bounds.ub(i)-p3(i),p6(i),p7(i));
+          case 1% Beta distribution (TODO: generalized beta distribution)
+            lbcum(i) = betainc((bounds.lb(i)-p3(i))./(p4(i)-p3(i)),p6(i),p7(i));
+            ubcum(i) = betainc((bounds.ub(i)-p3(i))./(p4(i)-p3(i)),p6(i),p7(i));
+          case 4% INV-GAMMA1 distribution
+                % TO BE CHECKED
+            lbcum(i) = gamcdf(1/(bounds.ub(i)-p3(i))^2,p7(i)/2,2/p6(i));
+            ubcum(i) = gamcdf(1/(bounds.lb(i)-p3(i))^2,p7(i)/2,2/p6(i));
+          case 6% INV-GAMMA2 distribution
+                % TO BE CHECKED
+            lbcum(i) = gamcdf(1/(bounds.ub(i)-p3(i)),p7(i)/2,2/p6(i));
+            ubcum(i) = gamcdf(1/(bounds.lb(i)-p3(i)),p7(i)/2,2/p6(i));
+          case 8
+            lbcum(i) = weibcdf(bounds.lb(i)-p3(i),p6(i),p7(i));
+            ubcum(i) = weibcdf(bounds.ub(i)-p3(i),p6(i),p7(i));
+          otherwise
+            % Nothing to do here.
+        end
     end
     return
 end
@@ -109,11 +106,11 @@ for i = 1:npar
         pdraw(:,i) = gaminv(rdraw(:,i),p6(i),p7(i))+p3(i);
       case 1% Beta distribution (TODO: generalized beta distribution)
         pdraw(:,i) = betainv(rdraw(:,i),p6(i),p7(i))*(p4(i)-p3(i))+p3(i);
-      case 4% INV-GAMMA1 distribution 
-        % TO BE CHECKED
+      case 4% INV-GAMMA1 distribution
+            % TO BE CHECKED
         pdraw(:,i) =  sqrt(1./gaminv(rdraw(:,i),p7(i)/2,2/p6(i)))+p3(i);
-      case 6% INV-GAMMA2 distribution  
-        % TO BE CHECKED
+      case 6% INV-GAMMA2 distribution
+            % TO BE CHECKED
         pdraw(:,i) =  1./gaminv(rdraw(:,i),p7(i)/2,2/p6(i))+p3(i);
       case 8
         pdraw(:,i) =  wblinv(rdraw(:,i),p6(i),p7(i))+p3(i);
@@ -121,5 +118,3 @@ for i = 1:npar
         % Nothing to do here.
     end
 end
-
-  
diff --git a/matlab/gsa/read_data.m b/matlab/gsa/read_data.m
index 7c7912f7c517b38b919918bf0e67bb6e6ac1a18b..bb2c71a611c19ecc317b5a85bf8b43839eff853a 100644
--- a/matlab/gsa/read_data.m
+++ b/matlab/gsa/read_data.m
@@ -1,13 +1,10 @@
 function [gend, data] = read_data()
 % Written by Marco Ratto
 % Joint Research Centre, The European Commission,
-% (http://eemc.jrc.ec.europa.eu/),
-% marco.ratto@jrc.it 
-%
-% Reference:
-% M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006.
+% marco.ratto@ec.europa.eu
 
-% Copyright (C) 2012-2015 Dynare Team
+% Copyright (C) 2012-2015 European Commission
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -33,15 +30,15 @@ gend = options_.nobs;
 
 rawdata = rawdata(options_.first_obs:options_.first_obs+gend-1,:);
 if options_.loglinear == 1 & ~options_.logdata
-  rawdata = log(rawdata);
+    rawdata = log(rawdata);
 end
 if options_.prefilter == 1
-  data = transpose(rawdata-ones(gend,1)* mean(rawdata,1));
+    data = transpose(rawdata-ones(gend,1)* mean(rawdata,1));
 else
-  data = transpose(rawdata);
+    data = transpose(rawdata);
 end
 
 if ~isreal(rawdata)
-  error(['There are complex values in the data. Probably  a wrong' ...
-	 ' transformation'])
+    error(['There are complex values in the data. Probably  a wrong' ...
+           ' transformation'])
 end
diff --git a/matlab/gsa/redform_map.m b/matlab/gsa/redform_map.m
index 8cf74e697666302c65856fa67c6f7ac6bd5955f5..a7ae7f712dd44dfc89858be4556395177b3d6dc4 100644
--- a/matlab/gsa/redform_map.m
+++ b/matlab/gsa/redform_map.m
@@ -13,13 +13,10 @@ function redform_map(dirname,options_gsa_)
 %
 % Written by Marco Ratto
 % Joint Research Centre, The European Commission,
-% (http://eemc.jrc.ec.europa.eu/),
-% marco.ratto@jrc.it
-%
-% Reference:
-% M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006.
+% marco.ratto@ec.europa.eu
 
-% Copyright (C) 2012-2016 Dynare Team
+% Copyright (C) 2012-2016 European Commission
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -58,7 +55,7 @@ np = estim_params_.np;
 nshock = estim_params_.nvx + estim_params_.nvn + estim_params_.ncx + estim_params_.ncn;
 pnames=cell(np,1);
 pnames_tex=cell(np,1);
-for jj=1:np        
+for jj=1:np
     if options_.TeX
         [param_name_temp, param_name_tex_temp]= get_the_name(nshock+jj,options_.TeX,M_,estim_params_,options_);
         pnames_tex{jj,1} = strrep(param_name_tex_temp,'$','');
@@ -73,7 +70,7 @@ fname_ = M_.fname;
 
 bounds = prior_bounds(bayestopt_, options_.prior_trunc);
 
-if nargin==0,
+if nargin==0
     dirname='';
 end
 
@@ -103,7 +100,7 @@ if ~exist('T')
     else
         load([dirname,filesep,M_.fname,'_mc'],'T');
     end
-    if ~exist('T'),
+    if ~exist('T')
         disp('The model is too large!')
         disp('Reduced form mapping stopped!')
         return
@@ -117,7 +114,7 @@ adir0=pwd;
 
 nspred=size(T,2)-M_.exo_nbr;
 x0=lpmat(istable,:);
-if isempty(lpmat0),
+if isempty(lpmat0)
     xx0=[];
     nshocks=0;
 else
@@ -126,7 +123,7 @@ else
 end
 [kn, np]=size(x0);
 offset = length(bayestopt_.pshape)-np;
-if options_gsa_.prior_range,
+if options_gsa_.prior_range
     pshape=5*(ones(np,1));
     pd =  [NaN(np,1) NaN(np,1) bounds.lb(offset+1:end) bounds.ub(offset+1:end)];
 else
@@ -161,20 +158,20 @@ for j=1:size(anamendo,1)
         skipline()
         disp(['[', namendo,' vs ',namexo,']'])
 
-        
-        if ~isempty(iexo),
+
+        if ~isempty(iexo)
             %y0=squeeze(T(iendo,iexo+nspred,istable));
             y0=squeeze(T(iendo,iexo+nspred,:));
-            if (max(y0)-min(y0))>1.e-10,
-                if mod(iplo,9)==0 && isempty(threshold) && ~options_.nograph,
+            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_.nodisplay,'name',['Reduced Form Mapping: ', namendo,' vs shocks ',int2str(ifig)]);
                     iplo=0;
                 end
                 iplo=iplo+1;
                 js=js+1;
                 xdir0 = [adir,filesep,namendo,'_vs_', namexo];
-                if ilog==0 || ~isempty(threshold),
+                if ilog==0 || ~isempty(threshold)
                     if isempty(threshold)
                         if isempty(dir(xdir0))
                             mkdir(xdir0)
@@ -195,8 +192,8 @@ for j=1:size(anamendo,1)
                         if isempty(dir(xdir))
                             mkdir(xdir)
                         end
-                        if ~options_.nograph,
-                            hf=dyn_figure(options_,'name',['Reduced Form Mapping (Monte Carlo Filtering): ',namendo,' vs ', namexo]); 
+                        if ~options_.nograph
+                            hf=dyn_figure(options_.nodisplay,'name',['Reduced Form Mapping (Monte Carlo Filtering): ',namendo,' vs ', namexo]);
                             hc = cumplot(y0);
                             a=axis; delete(hc);
                             %     hist(mat_moment{ij}),
@@ -209,12 +206,12 @@ for j=1:size(anamendo,1)
                             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_);
+                            dyn_saveas(hf,[xdir,filesep, fname_ '_' type '_' namendo,'_vs_', namexo],options_.nodisplay,options_.graph_format);
                             create_TeX_loader(options_,[xdir,filesep, fname_ '_' type '_' namendo,'_vs_', namexo],['Reduced Form Mapping (Monte Carlo Filtering): ',strrep(namendo,'_','\_'),' vs ', strrep(namexo,'_','\_')],[type '_' namendo,'_vs_', namexo])
                         end
                         si(:,js) = NaN(np,1);
                         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];
@@ -227,9 +224,9 @@ for j=1:size(anamendo,1)
                         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,
+                            if nshocks
                                 lpmat0=xx0(iy,:);
                             end
                             istable=[1:length(iy)];
@@ -238,11 +235,11 @@ for j=1:size(anamendo,1)
                         else
                             icheck=[];
                         end
-                        if isempty(icheck),
+                        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
@@ -257,11 +254,11 @@ for j=1:size(anamendo,1)
                     options_map.OutputDirectoryName = xdir0;
                     silog(:,js) = redform_private(x0, y0, options_map, options_);
                 end
-                
-                if isempty(threshold) && ~options_.nograph,
+
+                if isempty(threshold) && ~options_.nograph
                     figure(hfig)
                     subplot(3,3,iplo),
-                    if ilog,
+                    if ilog
                         [saso, iso] = sort(-silog(:,js));
                         bar([silog(iso(1:min(np,10)),js)])
                         logflag='log';
@@ -273,21 +270,21 @@ for j=1:size(anamendo,1)
                     %set(gca,'xticklabel',pnames(iso(1:min(np,10)),:),'fontsize',8)
                     set(gca,'xticklabel',' ','fontsize',10)
                     set(gca,'xlim',[0.5 10.5])
-                    for ip=1:min(np,10),
+                    for ip=1:min(np,10)
                         text(ip,-0.02,deblank(pnames(iso(ip),:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
                     end
                     title([logflag,' ',namendo,' vs ',namexo],'interpreter','none')
-                    if iplo==9 
-                        dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],options_);
+                    if iplo==9
+                        dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],options_.nodisplay,options_.graph_format);
                         create_TeX_loader(options_,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],[logflag,' ',strrep(namendo,'_','\_'),' vs ',strrep(namexo,'_','\_')],['redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],1)
                     end
                 end
-                
+
             end
         end
     end
-    if iplo<9 && iplo>0 && ifig && ~options_.nograph,
-        dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],options_);
+    if iplo<9 && iplo>0 && ifig && ~options_.nograph
+        dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],options_.nodisplay,options_.graph_format);
         create_TeX_loader(options_,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],[logflag,' ',strrep(namendo,'_','\_'),' vs ',strrep(namexo,'_','\_')],['redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],options_.figures.textwidth*min(iplo/3,1))
     end
     ifig=0;
@@ -297,20 +294,20 @@ for j=1:size(anamendo,1)
         ilagendo=strmatch(namlagendo,M_.endo_names(oo_.dr.order_var(M_.nstatic+1:M_.nstatic+nsok),:),'exact');
         skipline()
         disp(['[', namendo,' vs lagged ',namlagendo,']'])
-        
-        if ~isempty(ilagendo),
+
+        if ~isempty(ilagendo)
             %y0=squeeze(T(iendo,ilagendo,istable));
             y0=squeeze(T(iendo,ilagendo,:));
-            if (max(y0)-min(y0))>1.e-10,
-                if mod(iplo,9)==0 && isempty(threshold) && ~options_.nograph,
+            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_.nodisplay,'name',['Reduced Form Mapping: ' namendo,' vs lags ',int2str(ifig)]);
                     iplo=0;
                 end
                 iplo=iplo+1;
                 js=js+1;
                 xdir0 = [adir,filesep,namendo,'_vs_', namlagendo];
-                if ilog==0 || ~isempty(threshold),
+                if ilog==0 || ~isempty(threshold)
                     if isempty(threshold)
                         if isempty(dir(xdir0))
                             mkdir(xdir0)
@@ -331,8 +328,8 @@ for j=1:size(anamendo,1)
                         if isempty(dir(xdir))
                             mkdir(xdir)
                         end
-                        if ~options_.nograph,
-                            hf=dyn_figure(options_,'name',['Reduced Form Mapping (Monte Carlo Filtering): ',namendo,' vs lagged ', namlagendo]); 
+                        if ~options_.nograph
+                            hf=dyn_figure(options_.nodisplay,'name',['Reduced Form Mapping (Monte Carlo Filtering): ',namendo,' vs lagged ', namlagendo]);
                             hc = cumplot(y0);
                             a=axis; delete(hc);
                             %     hist(mat_moment{ij}),
@@ -345,12 +342,12 @@ for j=1:size(anamendo,1)
                             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_);
+                            dyn_saveas(hf,[xdir,filesep, fname_ '_' type '_' namendo,'_vs_', namlagendo],options_.nodisplay,options_.graph_format);
                             create_TeX_loader(options_,[xdir,filesep, fname_ '_' type '_' namendo,'_vs_', namlagendo],['Reduced Form Mapping (Monte Carlo Filtering): ',strrep(namendo,'_','\_'),' vs lagged ', strrep(namlagendo,'_','\_')],[type '_' namendo,'_vs_', namlagendo],1)
                         end
-                        
+
                         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];
@@ -364,19 +361,19 @@ for j=1:size(anamendo,1)
 
                             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,
+                            if nshocks
                                 lpmat0=xx0(iy,:);
                             end
                             istable=[1:length(iy)];
                             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),
+                        if isempty(icheck)
                             atitle0=['Monte Carlo Filtering for ',namendo,' vs ', namlagendo];
                             options_mcf.title = atitle0;
                             indmcf = redform_mcf(y0, x0, options_mcf, options_);
@@ -394,11 +391,11 @@ for j=1:size(anamendo,1)
                     options_map.OutputDirectoryName = xdir0;
                     silog(:,js) = redform_private(x0, y0, options_map, options_);
                 end
-                
+
                 if isempty(threshold) && ~options_.nograph
                     figure(hfig),
                     subplot(3,3,iplo),
-                    if ilog,
+                    if ilog
                         [saso, iso] = sort(-silog(:,js));
                         bar([silog(iso(1:min(np,10)),js)])
                         logflag='log';
@@ -410,58 +407,58 @@ for j=1:size(anamendo,1)
                     %set(gca,'xticklabel',pnames(iso(1:min(np,10)),:),'fontsize',8)
                     set(gca,'xticklabel',' ','fontsize',10)
                     set(gca,'xlim',[0.5 10.5])
-                    for ip=1:min(np,10),
+                    for ip=1:min(np,10)
                         text(ip,-0.02,deblank(pnames(iso(ip),:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
                     end
                     title([logflag,' ',namendo,' vs ',namlagendo,'(-1)'],'interpreter','none')
-                    if iplo==9,
-                        dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],options_);
+                    if iplo==9
+                        dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],options_.nodisplay,options_.graph_format);
                         create_TeX_loader(options_,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],[logflag,' ',strrep(namendo,'_','\_'),' vs ',strrep(namlagendo,'_','\_'),'(-1)'],['redform_', namendo,'_vs_lags_',logflag,':',num2str(ifig)],1)
                     end
                 end
-                
+
             end
         end
     end
-    if iplo<9 && iplo>0 && ifig && ~options_.nograph,
-        dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],options_);
+    if iplo<9 && iplo>0 && ifig && ~options_.nograph
+        dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],options_.nodisplay,options_.graph_format);
         create_TeX_loader(options_,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],[logflag,' ',strrep(namendo,'_','\_'),' vs ',strrep(namlagendo,'_','\_'),'(-1)'],['redform_', namendo,'_vs_lags_',logflag,':',num2str(ifig)],options_.figures.textwidth*min(iplo/3,1));
     end
 end
 
-if isempty(threshold) && ~options_.nograph,
-    if ilog==0,
-        hfig=dyn_figure(options_,'name','Reduced Form GSA'); %bar(si)
-        % boxplot(si','whis',10,'symbol','r.')
+if isempty(threshold) && ~options_.nograph
+    if ilog==0
+        hfig=dyn_figure(options_.nodisplay,'name','Reduced Form GSA'); %bar(si)
+                                                                       % boxplot(si','whis',10,'symbol','r.')
         myboxplot(si',[],'.',[],10)
         xlabel(' ')
         set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
         set(gca,'xlim',[0.5 np+0.5])
         set(gca,'ylim',[0 1])
         set(gca,'position',[0.13 0.2 0.775 0.7])
-        for ip=1:np,
+        for ip=1:np
             text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
         end
         title('Reduced form GSA')
-        dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_gsa'],options_);
+        dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_gsa'],options_.nodisplay,options_.graph_format);
         create_TeX_loader(options_,[dirname,filesep,M_.fname,'_redform_gsa'],'Reduced Form GSA','redform_gsa')
 
     else
-        hfig=dyn_figure(options_,'name','Reduced Form GSA'); %bar(silog)
-        % boxplot(silog','whis',10,'symbol','r.')
+        hfig=dyn_figure(options_.nodisplay,'name','Reduced Form GSA'); %bar(silog)
+                                                                       % boxplot(silog','whis',10,'symbol','r.')
         myboxplot(silog',[],'.',[],10)
         set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
         xlabel(' ')
         set(gca,'xlim',[0.5 np+0.5])
         set(gca,'ylim',[0 1])
         set(gca,'position',[0.13 0.2 0.775 0.7])
-        for ip=1:np,
+        for ip=1:np
             text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
         end
         title('Reduced form GSA - Log-transformed elements')
-        dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_gsa_log'],options_);
+        dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_gsa_log'],options_.nodisplay,options_.graph_format);
         create_TeX_loader(options_,[dirname,filesep,M_.fname,'_redform_gsa_log'],'Reduced form GSA - Log-transformed elements','redform_gsa_log')
-        
+
     end
 end
 
@@ -475,20 +472,20 @@ 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,
+if options_map.prior_range
+    for j=1:np
         x0(:,j)=(x0(:,j)-pd(j,3))./(pd(j,4)-pd(j,3));
     end
 else
     x0=priorcdf(x0,pshape, pd(:,1), pd(:,2), pd(:,3), pd(:,4));
 end
 
-if ilog,
+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 iload==0
     if isempty(dir(xdir))
         mkdir(xdir)
     end
@@ -497,44 +494,44 @@ if iload==0,
     nest=min(250,nest);
     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);
+    %     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);
-    if istep>1,
-    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 istep>1
+        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));
     else
         warning('the number of samples is too small for ANOVA estimation')
         si=nan(np,1);
         return
     end
-    if ~ismember(irest(end),ifit),
+    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;
+    %     ifit = union(iest, irest(randperm(nrun-nest,nfit-nest)));
+    %     ifit = iest;
+    %     nfit=nest;
     ipred = setdiff([1:nrun],ifit);
 
-    if ilog,
+    if ilog
         [y1, tmp, isig, lam] = log_trans_(y0(iest));
         y1 = log(y0*isig+lam);
     end
-    if ~options_.nograph,
-        hfig=dyn_figure(options_,'name',options_map.figtitle); 
+    if ~options_.nograph
+        hfig=dyn_figure(options_.nodisplay,'name',options_map.figtitle);
         subplot(221)
-        if ilog,
-            hist(y1,30),
+        if ilog
+            hist(y1,30)
         else
-            hist(y0,30),
+            hist(y0,30)
         end
         title(options_map.title,'interpreter','none')
         subplot(222)
-        if ilog,
+        if ilog
             hc = cumplot(y1);
         else
             hc = cumplot(y0);
@@ -544,88 +541,88 @@ if iload==0,
     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;
+        [gsa22, gsa1, gsax] = ss_anova_log(y1(iest), x0(iest,:), isig, lam, gsa0);
     end
-else
-    if ilog
-        gsa_ = gsa22;
+    %     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
-        gsa_ = gsa0;
+        if ilog
+            gsa_ = gsa22;
+        else
+            gsa_ = gsa0;
+        end
     end
-end
     save([fname,'_map.mat'],'gsa_')
     [sidum, iii]=sort(-gsa_.si);
     gsa_.x0=x00(ifit,:);
-    if ~options_.nograph,
+    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(ifit,:);
     %   copyfile([fname,'_est.mat'],[fname,'.mat'])
-    if ~options_.nograph,
+    if ~options_.nograph
         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
+        %         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,
-            if ilog,
+        if nfit<nrun
+            if ilog
                 yf = ss_anova_fcast(x0(ipred,:), gsa1);
                 yf = log_trans_(yf,'',isig,lam)+ss_anova_fcast(x0(ipred,:), gsax);
             else
@@ -637,7 +634,7 @@ end
             plot(yn,[yf yn],'.'),
             title(['Out-of-sample prediction - R2=' num2str(r2,2)],'interpreter','none')
         end
-        dyn_saveas(hfig,fname,options_);
+        dyn_saveas(hfig,fname,options_.nodisplay,options_.graph_format);
         create_TeX_loader(options_,fname,['Out-of-sample prediction - R2=' num2str(r2,2)],'redform_gsa_log')
 
         if options_.nodisplay
@@ -646,14 +643,14 @@ 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,
+    if ~options_.nograph
         yf = ss_anova_fcast(x0, gsa_);
-        hfig=dyn_figure(options_,'name',options_map.title);
+        hfig=dyn_figure(options_.nodisplay,'name',options_map.title);
         plot(y0,[yf y0],'.'),
         title([namy,' vs ', namx,' pred'],'interpreter','none')
-        dyn_saveas(hfig,[fname '_pred'],options_);
+        dyn_saveas(hfig,[fname '_pred'],options_.nodisplay,options_.graph_format);
         create_TeX_loader(options_,[fname '_pred'],options_map.title,[namy,' vs ', namx,' pred'])
 
     end
@@ -674,7 +671,7 @@ 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,
+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;
@@ -688,14 +685,14 @@ function [gsa22, gsa1, gsax] = ss_anova_log(y,x,isig,lam,gsa0,nvrs)
 
 [nest, np]=size(x);
 
-if nargin==6,
+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,
+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
@@ -705,7 +702,7 @@ if nargin >=5 && ~isempty(gsa0),
     gsa1 = ss_anova(y, x, 1, 0, 2, gsa1.nvr);
     gsa2 = log2level_map(gsa1, isig, lam);
 end
-if nargin==6,
+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);
@@ -716,7 +713,7 @@ 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,
+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);
@@ -727,13 +724,13 @@ return
 
 function indmcf = redform_mcf(y0, x0, options_mcf, options_)
 
-hfig=dyn_figure(options_,'name',options_mcf.amcf_title);
+hfig=dyn_figure(options_.nodisplay,'name',options_mcf.amcf_title);
 
 [post_mean, post_median, post_var, hpd_interval, post_deciles, ...
-    density] = posterior_moments(y0,1,0.9);
+ density] = posterior_moments(y0,1,0.9);
 post_deciles = [-inf; post_deciles; inf];
 
-for jt=1:10,
+for jt=1:10
     indy{jt}=find( (y0>post_deciles(jt)) & (y0<=post_deciles(jt+1)));
     leg{jt}=[int2str(jt) '-dec'];
 end
@@ -744,18 +741,18 @@ indmcf = indmcf(jtmp);
 nbr_par = length(indmcf);
 nrow=ceil(sqrt(nbr_par+1));
 ncol=nrow;
-if nrow*(nrow-1)>nbr_par,
+if nrow*(nrow-1)>nbr_par
     ncol=nrow-1;
 end
 
 cmap = colormap(jet(10));
-for jx=1:nbr_par,
+for jx=1:nbr_par
     subplot(nrow,ncol,jx)
     hold off
-    for jt=1:10,
+    for jt=1:10
         h=cumplot(x0(indy{jt},indmcf(jx)));
         set(h,'color', cmap(jt,:), 'linewidth', 2)
-        hold all,
+        hold all
     end
     title(options_mcf.param_names(indmcf(jx),:),'interpreter','none')
 end
@@ -766,16 +763,16 @@ 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');
+               '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_);
+dyn_saveas(hfig,[options_mcf.OutputDirectoryName filesep options_mcf.fname_,'_',options_mcf.amcf_name],options_.nodisplay,options_.graph_format);
 create_TeX_loader(options_,[options_mcf.OutputDirectoryName filesep options_mcf.fname_,'_',options_mcf.amcf_name],strrep(options_mcf.amcf_title,'_','\_'),[options_mcf.fname_,'_',options_mcf.amcf_name])
-        
+
 return
 
 function []=create_TeX_loader(options_,figpath,caption,label_name,scale_factor)
diff --git a/matlab/gsa/redform_screen.m b/matlab/gsa/redform_screen.m
index ab65d846a124a525e96e71c6fe6356502809366f..d4c007174674d177c7750dc034f5bff55dda1b6c 100644
--- a/matlab/gsa/redform_screen.m
+++ b/matlab/gsa/redform_screen.m
@@ -8,13 +8,10 @@ function redform_screen(dirname, options_gsa_)
 %
 % Written by Marco Ratto
 % Joint Research Centre, The European Commission,
-% (http://eemc.jrc.ec.europa.eu/),
-% marco.ratto@jrc.it
-%
-% Reference:
-% M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006.
+% marco.ratto@ec.europa.eu
 
-% Copyright (C) 2012-2016 Dynare Team
+% Copyright (C) 2012-2016 European Commission
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -42,8 +39,8 @@ iload = options_gsa_.load_redform;
 nliv = options_gsa_.morris_nliv;
 
 pnames = M_.param_names(estim_params_.param_vals(:,1),:);
-if nargin==0,
-  dirname='';
+if nargin==0
+    dirname='';
 end
 
 load([dirname,'/',M_.fname,'_prior'],'lpmat','lpmat0','istable','T');
@@ -56,96 +53,96 @@ nshock = length(bayestopt_.pshape)-np;
 nsok = length(find(M_.lead_lag_incidence(M_.maximum_lag,:)));
 
 js=0;
-for j=1:size(anamendo,1),
-  namendo=deblank(anamendo(j,:));
-  iendo=strmatch(namendo,M_.endo_names(oo_.dr.order_var,:),'exact');
-
-  iplo=0;
-  ifig=0;
-  for jx=1:size(anamexo,1)
-    namexo=deblank(anamexo(jx,:));
-    iexo=strmatch(namexo,M_.exo_names,'exact');
-
-    if ~isempty(iexo),
-      y0=teff(T(iendo,iexo+nspred,:),kn,istable);
-      if ~isempty(y0),
-        if mod(iplo,9)==0,
-          ifig=ifig+1;
-          hh=dyn_figure(options_,'name',[namendo,' vs. shocks ',int2str(ifig)]);
-          iplo=0;
-        end
-        iplo=iplo+1;
-        js=js+1;
-        subplot(3,3,iplo),
-        [SAmeas, SAMorris] = Morris_Measure_Groups(np+nshock, [lpmat0 lpmat], y0,nliv);
-        SAM = squeeze(SAMorris(nshock+1:end,1));
-        SA(:,js)=SAM./(max(SAM)+eps);
-        [saso, iso] = sort(-SA(:,js));
-        bar(SA(iso(1:min(np,10)),js))
-        %set(gca,'xticklabel',pnames(iso(1:min(np,10)),:),'fontsize',8)
-        set(gca,'xticklabel',' ','fontsize',10)
-        set(gca,'xlim',[0.5 10.5])
-        for ip=1:min(np,10),
-          text(ip,-0.02,deblank(pnames(iso(ip),:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-        end
-        title([namendo,' vs. ',namexo],'interpreter','none')
-        if iplo==9,
-          dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],options_); 
-          create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],ifig,[namendo,' vs. shocks ',int2str(ifig)],[namendo,'_vs_shock'],1)
+for j=1:size(anamendo,1)
+    namendo=deblank(anamendo(j,:));
+    iendo=strmatch(namendo,M_.endo_names(oo_.dr.order_var,:),'exact');
+
+    iplo=0;
+    ifig=0;
+    for jx=1:size(anamexo,1)
+        namexo=deblank(anamexo(jx,:));
+        iexo=strmatch(namexo,M_.exo_names,'exact');
+
+        if ~isempty(iexo)
+            y0=teff(T(iendo,iexo+nspred,:),kn,istable);
+            if ~isempty(y0)
+                if mod(iplo,9)==0
+                    ifig=ifig+1;
+                    hh=dyn_figure(options_.nodisplay,'name',[namendo,' vs. shocks ',int2str(ifig)]);
+                    iplo=0;
+                end
+                iplo=iplo+1;
+                js=js+1;
+                subplot(3,3,iplo),
+                [SAmeas, SAMorris] = Morris_Measure_Groups(np+nshock, [lpmat0 lpmat], y0,nliv);
+                SAM = squeeze(SAMorris(nshock+1:end,1));
+                SA(:,js)=SAM./(max(SAM)+eps);
+                [saso, iso] = sort(-SA(:,js));
+                bar(SA(iso(1:min(np,10)),js))
+                %set(gca,'xticklabel',pnames(iso(1:min(np,10)),:),'fontsize',8)
+                set(gca,'xticklabel',' ','fontsize',10)
+                set(gca,'xlim',[0.5 10.5])
+                for ip=1:min(np,10)
+                    text(ip,-0.02,deblank(pnames(iso(ip),:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+                end
+                title([namendo,' vs. ',namexo],'interpreter','none')
+                if iplo==9
+                    dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],options_.nodisplay,options_.graph_format);
+                    create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],ifig,[namendo,' vs. shocks ',int2str(ifig)],[namendo,'_vs_shock'],1)
+                end
+
+            end
         end
-
-      end
     end
-  end
-  if iplo<9 && iplo>0 && ifig,
-    dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_shocks_',num2str(ifig)],options_);
-    create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],ifig,[namendo,' vs. shocks ',int2str(ifig)],[namendo,'_vs_shock'],options_.figures.textwidth*min(iplo/3))
-  end
-
-  iplo=0;
-  ifig=0;
-  for je=1:size(anamlagendo,1)
-    namlagendo=deblank(anamlagendo(je,:));
-    ilagendo=strmatch(namlagendo,M_.endo_names(oo_.dr.order_var(M_.nstatic+1:M_.nstatic+nsok),:),'exact');
-
-    if ~isempty(ilagendo),
-      y0=teff(T(iendo,ilagendo,:),kn,istable);
-      if ~isempty(y0),
-        if mod(iplo,9)==0,
-          ifig=ifig+1;
-          hh=dyn_figure(options_,'name',[namendo,' vs. lagged endogenous ',int2str(ifig)]);
-          iplo=0;
-        end
-        iplo=iplo+1;
-        js=js+1;
-        subplot(3,3,iplo),
-        [SAmeas, SAMorris] = Morris_Measure_Groups(np+nshock, [lpmat0 lpmat], y0,nliv);
-        SAM = squeeze(SAMorris(nshock+1:end,1));
-        SA(:,js)=SAM./(max(SAM)+eps);
-        [saso, iso] = sort(-SA(:,js));
-        bar(SA(iso(1:min(np,10)),js))
-        %set(gca,'xticklabel',pnames(iso(1:min(np,10)),:),'fontsize',8)
-        set(gca,'xticklabel',' ','fontsize',10)
-        set(gca,'xlim',[0.5 10.5])
-        for ip=1:min(np,10),
-          text(ip,-0.02,deblank(pnames(iso(ip),:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-        end
+    if iplo<9 && iplo>0 && ifig
+        dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_shocks_',num2str(ifig)],options_.nodisplay,options_.graph_format);
+        create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],ifig,[namendo,' vs. shocks ',int2str(ifig)],[namendo,'_vs_shock'],options_.figures.textwidth*min(iplo/3))
+    end
 
-        title([namendo,' vs. ',namlagendo,'(-1)'],'interpreter','none')
-        if iplo==9,
-          dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],options_);  
-          create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],ifig,[namendo,' vs. lagged endogenous ',int2str(ifig)],[namendo,'_vs_lags'],1)
+    iplo=0;
+    ifig=0;
+    for je=1:size(anamlagendo,1)
+        namlagendo=deblank(anamlagendo(je,:));
+        ilagendo=strmatch(namlagendo,M_.endo_names(oo_.dr.order_var(M_.nstatic+1:M_.nstatic+nsok),:),'exact');
+
+        if ~isempty(ilagendo)
+            y0=teff(T(iendo,ilagendo,:),kn,istable);
+            if ~isempty(y0)
+                if mod(iplo,9)==0
+                    ifig=ifig+1;
+                    hh=dyn_figure(options_.nodisplay,'name',[namendo,' vs. lagged endogenous ',int2str(ifig)]);
+                    iplo=0;
+                end
+                iplo=iplo+1;
+                js=js+1;
+                subplot(3,3,iplo),
+                [SAmeas, SAMorris] = Morris_Measure_Groups(np+nshock, [lpmat0 lpmat], y0,nliv);
+                SAM = squeeze(SAMorris(nshock+1:end,1));
+                SA(:,js)=SAM./(max(SAM)+eps);
+                [saso, iso] = sort(-SA(:,js));
+                bar(SA(iso(1:min(np,10)),js))
+                %set(gca,'xticklabel',pnames(iso(1:min(np,10)),:),'fontsize',8)
+                set(gca,'xticklabel',' ','fontsize',10)
+                set(gca,'xlim',[0.5 10.5])
+                for ip=1:min(np,10)
+                    text(ip,-0.02,deblank(pnames(iso(ip),:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+                end
+
+                title([namendo,' vs. ',namlagendo,'(-1)'],'interpreter','none')
+                if iplo==9
+                    dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],options_.nodisplay,options_.graph_format);
+                    create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],ifig,[namendo,' vs. lagged endogenous ',int2str(ifig)],[namendo,'_vs_lags'],1)
+                end
+            end
         end
-      end
     end
-  end
-  if iplo<9 && iplo>0 && ifig,
-    dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],options_);      
-    create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],ifig,[namendo,' vs. lagged endogenous ',int2str(ifig)],[namendo,'_vs_lags'],options_.figures.textwidth*min(iplo/3))
-  end
+    if iplo<9 && iplo>0 && ifig
+        dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],options_.nodisplay,options_.graph_format);
+        create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],ifig,[namendo,' vs. lagged endogenous ',int2str(ifig)],[namendo,'_vs_lags'],options_.figures.textwidth*min(iplo/3))
+    end
 end
 
-hh=dyn_figure(options_,'Name','Reduced form screening'); 
+hh=dyn_figure(options_.nodisplay,'Name','Reduced form screening');
 %bar(SA)
 % boxplot(SA','whis',10,'symbol','r.')
 myboxplot(SA',[],'.',[],10)
@@ -153,13 +150,13 @@ set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
 set(gca,'xlim',[0.5 np+0.5])
 set(gca,'ylim',[0 1])
 set(gca,'position',[0.13 0.2 0.775 0.7])
-for ip=1:np,
-  text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+for ip=1:np
+    text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
 end
 xlabel(' ')
 ylabel('Elementary Effects')
 title('Reduced form screening')
-dyn_saveas(hh,[dirname,'/',M_.fname,'_redform_screen'],options_);
+dyn_saveas(hh,[dirname,'/',M_.fname,'_redform_screen'],options_.nodisplay,options_.graph_format);
 create_TeX_loader(options_,[dirname,'/',M_.fname,'_redform_screen'],1,'Reduced form screening','redform_screen',1)
 
 
@@ -180,4 +177,3 @@ if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
     fprintf(fidTeX,'%% End Of TeX file. \n');
     fclose(fidTeX);
 end
-
diff --git a/matlab/gsa/scatter_analysis.m b/matlab/gsa/scatter_analysis.m
new file mode 100644
index 0000000000000000000000000000000000000000..d526b3f0eafc5f7a9f28cb92b933c2de5716821d
--- /dev/null
+++ b/matlab/gsa/scatter_analysis.m
@@ -0,0 +1,52 @@
+function indmcf = scatter_analysis(lpmat, xdata, options_scatter, DynareOptions)
+%
+% Written by Marco Ratto
+% Joint Research Centre, The European Commission,
+% marco.ratto@ec.europa.eu
+%
+
+% Copyright (C) 2017 European Commission
+% Copyright (C) 2017 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/>.
+
+param_names = options_scatter.param_names;
+
+if DynareOptions.TeX
+    if ~isfield(options_scatter,'param_names_tex')
+        param_names_tex = options_scatter.param_names;
+    else
+        param_names_tex = options_scatter.param_names_tex;
+    end
+end
+amcf_name = options_scatter.amcf_name;
+amcf_title = options_scatter.amcf_title;
+title = options_scatter.title;
+fname_ = options_scatter.fname_;
+xparam1=[];
+if isfield(options_scatter,'xparam1')
+    xparam1=options_scatter.xparam1;
+end
+OutputDirectoryName = options_scatter.OutputDirectoryName;
+
+if ~DynareOptions.nograph
+    skipline()
+    xx=[];
+    if ~isempty(xparam1)
+        xx=xparam1;
+    end
+    scatter_plots(lpmat, xdata, param_names, '.', [fname_, '_', amcf_name], OutputDirectoryName, amcf_title, xx, DynareOptions)
+end
diff --git a/matlab/gsa/scatter_callback.m b/matlab/gsa/scatter_callback.m
new file mode 100644
index 0000000000000000000000000000000000000000..61345107caa1de5b2b7aed75e4739301770c428b
--- /dev/null
+++ b/matlab/gsa/scatter_callback.m
@@ -0,0 +1,42 @@
+function  scatter_callback(K, type)
+%
+% Written by Marco Ratto
+% Joint Research Centre, The European Commission,
+% marco.ratto@ec.europa.eu
+%
+
+% Copyright (C) 2017 European Commission
+% Copyright (C) 2017 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 oo_ M_ options_ bayestopt_ estim_params_
+
+x=get(gcf,'userdata');
+r2=x{1};
+x=x{2};
+
+xparam1=x(K,:)';
+
+switch type
+  case 'save'
+    save(['my_params_' int2str(K)],'xparam1')
+
+  case 'eval'
+    disp('Evaluating smoother ...')
+    [oo_, M_]=evaluate_smoother(xparam1,M_.endo_names,M_,oo_,options_,bayestopt_,estim_params_);
+    % [rmse, lnam, r2,vv] = plot_fit(obsname{:});
+end
diff --git a/matlab/gsa/scatter_mcf.m b/matlab/gsa/scatter_mcf.m
index 0c416299018a156c1d05d957ed9f417d9456fdc7..211b2e74bb47b8fb5fc3b2dad5263d72b035de47 100644
--- a/matlab/gsa/scatter_mcf.m
+++ b/matlab/gsa/scatter_mcf.m
@@ -1,182 +1,183 @@
-function  scatter_mcf(X,Y,vnames,plotsymbol, fnam, dirname, figtitle, xparam1, DynareOptions, beha_name, non_beha_name)
-% Frontend to the Sensitivity Analysis Toolbox for DYNARE
-%
-% Reference:
-% M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006.
-
-% Copyright (C) 2014-2016 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/>.
-
-% PURPOSE: Pairwise scatter plots of the columns of x and y after
-% Monte Carlo filtering
-%---------------------------------------------------
-% USAGE:    scatter_mcf(x,y,vnames,pltsym,diagon)
-%        or scatter_mcf(x,y) which relies on defaults
-% where:
-%        x = an nxk matrix with columns containing behavioural sample
-%        y = an mxk matrix with columns containing non-behavioural sample
-%   vnames = a vector of variable names
-%            (default = numeric labels 1,2,3 etc.)
-%   pltsym = a plt symbol
-%            (default = '.' for npts > 100, 'o' for npts < 100
-
-
-Z=[X;Y];
-[n,p] = size(X);
-% X = X - ones(n,1)*min(Z);
-% X = X ./ (ones(n,1)*max(Z));
-[n,p] = size(Y);
-% Y = Y - ones(n,1)*min(Z);
-% Y = Y ./ (ones(n,1)*max(Z));
-[n,p] = size(Z);
-clear Z;
-
-nflag = 0;
-if nargin >=3
-    nflag = 1;
-end;
-
-if nargin<4 || isempty(plotsymbol)
-    if n*p<100, plotsymbol = 'o';
-    else plotsymbol = '.';
-    end
-end
-
-if nargin<5
-    fnam='';
-end
-if nargin<6,
-  dirname='';
-  nograph=1;
-else
-  nograph=0;    
-end
-if nargin<7,
-  figtitle=fnam;
-end
-if nargin<8,
-  xparam1=[];
-end
-if nargin<10,
-  beha_name = 'BEHAVIOUR';
-  non_beha_name = 'NON-BEHAVIOUR';
-end
-if nargin==10,
-  non_beha_name = ['NON-' beha_name];
-end
-
-figtitle_tex=strrep(figtitle,'_','\_');
-
-fig_nam_=[fnam];
-if ~nograph,
-    hh=dyn_figure(DynareOptions,'name',figtitle);
-end
-
-bf = 0.1;
-ffs = 0.05/(p-1);
-ffl = (1-2*bf-0.05)/p;
-if p>1,
-    fL = linspace(bf,1-bf+ffs,p+1);
-else
-    fL = bf;
-end
-for i = 1:p
-    for j = 1:p
-        h = axes('position',[fL(i),fL(p+1-j),ffl,ffl]);
-        if i==j
-            h1=cumplot(X(:,j));
-            %             set(h1,'color',[0 0 1], 'linestyle','--','LineWidth',1.5)
-            set(h1,'color',[0 0 1],'LineWidth',1.5)
-            hold on,
-            h2=cumplot(Y(:,j));
-            set(h2,'color',[1 0 0],'LineWidth',1.5)
-            if ~isempty(xparam1)
-                hold on, plot(xparam1([j j]),[0 1],'k--')
-            end
-            if j<p
-                set(gca,'XTickLabel',[],'XTick',[]);
-            else
-                grid off
-            end
-            set(gca,'YTickLabel',[],'YTick',[]);
-        else
-            if j>i
-                plot(X(:,i),X(:,j),[plotsymbol,'b'])
-                hold on,
-                plot(Y(:,i),Y(:,j),[plotsymbol,'r'])
-            else
-                plot(Y(:,i),Y(:,j),[plotsymbol,'r'])
-                hold on,
-                plot(X(:,i),X(:,j),[plotsymbol,'b'])
-            end
-            if ~isempty(xparam1)
-                hold on, plot(xparam1(i),xparam1(j),'s','MarkerFaceColor',[0 0.75 0],'MarkerEdgeColor',[0 0.75 0])
-            end
-            hold off;
-            %             axis([-0.1 1.1 -0.1 1.1])
-            if i<p,
-                set(gca,'YTickLabel',[],'YTick',[]);
-            else
-                set(gca,'yaxislocation','right');
-            end
-            if j<p
-                set(gca,'XTickLabel',[],'XTick',[]);
-            end
-        end
-        if nflag == 1
-            set(gca,'fontsize',9);
-        end;
-        if i==1
-            if nflag == 1
-                ylabel(vnames(j,:),'Rotation',45,'interpreter','none', ...
-                    'HorizontalAlignment','right','VerticalAlignment','middle');
-            else
-                ylabel([num2str(j),' '],'Rotation',90)
-            end;
-        end
-        if j==1
-            if nflag == 1
-                title(vnames(i,:),'interpreter','none','Rotation',45, ...
-                    'HorizontalAlignment','left','VerticalAlignment','bottom')
-            else
-                title(num2str(i))
-            end;
-        end
-        drawnow
-    end
-end
-if ~isoctave
-    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,
-    dyn_saveas(hh,[dirname,filesep,fig_nam_],DynareOptions);
-    if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
-        fidTeX = fopen([dirname,'/',fig_nam_ '.tex'],'w');
-        fprintf(fidTeX,'%% TeX eps-loader file generated by scatter_mcf.m (Dynare).\n');
-        fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
-        fprintf(fidTeX,'\\begin{figure}[H]\n');
-        fprintf(fidTeX,'\\centering \n');
-        fprintf(fidTeX,'\\includegraphics[width=0.8\\textwidth]{%s}\n',strrep([dirname,'/',fig_nam_],'\','/'));
-        fprintf(fidTeX,'\\caption{%s.}',figtitle_tex);
-        fprintf(fidTeX,'\\label{Fig:%s}\n',fig_nam_);
-        fprintf(fidTeX,'\\end{figure}\n\n');
-        fprintf(fidTeX,'%% End Of TeX file. \n');
-        fclose(fidTeX);
-    end
+function  scatter_mcf(X,Y,vnames,plotsymbol, fnam, dirname, figtitle, xparam1, DynareOptions, beha_name, non_beha_name)
+%
+% Written by Marco Ratto
+% Joint Research Centre, The European Commission,
+% marco.ratto@ec.europa.eu
+
+% Copyright (C) 2014-2016 European Commission
+% Copyright (C) 2014-2017 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/>.
+
+% PURPOSE: Pairwise scatter plots of the columns of x and y after
+% Monte Carlo filtering
+%---------------------------------------------------
+% USAGE:    scatter_mcf(x,y,vnames,pltsym,diagon)
+%        or scatter_mcf(x,y) which relies on defaults
+% where:
+%        x = an nxk matrix with columns containing behavioural sample
+%        y = an mxk matrix with columns containing non-behavioural sample
+%   vnames = a vector of variable names
+%            (default = numeric labels 1,2,3 etc.)
+%   pltsym = a plt symbol
+%            (default = '.' for npts > 100, 'o' for npts < 100
+
+
+Z=[X;Y];
+[n,p] = size(X);
+% X = X - ones(n,1)*min(Z);
+% X = X ./ (ones(n,1)*max(Z));
+[n,p] = size(Y);
+% Y = Y - ones(n,1)*min(Z);
+% Y = Y ./ (ones(n,1)*max(Z));
+[n,p] = size(Z);
+clear Z;
+
+nflag = 0;
+if nargin >=3
+    nflag = 1;
+end
+
+if nargin<4 || isempty(plotsymbol)
+    if n*p<100, plotsymbol = 'o';
+    else plotsymbol = '.';
+    end
+end
+
+if nargin<5
+    fnam='';
+end
+if nargin<6
+    dirname='';
+    nograph=1;
+else
+    nograph=0;
+end
+if nargin<7
+    figtitle=fnam;
+end
+if nargin<8
+    xparam1=[];
+end
+if nargin<10
+    beha_name = 'BEHAVIOUR';
+    non_beha_name = 'NON-BEHAVIOUR';
+end
+if nargin==10
+    non_beha_name = ['NON-' beha_name];
+end
+
+figtitle_tex=strrep(figtitle,'_','\_');
+
+fig_nam_=[fnam];
+if ~nograph
+    hh=dyn_figure(DynareOptions.nodisplay,'name',figtitle);
+end
+
+bf = 0.1;
+ffs = 0.05/(p-1);
+ffl = (1-2*bf-0.05)/p;
+if p>1
+    fL = linspace(bf,1-bf+ffs,p+1);
+else
+    fL = bf;
+end
+for i = 1:p
+    for j = 1:p
+        h = axes('position',[fL(i),fL(p+1-j),ffl,ffl]);
+        if i==j
+            h1=cumplot(X(:,j));
+            %             set(h1,'color',[0 0 1], 'linestyle','--','LineWidth',1.5)
+            set(h1,'color',[0 0 1],'LineWidth',1.5)
+            hold on,
+            h2=cumplot(Y(:,j));
+            set(h2,'color',[1 0 0],'LineWidth',1.5)
+            if ~isempty(xparam1)
+                hold on, plot(xparam1([j j]),[0 1],'k--')
+            end
+            if j<p
+                set(gca,'XTickLabel',[],'XTick',[]);
+            else
+                grid off
+            end
+            set(gca,'YTickLabel',[],'YTick',[]);
+        else
+            if j>i
+                plot(X(:,i),X(:,j),[plotsymbol,'b'])
+                hold on,
+                plot(Y(:,i),Y(:,j),[plotsymbol,'r'])
+            else
+                plot(Y(:,i),Y(:,j),[plotsymbol,'r'])
+                hold on,
+                plot(X(:,i),X(:,j),[plotsymbol,'b'])
+            end
+            if ~isempty(xparam1)
+                hold on, plot(xparam1(i),xparam1(j),'s','MarkerFaceColor',[0 0.75 0],'MarkerEdgeColor',[0 0.75 0])
+            end
+            hold off;
+            %             axis([-0.1 1.1 -0.1 1.1])
+            if i<p
+                set(gca,'YTickLabel',[],'YTick',[]);
+            else
+                set(gca,'yaxislocation','right');
+            end
+            if j<p
+                set(gca,'XTickLabel',[],'XTick',[]);
+            end
+        end
+        if nflag == 1
+            set(gca,'fontsize',9);
+        end
+        if i==1
+            if nflag == 1
+                ylabel(vnames(j,:),'Rotation',45,'interpreter','none', ...
+                       'HorizontalAlignment','right','VerticalAlignment','middle');
+            else
+                ylabel([num2str(j),' '],'Rotation',90)
+            end
+        end
+        if j==1
+            if nflag == 1
+                title(vnames(i,:),'interpreter','none','Rotation',45, ...
+                      'HorizontalAlignment','left','VerticalAlignment','bottom')
+            else
+                title(num2str(i))
+            end
+        end
+        drawnow
+    end
+end
+if ~isoctave
+    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
+    dyn_saveas(hh,[dirname,filesep,fig_nam_],DynareOptions.nodisplay,DynareOptions.graph_format);
+    if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
+        fidTeX = fopen([dirname,'/',fig_nam_ '.tex'],'w');
+        fprintf(fidTeX,'%% TeX eps-loader file generated by scatter_mcf.m (Dynare).\n');
+        fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
+        fprintf(fidTeX,'\\begin{figure}[H]\n');
+        fprintf(fidTeX,'\\centering \n');
+        fprintf(fidTeX,'\\includegraphics[width=0.8\\textwidth]{%s}\n',strrep([dirname,'/',fig_nam_],'\','/'));
+        fprintf(fidTeX,'\\caption{%s.}',figtitle_tex);
+        fprintf(fidTeX,'\\label{Fig:%s}\n',fig_nam_);
+        fprintf(fidTeX,'\\end{figure}\n\n');
+        fprintf(fidTeX,'%% End Of TeX file. \n');
+        fclose(fidTeX);
+    end
 end
\ No newline at end of file
diff --git a/matlab/gsa/scatter_plots.m b/matlab/gsa/scatter_plots.m
new file mode 100644
index 0000000000000000000000000000000000000000..f9cf1fa4c45c27dba876a23951ca0a5baa646a5a
--- /dev/null
+++ b/matlab/gsa/scatter_plots.m
@@ -0,0 +1,189 @@
+function scatter_plots(X,xp,vnames,plotsymbol, fnam, dirname, figtitle, xparam1, DynareOptions)
+%
+% Written by Marco Ratto
+% Joint Research Centre, The European Commission,
+% marco.ratto@ec.europa.eu
+%
+
+% Copyright (C) 2017 European Commission
+% Copyright (C) 2017 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/>.
+
+% PURPOSE: Pairwise scatter plots of the columns of x and y after
+% Monte Carlo filtering
+%---------------------------------------------------
+% USAGE:    scatter_mcf(x,y,vnames,pltsym,diagon)
+%        or scatter_mcf(x,y) which relies on defaults
+% where:
+%        x = an nxk matrix with columns containing behavioural sample
+%        y = an mxk matrix with columns containing non-behavioural sample
+%   vnames = a vector of variable names
+%            (default = numeric labels 1,2,3 etc.)
+%   pltsym = a plt symbol
+%            (default = '.' for npts > 100, 'o' for npts < 100
+
+
+[n,p] = size(X);
+% X = X - ones(n,1)*min(Z);
+% X = X ./ (ones(n,1)*max(Z));
+
+nflag = 0;
+if nargin >=3
+    nflag = 1;
+end
+
+if nargin<4 || isempty(plotsymbol)
+    if n*p<100, plotsymbol = 'o';
+    else plotsymbol = '.';
+    end
+end
+
+if nargin<5 || isempty(fnam)
+    fnam='scatter_plot';
+end
+if nargin<6 || isempty(dirname)
+    dirname='';
+    nograph=1;
+    DynareOptions.nodisplay=0;
+else
+    nograph=0;
+end
+if nargin<7 || isempty(figtitle)
+    figtitle=fnam;
+end
+if nargin<8
+    xparam1=[];
+end
+
+figtitle_tex=strrep(figtitle,'_','\_');
+
+fig_nam_=[fnam];
+
+hh=dyn_figure(DynareOptions.nodisplay,'name',figtitle);
+set(hh,'userdata',{X,xp})
+
+bf = 0.1;
+ffs = 0.05/(p-1);
+ffl = (1-2*bf-0.05)/p;
+if p>1
+    fL = linspace(bf,1-bf+ffs,p+1);
+else
+    fL = bf;
+end
+for i = 1:p
+    for j = 1:p
+        h = axes('position',[fL(i),fL(p+1-j),ffl,ffl]);
+        if i==j
+            h1=cumplot(X(:,j));
+            set(h,'Tag','cumplot')
+            %             set(h1,'color',[0 0 1], 'linestyle','--','LineWidth',1.5)
+            set(h1,'color',[0 0 1],'LineWidth',1.5)
+            if ~isempty(xparam1)
+                hold on, plot(xparam1([j j]),[0 1],'k--')
+            end
+            if j<p
+                set(gca,'XTickLabel',[],'XTick',[]);
+            else
+                grid off
+            end
+            set(gca,'YTickLabel',[],'YTick',[]);
+        else
+            if j>i
+                plot(X(:,i),X(:,j),[plotsymbol,'b'])
+            else
+                plot(X(:,i),X(:,j),[plotsymbol,'b'])
+            end
+            set(h,'Tag','scatter')
+
+            %%
+            if ~isoctave
+                % Define a context menu; it is not attached to anything
+                hcmenu = uicontextmenu('Callback','pick','Tag','Run viewer');
+                % Define callbacks for context menu
+                % items that change linestyle
+                hcb1 = 'scatter_callback';
+                % hcb2 = ['set(gco,''LineStyle'','':'')'];
+                % hcb3 = ['set(gco,''LineStyle'',''-'')'];
+                % % Define the context menu items and install their callbacks
+                item1 = uimenu(hcmenu,'Label','save','Callback',hcb1,'Tag','save params');
+                item2 = uimenu(hcmenu,'Label','eval','Callback',hcb1,'Tag','eval params');
+                % item3 = uimenu(hcmenu,'Label','solid','Callback',hcb3);
+                % Locate line objects
+                hlines = findall(h,'Type','line');
+                % Attach the context menu to each line
+                for line = 1:length(hlines)
+                    set(hlines(line),'uicontextmenu',hcmenu)
+                end
+            end
+            %%
+            if ~isempty(xparam1)
+                hold on, plot(xparam1(i),xparam1(j),'s','MarkerFaceColor',[0 0.75 0],'MarkerEdgeColor',[0 0.75 0])
+            end
+            hold off;
+            %             axis([-0.1 1.1 -0.1 1.1])
+            if i<p
+                set(gca,'YTickLabel',[],'YTick',[]);
+            else
+                set(gca,'yaxislocation','right');
+            end
+            if j<p
+                set(gca,'XTickLabel',[],'XTick',[]);
+            end
+        end
+        if nflag == 1
+            set(gca,'fontsize',9);
+        end
+        if i==1
+            if nflag == 1
+                ylabel(vnames(j,:),'Rotation',45,'interpreter','none', ...
+                       'HorizontalAlignment','right','VerticalAlignment','middle');
+            else
+                ylabel([num2str(j),' '],'Rotation',90)
+            end
+        end
+        if j==1
+            if nflag == 1
+                title(vnames(i,:),'interpreter','none','Rotation',45, ...
+                      'HorizontalAlignment','left','VerticalAlignment','bottom')
+            else
+                title(num2str(i))
+            end
+        end
+        drawnow
+    end
+end
+% if ~isoctave
+%     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
+    dyn_saveas(hh,[dirname,filesep,fig_nam_],DynareOptions.nodisplay,DynareOptions.graph_format);
+    if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
+        fidTeX = fopen([dirname,'/',fig_nam_ '.tex'],'w');
+        fprintf(fidTeX,'%% TeX eps-loader file generated by scatter_plots.m (Dynare).\n');
+        fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
+        fprintf(fidTeX,'\\begin{figure}[H]\n');
+        fprintf(fidTeX,'\\centering \n');
+        fprintf(fidTeX,'\\includegraphics[width=0.8\\textwidth]{%s}\n',strrep([dirname,'/',fig_nam_],'\','/'));
+        fprintf(fidTeX,'\\caption{%s.}',figtitle_tex);
+        fprintf(fidTeX,'\\label{Fig:%s}\n',fig_nam_);
+        fprintf(fidTeX,'\\end{figure}\n\n');
+        fprintf(fidTeX,'%% End Of TeX file. \n');
+        fclose(fidTeX);
+    end
+end
\ No newline at end of file
diff --git a/matlab/gsa/set_shocks_param.m b/matlab/gsa/set_shocks_param.m
index 8902dfb102cd06f01a5830788cd4a25d0ecad8e4..69c12fdbbcaa7d0fc03010273f3305adff9fe175 100644
--- a/matlab/gsa/set_shocks_param.m
+++ b/matlab/gsa/set_shocks_param.m
@@ -2,7 +2,7 @@ function set_shocks_param(xparam1)
 % function set_shocks_param(xparam1)
 % Set the structural and measurement error variances and covariances
 
-% Copyright (C) 2012-2015 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -67,7 +67,7 @@ if ncx
 end
 %build covariance matrix from correlation matrix and variances already on
 %diagonal
-Sigma_e = diag(sqrt(diag(Sigma_e)))*Correlation_matrix*diag(sqrt(diag(Sigma_e))); 
+Sigma_e = diag(sqrt(diag(Sigma_e)))*Correlation_matrix*diag(sqrt(diag(Sigma_e)));
 %if calibrated covariances, set them now to their stored value
 if isfield(estim_params_,'calibrated_covariances')
     Sigma_e(estim_params_.calibrated_covariances.position)=estim_params_.calibrated_covariances.cov_value;
@@ -93,7 +93,7 @@ if isfield(estim_params_,'calibrated_covariances_ME')
     H(estim_params_.calibrated_covariances_ME.position)=estim_params_.calibrated_covariances_ME.cov_value;
 end
 
-  
+
 % updating matrices in M
 if nvx || ncx
     M_.Sigma_e = Sigma_e;
@@ -101,5 +101,5 @@ if nvx || ncx
 end
 if nvn || ncn
     M_.H = H;
-    M_.Correlation_matrix_ME=Correlation_matrix_ME;    
-end 
\ No newline at end of file
+    M_.Correlation_matrix_ME=Correlation_matrix_ME;
+end
\ No newline at end of file
diff --git a/matlab/gsa/smirnov.m b/matlab/gsa/smirnov.m
index 9568d1e9605eb577452b9afca21d684cfa8cd809..11dd4df7dfb328f599d8f01b0c0fbe60ebeac50b 100644
--- a/matlab/gsa/smirnov.m
+++ b/matlab/gsa/smirnov.m
@@ -4,13 +4,10 @@ function [H,prob,d] = smirnov(x1 , x2 , alpha, iflag )
 %
 % Written by Marco Ratto
 % Joint Research Centre, The European Commission,
-% (http://eemc.jrc.ec.europa.eu/),
-% marco.ratto@jrc.it 
-%
-% Reference:
-% M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006.
+% marco.ratto@ec.europa.eu
 
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012 European Commission
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -30,7 +27,7 @@ function [H,prob,d] = smirnov(x1 , x2 , alpha, iflag )
 if nargin<3
     alpha  =  0.05;
 end
-if nargin<4,
+if nargin<4
     iflag=0;
 end
 
@@ -55,7 +52,7 @@ n =  n1*n2 /(n1+n2);
 
 % Compute the d(n1,n2) statistics.
 
-if iflag==0,
+if iflag==0
     d  =  max(abs(cum1 - cum2));
 elseif iflag==-1
     d  =  max(cum2 - cum1);
@@ -67,10 +64,10 @@ end
 %
 
 lam =  max((sqrt(n) + 0.12 + 0.11/sqrt(n)) * d , 0);
-if iflag == 0        
+if iflag == 0
     j       =  [1:101]';
     prob  =  2 * sum((-1).^(j-1).*exp(-2*lam*lam*j.^2));
-    
+
     prob=max(prob,0);
     prob=min(1,prob);
 else
diff --git a/matlab/gsa/stab_map_.m b/matlab/gsa/stab_map_.m
index f6e6d1eeb40cf8608ca38be3a17c986b90d956d6..52f8d158806d980ab25eedda0edec2b3d8493998 100644
--- a/matlab/gsa/stab_map_.m
+++ b/matlab/gsa/stab_map_.m
@@ -32,13 +32,10 @@ function x0 = stab_map_(OutputDirectoryName,opt_gsa)
 %
 % Written by Marco Ratto
 % Joint Research Centre, The European Commission,
-% (http://eemc.jrc.ec.europa.eu/),
-% marco.ratto@jrc.it
-%
-% Reference:
-% M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006.
+% marco.ratto@ec.europa.eu
 
-% Copyright (C) 2012-2016 Dynare Team
+% Copyright (C) 2012-2016 European Commission
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -62,7 +59,6 @@ global bayestopt_ estim_params_ options_ oo_ M_
 
 Nsam   = opt_gsa.Nsam;
 fload  = opt_gsa.load_stab;
-ksstat = opt_gsa.ksstat;
 alpha2 = opt_gsa.alpha2_stab;
 pvalue_ks = opt_gsa.pvalue_ks;
 pvalue_corr = opt_gsa.pvalue_corr;
@@ -103,8 +99,8 @@ if ~isempty(bayestopt_) && any(bayestopt_.pshape > 0)
     bounds.lb = max(bounds.lb,lb);
     bounds.ub = min(bounds.ub,ub);
 else  % estimated parameters but no declared priors
-    % No priors are declared so Dynare will estimate the model by
-    % maximum likelihood with inequality constraints for the parameters.
+      % No priors are declared so Dynare will estimate the model by
+      % maximum likelihood with inequality constraints for the parameters.
     bounds.lb = lb;
     bounds.ub = ub;
     if opt_gsa.prior_range==0
@@ -113,7 +109,7 @@ else  % estimated parameters but no declared priors
     end
 end
 
-if nargin==0,
+if nargin==0
     OutputDirectoryName='';
 end
 
@@ -123,7 +119,7 @@ options_mcf.alpha2 = alpha2;
 
 name=cell(np,1);
 name_tex=cell(np,1);
-for jj=1:np        
+for jj=1:np
     if options_.TeX
         [param_name_temp, param_name_tex_temp]= get_the_name(nshock+jj,options_.TeX,M_,estim_params_,options_);
         name_tex{jj,1} = strrep(param_name_tex_temp,'$','');
@@ -147,12 +143,12 @@ options_.periods=0;
 options_.nomoments=1;
 options_.irf=0;
 options_.noprint=1;
-if fload==0,
+if fload==0
     %   if prepSA
     %     T=zeros(size(dr_.ghx,1),size(dr_.ghx,2)+size(dr_.ghu,2),Nsam/2);
     %   end
 
-    if isfield(dr_,'ghx'),
+    if isfield(dr_,'ghx')
         egg=zeros(length(dr_.eigval),Nsam);
     end
     yys=zeros(length(dr_.ys),Nsam);
@@ -163,20 +159,20 @@ if fload==0,
         Nsam=size(lpmat,1);
         lpmat0 = lpmat(:,1:nshock);
         lpmat = lpmat(:,nshock+1:end);
-%     elseif opt_gsa.morris==3,
-%         lpmat = prep_ide(Nsam,np,5);
-%         Nsam=size(lpmat,1);
+        %     elseif opt_gsa.morris==3,
+        %         lpmat = prep_ide(Nsam,np,5);
+        %         Nsam=size(lpmat,1);
     else
-        if np<52 && ilptau>0,
+        if np<52 && ilptau>0
             [lpmat] = qmc_sequence(np, int64(1), 0, Nsam)';
-            if np>30 || ilptau==2, % scrambled lptau
-                for j=1:np,
+            if np>30 || ilptau==2 % scrambled lptau
+                for j=1:np
                     lpmat(:,j)=lpmat(randperm(Nsam),j);
                 end
             end
         else %ilptau==0
             [lpmat] = NaN(Nsam,np);
-            for j=1:np,
+            for j=1:np
                 lpmat(:,j) = randperm(Nsam)'./(Nsam+1); %latin hypercube
             end
 
@@ -184,17 +180,17 @@ if fload==0,
     end
     %   try
     dummy=prior_draw_gsa(1); %initialize persistent variables
-    %   catch
-    %     if pprior,
-    %       if opt_gsa.prior_range==0;
-    %         error('Some unknown prior is specified or ML estimation,: use prior_range=1 option!!');
-    %       end
-    %     end
-    %
-    %   end
-    if pprior,
-        for j=1:nshock,
-            if opt_gsa.morris~=1,
+                             %   catch
+                             %     if pprior,
+                             %       if opt_gsa.prior_range==0;
+                             %         error('Some unknown prior is specified or ML estimation,: use prior_range=1 option!!');
+                             %       end
+                             %     end
+                             %
+                             %   end
+    if pprior
+        for j=1:nshock
+            if opt_gsa.morris~=1
                 lpmat0(:,j) = randperm(Nsam)'./(Nsam+1); %latin hypercube
             end
             if opt_gsa.prior_range
@@ -208,7 +204,7 @@ if fload==0,
             %           xdelt(:,:,j)=prior_draw_gsa(0,[lpmat0 lpmat]+deltx);
             %         end
             %       end
-            for j=1:np,
+            for j=1:np
                 lpmat(:,j)=lpmat(:,j).*(bounds.ub(j+nshock)-bounds.lb(j+nshock))+bounds.lb(j+nshock);
             end
         else
@@ -258,24 +254,24 @@ if fload==0,
         %             end
         %         end
         %load([fname_,'_mode'])
-        if neighborhood_width>0 && isempty(options_.mode_file),
+        if neighborhood_width>0 && isempty(options_.mode_file)
             xparam1 = get_all_parameters(estim_params_,M_);
         else
-        eval(['load ' options_.mode_file '.mat;']);
+            eval(['load ' options_.mode_file '.mat;']);
         end
-        if neighborhood_width>0,
-            for j=1:nshock,
+        if neighborhood_width>0
+            for j=1:nshock
                 if opt_gsa.morris ~= 1
-                   lpmat0(:,j) = randperm(Nsam)'./(Nsam+1); %latin hypercube
+                    lpmat0(:,j) = randperm(Nsam)'./(Nsam+1); %latin hypercube
                 end
                 ub=min([bounds.ub(j) xparam1(j)*(1+neighborhood_width)]);
                 lb=max([bounds.lb(j) xparam1(j)*(1-neighborhood_width)]);
                 lpmat0(:,j)=lpmat0(:,j).*(ub-lb)+lb;
             end
-            for j=1:np,
+            for j=1:np
                 ub=xparam1(j+nshock)*(1+sign(xparam1(j+nshock))*neighborhood_width);
                 lb=xparam1(j+nshock)*(1-sign(xparam1(j+nshock))*neighborhood_width);
-                if bounds.ub(j+nshock)>=xparam1(j) && bounds.lb(j)<=xparam1(j+nshock),
+                if bounds.ub(j+nshock)>=xparam1(j) && bounds.lb(j)<=xparam1(j+nshock)
                     ub=min([bounds.ub(j+nshock) ub]);
                     lb=max([bounds.lb(j+nshock) lb]);
                 else
@@ -287,7 +283,7 @@ if fload==0,
             d = chol(inv(hh));
             lp=randn(Nsam*2,nshock+np)*d+kron(ones(Nsam*2,1),xparam1');
             lnprior=zeros(1,Nsam*2);
-            for j=1:Nsam*2,
+            for j=1:Nsam*2
                 lnprior(j) = any(lp(j,:)'<=bounds.lb | lp(j,:)'>=bounds.ub);
             end
             ireal=[1:2*Nsam];
@@ -309,7 +305,7 @@ if fload==0,
     inorestriction=zeros(1,Nsam);
     irestriction=zeros(1,Nsam);
     infox=zeros(Nsam,1);
-    for j=1:Nsam,
+    for j=1:Nsam
         M_ = set_all_parameters([lpmat0(j,:) lpmat(j,:)]',estim_params_,M_);
         %try stoch_simul([]);
         try
@@ -319,14 +315,14 @@ if fload==0,
                 [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','var'),
+            if infox(j,1)==0 && ~exist('T','var')
                 dr_=oo_.dr;
-                if prepSA,
+                if prepSA
                     try
                         T=zeros(size(dr_.ghx,1),size(dr_.ghx,2)+size(dr_.ghu,2),Nsam);
                     catch
                         ME = lasterror();
-                        if strcmp('MATLAB:nomem',ME.identifier),
+                        if strcmp('MATLAB:nomem',ME.identifier)
                             prepSA=0;
                             disp('The model is too large for storing state space matrices ...')
                             disp('for mapping reduced form or for identification')
@@ -338,26 +334,26 @@ if fload==0,
                 end
                 egg=zeros(length(dr_.eigval),Nsam);
             end
-            if infox(j,1),
-%                 disp('no solution'),
-                if isfield(oo_.dr,'ghx'),
+            if infox(j,1)
+                %                 disp('no solution'),
+                if isfield(oo_.dr,'ghx')
                     oo_.dr=rmfield(oo_.dr,'ghx');
                 end
-                if (infox(j,1)<3 || infox(j,1)>5) && isfield(oo_.dr,'eigval'),
+                if (infox(j,1)<3 || infox(j,1)>5) && isfield(oo_.dr,'eigval')
                     oo_.dr=rmfield(oo_.dr,'eigval');
                 end
             end
         catch ME
-            if isfield(oo_.dr,'eigval'),
+            if isfield(oo_.dr,'eigval')
                 oo_.dr=rmfield(oo_.dr,'eigval');
             end
-            if isfield(oo_.dr,'ghx'),
+            if isfield(oo_.dr,'ghx')
                 oo_.dr=rmfield(oo_.dr,'ghx');
             end
-            disp('No solution could be found'),
+            disp('No solution could be found')
         end
         dr_ = oo_.dr;
-        if isfield(dr_,'ghx'),
+        if isfield(dr_,'ghx')
             egg(:,j) = sort(dr_.eigval);
             if prepSA
                 jstab=jstab+1;
@@ -367,14 +363,14 @@ if fload==0,
                 %           bayestopt_.restrict_columns, ...
                 %           bayestopt_.restrict_aux);
             end
-            if ~exist('nspred','var'),
+            if ~exist('nspred','var')
                 nspred = dr_.nspred; %size(dr_.ghx,2);
                 nboth = dr_.nboth;
                 nfwrd = dr_.nfwrd;
             end
             info=endogenous_prior_restrictions(Tt,Rr,M_,options_,oo_);
             infox(j,1)=info(1);
-            if info(1),
+            if info(1)
                 inorestriction(j)=j;
             else
                 iunstable(j)=0;
@@ -388,13 +384,13 @@ if fload==0,
                     if any(isnan(egg(1:nspred,j)))
                         iwrong(j)=j;
                     else
-                        if (nboth || nfwrd) && abs(egg(nspred+1,j))<=options_.qz_criterium,
+                        if (nboth || nfwrd) && abs(egg(nspred+1,j))<=options_.qz_criterium
                             iindeterm(j)=j;
                         end
                     end
                 end
             else
-                if exist('egg','var'),
+                if exist('egg','var')
                     egg(:,j)=ones(size(egg,1),1).*NaN;
                 end
                 iwrong(j)=j;
@@ -406,7 +402,7 @@ if fload==0,
         dyn_waitbar(j/Nsam,h,['MC iteration ',int2str(j),'/',int2str(Nsam)])
     end
     dyn_waitbar_close(h);
-    if prepSA && jstab,
+    if prepSA && jstab
         T=T(:,:,1:jstab);
     else
         T=[];
@@ -458,42 +454,42 @@ if fload==0,
     bkpprior.p2=bayestopt_.p2;
     bkpprior.p3=bayestopt_.p3;
     bkpprior.p4=bayestopt_.p4;
-    if pprior,
+    if pprior
         if ~prepSA
             save([OutputDirectoryName filesep fname_ '_prior.mat'], ...
-                'bkpprior','lpmat','lpmat0','irestriction','iunstable','istable','iindeterm','iwrong','ixun', ...
-                'egg','yys','nspred','nboth','nfwrd','infox')
+                 'bkpprior','lpmat','lpmat0','irestriction','iunstable','istable','iindeterm','iwrong','ixun', ...
+                 'egg','yys','nspred','nboth','nfwrd','infox')
         else
             save([OutputDirectoryName filesep fname_ '_prior.mat'], ...
-                'bkpprior','lpmat','lpmat0','irestriction','iunstable','istable','iindeterm','iwrong','ixun', ...
-                'egg','yys','T','nspred','nboth','nfwrd','infox')
+                 'bkpprior','lpmat','lpmat0','irestriction','iunstable','istable','iindeterm','iwrong','ixun', ...
+                 'egg','yys','T','nspred','nboth','nfwrd','infox')
         end
 
     else
         if ~prepSA
             save([OutputDirectoryName filesep fname_ '_mc.mat'], ...
-                'lpmat','lpmat0','irestriction','iunstable','istable','iindeterm','iwrong','ixun', ...
-                'egg','yys','nspred','nboth','nfwrd','infox')
+                 'lpmat','lpmat0','irestriction','iunstable','istable','iindeterm','iwrong','ixun', ...
+                 'egg','yys','nspred','nboth','nfwrd','infox')
         else
             save([OutputDirectoryName filesep fname_ '_mc.mat'], ...
-                'lpmat','lpmat0','irestriction','iunstable','istable','iindeterm','iwrong','ixun', ...
-                'egg','yys','T','nspred','nboth','nfwrd','infox')
+                 'lpmat','lpmat0','irestriction','iunstable','istable','iindeterm','iwrong','ixun', ...
+                 'egg','yys','T','nspred','nboth','nfwrd','infox')
         end
     end
 else
-    if pprior,
+    if pprior
         filetoload=[OutputDirectoryName filesep fname_ '_prior.mat'];
     else
         filetoload=[OutputDirectoryName filesep fname_ '_mc.mat'];
     end
     load(filetoload,'lpmat','lpmat0','irestriction','iunstable','istable','iindeterm','iwrong','ixun','egg','yys','nspred','nboth','nfwrd','infox')
     Nsam = size(lpmat,1);
-    if pprior==0 && ~isempty(options_.mode_file),
+    if pprior==0 && ~isempty(options_.mode_file)
         eval(['load ' options_.mode_file '.mat;']);
     end
 
 
-    if prepSA && isempty(strmatch('T',who('-file', filetoload),'exact')),
+    if prepSA && isempty(strmatch('T',who('-file', filetoload),'exact'))
         h = dyn_waitbar(0,'Please wait...');
         options_.periods=0;
         options_.nomoments=1;
@@ -503,7 +499,7 @@ else
         %T=zeros(size(dr_.ghx,1),size(dr_.ghx,2)+size(dr_.ghu,2),length(istable));
         ntrans=length(istable);
         yys=NaN(length(ys_),ntrans);
-        for j=1:ntrans,
+        for j=1:ntrans
             M_.params(estim_params_.param_vals(:,1)) = lpmat(istable(j),:)';
             %stoch_simul([]);
             [Tt,Rr,SteadyState,info,M_,options_,oo_] = dynare_resolve(M_,options_,oo_,'restrict');
@@ -552,51 +548,51 @@ delete([OutputDirectoryName,filesep,fname_,'_',aindname,'.*']);
 delete([OutputDirectoryName,filesep,fname_,'_',aunstname,'.*']);
 delete([OutputDirectoryName,filesep,fname_,'_',awrongname,'.*']);
 
-if length(iunstable)>0 || length(iwrong)>0,
+if length(iunstable)>0 || length(iwrong)>0
     fprintf(['%4.1f%% of the prior support gives unique saddle-path solution.\n'],length(istable)/Nsam*100)
     fprintf(['%4.1f%% of the prior support gives explosive dynamics.\n'],(length(ixun) )/Nsam*100)
-    if ~isempty(iindeterm),
+    if ~isempty(iindeterm)
         fprintf(['%4.1f%% of the prior support gives indeterminacy.\n'],length(iindeterm)/Nsam*100)
     end
     inorestriction = istable(find(~ismember(istable,irestriction))); % violation of prior restrictions
-    if ~isempty(iwrong) || ~isempty(inorestriction),
+    if ~isempty(iwrong) || ~isempty(inorestriction)
         skipline()
-        if any(infox==49),
+        if any(infox==49)
             fprintf(['%4.1f%% of the prior support violates prior restrictions.\n'],(length(inorestriction) )/Nsam*100)
         end
-        if ~isempty(iwrong),
+        if ~isempty(iwrong)
             skipline()
             disp(['For ',num2str(length(iwrong)/Nsam*100,'%4.1f'),'% of the prior support dynare could not find a solution.'])
             skipline()
         end
-        if any(infox==1),
+        if any(infox==1)
             disp(['    For ',num2str(length(find(infox==1))/Nsam*100,'%4.1f'),'% The model doesn''t determine the current variables uniquely.'])
         end
-        if any(infox==2),
+        if any(infox==2)
             disp(['    For ',num2str(length(find(infox==2))/Nsam*100,'%4.1f'),'% MJDGGES returned an error code.'])
         end
-        if any(infox==6),
+        if any(infox==6)
             disp(['    For ',num2str(length(find(infox==6))/Nsam*100,'%4.1f'),'% The jacobian evaluated at the deterministic steady state is complex.'])
         end
-        if any(infox==19),
+        if any(infox==19)
             disp(['    For ',num2str(length(find(infox==19))/Nsam*100,'%4.1f'),'% The steadystate routine thrown an exception (inconsistent deep parameters).'])
         end
-        if any(infox==20),
+        if any(infox==20)
             disp(['    For ',num2str(length(find(infox==20))/Nsam*100,'%4.1f'),'% Cannot find the steady state.'])
         end
-        if any(infox==21),
+        if any(infox==21)
             disp(['    For ',num2str(length(find(infox==21))/Nsam*100,'%4.1f'),'% The steady state is complex.'])
         end
-        if any(infox==22),
+        if any(infox==22)
             disp(['    For ',num2str(length(find(infox==22))/Nsam*100,'%4.1f'),'% The steady has NaNs.'])
         end
-        if any(infox==23),
+        if any(infox==23)
             disp(['    For ',num2str(length(find(infox==23))/Nsam*100,'%4.1f'),'% M_.params has been updated in the steadystate routine and has complex valued scalars.'])
         end
-        if any(infox==24),
+        if any(infox==24)
             disp(['    For ',num2str(length(find(infox==24))/Nsam*100,'%4.1f'),'% M_.params has been updated in the steadystate routine and has some NaNs.'])
         end
-        if any(infox==30),
+        if any(infox==30)
             disp(['    For ',num2str(length(find(infox==30))/Nsam*100,'%4.1f'),'% Ergodic variance can''t be computed.'])
         end
 
@@ -605,8 +601,8 @@ if length(iunstable)>0 || length(iwrong)>0,
     if length(iunstable)<Nsam || length(istable)>1
         itot = [1:Nsam];
         isolve = itot(find(~ismember(itot,iwrong))); % dynare could find a solution
-        % Blanchard Kahn
-        if neighborhood_width,
+                                                     % Blanchard Kahn
+        if neighborhood_width
             options_mcf.xparam1 = xparam1(nshock+1:end);
         end
         itmp = itot(find(~ismember(itot,istable)));
@@ -617,7 +613,7 @@ if length(iunstable)>0 || length(iwrong)>0,
         options_mcf.title = 'unique solution';
         mcf_analysis(lpmat, istable, itmp, options_mcf, options_);
 
-        if ~isempty(iindeterm),
+        if ~isempty(iindeterm)
             itmp = isolve(find(~ismember(isolve,iindeterm)));
             options_mcf.amcf_name = aindname;
             options_mcf.amcf_title = aindtitle;
@@ -626,8 +622,8 @@ if length(iunstable)>0 || length(iwrong)>0,
             options_mcf.title = 'indeterminacy';
             mcf_analysis(lpmat, itmp, iindeterm, options_mcf, options_);
         end
-        
-        if ~isempty(ixun),
+
+        if ~isempty(ixun)
             itmp = isolve(find(~ismember(isolve,ixun)));
             options_mcf.amcf_name = aunstname;
             options_mcf.amcf_title = aunsttitle;
@@ -636,10 +632,10 @@ if length(iunstable)>0 || length(iwrong)>0,
             options_mcf.title = 'instability';
             mcf_analysis(lpmat, itmp, ixun, options_mcf, options_);
         end
-        
+
         inorestriction = istable(find(~ismember(istable,irestriction))); % violation of prior restrictions
         iwrong = iwrong(find(~ismember(iwrong,inorestriction))); % what went wrong beyond prior restrictions
-        if ~isempty(iwrong),
+        if ~isempty(iwrong)
             itmp = itot(find(~ismember(itot,iwrong)));
             options_mcf.amcf_name = awrongname;
             options_mcf.amcf_title = awrongtitle;
@@ -648,9 +644,9 @@ if length(iunstable)>0 || length(iwrong)>0,
             options_mcf.title = 'inability to find a solution';
             mcf_analysis(lpmat, itmp, iwrong, options_mcf, options_);
         end
-        
-        if ~isempty(irestriction),
-            if neighborhood_width,
+
+        if ~isempty(irestriction)
+            if neighborhood_width
                 options_mcf.xparam1 = xparam1;
             end
             np=size(bayestopt_.name,1);
@@ -683,7 +679,7 @@ if length(iunstable)>0 || length(iwrong)>0,
             x0=0.5.*(bounds.ub(1:nshock)-bounds.lb(1:nshock))+bounds.lb(1:nshock);
             x0 = [x0; lpmat(iok,:)'];
         end
-        
+
         M_ = set_all_parameters(x0,estim_params_,M_);
         [oo_.dr,info,M_,options_,oo_] = resol(0,M_,options_,oo_);
         %     stoch_simul([]);
@@ -703,12 +699,8 @@ xparam1=x0;
 save prior_ok.mat xparam1;
 
 options_.periods=opt.periods;
-if isfield(opt,'nomoments'),
+if isfield(opt,'nomoments')
     options_.nomoments=opt.nomoments;
 end
 options_.irf=opt.irf;
 options_.noprint=opt.noprint;
-
-
-
-
diff --git a/matlab/gsa/stab_map_1.m b/matlab/gsa/stab_map_1.m
index a5818dd2cb83a30da78a663cfdacc3c78f0582d8..092b50daa439d85b5bb12a17df1739ad0d44e7c0 100644
--- a/matlab/gsa/stab_map_1.m
+++ b/matlab/gsa/stab_map_1.m
@@ -8,7 +8,7 @@ function [proba, dproba] = stab_map_1(lpmat, ibehaviour, inonbehaviour, aname, i
 % iplot = 1 plot cumulative distributions (default)
 % iplot = 0 no plots
 % ipar = index array of parameters to plot
-% dirname = (OPTIONAL) path of the directory where to save 
+% dirname = (OPTIONAL) path of the directory where to save
 %            (default: current directory)
 % pcrit = (OPTIONAL) critical value of the pvalue below which show the plots
 %
@@ -18,13 +18,10 @@ function [proba, dproba] = stab_map_1(lpmat, ibehaviour, inonbehaviour, aname, i
 %
 % Written by Marco Ratto
 % Joint Research Centre, The European Commission,
-% (http://eemc.jrc.ec.europa.eu/),
-% marco.ratto@jrc.it 
-%
-% Reference:
-% M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006.
+% marco.ratto@ec.europa.eu
 
-% Copyright (C) 2012-2016 Dynare Team
+% Copyright (C) 2012-2016 European Commission
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -43,15 +40,15 @@ function [proba, dproba] = stab_map_1(lpmat, ibehaviour, inonbehaviour, aname, i
 
 global estim_params_ bayestopt_ M_ options_
 
-if nargin<5,
-  iplot=1;
+if nargin<5
+    iplot=1;
 end
 fname_ = M_.fname;
-if nargin<7,
-  dirname='';
+if nargin<7
+    dirname='';
 end
 if nargin<9,
-  atitle=aname;
+    atitle=aname;
 end
 
 nshock = estim_params_.nvx;
@@ -62,46 +59,46 @@ nshock = nshock + estim_params_.ncn;
 npar=size(lpmat,2);
 ishock= npar>estim_params_.np;
 
-if nargin<6,
-  ipar=[];
+if nargin<6
+    ipar=[];
 end
-if nargin<8 || isempty(pcrit),
-  pcrit=1;
+if nargin<8 || isempty(pcrit)
+    pcrit=1;
 end
 
-% Smirnov test for Blanchard; 
-for j=1:npar,
-  [H,P,KSSTAT] = smirnov(lpmat(ibehaviour,j),lpmat(inonbehaviour,j));
-  proba(j)=P;
-  dproba(j)=KSSTAT;
+% Smirnov test for Blanchard;
+for j=1:npar
+    [H,P,KSSTAT] = smirnov(lpmat(ibehaviour,j),lpmat(inonbehaviour,j));
+    proba(j)=P;
+    dproba(j)=KSSTAT;
 end
-if isempty(ipar),
-%     ipar=find(dproba>dcrit);
+if isempty(ipar)
+    %     ipar=find(dproba>dcrit);
     ipar=find(proba<pcrit);
 end
 nparplot=length(ipar);
 if iplot && ~options_.nograph
     lpmat=lpmat(:,ipar);
     ftit=bayestopt_.name(ipar+nshock*(1-ishock));
-    
-    for i=1:ceil(nparplot/12),
-        hh=dyn_figure(options_,'name',atitle);
-        for j=1+12*(i-1):min(nparplot,12*i),
+
+    for i=1:ceil(nparplot/12)
+        hh=dyn_figure(options_.nodisplay,'name',atitle);
+        for j=1+12*(i-1):min(nparplot,12*i)
             subplot(3,4,j-12*(i-1))
-            if ~isempty(ibehaviour),
+            if ~isempty(ibehaviour)
                 h=cumplot(lpmat(ibehaviour,j));
                 set(h,'color',[0 0 1], 'linestyle',':','LineWidth',1.5)
             end
-            hold on,
-            if ~isempty(inonbehaviour),
+            hold on
+            if ~isempty(inonbehaviour)
                 h=cumplot(lpmat(inonbehaviour,j));
                 set(h,'color',[0 0 0],'LineWidth',1.5)
             end
             %     title([ftit{j},'. D-stat ', num2str(dproba(ipar(j)),2)],'interpreter','none')
             title([ftit{j},'. p-value ', num2str(proba(ipar(j)),2)],'interpreter','none')
         end
-        if nparplot>12,
-            dyn_saveas(hh,[dirname,filesep,fname_,'_',aname,'_SA_',int2str(i)],options_);
+        if nparplot>12
+            dyn_saveas(hh,[dirname,filesep,fname_,'_',aname,'_SA_',int2str(i)],options_.nodisplay,options_.graph_format);
             if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                 fidTeX = fopen([dirname,filesep,fname_,'_',aname,'_SA_',int2str(i) '.tex'],'w');
                 fprintf(fidTeX,'%% TeX eps-loader file generated by stab_map_1.m (Dynare).\n');
@@ -116,7 +113,7 @@ if iplot && ~options_.nograph
                 fclose(fidTeX);
             end
         else
-            dyn_saveas(hh,[dirname,filesep,fname_,'_',aname,'_SA'],options_);
+            dyn_saveas(hh,[dirname,filesep,fname_,'_',aname,'_SA'],options_.nodisplay,options_.graph_format);
             if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                 fidTeX = fopen([dirname,filesep,fname_,'_',aname,'_SA.tex'],'w');
                 fprintf(fidTeX,'%% TeX eps-loader file generated by stab_map_1.m (Dynare).\n');
diff --git a/matlab/gsa/stab_map_2.m b/matlab/gsa/stab_map_2.m
index c72e4c0a31f1cf3aa2c78ba81cff9276b1d8c0a3..f4b958355e276ed8af63a2cc7d6f53a014d7b788 100644
--- a/matlab/gsa/stab_map_2.m
+++ b/matlab/gsa/stab_map_2.m
@@ -3,14 +3,10 @@ function indcorr = stab_map_2(x,alpha2, pvalue_crit, fnam, dirname,xparam1,figti
 %
 % Written by Marco Ratto
 % Joint Research Centre, The European Commission,
-% (http://eemc.jrc.ec.europa.eu/),
-% marco.ratto@jrc.it 
-%
-% Reference:
-% M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006.
+% marco.ratto@ec.europa.eu
 
-% Copyright (C) 2012-2016 Dynare Team
-%
+% Copyright (C) 2011-2016 European Commission
+% Copyright (C) 2011-2017 Dynare Team
 % This file is part of Dynare.
 %
 % Dynare is free software: you can redistribute it and/or modify
@@ -33,18 +29,18 @@ npar=size(x,2);
 nsam=size(x,1);
 ishock= npar>estim_params_.np;
 nograph = options_.nograph;
-if nargin<4,
-  fnam='';
+if nargin<4
+    fnam='';
 end
-if nargin<5,
-  dirname='';
-  nograph=1;
+if nargin<5
+    dirname='';
+    nograph=1;
 end
-if nargin<6,
-  xparam1=[];
+if nargin<6
+    xparam1=[];
 end
-if nargin<7,
-  figtitle=fnam;
+if nargin<7
+    figtitle=fnam;
 end
 
 ys_ = oo_.dr.ys;
@@ -64,12 +60,12 @@ fig_nam_=strrep(fig_nam_,' ','_');
 ifig=0;
 j2=0;
 if ishock==0
-  npar=estim_params_.np;
-  if ~isempty(xparam1),
-      xparam1=xparam1(nshock+1:end);
-  end
+    npar=estim_params_.np;
+    if ~isempty(xparam1)
+        xparam1=xparam1(nshock+1:end);
+    end
 else
-  npar=estim_params_.np+nshock;
+    npar=estim_params_.np+nshock;
 end
 skipline();
 title_string=['Correlation analysis for ',fnam];
@@ -77,14 +73,14 @@ title_string_tex=['Correlation analysis for ',strrep(fnam,'_','\\_')];
 
 indcorr = [];
 entry_iter=1;
-for j=1:npar,
+for j=1:npar
     i2=find(abs(c00(:,j))>alpha2);
-    if length(i2)>0,
-        for jx=1:length(i2),
-            if pvalue(j,i2(jx))<pvalue_crit,
+    if length(i2)>0
+        for jx=1:length(i2)
+            if pvalue(j,i2(jx))<pvalue_crit
                 indcorr = [indcorr; [j i2(jx)]];
                 j2=j2+1;
-                if ishock,
+                if ishock
                     if options_.TeX
                         [param_name_temp1, param_name_tex_temp1]= get_the_name(j,options_.TeX,M_,estim_params_,options_);
                         param_name_tex_temp1 = strrep(param_name_tex_temp1,'$','');
@@ -116,58 +112,58 @@ for j=1:npar,
                         tmp_name=(['[',param_name_temp1,',',param_name_temp2,']']);
                         name{entry_iter,1}=tmp_name;
                     end
-                end                
+                end
                 data_mat(entry_iter,1)=c0(i2(jx),j);
                 entry_iter=entry_iter+1;
-                
-                if ~nograph,
-                    if mod(j2,12)==1,
-                    ifig=ifig+1;
-                    hh=dyn_figure(options_,'name',[figtitle,' sample bivariate projection ', num2str(ifig)]);
-                end
-                subplot(3,4,j2-(ifig-1)*12)
-                %             bar(c0(i2,j)),
-                %             set(gca,'xticklabel',bayestopt_.name(i2)),
-                %             set(gca,'xtick',[1:length(i2)])
-                %plot(stock_par(ixx(nfilt+1:end,i),j),stock_par(ixx(nfilt+1:end,i),i2(jx)),'.k')
-                %hold on,
-                plot(x(:,j),x(:,i2(jx)),'.')
-                if ~isempty(xparam1)
-                    hold on, plot(xparam1(j),xparam1(i2(jx)),'ro')
-                end
-                %             xlabel(deblank(estim_params_.param_names(j,:)),'interpreter','none'),
-                %             ylabel(deblank(estim_params_.param_names(i2(jx),:)),'interpreter','none'),
-                if ishock,
-                    xlabel(bayestopt_.name{j},'interpreter','none'),
-                    ylabel(bayestopt_.name{i2(jx)},'interpreter','none'),
-                else
-                    xlabel(bayestopt_.name{j+nshock},'interpreter','none'),
-                    ylabel(bayestopt_.name{i2(jx)+nshock},'interpreter','none'),
-                end
-                title(['cc = ',num2str(c0(i2(jx),j))])
-                if (mod(j2,12)==0) && j2>0,
-                    dyn_saveas(hh,[dirname,filesep,fig_nam_,int2str(ifig)],options_);
-                    if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
-                        fidTeX = fopen([dirname,filesep,fig_nam_,int2str(ifig),'.tex'],'w');
-                        fprintf(fidTeX,'%% TeX eps-loader file generated by stab_map_2.m (Dynare).\n');
-                        fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
-                        fprintf(fidTeX,'\\begin{figure}[H]\n');
-                        fprintf(fidTeX,'\\centering \n');
-                        fprintf(fidTeX,'\\includegraphics[width=0.8\\textwidth]{%s}\n',strrep([dirname,'/',fig_nam_,int2str(ifig)],'\','/'));
-                        fprintf(fidTeX,'\\caption{%s.}',[figtitle,' sample bivariate projection ', num2str(ifig)]);
-                        fprintf(fidTeX,'\\label{Fig:%s:%u}\n',fig_nam_,ifig);
-                        fprintf(fidTeX,'\\end{figure}\n\n');
-                        fprintf(fidTeX,'%% End Of TeX file. \n');
-                        fclose(fidTeX);
+
+                if ~nograph
+                    if mod(j2,12)==1
+                        ifig=ifig+1;
+                        hh=dyn_figure(options_.nodisplay,'name',[figtitle,' sample bivariate projection ', num2str(ifig)]);
+                    end
+                    subplot(3,4,j2-(ifig-1)*12)
+                    %             bar(c0(i2,j)),
+                    %             set(gca,'xticklabel',bayestopt_.name(i2)),
+                    %             set(gca,'xtick',[1:length(i2)])
+                    %plot(stock_par(ixx(nfilt+1:end,i),j),stock_par(ixx(nfilt+1:end,i),i2(jx)),'.k')
+                    %hold on,
+                    plot(x(:,j),x(:,i2(jx)),'.')
+                    if ~isempty(xparam1)
+                        hold on, plot(xparam1(j),xparam1(i2(jx)),'ro')
+                    end
+                    %             xlabel(deblank(estim_params_.param_names(j,:)),'interpreter','none'),
+                    %             ylabel(deblank(estim_params_.param_names(i2(jx),:)),'interpreter','none'),
+                    if ishock
+                        xlabel(bayestopt_.name{j},'interpreter','none'),
+                        ylabel(bayestopt_.name{i2(jx)},'interpreter','none'),
+                    else
+                        xlabel(bayestopt_.name{j+nshock},'interpreter','none'),
+                        ylabel(bayestopt_.name{i2(jx)+nshock},'interpreter','none'),
+                    end
+                    title(['cc = ',num2str(c0(i2(jx),j))])
+                    if (mod(j2,12)==0) && j2>0
+                        dyn_saveas(hh,[dirname,filesep,fig_nam_,int2str(ifig)],options_.nodisplay,options_.graph_format);
+                        if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
+                            fidTeX = fopen([dirname,filesep,fig_nam_,int2str(ifig),'.tex'],'w');
+                            fprintf(fidTeX,'%% TeX eps-loader file generated by stab_map_2.m (Dynare).\n');
+                            fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
+                            fprintf(fidTeX,'\\begin{figure}[H]\n');
+                            fprintf(fidTeX,'\\centering \n');
+                            fprintf(fidTeX,'\\includegraphics[width=0.8\\textwidth]{%s}\n',strrep([dirname,'/',fig_nam_,int2str(ifig)],'\','/'));
+                            fprintf(fidTeX,'\\caption{%s.}',[figtitle,' sample bivariate projection ', num2str(ifig)]);
+                            fprintf(fidTeX,'\\label{Fig:%s:%u}\n',fig_nam_,ifig);
+                            fprintf(fidTeX,'\\end{figure}\n\n');
+                            fprintf(fidTeX,'%% End Of TeX file. \n');
+                            fclose(fidTeX);
+                        end
                     end
-                end
                 end
             end
-            
+
         end
     end
-    if ~nograph && (j==(npar)) && j2>0 && (mod(j2,12)~=0),
-        dyn_saveas(hh,[dirname,filesep,fig_nam_,int2str(ifig)],options_);
+    if ~nograph && (j==(npar)) && j2>0 && (mod(j2,12)~=0)
+        dyn_saveas(hh,[dirname,filesep,fig_nam_,int2str(ifig)],options_.nodisplay,options_.graph_format);
         if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
             fidTeX = fopen([dirname,filesep,fig_nam_,int2str(ifig),'.tex'],'w');
             fprintf(fidTeX,'%% TeX eps-loader file generated by stab_map_2.m (Dynare).\n');
@@ -181,10 +177,10 @@ for j=1:npar,
             fprintf(fidTeX,'%% End Of TeX file. \n');
             fclose(fidTeX);
         end
-    end    
+    end
 end
 
-if j2==0,
+if j2==0
     disp(['No correlation term with pvalue <', num2str(pvalue_crit),' and |corr. coef.| >',num2str(alpha2),' found for ',fnam])
 else
     headers=strvcat('Parameters','corrcoef');
diff --git a/matlab/gsa/stand_.m b/matlab/gsa/stand_.m
index 46eb1159849ae78615786dd86037a4f46158ae9f..0a53f1a3b62368f7f3240ed03757698f5180a59a 100644
--- a/matlab/gsa/stand_.m
+++ b/matlab/gsa/stand_.m
@@ -9,10 +9,12 @@ function [y, meany, stdy] = stand_(x)
 % my: Vector of mean values for each column of y
 % sy: Vector of standard deviations for each column of y
 %
-% Author : Marco Ratto
+% Written by Marco Ratto
+% Joint Research Centre, The European Commission,
+% marco.ratto@ec.europa.eu
 
-% Copyright (C) 2012 Dynare Team
-%
+% Copyright (C) 2012 European Commission
+% Copyright (C) 2012-2017 Dynare Team%
 % This file is part of Dynare.
 %
 % Dynare is free software: you can redistribute it and/or modify
@@ -28,13 +30,13 @@ function [y, meany, stdy] = stand_(x)
 % 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==0,
-    return;
+if nargin==0
+    return
 end
 
-for j=1:size(x,2);
-meany(j)=mean(x(find(~isnan(x(:,j))),j));
-stdy(j)=std(x(find(~isnan(x(:,j))),j));
+for j=1:size(x,2)
+    meany(j)=mean(x(find(~isnan(x(:,j))),j));
+    stdy(j)=std(x(find(~isnan(x(:,j))),j));
     y(:,j)=(x(:,j)-meany(j))./stdy(j);
 end
 % end of m-file
\ No newline at end of file
diff --git a/matlab/gsa/tcrit.m b/matlab/gsa/tcrit.m
index 2efd947e646d58c355952ba05f46dc9bfd8c33f5..d65b97a3997f09cfef7c2323137a0edda2a6f557 100644
--- a/matlab/gsa/tcrit.m
+++ b/matlab/gsa/tcrit.m
@@ -1,15 +1,15 @@
 function t_crit = tcrit(n,pval0)
 % function t_crit = tcrit(n,pval0)
 %
-% given the p-value pval0, the function givese the 
-% critical value t_crit of the t-distribution with n degress of freedom 
+% given the p-value pval0, the function givese the
+% critical value t_crit of the t-distribution with n degress of freedom
 %
 % Written by Marco Ratto
 % Joint Research Centre, The European Commission,
-% (http://eemc.jrc.ec.europa.eu/),
-% marco.ratto@jrc.it 
+% marco.ratto@ec.europa.eu
 
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2012 European Commission
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -27,126 +27,126 @@ function t_crit = tcrit(n,pval0)
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 
-if nargin==1 || isempty(pval0),
+if nargin==1 || isempty(pval0)
     pval0=0.05;
 end
-if pval0==1,
+if pval0==1
     t_crit=0;
-    return,
+    return
 end
-if pval0==0,
+if pval0==0
     t_crit=inf;
-    return,
+    return
 end
 pval = [  0.10    0.05   0.025    0.01   0.005   0.001];
 pval0=max(pval0,min(pval));
 ncol=min(find(pval<=pval0))+1;
 
 t_crit=[
-  1      3.078   6.314  12.706  31.821  63.657 318.313
-  2      1.886   2.920   4.303   6.965   9.925  22.327
-  3      1.638   2.353   3.182   4.541   5.841  10.215
-  4      1.533   2.132   2.776   3.747   4.604   7.173
-  5      1.476   2.015   2.571   3.365   4.032   5.893
-  6      1.440   1.943   2.447   3.143   3.707   5.208
-  7      1.415   1.895   2.365   2.998   3.499   4.782
-  8      1.397   1.860   2.306   2.896   3.355   4.499
-  9      1.383   1.833   2.262   2.821   3.250   4.296
- 10      1.372   1.812   2.228   2.764   3.169   4.143
- 11      1.363   1.796   2.201   2.718   3.106   4.024
- 12      1.356   1.782   2.179   2.681   3.055   3.929
- 13      1.350   1.771   2.160   2.650   3.012   3.852
- 14      1.345   1.761   2.145   2.624   2.977   3.787
- 15      1.341   1.753   2.131   2.602   2.947   3.733
- 16      1.337   1.746   2.120   2.583   2.921   3.686
- 17      1.333   1.740   2.110   2.567   2.898   3.646
- 18      1.330   1.734   2.101   2.552   2.878   3.610
- 19      1.328   1.729   2.093   2.539   2.861   3.579
- 20      1.325   1.725   2.086   2.528   2.845   3.552
- 21      1.323   1.721   2.080   2.518   2.831   3.527
- 22      1.321   1.717   2.074   2.508   2.819   3.505
- 23      1.319   1.714   2.069   2.500   2.807   3.485
- 24      1.318   1.711   2.064   2.492   2.797   3.467
- 25      1.316   1.708   2.060   2.485   2.787   3.450
- 26      1.315   1.706   2.056   2.479   2.779   3.435
- 27      1.314   1.703   2.052   2.473   2.771   3.421
- 28      1.313   1.701   2.048   2.467   2.763   3.408
- 29      1.311   1.699   2.045   2.462   2.756   3.396
- 30      1.310   1.697   2.042   2.457   2.750   3.385
- 31      1.309   1.696   2.040   2.453   2.744   3.375
- 32      1.309   1.694   2.037   2.449   2.738   3.365
- 33      1.308   1.692   2.035   2.445   2.733   3.356
- 34      1.307   1.691   2.032   2.441   2.728   3.348
- 35      1.306   1.690   2.030   2.438   2.724   3.340
- 36      1.306   1.688   2.028   2.434   2.719   3.333
- 37      1.305   1.687   2.026   2.431   2.715   3.326
- 38      1.304   1.686   2.024   2.429   2.712   3.319
- 39      1.304   1.685   2.023   2.426   2.708   3.313
- 40      1.303   1.684   2.021   2.423   2.704   3.307
- 41      1.303   1.683   2.020   2.421   2.701   3.301
- 42      1.302   1.682   2.018   2.418   2.698   3.296
- 43      1.302   1.681   2.017   2.416   2.695   3.291
- 44      1.301   1.680   2.015   2.414   2.692   3.286
- 45      1.301   1.679   2.014   2.412   2.690   3.281
- 46      1.300   1.679   2.013   2.410   2.687   3.277
- 47      1.300   1.678   2.012   2.408   2.685   3.273
- 48      1.299   1.677   2.011   2.407   2.682   3.269
- 49      1.299   1.677   2.010   2.405   2.680   3.265
- 50      1.299   1.676   2.009   2.403   2.678   3.261
- 51      1.298   1.675   2.008   2.402   2.676   3.258
- 52      1.298   1.675   2.007   2.400   2.674   3.255
- 53      1.298   1.674   2.006   2.399   2.672   3.251
- 54      1.297   1.674   2.005   2.397   2.670   3.248
- 55      1.297   1.673   2.004   2.396   2.668   3.245
- 56      1.297   1.673   2.003   2.395   2.667   3.242
- 57      1.297   1.672   2.002   2.394   2.665   3.239
- 58      1.296   1.672   2.002   2.392   2.663   3.237
- 59      1.296   1.671   2.001   2.391   2.662   3.234
- 60      1.296   1.671   2.000   2.390   2.660   3.232
- 61      1.296   1.670   2.000   2.389   2.659   3.229
- 62      1.295   1.670   1.999   2.388   2.657   3.227
- 63      1.295   1.669   1.998   2.387   2.656   3.225
- 64      1.295   1.669   1.998   2.386   2.655   3.223
- 65      1.295   1.669   1.997   2.385   2.654   3.220
- 66      1.295   1.668   1.997   2.384   2.652   3.218
- 67      1.294   1.668   1.996   2.383   2.651   3.216
- 68      1.294   1.668   1.995   2.382   2.650   3.214
- 69      1.294   1.667   1.995   2.382   2.649   3.213
- 70      1.294   1.667   1.994   2.381   2.648   3.211
- 71      1.294   1.667   1.994   2.380   2.647   3.209
- 72      1.293   1.666   1.993   2.379   2.646   3.207
- 73      1.293   1.666   1.993   2.379   2.645   3.206
- 74      1.293   1.666   1.993   2.378   2.644   3.204
- 75      1.293   1.665   1.992   2.377   2.643   3.202
- 76      1.293   1.665   1.992   2.376   2.642   3.201
- 77      1.293   1.665   1.991   2.376   2.641   3.199
- 78      1.292   1.665   1.991   2.375   2.640   3.198
- 79      1.292   1.664   1.990   2.374   2.640   3.197
- 80      1.292   1.664   1.990   2.374   2.639   3.195
- 81      1.292   1.664   1.990   2.373   2.638   3.194
- 82      1.292   1.664   1.989   2.373   2.637   3.193
- 83      1.292   1.663   1.989   2.372   2.636   3.191
- 84      1.292   1.663   1.989   2.372   2.636   3.190
- 85      1.292   1.663   1.988   2.371   2.635   3.189
- 86      1.291   1.663   1.988   2.370   2.634   3.188
- 87      1.291   1.663   1.988   2.370   2.634   3.187
- 88      1.291   1.662   1.987   2.369   2.633   3.185
- 89      1.291   1.662   1.987   2.369   2.632   3.184
- 90      1.291   1.662   1.987   2.368   2.632   3.183
- 91      1.291   1.662   1.986   2.368   2.631   3.182
- 92      1.291   1.662   1.986   2.368   2.630   3.181
- 93      1.291   1.661   1.986   2.367   2.630   3.180
- 94      1.291   1.661   1.986   2.367   2.629   3.179
- 95      1.291   1.661   1.985   2.366   2.629   3.178
- 96      1.290   1.661   1.985   2.366   2.628   3.177
- 97      1.290   1.661   1.985   2.365   2.627   3.176
- 98      1.290   1.661   1.984   2.365   2.627   3.175
- 99      1.290   1.660   1.984   2.365   2.626   3.175
-100      1.290   1.660   1.984   2.364   2.626   3.174
-inf        1.282   1.645   1.960   2.326   2.576   3.090
-];
+    1      3.078   6.314  12.706  31.821  63.657 318.313
+    2      1.886   2.920   4.303   6.965   9.925  22.327
+    3      1.638   2.353   3.182   4.541   5.841  10.215
+    4      1.533   2.132   2.776   3.747   4.604   7.173
+    5      1.476   2.015   2.571   3.365   4.032   5.893
+    6      1.440   1.943   2.447   3.143   3.707   5.208
+    7      1.415   1.895   2.365   2.998   3.499   4.782
+    8      1.397   1.860   2.306   2.896   3.355   4.499
+    9      1.383   1.833   2.262   2.821   3.250   4.296
+    10      1.372   1.812   2.228   2.764   3.169   4.143
+    11      1.363   1.796   2.201   2.718   3.106   4.024
+    12      1.356   1.782   2.179   2.681   3.055   3.929
+    13      1.350   1.771   2.160   2.650   3.012   3.852
+    14      1.345   1.761   2.145   2.624   2.977   3.787
+    15      1.341   1.753   2.131   2.602   2.947   3.733
+    16      1.337   1.746   2.120   2.583   2.921   3.686
+    17      1.333   1.740   2.110   2.567   2.898   3.646
+    18      1.330   1.734   2.101   2.552   2.878   3.610
+    19      1.328   1.729   2.093   2.539   2.861   3.579
+    20      1.325   1.725   2.086   2.528   2.845   3.552
+    21      1.323   1.721   2.080   2.518   2.831   3.527
+    22      1.321   1.717   2.074   2.508   2.819   3.505
+    23      1.319   1.714   2.069   2.500   2.807   3.485
+    24      1.318   1.711   2.064   2.492   2.797   3.467
+    25      1.316   1.708   2.060   2.485   2.787   3.450
+    26      1.315   1.706   2.056   2.479   2.779   3.435
+    27      1.314   1.703   2.052   2.473   2.771   3.421
+    28      1.313   1.701   2.048   2.467   2.763   3.408
+    29      1.311   1.699   2.045   2.462   2.756   3.396
+    30      1.310   1.697   2.042   2.457   2.750   3.385
+    31      1.309   1.696   2.040   2.453   2.744   3.375
+    32      1.309   1.694   2.037   2.449   2.738   3.365
+    33      1.308   1.692   2.035   2.445   2.733   3.356
+    34      1.307   1.691   2.032   2.441   2.728   3.348
+    35      1.306   1.690   2.030   2.438   2.724   3.340
+    36      1.306   1.688   2.028   2.434   2.719   3.333
+    37      1.305   1.687   2.026   2.431   2.715   3.326
+    38      1.304   1.686   2.024   2.429   2.712   3.319
+    39      1.304   1.685   2.023   2.426   2.708   3.313
+    40      1.303   1.684   2.021   2.423   2.704   3.307
+    41      1.303   1.683   2.020   2.421   2.701   3.301
+    42      1.302   1.682   2.018   2.418   2.698   3.296
+    43      1.302   1.681   2.017   2.416   2.695   3.291
+    44      1.301   1.680   2.015   2.414   2.692   3.286
+    45      1.301   1.679   2.014   2.412   2.690   3.281
+    46      1.300   1.679   2.013   2.410   2.687   3.277
+    47      1.300   1.678   2.012   2.408   2.685   3.273
+    48      1.299   1.677   2.011   2.407   2.682   3.269
+    49      1.299   1.677   2.010   2.405   2.680   3.265
+    50      1.299   1.676   2.009   2.403   2.678   3.261
+    51      1.298   1.675   2.008   2.402   2.676   3.258
+    52      1.298   1.675   2.007   2.400   2.674   3.255
+    53      1.298   1.674   2.006   2.399   2.672   3.251
+    54      1.297   1.674   2.005   2.397   2.670   3.248
+    55      1.297   1.673   2.004   2.396   2.668   3.245
+    56      1.297   1.673   2.003   2.395   2.667   3.242
+    57      1.297   1.672   2.002   2.394   2.665   3.239
+    58      1.296   1.672   2.002   2.392   2.663   3.237
+    59      1.296   1.671   2.001   2.391   2.662   3.234
+    60      1.296   1.671   2.000   2.390   2.660   3.232
+    61      1.296   1.670   2.000   2.389   2.659   3.229
+    62      1.295   1.670   1.999   2.388   2.657   3.227
+    63      1.295   1.669   1.998   2.387   2.656   3.225
+    64      1.295   1.669   1.998   2.386   2.655   3.223
+    65      1.295   1.669   1.997   2.385   2.654   3.220
+    66      1.295   1.668   1.997   2.384   2.652   3.218
+    67      1.294   1.668   1.996   2.383   2.651   3.216
+    68      1.294   1.668   1.995   2.382   2.650   3.214
+    69      1.294   1.667   1.995   2.382   2.649   3.213
+    70      1.294   1.667   1.994   2.381   2.648   3.211
+    71      1.294   1.667   1.994   2.380   2.647   3.209
+    72      1.293   1.666   1.993   2.379   2.646   3.207
+    73      1.293   1.666   1.993   2.379   2.645   3.206
+    74      1.293   1.666   1.993   2.378   2.644   3.204
+    75      1.293   1.665   1.992   2.377   2.643   3.202
+    76      1.293   1.665   1.992   2.376   2.642   3.201
+    77      1.293   1.665   1.991   2.376   2.641   3.199
+    78      1.292   1.665   1.991   2.375   2.640   3.198
+    79      1.292   1.664   1.990   2.374   2.640   3.197
+    80      1.292   1.664   1.990   2.374   2.639   3.195
+    81      1.292   1.664   1.990   2.373   2.638   3.194
+    82      1.292   1.664   1.989   2.373   2.637   3.193
+    83      1.292   1.663   1.989   2.372   2.636   3.191
+    84      1.292   1.663   1.989   2.372   2.636   3.190
+    85      1.292   1.663   1.988   2.371   2.635   3.189
+    86      1.291   1.663   1.988   2.370   2.634   3.188
+    87      1.291   1.663   1.988   2.370   2.634   3.187
+    88      1.291   1.662   1.987   2.369   2.633   3.185
+    89      1.291   1.662   1.987   2.369   2.632   3.184
+    90      1.291   1.662   1.987   2.368   2.632   3.183
+    91      1.291   1.662   1.986   2.368   2.631   3.182
+    92      1.291   1.662   1.986   2.368   2.630   3.181
+    93      1.291   1.661   1.986   2.367   2.630   3.180
+    94      1.291   1.661   1.986   2.367   2.629   3.179
+    95      1.291   1.661   1.985   2.366   2.629   3.178
+    96      1.290   1.661   1.985   2.366   2.628   3.177
+    97      1.290   1.661   1.985   2.365   2.627   3.176
+    98      1.290   1.661   1.984   2.365   2.627   3.175
+    99      1.290   1.660   1.984   2.365   2.626   3.175
+    100      1.290   1.660   1.984   2.364   2.626   3.174
+    inf        1.282   1.645   1.960   2.326   2.576   3.090
+       ];
 
-if n<=100,
+if n<=100
     t_crit=t_crit(n,ncol);
 else
     t_crit=t_crit(end,ncol);
diff --git a/matlab/gsa/teff.m b/matlab/gsa/teff.m
index cd26b5a0718e768def3ab760d90cac513625b7e9..8ebea8d1c798050deba55f3a26d04599708b785a 100644
--- a/matlab/gsa/teff.m
+++ b/matlab/gsa/teff.m
@@ -3,13 +3,13 @@ function [yt, j0, ir, ic]=teff(T,Nsam,istable)
 %
 % Written by Marco Ratto
 % Joint Research Centre, The European Commission,
-% (http://eemc.jrc.ec.europa.eu/),
-% marco.ratto@jrc.it 
+% marco.ratto@ec.europa.eu
 %
 % Reference:
 % M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006.
 
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012 European Commission
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -27,33 +27,33 @@ function [yt, j0, ir, ic]=teff(T,Nsam,istable)
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 ndim = (length(size(T)));
-if ndim==3,
-if nargin==1,
-  Nsam=size(T,3);
-  istable = [1:Nsam]';
-end
-tmax=max(T,[],3);
-tmin=min(T,[],3);
-[ir, ic]=(find( (tmax-tmin)>1.e-8));
-j0 = length(ir);
-yt=zeros(Nsam, j0);
+if ndim==3
+    if nargin==1
+        Nsam=size(T,3);
+        istable = [1:Nsam]';
+    end
+    tmax=max(T,[],3);
+    tmin=min(T,[],3);
+    [ir, ic]=(find( (tmax-tmin)>1.e-8));
+    j0 = length(ir);
+    yt=zeros(Nsam, j0);
 
-for j=1:j0,
-  y0=squeeze(T(ir(j),ic(j),:));
-  %y1=ones(size(lpmat,1),1)*NaN;
-  y1=ones(Nsam,1)*NaN;
-  y1(istable,1)=y0;
-  yt(:,j)=y1;
-end
+    for j=1:j0
+        y0=squeeze(T(ir(j),ic(j),:));
+        %y1=ones(size(lpmat,1),1)*NaN;
+        y1=ones(Nsam,1)*NaN;
+        y1(istable,1)=y0;
+        yt(:,j)=y1;
+    end
 
 else
-tmax=max(T,[],2);
-tmin=min(T,[],2);
-ir=(find( (tmax-tmin)>1.e-8));
-j0 = length(ir);
-yt=NaN(Nsam, j0);
-yt(istable,:)=T(ir,:)';
+    tmax=max(T,[],2);
+    tmin=min(T,[],2);
+    ir=(find( (tmax-tmin)>1.e-8));
+    j0 = length(ir);
+    yt=NaN(Nsam, j0);
+    yt(istable,:)=T(ir,:)';
+
 
-  
 end
 %clear y0 y1;
diff --git a/matlab/gsa/th_moments.m b/matlab/gsa/th_moments.m
index 5616b4045e95eadb94702fca572ad9a9d7969d4f..9b886e85197fc4220c6de64d32edcdbd44ec1f26 100644
--- a/matlab/gsa/th_moments.m
+++ b/matlab/gsa/th_moments.m
@@ -1,7 +1,7 @@
 function [vdec, corr, autocorr, z, zz] = th_moments(dr,var_list)
 % [vdec, corr, autocorr, z, zz] = th_moments(dr,var_list)
 
-% Copyright (C) 2012-2016 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -56,13 +56,13 @@ var = gamma_y{1};
 z;
 
 %'VARIANCE DECOMPOSITION (in percent)';
-if M_.exo_nbr>1,
+if M_.exo_nbr>1
     vdec = 100*gamma_y{options_.ar+2}(i1,:);
 else
     vdec = 100*ones(size(gamma_y{1}(i1,1)));
 end
 %'MATRIX OF CORRELATIONS';
-if options_.opt_gsa.useautocorr,
+if options_.opt_gsa.useautocorr
     corr = gamma_y{1}(i1,i1)./(sd(i1)*sd(i1)');
     corr = corr-diag(diag(corr))+diag(diag(gamma_y{1}(i1,i1)));
 else
@@ -71,7 +71,7 @@ end
 if options_.ar > 0
     %'COEFFICIENTS OF AUTOCORRELATION';
     for i=1:options_.ar
-        if options_.opt_gsa.useautocorr,
+        if options_.opt_gsa.useautocorr
             autocorr{i} = gamma_y{i+1}(i1,i1);
         else
             autocorr{i} = gamma_y{i+1}(i1,i1).*(sd(i1)*sd(i1)');
@@ -79,5 +79,3 @@ if options_.ar > 0
         zz(:,i) = diag(gamma_y{i+1}(i1,i1));
     end
 end
-
-
diff --git a/matlab/gsa/trank.m b/matlab/gsa/trank.m
index d788cf0856ed0dd260d1c538acc52683729be8eb..eb39f16478ef835c48c0e69eea62313e3731a008 100644
--- a/matlab/gsa/trank.m
+++ b/matlab/gsa/trank.m
@@ -1,16 +1,16 @@
-function yr = trank(y);
+function yr = trank(y)
 % yr = trank(y);
 % yr is the rank transformation of y
 %
 % Written by Marco Ratto
 % Joint Research Centre, The European Commission,
-% (http://eemc.jrc.ec.europa.eu/),
-% marco.ratto@jrc.it 
+% marco.ratto@ec.europa.eu
 %
 % Reference:
 % M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006.
 
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012 European Commission
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -28,7 +28,7 @@ function yr = trank(y);
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 [nr, nc] = size(y);
-for j=1:nc,
-  [dum, is]=sort(y(:,j));
-  yr(is,j)=[1:nr]'./nr;
+for j=1:nc
+    [dum, is]=sort(y(:,j));
+    yr(is,j)=[1:nr]'./nr;
 end
diff --git a/matlab/hessian.m b/matlab/hessian.m
index 4faa4c50008dee3f7f754e18e37bc315b88c5920..844251f7cf5c95a099f16b01ac7d29824845b1c2 100644
--- a/matlab/hessian.m
+++ b/matlab/hessian.m
@@ -12,19 +12,19 @@ function hessian_mat = hessian(func,x, gstep, varargin) % --*-- Unitary tests --
 %    hessian_mat [double]   Hessian matrix
 %
 % ALGORITHM
-%    Uses Abramowitz and Stegun (1965) formulas 25.3.23 
+%    Uses Abramowitz and Stegun (1965) formulas 25.3.23
 % \[
 %     \frac{\partial^2 f_{0,0}}{\partial {x^2}} = \frac{1}{h^2}\left( f_{1,0} - 2f_{0,0} + f_{ - 1,0} \right)
 % \]
 % and 25.3.27 p. 884
-% 
+%
 % \[
 %     \frac{\partial ^2f_{0,0}}{\partial x\partial y} = \frac{-1}{2h^2}\left(f_{1,0} + f_{-1,0} + f_{0,1} + f_{0,-1} - 2f_{0,0} - f_{1,1} - f_{-1,-1} \right)
 % \]
 %
 % SPECIAL REQUIREMENTS
 %    none
-%  
+%
 
 % Copyright (C) 2001-2017 Dynare Team
 %
@@ -43,7 +43,7 @@ function hessian_mat = hessian(func,x, gstep, varargin) % --*-- Unitary tests --
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-if ~isa(func, 'function_handle') 
+if ~isa(func, 'function_handle')
     func = str2func(func);
 end
 
@@ -67,7 +67,7 @@ for i=1:n
     xh1(i)   = x(i)-h_1(i);
     f_1(:,i) = feval(func, xh1, varargin{:});
     %reset parameter
-    xh1(i)   = x(i); 
+    xh1(i)   = x(i);
 end
 
 xh_1 = xh1;
@@ -75,14 +75,14 @@ temp = f1+f_1-f0*ones(1, n); %term f_(1,0)+f_(-1,0)-f_(0,0) used later
 
 hessian_mat = zeros(size(f0,1), n*n);
 
-for i=1:n    
-    if i > 1  
-        %fill symmetric part of Hessian based on previously computed results      
+for i=1:n
+    if i > 1
+        %fill symmetric part of Hessian based on previously computed results
         k = [i:n:n*(i-1)];
         hessian_mat(:,(i-1)*n+1:(i-1)*n+i-1) = hessian_mat(:,k);
-    end     
+    end
     hessian_mat(:,(i-1)*n+i) = (f1(:,i)+f_1(:,i)-2*f0)./(h1(i)*h_1(i)); %formula 25.3.23
-    for j=i+1:n        
+    for j=i+1:n
         %step in up direction
         xh1(i) = x(i)+h1(i);
         xh1(j) = x(j)+h_1(j);
@@ -90,12 +90,12 @@ for i=1:n
         xh_1(i) = x(i)-h1(i);
         xh_1(j) = x(j)-h_1(j);
         hessian_mat(:,(i-1)*n+j) =-(-feval(func, xh1, varargin{:})-feval(func, xh_1, varargin{:})+temp(:,i)+temp(:,j))./(2*h1(i)*h_1(j)); %formula 25.3.27
-        %reset grid points
+                                                                                                                                          %reset grid points
         xh1(i)  = x(i);
         xh1(j)  = x(j);
         xh_1(i) = x(i);
         xh_1(j) = x(j);
-    end    
+    end
 end
 
 
diff --git a/matlab/hessian_sparse.m b/matlab/hessian_sparse.m
index eb447f8d34d9ac9c9237c021dba01762a708a911..1d7a75dbed87dd5ede7b82f5b6c67982d583bd36 100644
--- a/matlab/hessian_sparse.m
+++ b/matlab/hessian_sparse.m
@@ -16,9 +16,9 @@ function hessian_mat = hessian_sparse(func,x,gstep,varargin)
 %
 % SPECIAL REQUIREMENTS
 %    none
-%  
+%
 
-% Copyright (C) 2001-2012 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -35,7 +35,7 @@ function hessian_mat = hessian_sparse(func,x,gstep,varargin)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-if ~isa(func, 'function_handle') 
+if ~isa(func, 'function_handle')
     func = str2func(func);
 end
 n=size(x,1);
@@ -49,7 +49,7 @@ xh1=x;
 f0=feval(func,x,varargin{:});
 f1=zeros(size(f0,1),n);
 f_1=f1;
-for i=1:n    
+for i=1:n
     xh1(i)=x(i)+h1(i);
     f1(:,i)=feval(func,xh1,varargin{:});
     xh1(i)=x(i)-h_1(i);
@@ -59,15 +59,15 @@ end
 xh_1=xh1;
 hessian_mat = sparse(size(f0,1),n*n);
 
-for i=1:n    
-%     if i > 1        
-%         k=[i:n:n*(i-1)];
-%         hessian_mat(:,(i-1)*n+1:(i-1)*n+i-1)=hessian_mat(:,k);
-%         hessian_mat(:,k)=0;
-%     end     
+for i=1:n
+    %     if i > 1
+    %         k=[i:n:n*(i-1)];
+    %         hessian_mat(:,(i-1)*n+1:(i-1)*n+i-1)=hessian_mat(:,k);
+    %         hessian_mat(:,k)=0;
+    %     end
     hessian_mat(:,(i-1)*n+i)=(f1(:,i)+f_1(:,i)-2*f0)./(h1(i)*h_1(i));
     temp=f1+f_1-f0*ones(1,n);
-    for j=1:i-1        
+    for j=1:i-1
         xh1(i)=x(i)+h1(i);
         xh1(j)=x(j)+h_1(j);
         xh_1(i)=x(i)-h1(i);
@@ -77,5 +77,5 @@ for i=1:n
         xh1(j)=x(j);
         xh_1(i)=x(i);
         xh_1(j)=x(j);
-    end    
+    end
 end
\ No newline at end of file
diff --git a/matlab/histvalf.m b/matlab/histvalf.m
index e2c1445546ada6e61da5bc30228638b74216a0c0..580c9be92fb962bb57045895201b95f2f3c227ce 100644
--- a/matlab/histvalf.m
+++ b/matlab/histvalf.m
@@ -1,6 +1,6 @@
 function histvalf(fname)
 
-% Copyright (C) 2014 Dynare Team
+% Copyright (C) 2014-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -86,4 +86,3 @@ for i = 1:length(outvars)
     end
     M_.endo_histval(j, :) = getfield(S, ov_);
 end
-
diff --git a/matlab/homotopy1.m b/matlab/homotopy1.m
index e7de1f16a73e6682703a2f2731ecbd045d8f4479..e849fceca4f632f821d6219488a7321718fa7847 100644
--- a/matlab/homotopy1.m
+++ b/matlab/homotopy1.m
@@ -30,7 +30,7 @@ function [M,oo,info,ip,ix,ixd] = homotopy1(values, step_nbr, M, options, oo)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2008-2012 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -90,7 +90,7 @@ for i=1:step_nbr+1
         % if homotopy step is not successful, current values of steady
         % state are not modified
         oo.steady_state = steady_state;
-    else 
+    else
         M.params = old_params;
         oo.exo_steady_state = old_exo;
         oo.exo_det_steady_state = old_exo_det;
diff --git a/matlab/homotopy2.m b/matlab/homotopy2.m
index 8e1318a86b38c568501d2a5eff01de59a31b1214..7ec87258daa545f39185e4a2db0b7e0649a92263 100644
--- a/matlab/homotopy2.m
+++ b/matlab/homotopy2.m
@@ -25,7 +25,7 @@ function homotopy2(values, step_nbr)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2008-2012 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -99,7 +99,7 @@ for i = 1:nv
         end
 
         disp([ 'HOMOTOPY mode 2: lauching solver with ' deblank(varname) ' = ' num2str(v) ' ...'])
-        
+
         oo_.steady_state = steady_(M_,options_,oo_);
     end
 end
diff --git a/matlab/homotopy3.m b/matlab/homotopy3.m
index a506bb6b66bc0f566893abdda58342b025a88e5e..b4b46d6f281389761ded8ff327b3890fc3acb4f1 100644
--- a/matlab/homotopy3.m
+++ b/matlab/homotopy3.m
@@ -33,7 +33,7 @@ function [M,oo,info,ip,ix,ixd]=homotopy3(values, step_nbr, M, options, oo)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2008-2012 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -91,11 +91,11 @@ disp('HOMOTOPY mode 3: launching solver at initial point...')
 
 iter = 1;
 while iter <= step_nbr
-    
+
     M.params(values(ip,2)) = curvalues(ip);
     oo.exo_steady_state(values(ix,2)) = curvalues(ix);
     oo.exo_det_steady_state(values(ixd,2)) = curvalues(ixd);
-    
+
     old_ss = oo.steady_state;
 
     [steady_state,params,info] = steady_(M,options,oo);
@@ -121,8 +121,8 @@ while iter <= step_nbr
         disp('HOMOTOPY mode 3: failed step, now dividing increment by 2...')
         inc = inc/2;
         oo.steady_state = old_ss;
-    end      
-    
+    end
+
     curvalues = last_values + inc;
     kplus = find(curvalues(iplus) >= targetvalues(iplus));
     curvalues(iplus(kplus)) = targetvalues(iplus(kplus));
@@ -136,7 +136,7 @@ while iter <= step_nbr
         oo.exo_det_steady_state = old_exo_det_steady_state;
         return
     end
-    
+
     iter = iter + 1;
 end
 disp('HOMOTOPY mode 3: failed, maximum iterations reached')
diff --git a/matlab/ident_bruteforce.m b/matlab/ident_bruteforce.m
index 41ed952d71ce9ce83af4fdd6b860ec848ae9ec1d..34725ade4c17b0c0537ab5ef70d54d550fc49a50 100644
--- a/matlab/ident_bruteforce.m
+++ b/matlab/ident_bruteforce.m
@@ -12,12 +12,12 @@ function [pars, cosnJ] = ident_bruteforce(J,n,TeX, pnames_TeX,tittxt)
 %  pnames_TeX         [char] list of tex names
 %  tittxt             [string]  string indicating the title text for
 %                               graphs and figures
-% 
+%
 % OUTPUTS
 %  pars  : cell array with groupf of params for each column of J for 1 to n
 %  cosnJ : the cosn of each column with the selected group of columns
 
-% Copyright (C) 2009-2016 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -52,7 +52,7 @@ tittxt1=strrep(tittxt1, '.', '');
 
 cosnJ=zeros(k,n);
 pars{k,n}=[];
-for ll = 1:n,
+for ll = 1:n
     h = dyn_waitbar(0,['Brute force collinearity for ' int2str(ll) ' parameters.']);
     for ii = 1:k
         tmp = find([1:k]~=ii);
@@ -63,8 +63,8 @@ for ll = 1:n,
             [cosnJ2(jj,1), b(:,jj)] = cosn([J(:,ii),J(:,tmp2(jj,:))]);
         end
         cosnJ(ii,ll) = max(cosnJ2(:,1));
-        if cosnJ(ii,ll)>1.e-8,
-            if ll>1 && ((cosnJ(ii,ll)-cosnJ(ii,ll-1))<1.e-8),
+        if cosnJ(ii,ll)>1.e-8
+            if ll>1 && ((cosnJ(ii,ll)-cosnJ(ii,ll-1))<1.e-8)
                 pars{ii,ll} = [pars{ii,ll-1} NaN];
                 cosnJ(ii,ll) = cosnJ(ii,ll-1);
             else
@@ -85,7 +85,7 @@ for ll = 1:n,
         fprintf(fidTeX,['%% ' datestr(now,0)]);
         fprintf(fidTeX,' \n');
         fprintf(fidTeX,' \n');
-        
+
         fprintf(fidTeX,'{\\tiny \n');
         fprintf(fidTeX,'\\begin{longtable}{llc} \n');
         fprintf(fidTeX,['\\caption{Collinearity patterns with ',int2str(ll),' parameter(s): ',tittxt,'}\n ']);
@@ -101,19 +101,19 @@ for ll = 1:n,
         fprintf(fidTeX,'\\midrule \\endhead \n');
         fprintf(fidTeX,'\\bottomrule \\multicolumn{3}{r}{(Continued on next page)}\\endfoot \n');
         fprintf(fidTeX,'\\bottomrule\\endlastfoot \n');
-        for i=1:k,
+        for i=1:k
             plist='';
-            for ii=1:ll,
-                if ~isnan(pars{i,ll}(ii)),
+            for ii=1:ll
+                if ~isnan(pars{i,ll}(ii))
                     plist = [plist ' $' pnames_TeX(pars{i,ll}(ii),:) '\;\; $ '];
                 else
                     plist = [plist ' ---- '];
                 end
             end
             fprintf(fidTeX,'$%s$ & [%s] & %7.3f \\\\ \n',...
-                pnames_TeX(i,:),...
-                plist,...
-                cosnJ(i,ll));
+                    pnames_TeX(i,:),...
+                    plist,...
+                    cosnJ(i,ll));
         end
         fprintf(fidTeX,'\\bottomrule \n');
         fprintf(fidTeX,'\\end{longtable}\n');
diff --git a/matlab/identification_analysis.m b/matlab/identification_analysis.m
index 88b60ca4d457900fb807c63e9e827c1751119842..c59e08ec6d2091b652d4ea3d82433d6579ac587b 100644
--- a/matlab/identification_analysis.m
+++ b/matlab/identification_analysis.m
@@ -9,14 +9,14 @@ function [ide_hess, ide_moments, ide_model, ide_lre, derivatives_info, info, opt
 %    o options_ident      [structure] identification options
 %    o dataset_           [structure] the dataset after required transformation
 %    o dataset_info       [structure] Various informations about the dataset (descriptive statistics and missing observations) info for Kalman Filter
-%    o prior_exist        [integer] 
+%    o prior_exist        [integer]
 %                           =1 when prior exists and indentification is checked only for estimated params and shocks
 %                           =0 when prior is not defined and indentification is checked for all params and shocks
 %    o name_tex           [char] list of tex names
 %    o init               [integer] flag  for initialization of persistent vars
 %    o tittxt             [string]  string indicating the title text for
 %                                   graphs and figures
-%    
+%
 % OUTPUTS
 %    o ide_hess           [structure] identification results using Asymptotic Hessian
 %    o ide_moments        [structure] identification results using theoretical moments
@@ -24,11 +24,11 @@ function [ide_hess, ide_moments, ide_model, ide_lre, derivatives_info, info, opt
 %    o ide_lre            [structure] identification results using LRE model
 %    o derivatives_info   [structure] info about analytic derivs
 %    o info               output from dynare resolve
-%    
+%
 % SPECIAL REQUIREMENTS
 %    None
 
-% Copyright (C) 2008-2016 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -42,7 +42,7 @@ function [ide_hess, ide_moments, ide_model, ide_lre, derivatives_info, info, opt
 % 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 
+% You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 global oo_ M_ options_ bayestopt_ estim_params_
@@ -51,7 +51,7 @@ persistent indH indJJ indLRE
 nparam=length(params);
 np=length(indx);
 offset=nparam-np;
-if ~isempty(estim_params_),
+if ~isempty(estim_params_)
     M_ = set_all_parameters(params,estim_params_,M_);
 end
 
@@ -63,7 +63,7 @@ periods = options_ident.periods;
 max_dim_cova_group = options_ident.max_dim_cova_group;
 normalize_jacobians = options_ident.normalize_jacobians;
 kron_flag = options_ident.analytic_derivation_mode;
-    
+
 [I,J]=find(M_.lead_lag_incidence');
 
 ide_hess = struct();
@@ -73,29 +73,29 @@ ide_lre = struct();
 derivatives_info = struct();
 
 [A,B,ys,info,M_,options_,oo_] = dynare_resolve(M_,options_,oo_);
-if info(1)==0,
+if info(1)==0
     oo0=oo_;
     tau=[oo_.dr.ys(oo_.dr.order_var); vec(A); dyn_vech(B*M_.Sigma_e*B')];
     yy0=oo_.dr.ys(I);
     [residual, g1 ] = feval([M_.fname,'_dynamic'],yy0, ...
-        repmat(oo_.exo_steady_state',[M_.maximum_exo_lag+M_.maximum_exo_lead+1]), M_.params, ...
-        oo_.dr.ys, 1);
+                            repmat(oo_.exo_steady_state',[M_.maximum_exo_lag+M_.maximum_exo_lead+1]), M_.params, ...
+                            oo_.dr.ys, 1);
     vg1 = [oo_.dr.ys(oo_.dr.order_var); vec(g1)];
 
     [JJ, H, gam, gp, dA, dOm, dYss] = getJJ(A, B, estim_params_, M_,oo0,options_,kron_flag,indx,indexo,bayestopt_.mf2,nlags,useautocorr);
     derivatives_info.DT=dA;
     derivatives_info.DOm=dOm;
     derivatives_info.DYss=dYss;
-    if init,
+    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 diffuse_filter=1.' )
         elseif any(any(isnan(gam)))
             error('There are NaN''s in the theoretical moments: make sure that for non-stationary models stationary transformations of non-stationary observables are used for checking identification. [TIP: use first differences].')
         end
-        while length(indJJ)<nparam && nlags<10,
+        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)])           
+            disp(['Try increasing ar = ', int2str(nlags+1)])
             nlags=nlags+1;
             [JJ, H, gam, gp, dA, dOm, dYss] = getJJ(A, B, estim_params_, M_,oo0,options_,kron_flag,indx,indexo,bayestopt_.mf2,nlags,useautocorr);
             derivatives_info.DT=dA;
@@ -104,10 +104,10 @@ if info(1)==0,
             options_.ar=nlags;
             indJJ = (find(max(abs(JJ'),[],1)>1.e-8));
         end
-        if length(indJJ)<nparam,
+        if length(indJJ)<nparam
             disp('The number of moments with non-zero derivative is smaller than the number of parameters')
-            disp('up to 10 lags: check your model')           
-            disp('Either further increase ar or reduce the list of estimated parameters')           
+            disp('up to 10 lags: check your model')
+            disp('Either further increase ar or reduce the list of estimated parameters')
             error('identification_analysis: there are not enough moments and too many parameters'),
         end
         indH = (find(max(abs(H'),[],1)>1.e-8));
@@ -117,58 +117,58 @@ if info(1)==0,
     LRE(:,1)=vg1(indLRE);
     GAM(:,1)=gam(indJJ);
     siJ = (JJ(indJJ,:));
-    siH = (H(indH,:));   
+    siH = (H(indH,:));
     siLRE = (gp(indLRE,:));
     ide_strength_J=NaN(1,nparam);
     ide_strength_J_prior=NaN(1,nparam);
-    if init, %~isempty(indok),
+    if init
         normaliz = NaN(1,nparam);
-        if prior_exist,
-            if ~isempty(estim_params_.var_exo),
+        if prior_exist
+            if ~isempty(estim_params_.var_exo)
                 normaliz1 = estim_params_.var_exo(:,7)'; % normalize with prior standard deviation
             else
                 normaliz1=[];
             end
-            if ~isempty(estim_params_.corrx),
+            if ~isempty(estim_params_.corrx)
                 normaliz1 = [normaliz1 estim_params_.corrx(:,8)']; % normalize with prior standard deviation
             end
-            if ~isempty(estim_params_.param_vals),
+            if ~isempty(estim_params_.param_vals)
                 normaliz1 = [normaliz1 estim_params_.param_vals(:,7)']; % normalize with prior standard deviation
             end
             %                         normaliz = max([normaliz; normaliz1]);
             normaliz1(isinf(normaliz1)) = 1;
-            
+
         else
             normaliz1 = NaN(1,nparam);
         end
-        try,
+        try
             options_.irf = 0;
             options_.noprint = 1;
             options_.order = 1;
             options_.SpectralDensity.trigger = 0;
             options_.periods = periods+100;
-            if options_.kalman_algo > 2,
+            if options_.kalman_algo > 2
                 options_.kalman_algo = 1;
             end
             analytic_derivation = options_.analytic_derivation;
             options_.analytic_derivation = -2;
             info = stoch_simul(char(options_.varobs));
-            dataset_ = dseries(oo_.endo_simul(options_.varobs_id,100+1:end)',dates('1Q1'), options_.varobs);            
+            dataset_ = dseries(oo_.endo_simul(options_.varobs_id,100+1:end)',dates('1Q1'), options_.varobs);
             derivatives_info.no_DLIK=1;
             %bounds = prior_bounds(bayestopt_, options_.prior_trunc);
-            [fval,info,cost_flag,DLIK,AHess,ys,trend_coeff,M_,options_,bayestopt_,oo_] = dsge_likelihood(params',dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_,derivatives_info);             
-%                 fval = DsgeLikelihood(xparam1,data_info,options_,M_,estim_params_,bayestopt_,oo_);
+            [fval,info,cost_flag,DLIK,AHess,ys,trend_coeff,M_,options_,bayestopt_,oo_] = dsge_likelihood(params',dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_,derivatives_info);
+            %                 fval = DsgeLikelihood(xparam1,data_info,options_,M_,estim_params_,bayestopt_,oo_);
             options_.analytic_derivation = analytic_derivation;
             AHess=-AHess;
-            if min(eig(AHess))<-1.e-10,
+            if min(eig(AHess))<-1.e-10
                 error('identification_analysis: Analytic Hessian is not positive semi-definite!')
             end
-%             chol(AHess);
+            %             chol(AHess);
             ide_hess.AHess= AHess;
             deltaM = sqrt(diag(AHess));
             iflag=any((deltaM.*deltaM)==0);
             tildaM = AHess./((deltaM)*(deltaM'));
-            if iflag || rank(AHess)>rank(tildaM),
+            if iflag || rank(AHess)>rank(tildaM)
                 [ide_hess.cond, ide_hess.ind0, ide_hess.indno, ide_hess.ino, ide_hess.Mco, ide_hess.Pco] = identification_checks(AHess, 1);
             else
                 [ide_hess.cond, ide_hess.ind0, ide_hess.indno, ide_hess.ino, ide_hess.Mco, ide_hess.Pco] = identification_checks(tildaM, 1);
@@ -181,23 +181,23 @@ if info(1)==0,
             cmm = siJ(:,ind1)*((AHess(ind1,ind1))\siJ(:,ind1)');
             temp1=((AHess(ind1,ind1))\siH(:,ind1)');
             diag_chh=sum(siH(:,ind1)'.*temp1)';
-%             chh = siH(:,ind1)*((AHess(ind1,ind1))\siH(:,ind1)');
+            %             chh = siH(:,ind1)*((AHess(ind1,ind1))\siH(:,ind1)');
             ind1=ind1(ind1>offset);
             clre = siLRE(:,ind1-offset)*((AHess(ind1,ind1))\siLRE(:,ind1-offset)');
             rhoM=sqrt(1./diag(inv(tildaM(indok,indok))));
-%             deltaM = deltaM.*abs(params');
+            %             deltaM = deltaM.*abs(params');
             flag_score=1;
-        catch,
-%             replic = max([replic, nparam*(nparam+1)/2*10]);
+        catch
+            %             replic = max([replic, nparam*(nparam+1)/2*10]);
             replic = max([replic, length(indJJ)*3]);
             cmm = simulated_moment_uncertainty(indJJ, periods, replic,options_,M_,oo_);
-%             [V,D,W]=eig(cmm);
+            %             [V,D,W]=eig(cmm);
             sd=sqrt(diag(cmm));
             cc=cmm./(sd*sd');
             if isoctave || matlab_ver_less_than('8.3')
                 [V,D]=eig(cc);
                 %fix for older Matlab versions that do not support computing left eigenvalues, see http://mathworks.com/help/releases/R2012b/matlab/ref/eig.html
-                [W,junk] = eig(cc.'); 
+                [W,junk] = eig(cc.');
                 W = conj(W);
             else
                 [V,D,W]=eig(cc);
@@ -206,40 +206,40 @@ if info(1)==0,
             siTMP=siJ./repmat(sd,[1 nparam]);
             MIM=(siTMP'*V(:,id))*(D(id,id)\(W(:,id)'*siTMP));
             clear siTMP;
-%           MIM=siJ(:,indok)'*(cmm\siJ(:,indok));
-%           look for independent moments!
-% % %             sd=sqrt(diag(cmm));
-% % %             cc=cmm./(sd*sd');
-% % %             ix=[];
-% % %             for jc=1:length(cmm),
-% % %                 jcheck=find(abs(cc(:,jc))>(1-1.e-6));
-% % %                 ix=[ix; jcheck(jcheck>jc)];
-% % %             end
-% % %             iy=find(~ismember([1:length(cmm)],ix));
-% % %             indJJ=indJJ(iy);
-% % %             GAM=GAM(iy);
-% % %             cmm=cmm(iy,iy);
-% % %             siJ = (JJ(indJJ,:));
-% % %             MIM=siJ'*(cmm\siJ);
+            %           MIM=siJ(:,indok)'*(cmm\siJ(:,indok));
+            %           look for independent moments!
+            % % %             sd=sqrt(diag(cmm));
+            % % %             cc=cmm./(sd*sd');
+            % % %             ix=[];
+            % % %             for jc=1:length(cmm),
+            % % %                 jcheck=find(abs(cc(:,jc))>(1-1.e-6));
+            % % %                 ix=[ix; jcheck(jcheck>jc)];
+            % % %             end
+            % % %             iy=find(~ismember([1:length(cmm)],ix));
+            % % %             indJJ=indJJ(iy);
+            % % %             GAM=GAM(iy);
+            % % %             cmm=cmm(iy,iy);
+            % % %             siJ = (JJ(indJJ,:));
+            % % %             MIM=siJ'*(cmm\siJ);
             ide_hess.AHess= MIM;
             deltaM = sqrt(diag(MIM));
             iflag=any((deltaM.*deltaM)==0);
             tildaM = MIM./((deltaM)*(deltaM'));
-            if iflag || rank(MIM)>rank(tildaM),
+            if iflag || rank(MIM)>rank(tildaM)
                 [ide_hess.cond, ide_hess.ind0, ide_hess.indno, ide_hess.ino, ide_hess.Mco, ide_hess.Pco] = identification_checks(MIM, 1);
             else
                 [ide_hess.cond, ide_hess.ind0, ide_hess.indno, ide_hess.ino, ide_hess.Mco, ide_hess.Pco] = identification_checks(tildaM, 1);
             end
             indok = find(max(ide_hess.indno,[],1)==0);
-%             rhoM=sqrt(1-1./diag(inv(tildaM)));
-%             rhoM=(1-1./diag(inv(tildaM)));
+            %             rhoM=sqrt(1-1./diag(inv(tildaM)));
+            %             rhoM=(1-1./diag(inv(tildaM)));
             ind1=find(ide_hess.ind0);
             temp1=((MIM(ind1,ind1))\siH(:,ind1)');
             diag_chh=sum(siH(:,ind1)'.*temp1)';
-%             chh = siH(:,ind1)*((MIM(ind1,ind1))\siH(:,ind1)');
+            %             chh = siH(:,ind1)*((MIM(ind1,ind1))\siH(:,ind1)');
             ind1=ind1(ind1>offset);
             clre = siLRE(:,ind1-offset)*((MIM(ind1,ind1))\siLRE(:,ind1-offset)');
-            if ~isempty(indok),
+            if ~isempty(indok)
                 rhoM(indok)=sqrt(1./diag(inv(tildaM(indok,indok))));
                 normaliz(indok) = (sqrt(diag(inv(tildaM(indok,indok))))./deltaM(indok))'; %sqrt(diag(inv(MIM(indok,indok))))';
             end
@@ -253,24 +253,24 @@ if info(1)==0,
         deltaM = deltaM.*abs(params');
         deltaM(params==0)=deltaM_prior(params==0);
         quant = siJ./repmat(sqrt(diag(cmm)),1,nparam);
-        if size(quant,1)==1,
+        if size(quant,1)==1
             siJnorm = abs(quant).*normaliz1;
         else
             siJnorm = vnorm(quant).*normaliz1;
         end
         %                 siJnorm = vnorm(siJ(inok,:)).*normaliz;
         quant=[];
-%         inok = find((abs(TAU)<1.e-8));
-%         isok = find((abs(TAU)>=1.e-8));
-%         quant(isok,:) = siH(isok,:)./repmat(TAU(isok,1),1,nparam);
-%         quant(inok,:) = siH(inok,:)./repmat(mean(abs(TAU)),length(inok),nparam);
-%         quant = siH./repmat(sqrt(diag(chh)),1,nparam);
+        %         inok = find((abs(TAU)<1.e-8));
+        %         isok = find((abs(TAU)>=1.e-8));
+        %         quant(isok,:) = siH(isok,:)./repmat(TAU(isok,1),1,nparam);
+        %         quant(inok,:) = siH(inok,:)./repmat(mean(abs(TAU)),length(inok),nparam);
+        %         quant = siH./repmat(sqrt(diag(chh)),1,nparam);
         iy = find(diag_chh);
         indH=indH(iy);
         siH=siH(iy,:);
-        if ~isempty(iy),
+        if ~isempty(iy)
             quant = siH./repmat(sqrt(diag_chh(iy)),1,nparam);
-            if size(quant,1)==1,
+            if size(quant,1)==1
                 siHnorm = abs(quant).*normaliz1;
             else
                 siHnorm = vnorm(quant).*normaliz1;
@@ -280,17 +280,17 @@ if info(1)==0,
         end
         %                 siHnorm = vnorm(siH./repmat(TAU,1,nparam)).*normaliz;
         quant=[];
-%         inok = find((abs(LRE)<1.e-8));
-%         isok = find((abs(LRE)>=1.e-8));
-%         quant(isok,:) = siLRE(isok,:)./repmat(LRE(isok,1),1,np);
-%         quant(inok,:) = siLRE(inok,:)./repmat(mean(abs(LRE)),length(inok),np);
+        %         inok = find((abs(LRE)<1.e-8));
+        %         isok = find((abs(LRE)>=1.e-8));
+        %         quant(isok,:) = siLRE(isok,:)./repmat(LRE(isok,1),1,np);
+        %         quant(inok,:) = siLRE(inok,:)./repmat(mean(abs(LRE)),length(inok),np);
         diag_clre = diag(clre);
         iy = find(diag_clre);
         indLRE=indLRE(iy);
         siLRE=siLRE(iy,:);
-        if ~isempty(iy),
+        if ~isempty(iy)
             quant = siLRE./repmat(sqrt(diag_clre(iy)),1,np);
-            if size(quant,1)==1,
+            if size(quant,1)==1
                 siLREnorm = abs(quant).*normaliz1(offset+1:end);
             else
                 siLREnorm = vnorm(quant).*normaliz1(offset+1:end);
@@ -299,16 +299,16 @@ if info(1)==0,
             siLREnorm=[];
         end
         %                 siLREnorm = vnorm(siLRE./repmat(LRE,1,nparam-offset)).*normaliz(offset+1:end);
-        ide_hess.ide_strength_J=ide_strength_J; 
-        ide_hess.ide_strength_J_prior=ide_strength_J_prior; 
-        ide_hess.deltaM=deltaM; 
-        ide_hess.deltaM_prior=deltaM_prior; 
-        ide_moments.siJnorm=siJnorm; 
-        ide_model.siHnorm=siHnorm; 
-        ide_lre.siLREnorm=siLREnorm; 
-        ide_hess.flag_score=flag_score; 
-    end,
-    if normalize_jacobians,
+        ide_hess.ide_strength_J=ide_strength_J;
+        ide_hess.ide_strength_J_prior=ide_strength_J_prior;
+        ide_hess.deltaM=deltaM;
+        ide_hess.deltaM_prior=deltaM_prior;
+        ide_moments.siJnorm=siJnorm;
+        ide_model.siHnorm=siHnorm;
+        ide_lre.siLREnorm=siLREnorm;
+        ide_hess.flag_score=flag_score;
+    end
+    if normalize_jacobians
         normH = max(abs(siH)')';
         normH = normH(:,ones(nparam,1));
         normJ = max(abs(siJ)')';
@@ -329,14 +329,14 @@ if info(1)==0,
     ide_moments.GAM=GAM;
     ide_model.TAU=TAU;
     ide_lre.LRE=LRE;
-%     [ide_checks.idemodel_Mco, ide_checks.idemoments_Mco, ide_checks.idelre_Mco, ...
-%         ide_checks.idemodel_Pco, ide_checks.idemoments_Pco, ide_checks.idelre_Pco, ...
-%         ide_checks.idemodel_cond, ide_checks.idemoments_cond, ide_checks.idelre_cond, ...
-%         ide_checks.idemodel_ee, ide_checks.idemoments_ee, ide_checks.idelre_ee, ...
-%         ide_checks.idemodel_ind, ide_checks.idemoments_ind, ...
-%         ide_checks.idemodel_indno, ide_checks.idemoments_indno, ...
-%         ide_checks.idemodel_ino, ide_checks.idemoments_ino] = ...
-%         identification_checks(H(indH,:)./normH(:,ones(nparam,1)),JJ(indJJ,:)./normJ(:,ones(nparam,1)), gp(indLRE,:)./normLRE(:,ones(size(gp,2),1)));
+    %     [ide_checks.idemodel_Mco, ide_checks.idemoments_Mco, ide_checks.idelre_Mco, ...
+    %         ide_checks.idemodel_Pco, ide_checks.idemoments_Pco, ide_checks.idelre_Pco, ...
+    %         ide_checks.idemodel_cond, ide_checks.idemoments_cond, ide_checks.idelre_cond, ...
+    %         ide_checks.idemodel_ee, ide_checks.idemoments_ee, ide_checks.idelre_ee, ...
+    %         ide_checks.idemodel_ind, ide_checks.idemoments_ind, ...
+    %         ide_checks.idemodel_indno, ide_checks.idemoments_indno, ...
+    %         ide_checks.idemodel_ino, ide_checks.idemoments_ino] = ...
+    %         identification_checks(H(indH,:)./normH(:,ones(nparam,1)),JJ(indJJ,:)./normJ(:,ones(nparam,1)), gp(indLRE,:)./normLRE(:,ones(size(gp,2),1)));
     [ide_moments.cond, ide_moments.ind0, ide_moments.indno, ide_moments.ino, ide_moments.Mco, ide_moments.Pco, ide_moments.jweak, ide_moments.jweak_pair] = ...
         identification_checks(JJ(indJJ,:)./normJ, 0);
     [ide_model.cond, ide_model.ind0, ide_model.indno, ide_model.ino, ide_model.Mco, ide_model.Pco, ide_model.jweak, ide_model.jweak_pair] = ...
@@ -354,9 +354,8 @@ if info(1)==0,
         ide_moments.S = S;
         ide_moments.V = V;
     end
-    
     indok = find(max(ide_moments.indno,[],1)==0);
-    if advanced,
+    if advanced
         [ide_moments.pars, ide_moments.cosnJ] = ident_bruteforce(JJ(indJJ,:)./normJ,max_dim_cova_group,options_.TeX,name_tex,tittxt);
     end
-end    
+end
diff --git a/matlab/identification_checks.m b/matlab/identification_checks.m
index 208d7ecd4efca23b10721d6d80428be7dbb5eeb8..e52fa960d882b1b93514de450bffde6fa6481def 100644
--- a/matlab/identification_checks.m
+++ b/matlab/identification_checks.m
@@ -7,21 +7,21 @@ function [condJ, ind0, indnoJ, ixnoJ, McoJ, PcoJ, jweak, jweak_pair] = identific
 %                                 derivatives of output w.r.t. parameters and shocks
 %    o JJ               [matrix] [nparams x nparams] IF hess_flag==1
 %                                 information matrix
-%    
+%
 % OUTPUTS
 %    o cond             condition number of JJ
 %    o ind0             [array] binary indicator for non-zero columns of H
-%    o indnoJ           [matrix] index of non-identified params 
+%    o indnoJ           [matrix] index of non-identified params
 %    o ixnoJ            number of rows in indnoJ
 %    o Mco              [array] multicollinearity coefficients
-%    o Pco              [matrix] pairwise correlations 
+%    o Pco              [matrix] pairwise correlations
 %    o jweak            [binary array] gives 1 if the  parameter has Mco=1(with tolerance 1.e-10)
 %    o jweak_pair       [binary matrix] gives 1 if a couple parameters has Pco=1(with tolerance 1.e-10)
-%    
+%
 % SPECIAL REQUIREMENTS
 %    None
 
-% Copyright (C) 2008-2011 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -45,23 +45,23 @@ function [condJ, ind0, indnoJ, ixnoJ, McoJ, PcoJ, jweak, jweak_pair] = identific
 npar = size(JJ,2);
 indnoJ = zeros(1,npar);
 
-if size(JJ,1)>1,
+if size(JJ,1)>1
     ind1 = find(vnorm(JJ)>=eps); % take non-zero columns
 else
     ind1 = find(abs(JJ)>=eps); % take non-zero columns
-end    
+end
 JJ1 = JJ(:,ind1);
 [eu,ee2,ee1] = svd( JJ1, 0 );
 condJ= cond(JJ1);
 rankJ = rank(JJ);
 rankJJ = rankJ;
 icheck=0;
-if npar>0 && (rankJ<npar), 
+if npar>0 && (rankJ<npar)
     % search for singular values associated to ONE individual parameter
     ee0 = [rankJJ+1:length(ind1)];
     ind11=ones(length(ind1),1);
-    for j=1:length(ee0),
-        if length(find(abs(ee1(:,ee0(j))) > 1.e-3))==1,
+    for j=1:length(ee0)
+        if length(find(abs(ee1(:,ee0(j))) > 1.e-3))==1
             icheck=1;
             ind11 = ind11.*(abs(ee1(:,ee0(j))) <= 1.e-3); % take non-zero columns
         end
@@ -69,26 +69,26 @@ if npar>0 && (rankJ<npar),
     ind1 = ind1(find(ind11)); % take non-zero columns
 end
 
-if icheck,
-JJ1 = JJ(:,ind1);
-[eu,ee2,ee1] = svd( JJ1, 0 );
-condJ= cond(JJ1);
-rankJ = rank(JJ);
-rankJJ = rankJ;
-end    
-    
+if icheck
+    JJ1 = JJ(:,ind1);
+    [eu,ee2,ee1] = svd( JJ1, 0 );
+    condJ= cond(JJ1);
+    rankJ = rank(JJ);
+    rankJJ = rankJ;
+end
+
 
 % if hess_flag==0,
 %     rankJJ = rank(JJ'*JJ);
-% end   
+% end
 
 ind0 = zeros(1,npar);
 ind0(ind1) = 1;
 
-if hess_flag==0,
+if hess_flag==0
     % find near linear dependence problems:
     McoJ = NaN(npar,1);
-    for ii = 1:size(JJ1,2);
+    for ii = 1:size(JJ1,2)
         McoJ(ind1(ii),:) = cosn([JJ1(:,ii),JJ1(:,find([1:1:size(JJ1,2)]~=ii))]);
     end
 else
@@ -96,7 +96,7 @@ else
     tildaJ = JJ(ind1,ind1)./((deltaJ)*(deltaJ'));
     McoJ(ind1,1)=(1-1./diag(inv(tildaJ)));
     rhoM=sqrt(1-McoJ);
-%     PcoJ=inv(tildaJ);
+    %     PcoJ=inv(tildaJ);
     PcoJ=NaN(npar,npar);
     PcoJ(ind1,ind1)=inv(JJ(ind1,ind1));
     sd=sqrt(diag(PcoJ));
@@ -109,19 +109,17 @@ if npar>0 && (rankJ<npar || rankJJ<npar || min(1-McoJ)<1.e-10)
     %         - find out which parameters are involved
     %   disp('Some parameters are NOT identified by the moments included in J')
     %   disp(' ')
-    if length(ind1)<npar,
+    if length(ind1)<npar
         % parameters with zero column in JJ
         ixnoJ = ixnoJ + 1;
         indnoJ(ixnoJ,:) = (~ismember([1:npar],ind1));
     end
     ee0 = [rankJJ+1:length(ind1)];
-    for j=1:length(ee0),
+    for j=1:length(ee0)
         % linearely dependent parameters in JJ
         ixnoJ = ixnoJ + 1;
         indnoJ(ixnoJ,ind1) = (abs(ee1(:,ee0(j))) > 1.e-3)';
     end
-else  %rank(J)==length(theta) =>
-      %         disp('All parameters are identified at theta by the moments included in J')
 end
 
 % here there is no exact linear dependence, but there are several
@@ -132,27 +130,26 @@ jweak=zeros(1,npar);
 jweak_pair=zeros(npar,npar);
 
 if hess_flag==0,
-PcoJ = NaN(npar,npar);
+    PcoJ = NaN(npar,npar);
 
-for ii = 1:size(JJ1,2);
-    PcoJ(ind1(ii),ind1(ii)) = 1;
-    for jj = ii+1:size(JJ1,2);
-        PcoJ(ind1(ii),ind1(jj)) = cosn([JJ1(:,ii),JJ1(:,jj)]);
-        PcoJ(ind1(jj),ind1(ii)) = PcoJ(ind1(ii),ind1(jj));
+    for ii = 1:size(JJ1,2)
+        PcoJ(ind1(ii),ind1(ii)) = 1;
+        for jj = ii+1:size(JJ1,2)
+            PcoJ(ind1(ii),ind1(jj)) = cosn([JJ1(:,ii),JJ1(:,jj)]);
+            PcoJ(ind1(jj),ind1(ii)) = PcoJ(ind1(ii),ind1(jj));
+        end
     end
-end
 
-for j=1:npar,
-    if McoJ(j)>(1-1.e-10), 
-        jweak(j)=1;
-        [ipair, jpair] = find(PcoJ(j,j+1:end)>(1-1.e-10));
-        for jx=1:length(jpair),
-            jweak_pair(j, jpair(jx)+j)=1;
-            jweak_pair(jpair(jx)+j, j)=1;
+    for j=1:npar
+        if McoJ(j)>(1-1.e-10)
+            jweak(j)=1;
+            [ipair, jpair] = find(PcoJ(j,j+1:end)>(1-1.e-10));
+            for jx=1:length(jpair)
+                jweak_pair(j, jpair(jx)+j)=1;
+                jweak_pair(jpair(jx)+j, j)=1;
+            end
         end
     end
 end
-end
 
 jweak_pair=dyn_vech(jweak_pair)';
-
diff --git a/matlab/imcforecast.m b/matlab/imcforecast.m
index f40475e486f23833d3bc3bcda3714096d75c878b..66841319a847fd3bf43f1d5269cfc2ea6ab6a114 100644
--- a/matlab/imcforecast.m
+++ b/matlab/imcforecast.m
@@ -2,31 +2,31 @@ function imcforecast(constrained_paths, constrained_vars, options_cond_fcst)
 % Computes conditional forecasts.
 %
 % 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 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". 
+%                                                                                               "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. 
+%                                                             + conf_sig            [double]     scalar in [0,1], probability mass covered by the confidence bands.
 %
 % 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. 
+%  [2] Use the function plot_icforecast to plot the results.
 
-% Copyright (C) 2006-2016 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -119,7 +119,7 @@ if estimated_model
     data_index = dataset_info.missing.aindex;
     gend = dataset_.nobs;
     missing_value = dataset_info.missing.state;
-    
+
     %store qz_criterium
     qz_criterium_old=options_.qz_criterium;
     options_=select_qz_criterium_value(options_);
@@ -147,7 +147,7 @@ if estimated_model
     % add trend to constant
     for obs_iter=1:length(options_.varobs)
         j = strmatch(options_.varobs{obs_iter},M_.endo_names,'exact');
-        constant(j,:) = constant(j,:)+trend_addition(obs_iter,:);        
+        constant(j,:) = constant(j,:)+trend_addition(obs_iter,:);
     end
     trend = constant(oo_.dr.order_var,:);
     InitState(:,1) = atT(:,end);
@@ -162,8 +162,21 @@ else
     end
 end
 
+if options_.logged_steady_state %if steady state was previously logged, undo this
+    oo_.dr.ys=exp(oo_.dr.ys);
+    oo_.steady_state=exp(oo_.steady_state);
+    options_.logged_steady_state=0;
+end
+
 [T,R,ys,info,M_,options_,oo_] = dynare_resolve(M_,options_,oo_);
 
+if options_.loglinear && isfield(oo_.dr,'ys') && options_.logged_steady_state==0 %log steady state
+    oo_.dr.ys=log_variable(1:M_.endo_nbr,oo_.dr.ys,M_);
+    ys=oo_.dr.ys;
+    oo_.steady_state=log_variable(1:M_.endo_nbr,oo_.steady_state,M_);
+    options_.logged_steady_state=1; %set option for use in stoch_simul
+end
+
 if ~isdiagonal(M_.Sigma_e)
     warning(sprintf('The innovations are correlated (the covariance matrix has non zero off diagonal elements), the results of the conditional forecasts will\ndepend on the ordering of the innovations (as declared after varexo) because a Cholesky decomposition is used to factorize the covariance matrix.\n\n=> It is preferable to declare the correlations in the model block (explicitly imposing the identification restrictions), unless you are satisfied\nwith the implicit identification restrictions implied by the Cholesky decomposition.'))
     sQ = chol(M_.Sigma_e,'lower');
@@ -175,7 +188,14 @@ if ~estimated_model
     if isempty(M_.endo_histval)
         y0 = ys;
     else
-        y0 = M_.endo_histval;
+        if options_.loglinear
+            %make sure that only states are updated (controls have value of 0 in vector)
+            y0=zeros(size(ys));
+            y0_logged = log_variable(1:M_.endo_nbr,M_.endo_histval,M_);
+            y0(M_.endo_histval~=0)=y0_logged(M_.endo_histval~=0);
+        else
+            y0 = M_.endo_histval;
+        end
     end
     InitState(:,1) = y0(oo_.dr.order_var)-ys(oo_.dr.order_var,:); %initial state in deviations from steady state
     trend = repmat(ys(oo_.dr.order_var,:),1,options_cond_fcst.periods+1); %trend needs to contain correct steady state
@@ -205,7 +225,7 @@ jdx = [];
 
 for i = 1:n1
     idx = [idx ; constrained_vars(i,:)];
-%     idx = [idx ; oo_.dr.inv_order_var(constrained_vars(i,:))];
+    %     idx = [idx ; oo_.dr.inv_order_var(constrained_vars(i,:))];
     jdx = [jdx ; strmatch(deblank(options_cond_fcst.controlled_varexo(i,:)),M_.exo_names,'exact')];
 end
 mv = zeros(n1,NumberOfStates);
diff --git a/matlab/indnv.m b/matlab/indnv.m
index 1df707786504f55a1038c7947bc88b7dda42bb11..0cc88ab5bbe4ce1d64ed99f52d74dc35d80ed477 100644
--- a/matlab/indnv.m
+++ b/matlab/indnv.m
@@ -13,7 +13,7 @@ function a=indnv(x,y)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2001-2009 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -40,6 +40,3 @@ for i = 1:size(x,1)
         a(i) = j;
     end
 end
-
-
-
diff --git a/matlab/init_plan.m b/matlab/init_plan.m
index 0e9957f48f68c3936adf650911f59b7e81fbc6a4..c82433be3b3401fef70fc46fe9194caa904da2b7 100644
--- a/matlab/init_plan.m
+++ b/matlab/init_plan.m
@@ -1,4 +1,4 @@
-function plan = init_plan(date) 
+function plan = init_plan(date)
 % Creates and initializes a new forecast scenario
 %
 % INPUTS
@@ -9,7 +9,7 @@ function plan = init_plan(date)
 %  plan                   [structure]       Returns a structure containing a new forecast scenario
 %
 %
-% Copyright (C) 2013-2014 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -25,28 +25,27 @@ function plan = init_plan(date)
 %
 % 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_
-  plan = struct();
-  plan.date = date;
-  plan.date_str = strings(date);
-  endo_names_length = size(M_.endo_names,2);
-  plan.endo_names = deblank(mat2cell(M_.endo_names(1:M_.orig_endo_nbr,:),ones(1,M_.orig_endo_nbr),endo_names_length));
-  exo_names_length = size(M_.exo_names,2);
-  plan.exo_names = deblank(mat2cell(M_.exo_names(1:M_.exo_nbr,:),ones(1,M_.exo_nbr),exo_names_length));
-  plan.constrained_vars_ = [];
-  plan.constrained_paths_ = [];
-  plan.constrained_date_ = [];
-  plan.constrained_int_date_ = []; 
-  plan.constrained_str_date_ = [];
-  plan.constrained_perfect_foresight_ = [];
-  plan.shock_vars_ = [];
-  plan.shock_paths_ = [];
-  plan.shock_date_ = [];
-  plan.shock_int_date_ = []; 
-  plan.shock_str_date_ = [];
-  plan.shock_perfect_foresight_ = [];
-  plan.options_cond_fcst_ = struct();
-  plan.options_cond_fcst_.parameter_set = 'calibration';
-  plan.options_cond_fcst_.simulation_type = 'deterministic';
-  plan.options_cond_fcst_.controlled_varexo = [];
-  
+global M_
+plan = struct();
+plan.date = date;
+plan.date_str = strings(date);
+endo_names_length = size(M_.endo_names,2);
+plan.endo_names = deblank(mat2cell(M_.endo_names(1:M_.orig_endo_nbr,:),ones(1,M_.orig_endo_nbr),endo_names_length));
+exo_names_length = size(M_.exo_names,2);
+plan.exo_names = deblank(mat2cell(M_.exo_names(1:M_.exo_nbr,:),ones(1,M_.exo_nbr),exo_names_length));
+plan.constrained_vars_ = [];
+plan.constrained_paths_ = [];
+plan.constrained_date_ = [];
+plan.constrained_int_date_ = [];
+plan.constrained_str_date_ = [];
+plan.constrained_perfect_foresight_ = [];
+plan.shock_vars_ = [];
+plan.shock_paths_ = [];
+plan.shock_date_ = [];
+plan.shock_int_date_ = [];
+plan.shock_str_date_ = [];
+plan.shock_perfect_foresight_ = [];
+plan.options_cond_fcst_ = struct();
+plan.options_cond_fcst_.parameter_set = 'calibration';
+plan.options_cond_fcst_.simulation_type = 'deterministic';
+plan.options_cond_fcst_.controlled_varexo = [];
diff --git a/matlab/initial_condition_decomposition.m b/matlab/initial_condition_decomposition.m
new file mode 100644
index 0000000000000000000000000000000000000000..cee5335a864da6f5d2ebeac0a3bf4a803e709ec7
--- /dev/null
+++ b/matlab/initial_condition_decomposition.m
@@ -0,0 +1,132 @@
+function oo_ = initial_condition_decomposition(M_,oo_,options_,varlist,bayestopt_,estim_params_)
+% function oo_ = initial_condition_decomposition(M_,oo_,options_,varlist,bayestopt_,estim_params_)
+% Computes initial condition contribution to a simulated trajectory. The field set is
+% oo_.initval_decomposition. It is a n_var by n_var+2 by nperiods array. The
+% first n_var columns store the respective endogenous initval contribution, column n+1
+% stores the role of the shocks, while column n+2 stores the
+% value of the smoothed variables.  Variables are stored
+% in the order of declaration, i.e. M_.endo_names.
+%
+% INPUTS
+%    M_:          [structure]  Definition of the model
+%    oo_:         [structure]  Storage of results
+%    options_:    [structure]  Options
+%    varlist:     [char]       List of variables
+%    bayestopt_:  [structure]  describing the priors
+%    estim_params_: [structure] characterizing parameters to be estimated
+%
+% OUTPUTS
+%    oo_:         [structure]  Storage of results
+%
+% SPECIAL REQUIREMENTS
+%    none
+
+% Copyright (C) 2017 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/>.
+
+options_.plot_shock_decomp.detail_plot = options_.initial_condition_decomp.detail_plot;
+options_.plot_shock_decomp.steadystate = options_.initial_condition_decomp.steadystate;
+options_.plot_shock_decomp.write_xls = options_.initial_condition_decomp.write_xls;
+options_.plot_shock_decomp.type = options_.initial_condition_decomp.type;
+options_.plot_shock_decomp.plot_init_date = options_.initial_condition_decomp.plot_init_date;
+options_.plot_shock_decomp.plot_end_date = options_.initial_condition_decomp.plot_end_date;
+
+% indices of endogenous variables
+if size(varlist,1) == 0
+    varlist = M_.endo_names(1:M_.orig_endo_nbr,:);
+end
+
+[i_var,nvar,index_uniques] = varlist_indices(varlist,M_.endo_names);
+varlist=varlist(index_uniques,:);
+
+% number of variables
+endo_nbr = M_.endo_nbr;
+
+% parameter set
+parameter_set = options_.parameter_set;
+if isempty(parameter_set)
+    if isfield(oo_,'posterior_mean')
+        parameter_set = 'posterior_mean';
+    elseif isfield(oo_,'mle_mode')
+        parameter_set = 'mle_mode';
+    elseif isfield(oo_,'posterior')
+        parameter_set = 'posterior_mode';
+    else
+        error(['shock_decomposition: option parameter_set is not specified ' ...
+               'and posterior mode is not available'])
+    end
+end
+
+if ~isfield(oo_,'initval_decomposition')
+    options_.selected_variables_only = 0; %make sure all variables are stored
+    options_.plot_priors=0;
+    [oo,junk1,junk2,Smoothed_Variables_deviation_from_mean] = evaluate_smoother(parameter_set,varlist,M_,oo_,options_,bayestopt_,estim_params_);
+
+    % reduced form
+    dr = oo.dr;
+
+    % data reordering
+    order_var = dr.order_var;
+    inv_order_var = dr.inv_order_var;
+
+
+    % coefficients
+    A = dr.ghx;
+    B = dr.ghu;
+
+    % initialization
+    gend = size(oo.SmoothedShocks.(deblank(M_.exo_names(1,:))),1); %+options_.forecast;
+    z = zeros(endo_nbr,endo_nbr+2,gend);
+    z(:,end,:) = Smoothed_Variables_deviation_from_mean;
+
+    for i=1:endo_nbr
+        z(i,i,1) = Smoothed_Variables_deviation_from_mean(i,1);
+    end
+
+    maximum_lag = M_.maximum_lag;
+
+    k2 = dr.kstate(find(dr.kstate(:,2) <= maximum_lag+1),[1 2]);
+    i_state = order_var(k2(:,1))+(min(i,maximum_lag)+1-k2(:,2))*M_.endo_nbr;
+    for i=1:gend
+        if i > 1 && i <= maximum_lag+1
+            lags = min(i-1,maximum_lag):-1:1;
+        end
+
+        if i > 1
+            tempx = permute(z(:,1:endo_nbr,lags),[1 3 2]);
+            m = min(i-1,maximum_lag);
+            tempx = [reshape(tempx,endo_nbr*m,endo_nbr); zeros(endo_nbr*(maximum_lag-i+1),endo_nbr)];
+            z(:,1:endo_nbr,i) = A(inv_order_var,:)*tempx(i_state,:);
+            lags = lags+1;
+        end
+        z(:,endo_nbr+1,i) = z(:,endo_nbr+2,i) - sum(z(:,1:endo_nbr,i),2);
+
+    end
+
+
+    oo_.initval_decomposition = z;
+end
+% if ~options_.no_graph.shock_decomposition
+oo=oo_;
+oo.shock_decomposition = oo_.initval_decomposition;
+M_.exo_names = M_.endo_names;
+M_.exo_nbr = M_.endo_nbr;
+options_.plot_shock_decomp.screen_shocks=1;
+options_.plot_shock_decomp.use_shock_groups = '';
+options_.plot_shock_decomp.fig_names='initval';
+plot_shock_decomposition(M_,oo,options_,varlist);
+% end
\ No newline at end of file
diff --git a/matlab/initial_estimation_checks.m b/matlab/initial_estimation_checks.m
index 03f0eac05e1121048de9daaa7ce83cd161f24baf..7dfc4d9a2a74e2bd2bdd7800b4a887c16234b944 100644
--- a/matlab/initial_estimation_checks.m
+++ b/matlab/initial_estimation_checks.m
@@ -20,7 +20,7 @@ function DynareResults = initial_estimation_checks(objective_function,xparam1,Dy
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2016 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -54,7 +54,7 @@ if maximum_number_non_missing_observations>length(find(diag(Model.Sigma_e)))+Est
 end
 
 if (any(BayesInfo.pshape  >0 ) && DynareOptions.mh_replic) && DynareOptions.mh_nblck<1
-    error(['initial_estimation_checks:: Bayesian estimation cannot be conducted with mh_nblocks=0.'])    
+    error(['initial_estimation_checks:: Bayesian estimation cannot be conducted with mh_nblocks=0.'])
 end
 
 old_steady_params=Model.params; %save initial parameters for check if steady state changes param values
@@ -69,35 +69,35 @@ if isfield(EstimatedParameters,'param_vals') && ~isempty(EstimatedParameters.par
     [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))));
+                             | (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(EstimatedParameters.param_vals(changed_par_indices,1),:));
         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')    
+        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;
-    if nvx && any(BayesInfo.p3(1:nvx)<0) 
+    if nvx && any(BayesInfo.p3(1:nvx)<0)
         warning('Your prior allows for negative standard deviations for structural shocks. Due to working with variances, Dynare will be able to continue, but it is recommended to change your prior.')
     end
     offset=nvx;
     nvn=EstimatedParameters.nvn;
-    if nvn && any(BayesInfo.p3(1+offset:offset+nvn)<0) 
+    if nvn && any(BayesInfo.p3(1+offset:offset+nvn)<0)
         warning('Your prior allows for negative standard deviations for measurement error. Due to working with variances, Dynare will be able to continue, but it is recommended to change your prior.')
     end
     offset = nvx+nvn;
-    ncx=EstimatedParameters.ncx; 
-    if ncx && (any(BayesInfo.p3(1+offset:offset+ncx)<-1) || any(BayesInfo.p4(1+offset:offset+ncx)>1)) 
+    ncx=EstimatedParameters.ncx;
+    if ncx && (any(BayesInfo.p3(1+offset:offset+ncx)<-1) || any(BayesInfo.p4(1+offset:offset+ncx)>1))
         warning('Your prior allows for correlations between structural shocks larger than +-1 and will not integrate to 1 due to truncation. Please change your prior')
     end
     offset = nvx+nvn+ncx;
-    ncn=EstimatedParameters.ncn; 
-    if ncn && (any(BayesInfo.p3(1+offset:offset+ncn)<-1) || any(BayesInfo.p4(1+offset:offset+ncn)>1)) 
+    ncn=EstimatedParameters.ncn;
+    if ncn && (any(BayesInfo.p3(1+offset:offset+ncn)<-1) || any(BayesInfo.p4(1+offset:offset+ncn)>1))
         warning('Your prior allows for correlations between measurement errors larger than +-1 and will not integrate to 1 due to truncation. Please change your prior')
     end
 end
@@ -142,9 +142,9 @@ if ~isequal(DynareOptions.mode_compute,11) || ...
         fprintf('initial_estimation_checks:: If you think the latter is the case, you should try with different initial values for the estimated parameters.\n')
         error('initial_estimation_checks:: The forecast error variance in the multivariate Kalman filter became singular.')
     end
-    %reset options 
+    %reset options
     DynareOptions.use_univariate_filters_if_singularity_is_detected=use_univariate_filters_if_singularity_is_detected_old;
-else 
+else
     info=0;
     fval = 0;
 end
@@ -165,8 +165,15 @@ elseif imag(fval)
 end
 
 if info(1) > 0
-    disp('Error in computing likelihood for initial parameter values')
-    print_info(info, DynareOptions.noprint, DynareOptions)
+    if DynareOptions.order>1
+        [eigenvalues_] = check(Model,DynareOptions, DynareResults);
+        if any(abs(1-abs(eigenvalues_))<abs(DynareOptions.qz_criterium-1))
+            error('Your model has at least one unit root and you are using a nonlinear filter. Please set nonlinear_filter_initialization=3.')
+        end
+    else
+        disp('Error in computing likelihood for initial parameter values')
+        print_info(info, DynareOptions.noprint, DynareOptions)
+    end
 end
 
 if DynareOptions.prefilter==1
diff --git a/matlab/initialize_from_mode.m b/matlab/initialize_from_mode.m
index d7c11a9d0d5f289705bb80556a2db3fe4c33fced..4521ec255bff48a31623888d35acb4796da4134a 100644
--- a/matlab/initialize_from_mode.m
+++ b/matlab/initialize_from_mode.m
@@ -1,20 +1,20 @@
 function estim_params_ = initialize_from_mode(fname,M_,estim_params_)
 % function estim_params_ = initialize_from_mode(fname,M_,estim_params_)
 % initialize parameters and initial value of estimated parameters
-% from a *_mode.mat file    
-%  
+% from a *_mode.mat file
+%
 % INPUTS
 %   fname:  mode file name (*.mat file)
 %   M_:     sructure of model characteristics
 %   estim_params_: structure of estimated parameters
-%  
+%
 % OUTPUTS
 %   estim_params:  modified structure of estimated parameters
 %
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2003-2011 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -99,4 +99,3 @@ for i=1:length(parameter_names)
     end
     error([name 'doesn''t exist in this model'])
 end
-
diff --git a/matlab/initvalf.m b/matlab/initvalf.m
index 0493a2b48a8efdb378b478685083c6dacdbd02b8..afffede434d917905c7cce3567dff258d9410137 100644
--- a/matlab/initvalf.m
+++ b/matlab/initvalf.m
@@ -1,7 +1,7 @@
 function initvalf(fname_)
 % function initvalf(fname_)
 %
-% Reads an initial path from the 'fname_' file for exogenous and endogenous variables   
+% Reads an initial path from the 'fname_' file for exogenous and endogenous variables
 %
 % INPUTS
 %    fname_:         name of the function or file containing the data
@@ -13,7 +13,7 @@ function initvalf(fname_)
 %    All variables local to this function have an underscore appended to
 %    their name, to minimize clashes with model variables loaded by this function.
 
-% Copyright (C) 2003-2012 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -58,15 +58,15 @@ if ~exist(fullname)
 end
 
 switch (extension)
-    case '.m'
-        eval(basename);
-    case '.mat'
-        load(basename);
-    case { '.xls', '.xlsx' }
-        [data_,names_v_]=xlsread(fullname); % Octave needs the extension explicitly
-        series_=0;
-    otherwise
-        error(['Unsupported extension for datafile: ' extension])
+  case '.m'
+    eval(basename);
+  case '.mat'
+    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
 
 options_.initval_file = 1;
@@ -79,7 +79,7 @@ for i_=1:size(M_.endo_names,1)
         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_'];            
+            oo_.endo_simul = [oo_.endo_simul; x_'];
         end
     else
         k_ = strmatch(deblank(M_.endo_names(i_,:)),names_v_,'exact');
@@ -87,7 +87,7 @@ for i_=1:size(M_.endo_names,1)
             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
 
@@ -97,7 +97,7 @@ for i_=1:size(M_.exo_names,1)
         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_];            
+            oo_.exo_simul = [oo_.exo_simul x_];
         end
     else
         k_ = strmatch(deblank(M_.exo_names(i_,:)),names_v_,'exact');
@@ -105,6 +105,6 @@ for i_=1:size(M_.exo_names,1)
             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
\ No newline at end of file
diff --git a/matlab/internals.m b/matlab/internals.m
index 4fc079ec28fd4f2064cfe3245f055a6ba48eb2bc..a7b96a81f8b194f5cd92030e533ef77c0ca243e2 100644
--- a/matlab/internals.m
+++ b/matlab/internals.m
@@ -56,7 +56,7 @@ function internals(flag, varargin)
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2014 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/interpret_resol_info.m b/matlab/interpret_resol_info.m
index de16d47e093ffba38e9b35740a705bac521ff205..45b3993ff8f637a43f1b2d58901e0498e88299dc 100644
--- a/matlab/interpret_resol_info.m
+++ b/matlab/interpret_resol_info.m
@@ -1,15 +1,15 @@
 function message = interpret_resol_info(info)
-    
+
 % Returns a message describing problem encountered during the resolution of
 % a model.
 %
-% INPUTS 
+% INPUTS
 % - info       [struct]  Second output argument return by the resol routine
 %
-% OUTPUTS 
+% OUTPUTS
 % - message    [string]  Description of the issue preventing model's resolution.
- 
-% Copyright (C) 2001-2016 Dynare Team
+
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/irf.m b/matlab/irf.m
index f4be40503a07b74a5b8b051b2f85e2609befea77..2355392d76c32bfe1a90491208104e856f9c4cbb 100644
--- a/matlab/irf.m
+++ b/matlab/irf.m
@@ -2,7 +2,7 @@ function y = irf(dr, e1, long, drop, replic, iorder)
 
 % function y = irf(dr, e1, long, drop, replic, iorder)
 % Computes impulse response functions
-% 
+%
 % INPUTS
 %    dr:     structure of decisions rules for stochastic simulations
 %    e1:     exogenous variables value in time 1 after one shock
@@ -13,11 +13,11 @@ function y = irf(dr, e1, long, drop, replic, iorder)
 %
 % OUTPUTS
 %    y:      impulse response matrix
-%        
+%
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2010 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -44,11 +44,16 @@ else
 end
 y       = 0;
 
-if iorder == 1
+local_order = iorder;
+if M_.hessian_eq_zero && local_order~=1
+    local_order = 1;
+end
+
+if local_order == 1
     y1 = repmat(dr.ys,1,long);
     ex2 = zeros(long,M_.exo_nbr);
     ex2(1,:) = e1';
-    y2 = simult_(temps,dr,ex2,iorder);
+    y2 = simult_(temps,dr,ex2,local_order);
     y = y2(:,M_.maximum_lag+1:end)-y1;
 else
     % eliminate shocks with 0 variance
@@ -60,9 +65,9 @@ else
     for j = 1: replic
         ex1(:,i_exo_var) = randn(long+drop,nxs)*chol_S;
         ex2 = ex1;
-        ex2(drop+1,:) = ex2(drop+1,:)+e1';   
-        y1 = simult_(temps,dr,ex1,iorder);
-        y2 = simult_(temps,dr,ex2,iorder);
+        ex2(drop+1,:) = ex2(drop+1,:)+e1';
+        y1 = simult_(temps,dr,ex1,local_order);
+        y2 = simult_(temps,dr,ex2,local_order);
         y = y+(y2(:,M_.maximum_lag+drop+1:end)-y1(:,M_.maximum_lag+drop+1:end));
     end
     y=y/replic;
diff --git a/matlab/isoctave.m b/matlab/isoctave.m
index 15c6fb38d1ef3df32cee857f08261ebc9b3ab262..22941ce9e9e8d3bab51503ddb7d6022ed2549de9 100644
--- a/matlab/isoctave.m
+++ b/matlab/isoctave.m
@@ -1,6 +1,6 @@
 function A = isoctave()
 
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2016 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/isolder.m b/matlab/isolder.m
index 091455ad0781022e52a9e31472e7fcc2d683e5c0..d364c5c626e3d4871dafbd924262ce91926cf15d 100644
--- a/matlab/isolder.m
+++ b/matlab/isolder.m
@@ -2,14 +2,14 @@ function b = isolder(f, F) % --*-- Unitary tests --*--
 
 % Returns true if f is older than any file in folder (and subfolders) F.
 %
-% INPUTS 
+% INPUTS
 % - f   [string]  file name
 % - F   [string]  folder name
 %
-% OUTPUT 
-% - b   [logical] 
+% OUTPUT
+% - b   [logical]
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -29,9 +29,9 @@ function b = isolder(f, F) % --*-- Unitary tests --*--
 if nargin<2 || isempty(F)
     F = pwd();
 end
- 
+
 b = true;
-    
+
 files = dir(F);
 tfile = dir(f);
 tdate = tfile.datenum;
diff --git a/matlab/k_order_pert.m b/matlab/k_order_pert.m
index db1ef91f48587ba727b132f73f37c53128f49c8d..05c56eb37abbe3770efa798da64a8344d4e52e96 100644
--- a/matlab/k_order_pert.m
+++ b/matlab/k_order_pert.m
@@ -1,7 +1,7 @@
 function [dr,info] = k_order_pert(dr,M,options)
 % Compute decision rules using the k-order DLL from Dynare++
 
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -27,45 +27,45 @@ endo_nbr = M.endo_nbr;
 exo_nbr = M.exo_nbr;
 nspred = M.nspred;
 
-if order>1 && options.loglinear 
-   error('The loglinear-option currently only works at order 1') 
+if order>1 && options.loglinear
+    error('The loglinear-option currently only works at order 1')
 end
 if M.maximum_endo_lead == 0 && order>1
-  error(['2nd and 3rd order approximation not implemented for purely ' ...
-       'backward models'])
+    error(['2nd and 3rd order approximation not implemented for purely ' ...
+           'backward models'])
 end
 
 switch(order)
   case 1
     [err, g_1] = k_order_perturbation(dr,M,options);
     if err
-      info(1)=9;
-      return;
+        info(1)=9;
+        return
     end
     dr.g_1 = g_1;
   case 2
     [err, g_0, g_1, g_2] = k_order_perturbation(dr,M,options);
     if err
-      info(1)=9;
-      return;
+        info(1)=9;
+        return
     end
     dr.g_0 = g_0;
     dr.g_1 = g_1;
     dr.g_2 = g_2;
   case 3
-    if options.pruning 
+    if options.pruning
         [err, g_0, g_1, g_2, g_3, derivs] = k_order_perturbation(dr, ...
                                                           M,options);
         if err
-          info(1)=9;
-          return;
+            info(1)=9;
+            return
         end
     else
         [err, g_0, g_1, g_2, g_3] = k_order_perturbation(dr, ...
                                                          M,options);
         if err
-          info(1)=9;
-          return;
+            info(1)=9;
+            return
         end
     end
     dr.g_0 = g_0;
@@ -119,7 +119,7 @@ else
                 if s1 > s0
                     ghxx(:,s1*nspred+s0+1) = 2*g_2(:,i);
                 end
-            elseif s0 < nspred && s1 < nspred+exo_nbr 
+            elseif s0 < nspred && s1 < nspred+exo_nbr
                 ghxu(:,(s0*exo_nbr+s1-nspred+1)) = 2*g_2(:,i);
             elseif s0 < nspred+exo_nbr && s1 < nspred+exo_nbr
                 ghuu(:,(s0-nspred)*exo_nbr+s1-nspred +1) = 2*g_2(:,i);
@@ -132,7 +132,7 @@ else
             s1 = s1+1;
             if s1 == nspred+exo_nbr
                 s0 = s0+1;
-                s1 = s0; 
+                s1 = s0;
             end
         end % for loop
         dr.ghxx = ghxx;
@@ -186,7 +186,7 @@ for i=1:n1
             m = m + 1;
         end
     end
-end 
+end
 
 function y = unfold12(x,n1,n2)
 y = zeros(size(x,1),n1*n2*n2);
@@ -203,7 +203,3 @@ for i=1:n1
         end
     end
 end
-
-
-            
-            
diff --git a/matlab/kalman/build_selection_matrix.m b/matlab/kalman/build_selection_matrix.m
index f78662ddb000dc34019450f775cb01dc9c7ee389..e9899591c2cd04dcc0291423a0d22159b450ad19 100644
--- a/matlab/kalman/build_selection_matrix.m
+++ b/matlab/kalman/build_selection_matrix.m
@@ -2,7 +2,7 @@ function Z = build_selection_matrix(mf,m,p)
 % Builds the selection matrix of the measurement equation from the vector
 % of indices mf.
 
-% Copyright (C) 2004-2009 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -17,7 +17,7 @@ function Z = build_selection_matrix(mf,m,p)
 % 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/>.
 Z = zeros(p,m);
 for i=1:p
     Z(i,mf(i)) = 1;
diff --git a/matlab/kalman/likelihood/computeDLIK.m b/matlab/kalman/likelihood/computeDLIK.m
index 1acb0796ff167c6112be36ad521eb0051a391635..0fc417220c2a3f43314138bd0f656f5395655dfa 100644
--- a/matlab/kalman/likelihood/computeDLIK.m
+++ b/matlab/kalman/likelihood/computeDLIK.m
@@ -1,6 +1,6 @@
 function [Da,DP,DLIK,D2a,D2P,Hesst] = computeDLIK(k,tmp,Z,Zflag,v,T,K,P,iF,Da,DYss,DT,DOm,DP,DH,notsteady,D2a,D2Yss,D2T,D2Om,D2P)
 
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -22,22 +22,22 @@ function [Da,DP,DLIK,D2a,D2P,Hesst] = computeDLIK(k,tmp,Z,Zflag,v,T,K,P,iF,Da,DY
 persistent DK DF D2K D2F
 
 if notsteady
-if Zflag
-    [DK,DF,DP1] = computeDKalmanZ(T,DT,DOm,P,DP,DH,Z,iF,K);
-    if nargout>4,
-        [D2K,D2F,D2P] = computeD2KalmanZ(T,DT,D2T,D2Om,P,DP,D2P,DH,Z,iF,K,DK);
-    end
-else
-    [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,Z,iF,K);
-    if nargout>4,
-        [D2K,D2F,D2P] = computeD2Kalman(T,DT,D2T,D2Om,P,DP,D2P,DH,Z,iF,K,DK);
+    if Zflag
+        [DK,DF,DP1] = computeDKalmanZ(T,DT,DOm,P,DP,DH,Z,iF,K);
+        if nargout>4
+            [D2K,D2F,D2P] = computeD2KalmanZ(T,DT,D2T,D2Om,P,DP,D2P,DH,Z,iF,K,DK);
+        end
+    else
+        [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,Z,iF,K);
+        if nargout>4
+            [D2K,D2F,D2P] = computeD2Kalman(T,DT,D2T,D2Om,P,DP,D2P,DH,Z,iF,K,DK);
+        end
     end
-end
-DP=DP1;
-clear DP1,
+    DP=DP1;
+    clear DP1
 else
     DP=DP;
-    if nargout>4,
+    if nargout>4
         D2P=D2P;
     end
 end
@@ -47,20 +47,20 @@ Dv=zeros(length(v),k);
 for ii = 1:k
     if Zflag
         Dv(:,ii)   = -Z*Da(:,ii) - Z*DYss(:,ii);
-%         if nargout>4,
-%             for jj = 1:ii
-%                 D2v(:,jj,ii)  = -Z*D2Yss(:,jj,ii)  - Z*D2a(:,jj,ii);
-%                 D2v(:,ii,jj) = D2v(:,jj,ii);
-%             end
-%         end
+        %         if nargout>4,
+        %             for jj = 1:ii
+        %                 D2v(:,jj,ii)  = -Z*D2Yss(:,jj,ii)  - Z*D2a(:,jj,ii);
+        %                 D2v(:,ii,jj) = D2v(:,jj,ii);
+        %             end
+        %         end
     else
         Dv(:,ii)   = -Da(Z,ii) - DYss(Z,ii);
-%         if nargout>4,
-%             for jj = 1:ii
-%                 D2v(:,jj,ii)  = -D2Yss(Z,jj,ii)  - D2a(Z,jj,ii);
-%                 D2v(:,ii,jj) = D2v(:,jj,ii);
-%             end
-%         end
+        %         if nargout>4,
+        %             for jj = 1:ii
+        %                 D2v(:,jj,ii)  = -D2Yss(Z,jj,ii)  - D2a(Z,jj,ii);
+        %                 D2v(:,ii,jj) = D2v(:,jj,ii);
+        %             end
+        %         end
     end
 end
 
@@ -71,8 +71,8 @@ for ii = 1:k
     %  dai = da(:,:,ii);
     dKi  = DK(:,:,ii);
     dtmp(:,ii) = Da(:,ii)+dKi*v+K*Dv(:,ii);
-    
-    if nargout>4,
+
+    if nargout>4
         diFi = -iF*DF(:,:,ii)*iF;
         for jj = 1:ii
             jcount=jcount+1;
@@ -82,9 +82,9 @@ for ii = 1:k
             d2Kij  = D2K(:,:,jj,ii);
             d2Fij  = D2F(:,:,jj,ii);
             d2iFij = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi;
-%             dtmpj = Da(:,jj)+dKj*v+K*Dv(:,jj);
-            
-%             d2vij  = D2v(:,ii,jj);
+            %             dtmpj = Da(:,jj)+dKj*v+K*Dv(:,jj);
+
+            %             d2vij  = D2v(:,ii,jj);
             if Zflag
                 d2vij  = -Z*D2Yss(:,jj,ii)  - Z*D2a(:,jj,ii);
             else
@@ -93,36 +93,36 @@ for ii = 1:k
             d2tmpij = D2a(:,jj,ii) + d2Kij*v + dKj*Dv(:,ii) + dKi*Dv(:,jj) + K*d2vij;
             D2a(:,jj,ii) = reshape(D2T(:,jcount),size(T))*tmp + DT(:,:,jj)*dtmp(:,ii) + DT(:,:,ii)*dtmp(:,jj) + T*d2tmpij;
             D2a(:,ii,jj) = D2a(:,jj,ii);
-            
-            if nargout==6,
+
+            if nargout==6
                 Hesst(ii,jj) = getHesst_ij(v,Dv(:,ii),Dv(:,jj),d2vij,iF,diFi,diFj,d2iFij,dFj,d2Fij);
             end
         end
     end
-        
+
     Da(:,ii)   = DT(:,:,ii)*tmp + T*dtmp(:,ii);
     DLIK(ii,1)  = trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v;
 end
 
-if nargout==4,
+if nargout==4
     %         Hesst(ii,jj) = getHesst_ij(v,Dv(:,ii),Dv(:,jj),0,iF,diFi,diFj,0,dFj,0);
     vecDPmf = reshape(DF,[],k);
     D2a = 2*Dv'*iF*Dv + (vecDPmf' * kron(iF,iF) * vecDPmf);
-%     for ii = 1:k
-%         
-%         diFi = -iF*DF(:,:,ii)*iF;
-%         for jj = 1:ii
-%             dFj    = DF(:,:,jj);
-%             diFj   = -iF*DF(:,:,jj)*iF;
-%             
-%             Hesst(ii,jj) = getHesst_ij(v*0,Dv(:,ii),Dv(:,jj),v*0,iF,diFi,diFj,0,-dFj,0);
-%         end
-%     end
+    %     for ii = 1:k
+    %
+    %         diFi = -iF*DF(:,:,ii)*iF;
+    %         for jj = 1:ii
+    %             dFj    = DF(:,:,jj);
+    %             diFj   = -iF*DF(:,:,jj)*iF;
+    %
+    %             Hesst(ii,jj) = getHesst_ij(v*0,Dv(:,ii),Dv(:,jj),v*0,iF,diFi,diFj,0,-dFj,0);
+    %         end
+    %     end
 end
 
 % end of computeDLIK
 
-function Hesst_ij = getHesst_ij(e,dei,dej,d2eij,iS,diSi,diSj,d2iSij,dSj,d2Sij);
+function Hesst_ij = getHesst_ij(e,dei,dej,d2eij,iS,diSi,diSj,d2iSij,dSj,d2Sij)
 % computes (i,j) term in the Hessian
 
 Hesst_ij = trace(diSi*dSj + iS*d2Sij) + e'*d2iSij*e + 2*(dei'*diSj*e + dei'*iS*dej + e'*diSi*dej + e'*iS*d2eij);
@@ -165,12 +165,12 @@ end
 
 % end of computeDKalmanZ
 
-function [d2K,d2S,d2P1] = computeD2Kalman(A,dA,d2A,d2Om,P0,dP0,d2P1,DH,Z,iF,K0,dK0);
+function [d2K,d2S,d2P1] = computeD2Kalman(A,dA,d2A,d2Om,P0,dP0,d2P1,DH,Z,iF,K0,dK0)
 % computes the second derivatives of the Kalman matrices
 % note: A=T in main func.
-        
-            k      = size(dA,3);
-            tmp    = P0-K0*P0(Z,:);
+
+k      = size(dA,3);
+tmp    = P0-K0*P0(Z,:);
 [ns,no] = size(K0);
 
 % CPC = C*P0*C'; CPC = .5*(CPC+CPC');iF = inv(CPC);
@@ -186,14 +186,14 @@ jcount=0;
 for ii = 1:k
     dAi = dA(:,:,ii);
     dFi = dP0(Z,Z,ii);
-%     d2Omi = d2Om(:,:,ii);
+    %     d2Omi = d2Om(:,:,ii);
     diFi = -iF*dFi*iF;
     dKi = dK0(:,:,ii);
-    for jj = 1:ii,
+    for jj = 1:ii
         jcount=jcount+1;
         dAj = dA(:,:,jj);
         dFj = dP0(Z,Z,jj);
-%         d2Omj = d2Om(:,:,jj);
+        %         d2Omj = d2Om(:,:,jj);
         dFj = dP0(Z,Z,jj);
         diFj = -iF*dFj*iF;
         dKj = dK0(:,:,jj);
@@ -201,44 +201,44 @@ for ii = 1:k
         d2Aij = reshape(d2A(:,jcount),[ns ns]);
         d2Pij = dyn_unvech(d2P1(:,jcount));
         d2Omij = dyn_unvech(d2Om(:,jcount));
-       
-    % second order
-    
-    d2Fij = d2Pij(Z,Z) ;
-    
-%     d2APC = d2Aij*P0*C' + A*d2Pij*C' + A*P0*d2Cij' + dAi*dPj*C' + dAj*dPi*C' + A*dPj*dCi' + A*dPi*dCj' + dAi*P0*dCj' + dAj*P0*dCi';
-    d2APC = d2Pij(:,Z);
-    
-    d2iF = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi;
-    
-    d2Kij= d2Pij(:,Z)*iF + P0(:,Z)*d2iF + dP0(:,Z,jj)*diFi + dP0(:,Z,ii)*diFj;
-        
-    d2KCP = d2Kij*P0(Z,:) + K0*d2Pij(Z,:) + dKi*dP0(Z,:,jj) + dKj*dP0(Z,:,ii) ;
-    
-    dtmpi        = dP0(:,:,ii) - dK0(:,:,ii)*P0(Z,:) - K0*dP0(Z,:,ii);
-    dtmpj        = dP0(:,:,jj) - dK0(:,:,jj)*P0(Z,:) - K0*dP0(Z,:,jj);
-    d2tmp = d2Pij - d2KCP;
-
-    d2AtmpA = d2Aij*tmp*A' + A*d2tmp*A' + A*tmp*d2Aij' + dAi*dtmpj*A' + dAj*dtmpi*A' + A*dtmpj*dAi' + A*dtmpi*dAj' + dAi*tmp*dAj' + dAj*tmp*dAi';
-
-    d2K(:,:,ii,jj)  = d2Kij; %#ok<NASGU>
-    d2P1(:,jcount) = dyn_vech(d2AtmpA  + d2Omij);  %#ok<*NASGU>
-    d2S(:,:,ii,jj)  = d2Fij;
-    d2K(:,:,jj,ii)  = d2Kij; %#ok<NASGU>
-%     d2P1(:,:,jj,ii) = d2AtmpA  + d2Omij;  %#ok<*NASGU>
-    d2S(:,:,jj,ii)  = d2Fij;
-%     d2iS(:,:,ii,jj) = d2iF;
+
+        % second order
+
+        d2Fij = d2Pij(Z,Z) ;
+
+        %     d2APC = d2Aij*P0*C' + A*d2Pij*C' + A*P0*d2Cij' + dAi*dPj*C' + dAj*dPi*C' + A*dPj*dCi' + A*dPi*dCj' + dAi*P0*dCj' + dAj*P0*dCi';
+        d2APC = d2Pij(:,Z);
+
+        d2iF = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi;
+
+        d2Kij= d2Pij(:,Z)*iF + P0(:,Z)*d2iF + dP0(:,Z,jj)*diFi + dP0(:,Z,ii)*diFj;
+
+        d2KCP = d2Kij*P0(Z,:) + K0*d2Pij(Z,:) + dKi*dP0(Z,:,jj) + dKj*dP0(Z,:,ii) ;
+
+        dtmpi        = dP0(:,:,ii) - dK0(:,:,ii)*P0(Z,:) - K0*dP0(Z,:,ii);
+        dtmpj        = dP0(:,:,jj) - dK0(:,:,jj)*P0(Z,:) - K0*dP0(Z,:,jj);
+        d2tmp = d2Pij - d2KCP;
+
+        d2AtmpA = d2Aij*tmp*A' + A*d2tmp*A' + A*tmp*d2Aij' + dAi*dtmpj*A' + dAj*dtmpi*A' + A*dtmpj*dAi' + A*dtmpi*dAj' + dAi*tmp*dAj' + dAj*tmp*dAi';
+
+        d2K(:,:,ii,jj)  = d2Kij; %#ok<NASGU>
+        d2P1(:,jcount) = dyn_vech(d2AtmpA  + d2Omij);  %#ok<*NASGU>
+        d2S(:,:,ii,jj)  = d2Fij;
+        d2K(:,:,jj,ii)  = d2Kij; %#ok<NASGU>
+                                 %     d2P1(:,:,jj,ii) = d2AtmpA  + d2Omij;  %#ok<*NASGU>
+        d2S(:,:,jj,ii)  = d2Fij;
+        %     d2iS(:,:,ii,jj) = d2iF;
     end
 end
 
 % end of computeD2Kalman
 
-function [d2K,d2S,d2P1] = computeD2KalmanZ(A,dA,d2A,d2Om,P0,dP0,d2P1,DH,Z,iF,K0,dK0);
+function [d2K,d2S,d2P1] = computeD2KalmanZ(A,dA,d2A,d2Om,P0,dP0,d2P1,DH,Z,iF,K0,dK0)
 % computes the second derivatives of the Kalman matrices
 % note: A=T in main func.
-        
-            k      = size(dA,3);
-            tmp    = P0-K0*Z*P0(:,:);
+
+k      = size(dA,3);
+tmp    = P0-K0*Z*P0(:,:);
 [ns,no] = size(K0);
 
 % CPC = C*P0*C'; CPC = .5*(CPC+CPC');iF = inv(CPC);
@@ -251,17 +251,17 @@ d2S  = zeros(no,no,k,k);
 % d2P1 = zeros(ns,ns,k,k);
 
 jcount=0;
-for ii = 1:k,
+for ii = 1:k
     dAi = dA(:,:,ii);
     dFi = Z*dP0(:,:,ii)*Z;
-%     d2Omi = d2Om(:,:,ii);
+    %     d2Omi = d2Om(:,:,ii);
     diFi = -iF*dFi*iF;
     dKi = dK0(:,:,ii);
-    for jj = 1:ii,
+    for jj = 1:ii
         jcount=jcount+1;
         dAj = dA(:,:,jj);
         dFj = Z*dP0(:,:,jj)*Z;
-%         d2Omj = d2Om(:,:,jj);
+        %         d2Omj = d2Om(:,:,jj);
         dFj = Z*dP0(:,:,jj)*Z;
         diFj = -iF*dFj*iF;
         dKj = dK0(:,:,jj);
@@ -269,36 +269,34 @@ for ii = 1:k,
         d2Aij = reshape(d2A(:,jcount),[ns ns]);
         d2Pij = dyn_unvech(d2P1(:,jcount));
         d2Omij = dyn_unvech(d2Om(:,jcount));
-       
-    % second order
-    
-    d2Fij = Z*d2Pij(:,:)*Z ;
-    
-%     d2APC = d2Aij*P0*C' + A*d2Pij*C' + A*P0*d2Cij' + dAi*dPj*C' + dAj*dPi*C' + A*dPj*dCi' + A*dPi*dCj' + dAi*P0*dCj' + dAj*P0*dCi';
-    d2APC = d2Pij(:,:)*Z;
-    
-    d2iF = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi;
-    
-    d2Kij= d2Pij(:,:)*Z*iF + P0(:,:)*Z*d2iF + dP0(:,:,jj)*Z*diFi + dP0(:,:,ii)*Z*diFj;
-        
-    d2KCP = d2Kij*Z*P0(:,:) + K0*Z*d2Pij(:,:) + dKi*Z*dP0(:,:,jj) + dKj*Z*dP0(:,:,ii) ;
-    
-    dtmpi        = dP0(:,:,ii) - dK0(:,:,ii)*Z*P0(:,:) - K0*Z*dP0(:,:,ii);
-    dtmpj        = dP0(:,:,jj) - dK0(:,:,jj)*Z*P0(:,:) - K0*Z*dP0(:,:,jj);
-    d2tmp = d2Pij - d2KCP;
-
-    d2AtmpA = d2Aij*tmp*A' + A*d2tmp*A' + A*tmp*d2Aij' + dAi*dtmpj*A' + dAj*dtmpi*A' + A*dtmpj*dAi' + A*dtmpi*dAj' + dAi*tmp*dAj' + dAj*tmp*dAi';
-
-    d2K(:,:,ii,jj)  = d2Kij; %#ok<NASGU>
-    d2P1(:,jcount) = dyn_vech(d2AtmpA  + d2Omij);  %#ok<*NASGU>
-    d2S(:,:,ii,jj)  = d2Fij;
-%     d2iS(:,:,ii,jj) = d2iF;
-    d2K(:,:,jj,ii)  = d2Kij; %#ok<NASGU>
-%     d2P1(:,:,jj,ii) = d2AtmpA  + d2Omij;  %#ok<*NASGU>
-    d2S(:,:,jj,ii)  = d2Fij;
+
+        % second order
+
+        d2Fij = Z*d2Pij(:,:)*Z ;
+
+        %     d2APC = d2Aij*P0*C' + A*d2Pij*C' + A*P0*d2Cij' + dAi*dPj*C' + dAj*dPi*C' + A*dPj*dCi' + A*dPi*dCj' + dAi*P0*dCj' + dAj*P0*dCi';
+        d2APC = d2Pij(:,:)*Z;
+
+        d2iF = -diFi*dFj*iF -iF*d2Fij*iF -iF*dFj*diFi;
+
+        d2Kij= d2Pij(:,:)*Z*iF + P0(:,:)*Z*d2iF + dP0(:,:,jj)*Z*diFi + dP0(:,:,ii)*Z*diFj;
+
+        d2KCP = d2Kij*Z*P0(:,:) + K0*Z*d2Pij(:,:) + dKi*Z*dP0(:,:,jj) + dKj*Z*dP0(:,:,ii) ;
+
+        dtmpi        = dP0(:,:,ii) - dK0(:,:,ii)*Z*P0(:,:) - K0*Z*dP0(:,:,ii);
+        dtmpj        = dP0(:,:,jj) - dK0(:,:,jj)*Z*P0(:,:) - K0*Z*dP0(:,:,jj);
+        d2tmp = d2Pij - d2KCP;
+
+        d2AtmpA = d2Aij*tmp*A' + A*d2tmp*A' + A*tmp*d2Aij' + dAi*dtmpj*A' + dAj*dtmpi*A' + A*dtmpj*dAi' + A*dtmpi*dAj' + dAi*tmp*dAj' + dAj*tmp*dAi';
+
+        d2K(:,:,ii,jj)  = d2Kij; %#ok<NASGU>
+        d2P1(:,jcount) = dyn_vech(d2AtmpA  + d2Omij);  %#ok<*NASGU>
+        d2S(:,:,ii,jj)  = d2Fij;
+        %     d2iS(:,:,ii,jj) = d2iF;
+        d2K(:,:,jj,ii)  = d2Kij; %#ok<NASGU>
+                                 %     d2P1(:,:,jj,ii) = d2AtmpA  + d2Omij;  %#ok<*NASGU>
+        d2S(:,:,jj,ii)  = d2Fij;
     end
 end
 
 % end of computeD2KalmanZ
-
-
diff --git a/matlab/kalman/likelihood/kalman_filter.m b/matlab/kalman/likelihood/kalman_filter.m
index 5c375a241f99c9df9b5a30171bf8a17529f96d07..441ee8525190e9a8a1cb1fd33acb3d931e2ceecc 100644
--- a/matlab/kalman/likelihood/kalman_filter.m
+++ b/matlab/kalman/likelihood/kalman_filter.m
@@ -1,4 +1,4 @@
-function [LIK, LIKK, a, P] = kalman_filter(Y,start,last,a,P,kalman_tol,riccati_tol,presample,T,Q,R,H,Z,mm,pp,rr,Zflag,diffuse_periods,analytic_derivation,DT,DYss,DOm,DH,DP,D2T,D2Yss,D2Om,D2H,D2P)
+function [LIK, LIKK, a, P] = kalman_filter(Y,start,last,a,P,kalman_tol,riccati_tol,rescale_prediction_error_covariance,presample,T,Q,R,H,Z,mm,pp,rr,Zflag,diffuse_periods,analytic_derivation,DT,DYss,DOm,DH,DP,D2T,D2Yss,D2Om,D2H,D2P)
 % Computes the likelihood of a stationary state space model.
 
 %@info:
@@ -71,7 +71,7 @@ function [LIK, LIKK, a, P] = kalman_filter(Y,start,last,a,P,kalman_tol,riccati_t
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2004-2013 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -88,8 +88,6 @@ function [LIK, LIKK, a, P] = kalman_filter(Y,start,last,a,P,kalman_tol,riccati_t
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-% AUTHOR(S) stephane DOT adjemian AT univ DASH lemans DOT fr
-
 % Set defaults.
 if nargin<17
     Zflag = 0;
@@ -122,10 +120,10 @@ likk = zeros(smpl,1);      % Initialization of the vector gathering the densitie
 LIK  = Inf;                % Default value of the log likelihood.
 oldK = Inf;
 notsteady   = 1;
-F_singular  = 1;
+F_singular  = true;
 asy_hess=0;
 
-if  analytic_derivation == 0,
+if  analytic_derivation == 0
     DLIK=[];
     Hess=[];
     LIKK=[];
@@ -134,15 +132,15 @@ else
     DLIK  = zeros(k,1);                             % Initialization of the score.
     Da    = zeros(mm,k);                            % Derivative State vector.
     dlikk = zeros(smpl,k);
-    
-    if Zflag==0,
+
+    if Zflag==0
         C = zeros(pp,mm);
-        for ii=1:pp; C(ii,Z(ii))=1;end         % SELECTION MATRIX IN MEASUREMENT EQ. (FOR WHEN IT IS NOT CONSTANT)
+        for ii=1:pp, C(ii,Z(ii))=1; end         % SELECTION MATRIX IN MEASUREMENT EQ. (FOR WHEN IT IS NOT CONSTANT)
     else
         C=Z;
     end
     dC = zeros(pp,mm,k);   % either selection matrix or schur have zero derivatives
-    if analytic_derivation==2,
+    if analytic_derivation==2
         Hess  = zeros(k,k);                             % Initialization of the Hessian
         D2a    = zeros(mm,k,k);                             % State vector.
         d2C = zeros(pp,mm,k,k);
@@ -153,7 +151,7 @@ else
         D2T=[];
         D2Yss=[];
     end
-    if asy_hess,
+    if asy_hess
         Hess  = zeros(k,k);                             % Initialization of the Hessian
     end
     LIK={inf,DLIK,Hess};
@@ -169,19 +167,34 @@ while notsteady && t<=last
         v  = Y(:,t)-a(Z);
         F  = P(Z,Z) + H;
     end
-    sig=sqrt(diag(F));
-    if any(diag(F)<kalman_tol) || rcond(F./(sig*sig')) < kalman_tol
+    badly_conditioned_F = false;
+    if rescale_prediction_error_covariance
+        sig=sqrt(diag(F));
+        if any(diag(F)<kalman_tol) || rcond(F./(sig*sig'))<kalman_tol
+            badly_conditioned_F = true;
+        end
+    else
+        if rcond(F)<kalman_tol
+            badly_conditioned_F = true;
+        end
+    end
+    if badly_conditioned_F
         if ~all(abs(F(:))<kalman_tol)
-            %use diffuse filter
+            % Use univariate filter (will remove observations with zero variance prediction error)
             return
         else
-            %pathological case, discard draw
+            % Pathological case, discard draw.
             return
         end
     else
-        F_singular = 0;
-        log_dF      = log(det(F./(sig*sig')))+2*sum(log(sig));
-        iF      = inv(F./(sig*sig'))./(sig*sig');
+        F_singular = false;
+        if rescale_prediction_error_covariance
+            log_dF = log(det(F./(sig*sig')))+2*sum(log(sig));
+            iF = inv(F./(sig*sig'))./(sig*sig');
+        else
+            log_dF = log(det(F));
+            iF = inv(F);
+        end
         likk(s) = log_dF+transpose(v)*iF*v;
         if Zflag
             K = P*Z'*iF;
@@ -191,22 +204,22 @@ while notsteady && t<=last
             Ptmp = T*(P-K*P(Z,:))*transpose(T)+QQ;
         end
         tmp = (a+K*v);
-        if analytic_derivation,
-            if analytic_derivation==2,
+        if analytic_derivation
+            if analytic_derivation==2
                 [Da,DP,DLIKt,D2a,D2P, Hesst] = computeDLIK(k,tmp,Z,Zflag,v,T,K,P,iF,Da,DYss,DT,DOm,DP,DH,notsteady,D2a,D2Yss,D2T,D2Om,D2P);
             else
                 [Da,DP,DLIKt,Hesst] = computeDLIK(k,tmp,Z,Zflag,v,T,K,P,iF,Da,DYss,DT,DOm,DP,DH,notsteady);
             end
             if t>presample
                 DLIK = DLIK + DLIKt;
-                if analytic_derivation==2 || asy_hess,
+                if analytic_derivation==2 || asy_hess
                     Hess = Hess + Hesst;
                 end
             end
             dlikk(s,:)=DLIKt;
         end
         a = T*tmp;
-        P=Ptmp;
+        P = Ptmp;
         notsteady = max(abs(K(:)-oldK))>riccati_tol;
         oldK = K(:);
     end
@@ -219,12 +232,12 @@ end
 
 % Add observation's densities constants and divide by two.
 likk(1:s) = .5*(likk(1:s) + pp*log(2*pi));
-if analytic_derivation,
+if analytic_derivation
     DLIK = DLIK/2;
     dlikk = dlikk/2;
-    if analytic_derivation==2 || asy_hess,
-        if asy_hess==0,
-        Hess = Hess + tril(Hess,-1)';
+    if analytic_derivation==2 || asy_hess
+        if asy_hess==0
+            Hess = Hess + tril(Hess,-1)';
         end
         Hess = -Hess/2;
     end
@@ -232,34 +245,32 @@ end
 
 % Call steady state Kalman filter if needed.
 if t <= last
-    if analytic_derivation,
-        if analytic_derivation==2,
-            [tmp, tmp2] = kalman_filter_ss(Y,t,last,a,T,K,iF,dF,Z,pp,Zflag, ...
-                analytic_derivation,Da,DT,DYss,D2a,D2T,D2Yss);
+    if analytic_derivation
+        if analytic_derivation==2
+            [tmp, tmp2] = kalman_filter_ss(Y, t, last, a, T, K, iF, dF, Z, pp, Zflag, analytic_derivation, Da, DT, DYss, D2a, D2T, D2Yss);
         else
-            [tmp, tmp2] = kalman_filter_ss(Y,t,last,a,T,K,iF,dF,Z,pp,Zflag, ...
-                analytic_derivation,Da,DT,DYss,asy_hess);
+            [tmp, tmp2] = kalman_filter_ss(Y, t, last, a, T, K, iF, dF, Z, pp, Zflag, analytic_derivation, Da, DT, DYss, asy_hess);
         end
-        likk(s+1:end)=tmp2{1};
-        dlikk(s+1:end,:)=tmp2{2};
+        likk(s+1:end) = tmp2{1};
+        dlikk(s+1:end,:) = tmp2{2};
         DLIK = DLIK + tmp{2};
-        if analytic_derivation==2 || asy_hess,
+        if analytic_derivation==2 || asy_hess
             Hess = Hess + tmp{3};
         end
     else
-        [tmp, likk(s+1:end)] = kalman_filter_ss(Y,t,last,a,T,K,iF,log_dF,Z,pp,Zflag);
+        [tmp, likk(s+1:end)] = kalman_filter_ss(Y, t, last, a, T, K, iF, log_dF, Z, pp, Zflag);
     end
 end
 
 % Compute minus the log-likelihood.
-if presample>diffuse_periods,
+if presample>diffuse_periods
     LIK = sum(likk(1+(presample-diffuse_periods):end));
 else
     LIK = sum(likk);
 end
 
-if analytic_derivation,
-    if analytic_derivation==2 || asy_hess,
+if analytic_derivation
+    if analytic_derivation==2 || asy_hess
         LIK={LIK, DLIK, Hess};
     else
         LIK={LIK, DLIK};
diff --git a/matlab/kalman/likelihood/kalman_filter_d.m b/matlab/kalman/likelihood/kalman_filter_d.m
index a10cf6f4d2c243eac5011f56db5df5d2bb7fc399..79b3607fb21de53cfc895071501657715dc9c332 100644
--- a/matlab/kalman/likelihood/kalman_filter_d.m
+++ b/matlab/kalman/likelihood/kalman_filter_d.m
@@ -1,7 +1,7 @@
 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 
+% INPUTS
 %    Y           [double]      pp*smpl matrix of (detrended) data, where pp is the number of observed variables.
 %    start       [integer]     scalar, first observation.
 %    last        [integer]     scalar, last observation.
@@ -10,33 +10,33 @@ function [dLIK,dlik,a,Pstar] = kalman_filter_d(Y, start, last, a, Pinf, Pstar, k
 %    Pstar       [double]      mm*mm matrix used to initialize the covariance matrix of the state vector.
 %    kalman_tol  [double]      scalar, tolerance parameter (rcond) of F_star.
 %    diffuse_kalman_tol [double]      scalar, tolerance parameter (rcond) of Pinf to signify end of diffuse filtering and Finf.
-%    riccati_tol [double]      scalar, tolerance parameter (riccati iteration); 
+%    riccati_tol [double]      scalar, tolerance parameter (riccati iteration);
 %                              not used in this filter as usually diffuse phase will be left before convergence of filter to steady state.
-%    presample   [integer]     scalar, presampling if strictly positive.    
+%    presample   [integer]     scalar, presampling if strictly positive.
 %    T           [double]      mm*mm matrix, transition matrix in  the state equations.
 %    R           [double]      mm*rr matrix relating the structural innovations to the state vector.
 %    Q           [double]      rr*rr covariance matrix of the structural innovations.
-%    H           [double]      pp*pp covariance matrix of the measurement errors (if H is equal to zero (scalar) there is no measurement error). 
+%    H           [double]      pp*pp covariance matrix of the measurement errors (if H is equal to zero (scalar) there is no measurement error).
 %    Z           [double]      pp*mm matrix, selection matrix or pp linear independent combinations of the state vector.
 %    mm          [integer]     scalar, number of state variables.
 %    pp          [integer]     scalar, number of observed variables.
-%    rr          [integer]     scalar, number of structural innovations.    
-%             
-% OUTPUTS 
+%    rr          [integer]     scalar, number of structural innovations.
+%
+% OUTPUTS
 %    LIK         [double]      scalar, minus loglikelihood
 %    lik         [double]      smpl*1 vector, log density of each vector of observations.
 %    a           [double]      mm*1 vector, current estimate of the state vector.
-%    Pstar       [double]      mm*mm matrix, covariance matrix of the state vector.    
-%        
-% REFERENCES 
+%    Pstar       [double]      mm*mm matrix, covariance matrix of the state vector.
+%
+% REFERENCES
 %   See "Filtering and Smoothing of State Vector for Diffuse State Space
-%   Models", S.J. Koopman and J. Durbin (2003), in Journal of Time Series 
-%   Analysis, vol. 24(1), pp. 85-98. 
+%   Models", S.J. Koopman and J. Durbin (2003), in Journal of Time Series
+%   Analysis, vol. 24(1), pp. 85-98.
 %   and
 %   Durbin/Koopman (2012): "Time Series Analysis by State Space Methods", Oxford University Press,
 %   Second Edition, Ch. 5 and 7.2
 
-% Copyright (C) 2004-2016 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -69,10 +69,10 @@ while rank(Pinf,diffuse_kalman_tol) && (t<=last)
     s = t-start+1;
     v = Y(:,t)-Z*a;                                                     %get prediction error v^(0) in (5.13) DK (2012)
     Finf  = Z*Pinf*Z';                                                  % (5.7) in DK (2012)
-    %do case distinction based on whether F_{\infty,t} has full rank or 0 rank
-    if rcond(Finf) < diffuse_kalman_tol                                 %F_{\infty,t} = 0 
+                                                                        %do case distinction based on whether F_{\infty,t} has full rank or 0 rank
+    if rcond(Finf) < diffuse_kalman_tol                                 %F_{\infty,t} = 0
         if ~all(abs(Finf(:)) < diffuse_kalman_tol)                      %rank-deficient but not rank 0
-            % The univariate diffuse kalman filter should be used instead.
+                                                                        % The univariate diffuse kalman filter should be used instead.
             return
         else                                                            %rank of F_{\infty,t} is 0
             Fstar  = Z*Pstar*Z' + H;                                    % (5.7) in DK (2012)
@@ -81,8 +81,8 @@ while rank(Pinf,diffuse_kalman_tol) && (t<=last)
                     % The univariate diffuse kalman filter should be used.
                     return
                 else                                                    %rank 0
-                   %pathological case, discard draw
-                   return
+                                                                        %pathological case, discard draw
+                    return
                 end
             else
                 iFstar = inv(Fstar);
@@ -95,15 +95,15 @@ while rank(Pinf,diffuse_kalman_tol) && (t<=last)
             end
         end
     else                                                                %F_{\infty,t} positive definite
-        %To compare to DK (2012), this block makes use of the following transformation
-        %Kstar=T^{-1}*K^{(1)}=M_{*}*F^{(1)}+M_{\infty}*F^{(2)}
-        %     =P_{*}*Z'*F^{(1)}+P_{\infty}*Z'*((-1)*(-F_{\infty}^{-1})*F_{*}*(F_{\infty}^{-1}))
-        %     =[P_{*}*Z'-Kinf*F_{*})]*F^{(1)}
-        %Make use of L^{0}'=(T-K^{(0)}*Z)'=(T-T*M_{\infty}*F^{(1)}*Z)'
-        %                  =(T-T*P_{\infty*Z'*F^{(1)}*Z)'=(T-T*Kinf*Z)'
-        %                  = (T*(I-*Kinf*Z))'=(I-Z'*Kinf')*T'
-        %P_{*}=T*P_{\infty}*L^{(1)}+T*P_{*}*L^{(0)}+RQR
-        %     =T*[(P_{\infty}*(-K^{(1)*Z}))+P_{*}*(I-Z'*Kinf')*T'+RQR]
+                                                                        %To compare to DK (2012), this block makes use of the following transformation
+                                                                        %Kstar=T^{-1}*K^{(1)}=M_{*}*F^{(1)}+M_{\infty}*F^{(2)}
+                                                                        %     =P_{*}*Z'*F^{(1)}+P_{\infty}*Z'*((-1)*(-F_{\infty}^{-1})*F_{*}*(F_{\infty}^{-1}))
+                                                                        %     =[P_{*}*Z'-Kinf*F_{*})]*F^{(1)}
+                                                                        %Make use of L^{0}'=(T-K^{(0)}*Z)'=(T-T*M_{\infty}*F^{(1)}*Z)'
+                                                                        %                  =(T-T*P_{\infty*Z'*F^{(1)}*Z)'=(T-T*Kinf*Z)'
+                                                                        %                  = (T*(I-*Kinf*Z))'=(I-Z'*Kinf')*T'
+                                                                        %P_{*}=T*P_{\infty}*L^{(1)}+T*P_{*}*L^{(0)}+RQR
+                                                                        %     =T*[(P_{\infty}*(-K^{(1)*Z}))+P_{*}*(I-Z'*Kinf')*T'+RQR]
         dlik(s)= log(det(Finf));                                        %set w_t to top case in bottom equation page 172, DK (2012)
         iFinf  = inv(Finf);
         Kinf   = Pinf*Z'*iFinf;                                         %define Kinf=T^{-1}*K_0 with M_{\infty}=Pinf*Z'
@@ -117,7 +117,7 @@ while rank(Pinf,diffuse_kalman_tol) && (t<=last)
 end
 
 if t>last
-    warning(['kalman_filter_d: There isn''t enough information to estimate the initial conditions of the nonstationary variables. The diffuse Kalman filter never left the diffuse stage.']);                   
+    warning(['kalman_filter_d: There isn''t enough information to estimate the initial conditions of the nonstationary variables. The diffuse Kalman filter never left the diffuse stage.']);
     dLIK = NaN;
     return
 end
diff --git a/matlab/kalman/likelihood/kalman_filter_fast.m b/matlab/kalman/likelihood/kalman_filter_fast.m
index a60011ade8614dc1761589493573324121775da4..db3dec3b755d406d55bf89005c80b6946b3a49e6 100644
--- a/matlab/kalman/likelihood/kalman_filter_fast.m
+++ b/matlab/kalman/likelihood/kalman_filter_fast.m
@@ -74,7 +74,7 @@ function [LIK, LIKK, a, P] = kalman_filter_fast(Y,start,last,a,P,kalman_tol,ricc
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2004-2013 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -152,7 +152,7 @@ while notsteady && t<=last
     end
     if rcond(F) < kalman_tol
         if ~all(abs(F(:))<kalman_tol)
-            % The univariate diffuse kalman filter should be used.            
+            % The univariate diffuse kalman filter should be used.
             return
         else
             %pathological case, discard draw
@@ -194,12 +194,12 @@ end
 
 % Add observation's densities constants and divide by two.
 likk(1:s) = .5*(likk(1:s) + pp*log(2*pi));
-if analytic_derivation,
+if analytic_derivation
     DLIK = DLIK/2;
     dlikk = dlikk/2;
-    if analytic_derivation==2 || asy_hess,
-        if asy_hess==0,
-        Hess = Hess + tril(Hess,-1)';
+    if analytic_derivation==2 || asy_hess
+        if asy_hess==0
+            Hess = Hess + tril(Hess,-1)';
         end
         Hess = -Hess/2;
     end
@@ -207,34 +207,34 @@ end
 
 % Call steady state Kalman filter if needed.
 if t <= last
-    if analytic_derivation,
-        if analytic_derivation==2,
+    if analytic_derivation
+        if analytic_derivation==2
             [tmp, tmp2] = kalman_filter_ss(Y,t,last,a,T,K,iF,dF,Z,pp,Zflag, ...
-                analytic_derivation,Da,DT,DYss,D2a,D2T,D2Yss);
+                                           analytic_derivation,Da,DT,DYss,D2a,D2T,D2Yss);
         else
             [tmp, tmp2] = kalman_filter_ss(Y,t,last,a,T,K,iF,dF,Z,pp,Zflag, ...
-                analytic_derivation,Da,DT,DYss,asy_hess);
+                                           analytic_derivation,Da,DT,DYss,asy_hess);
         end
         likk(s+1:end)=tmp2{1};
         dlikk(s+1:end,:)=tmp2{2};
         DLIK = DLIK + tmp{2};
-        if analytic_derivation==2 || asy_hess,
+        if analytic_derivation==2 || asy_hess
             Hess = Hess + tmp{3};
         end
     else
-        [tmp, likk(s+1:end)] = kalman_filter_ss(Y,t,last,a,T,K,iF,log(dF),Z,pp,Zflag);
+        [tmp, likk(s+1:end)] = kalman_filter_ss(Y, t, last, a, T, K, iF, log(dF), Z, pp, Zflag);
     end
 end
 
 % Compute minus the log-likelihood.
-if presample>diffuse_periods,
+if presample>diffuse_periods
     LIK = sum(likk(1+(presample-diffuse_periods):end));
 else
     LIK = sum(likk);
 end
 
-if analytic_derivation,
-    if analytic_derivation==2 || asy_hess,
+if analytic_derivation
+    if analytic_derivation==2 || asy_hess
         LIK={LIK, DLIK, Hess};
     else
         LIK={LIK, DLIK};
diff --git a/matlab/kalman/likelihood/kalman_filter_ss.m b/matlab/kalman/likelihood/kalman_filter_ss.m
index 8e5f927338576cc0a2f8154c030446b48f5c796c..5510de9f36b9d262f470551878c6742b9e1e71fe 100644
--- a/matlab/kalman/likelihood/kalman_filter_ss.m
+++ b/matlab/kalman/likelihood/kalman_filter_ss.m
@@ -54,7 +54,7 @@ function [LIK, likk, a] = kalman_filter_ss(Y,start,last,a,T,K,iF,log_dF,Z,pp,Zfl
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -86,18 +86,18 @@ if nargin<12
     analytic_derivation = 0;
 end
 
-if  analytic_derivation == 0,
+if  analytic_derivation == 0
     DLIK=[];
     Hess=[];
 else
     k = size(DT,3);                                 % number of structural parameters
     DLIK  = zeros(k,1);                             % Initialization of the score.
     dlikk = zeros(smpl,k);
-    if analytic_derivation==2,
+    if analytic_derivation==2
         Hess  = zeros(k,k);                             % Initialization of the Hessian
     else
         asy_hess=D2a;
-        if asy_hess,
+        if asy_hess
             Hess  = zeros(k,k);                             % Initialization of the Hessian
         else
             Hess=[];
@@ -112,14 +112,14 @@ while t <= last
         v = Y(:,t)-a(Z);
     end
     tmp = (a+K*v);
-    if analytic_derivation,
-        if analytic_derivation==2,
+    if analytic_derivation
+        if analytic_derivation==2
             [Da,junk,DLIKt,D2a,junk2, Hesst] = computeDLIK(k,tmp,Z,Zflag,v,T,K,[],iF,Da,DYss,DT,[],[],[],notsteady,D2a,D2Yss,D2T,[],[]);
         else
             [Da,junk,DLIKt,Hesst] = computeDLIK(k,tmp,Z,Zflag,v,T,K,[],iF,Da,DYss,DT,[],[],[],notsteady);
         end
         DLIK = DLIK + DLIKt;
-        if analytic_derivation==2 || asy_hess,
+        if analytic_derivation==2 || asy_hess
             Hess = Hess + Hesst;
         end
         dlikk(t-start+1,:)=DLIKt;
@@ -137,17 +137,17 @@ likk = .5*(likk + pp*log(2*pi));
 
 % Sum the observation's densities (minus the likelihood)
 LIK = sum(likk);
-if analytic_derivation,
+if analytic_derivation
     dlikk = dlikk/2;
     DLIK = DLIK/2;
     likk = {likk, dlikk};
 end
-if analytic_derivation==2 || asy_hess,
-    if asy_hess==0,
+if analytic_derivation==2 || asy_hess
+    if asy_hess==0
         Hess = Hess + tril(Hess,-1)';
     end
     Hess = -Hess/2;
     LIK={LIK,DLIK,Hess};
-elseif analytic_derivation==1,
+elseif analytic_derivation==1
     LIK={LIK,DLIK};
 end
diff --git a/matlab/kalman/likelihood/missing_observations_kalman_filter.m b/matlab/kalman/likelihood/missing_observations_kalman_filter.m
index 6b70a59af1d3583bde101dec003b1c5cef8f0cc9..f1bd40cb59e5e0ce3198019d3e83c599228635e1 100644
--- a/matlab/kalman/likelihood/missing_observations_kalman_filter.m
+++ b/matlab/kalman/likelihood/missing_observations_kalman_filter.m
@@ -1,38 +1,38 @@
-function  [LIK, lik, a, P] = missing_observations_kalman_filter(data_index,number_of_observations,no_more_missing_observations,Y,start,last,a,P,kalman_tol,riccati_tol,presample,T,Q,R,H,Z,mm,pp,rr,Zflag,diffuse_periods)
+function  [LIK, lik, a, P] = missing_observations_kalman_filter(data_index,number_of_observations,no_more_missing_observations,Y,start,last,a,P,kalman_tol,riccati_tol,rescale_prediction_error_covariance,presample,T,Q,R,H,Z,mm,pp,rr,Zflag,diffuse_periods)
 % Computes the likelihood of a state space model in the case with missing observations.
 %
 % INPUTS
 %    data_index                   [cell]      1*smpl cell of column vectors of indices.
 %    number_of_observations       [integer]   scalar.
 %    no_more_missing_observations [integer]   scalar.
-%    Y                            [double]    pp*smpl matrix of data.    
+%    Y                            [double]    pp*smpl matrix of data.
 %    start                        [integer]   scalar, index of the first observation.
 %    last                         [integer]   scalar, index of the last observation.
 %    a                            [double]    pp*1 vector, initial level of the state vector.
 %    P                            [double]    pp*pp matrix, covariance matrix of the initial state vector.
 %    kalman_tol                   [double]    scalar, tolerance parameter (rcond).
-%    riccati_tol                  [double]    scalar, tolerance parameter (riccati iteration).    
+%    riccati_tol                  [double]    scalar, tolerance parameter (riccati iteration).
 %    presample                    [integer]   scalar, presampling if strictly positive.
 %    T                            [double]    mm*mm transition matrix of the state equation.
-%    Q                            [double]    rr*rr covariance matrix of the structural innovations.    
+%    Q                            [double]    rr*rr covariance matrix of the structural innovations.
 %    R                            [double]    mm*rr matrix, mapping structural innovations to state variables.
-%    H                            [double]    pp*pp (or 1*1 =0 if no measurement error) covariance matrix of the measurement errors. 
-%    Z                            [integer]   pp*1 vector of indices for the observed variables.    
+%    H                            [double]    pp*pp (or 1*1 =0 if no measurement error) covariance matrix of the measurement errors.
+%    Z                            [integer]   pp*1 vector of indices for the observed variables.
 %    mm                           [integer]   scalar, dimension of the state vector.
 %    pp                           [integer]   scalar, number of observed variables.
-%    rr                           [integer]   scalar, number of structural innovations.    
-%    
-% OUTPUTS 
+%    rr                           [integer]   scalar, number of structural innovations.
+%
+% OUTPUTS
 %    LIK        [double]    scalar, MINUS loglikelihood
 %    lik        [double]    vector, density of observations in each period.
 %    a          [double]    mm*1 vector, estimated level of the states.
-%    P          [double]    mm*mm matrix, covariance matrix of the states.        
-%        
+%    P          [double]    mm*mm matrix, covariance matrix of the states.
+%
 %
 % NOTES
-%   The vector "lik" is used to evaluate the jacobian of the likelihood.   
+%   The vector "lik" is used to evaluate the jacobian of the likelihood.
 
-% Copyright (C) 2004-2012 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -82,7 +82,7 @@ lik  = zeros(smpl,1);      % Initialization of the vector gathering the densitie
 LIK  = Inf;                % Default value of the log likelihood.
 oldK = Inf;
 notsteady   = 1;
-F_singular  = 1;
+F_singular  = true;
 s = 0;
 
 while notsteady && t<=last
@@ -102,19 +102,34 @@ while notsteady && t<=last
             v = Y(d_index,t) - a(z);
             F = P(z,z) + H(d_index,d_index);
         end
-        sig=sqrt(diag(F));
-        if any(diag(F)<kalman_tol) || rcond(F./(sig*sig')) < kalman_tol
+        badly_conditioned_F = false;
+        if rescale_prediction_error_covariance
+            sig=sqrt(diag(F));
+            if any(diag(F)<kalman_tol) || rcond(F./(sig*sig'))<kalman_tol
+                badly_conditioned_F = true;
+            end
+        else
+            if rcond(F)<kalman_tol
+                badly_conditioned_F = true;
+            end
+        end
+        if badly_conditioned_F
             if ~all(abs(F(:))<kalman_tol)
-                %use diffuse filter
+                % Use univariate filter.
                 return
             else
-                %pathological case, discard draw
+                % Pathological case, discard draw
                 return
             end
         else
-            F_singular = 0;
-            log_dF      = log(det(F./(sig*sig')))+2*sum(log(sig));
-            iF      = inv(F./(sig*sig'))./(sig*sig');
+            F_singular = false;
+            if rescale_prediction_error_covariance
+                log_dF = log(det(F./(sig*sig')))+2*sum(log(sig));
+                iF = inv(F./(sig*sig'))./(sig*sig');
+            else
+                log_dF = log(det(F));
+                iF = inv(F);
+            end
             lik(s) = log_dF + transpose(v)*iF*v + length(d_index)*log(2*pi);
             if Zflag
                 K = P*z'*iF;
@@ -142,7 +157,7 @@ lik(1:s) = .5*lik(1:s);
 
 % Call steady state Kalman filter if needed.
 if t<=last
-    [tmp, lik(s+1:end)] = kalman_filter_ss(Y,t,last,a,T,K,iF,log_dF,Z,pp,Zflag);
+    [tmp, lik(s+1:end)] = kalman_filter_ss(Y, t, last, a, T, K, iF, log_dF, Z, pp, Zflag);
 end
 
 % Compute minus the log-likelihood.
diff --git a/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m b/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m
index a497d6e53f1e2af7d998af1cdf120332f9d9025a..ec8c286a4cf67f650724ee1ddf43ce0d54d5169f 100644
--- a/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m
+++ b/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m
@@ -1,11 +1,11 @@
 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, diffuse_kalman_tol, riccati_tol, presample, ...
-                                                      T, R, Q, H, Z, mm, pp, rr)
+                                                  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 when some observations are missing.
 %
-% INPUTS 
+% INPUTS
 %    data_index                   [cell]      1*smpl cell of column vectors of indices.
 %    number_of_observations       [integer]   scalar.
 %    no_more_missing_observations [integer]   scalar.
@@ -17,32 +17,32 @@ function [dLIK,dlik,a,Pstar] = missing_observations_kalman_filter_d(data_index,n
 %    Pstar                        [double]      mm*mm matrix used to initialize the covariance matrix of the state vector.
 %    kalman_tol                   [double]      scalar, tolerance parameter (rcond).
 %    riccati_tol                  [double]      scalar, tolerance parameter (riccati iteration).
-%    presample                    [integer]     scalar, presampling if strictly positive.    
+%    presample                    [integer]     scalar, presampling if strictly positive.
 %    T                            [double]      mm*mm matrix, transition matrix in  the state equations.
 %    R                            [double]      mm*rr matrix relating the structural innovations to the state vector.
 %    Q                            [double]      rr*rr covariance matrix of the structural innovations.
-%    H                            [double]      pp*pp covariance matrix of the measurement errors (if H is equal to zero (scalar) there is no measurement error). 
+%    H                            [double]      pp*pp covariance matrix of the measurement errors (if H is equal to zero (scalar) there is no measurement error).
 %    Z                            [double]      pp*mm matrix, selection matrix or pp linear independant combinations of the state vector.
 %    mm                           [integer]     scalar, number of state variables.
 %    pp                           [integer]     scalar, number of observed variables.
-%    rr                           [integer]     scalar, number of structural innovations.    
-%             
-% OUTPUTS 
+%    rr                           [integer]     scalar, number of structural innovations.
+%
+% OUTPUTS
 %    dLIK        [double]    scalar, MINUS loglikelihood
 %    dlik        [double]    vector, density of observations in each period.
 %    a           [double]    mm*1 vector, estimated level of the states.
-%    Pstar       [double]    mm*mm matrix, covariance matrix of the states.        
-%        
+%    Pstar       [double]    mm*mm matrix, covariance matrix of the states.
+%
 % REFERENCES
 %   See "Filtering and Smoothing of State Vector for Diffuse State Space
-%   Models", S.J. Koopman and J. Durbin (2003), in Journal of Time Series 
-%   Analysis, vol. 24(1), pp. 85-98. 
+%   Models", S.J. Koopman and J. Durbin (2003), in Journal of Time Series
+%   Analysis, vol. 24(1), pp. 85-98.
 %   and
 %   Durbin/Koopman (2012): "Time Series Analysis by State Space Methods", Oxford University Press,
 %   Second Edition, Ch. 5 and 7.2
 
-% 
-% Copyright (C) 2004-2016 Dynare Team
+%
+% Copyright (C) 2004-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -87,11 +87,11 @@ while rank(Pinf,diffuse_kalman_tol) && (t<=last)
         Pinf  = T*Pinf*transpose(T);
     else
         ZZ = Z(d_index,:);                                                  %span selector matrix
-        v  = Y(d_index,t)-ZZ*a;                                             %get prediction error v^(0) in (5.13) DK (2012)         
+        v  = Y(d_index,t)-ZZ*a;                                             %get prediction error v^(0) in (5.13) DK (2012)
         Finf  = ZZ*Pinf*ZZ';                                                % (5.7) in DK (2012)
-        if rcond(Finf) < diffuse_kalman_tol                                 %F_{\infty,t} = 0 
+        if rcond(Finf) < diffuse_kalman_tol                                 %F_{\infty,t} = 0
             if ~all(abs(Finf(:)) < diffuse_kalman_tol)                      %rank-deficient but not rank 0
-                % The univariate diffuse kalman filter should be used.
+                                                                            % The univariate diffuse kalman filter should be used.
                 return
             else                                                            %rank of F_{\infty,t} is 0
                 Fstar = ZZ*Pstar*ZZ' + H(d_index,d_index);                  % (5.7) in DK (2012)
@@ -100,7 +100,7 @@ while rank(Pinf,diffuse_kalman_tol) && (t<=last)
                         % The univariate diffuse kalman filter should be used.
                         return
                     else %rank 0
-                        %pathological case, discard draw
+                         %pathological case, discard draw
                         return
                     end
                 else
@@ -129,7 +129,7 @@ while rank(Pinf,diffuse_kalman_tol) && (t<=last)
 end
 
 if t==(last+1)
-    warning(['kalman_filter_d: There isn''t enough information to estimate the initial conditions of the nonstationary variables. The diffuse Kalman filter never left the diffuse stage.']);                   
+    warning(['kalman_filter_d: There isn''t enough information to estimate the initial conditions of the nonstationary variables. The diffuse Kalman filter never left the diffuse stage.']);
     dLIK = NaN;
     return
 end
diff --git a/matlab/kalman/likelihood/univariate_computeDLIK.m b/matlab/kalman/likelihood/univariate_computeDLIK.m
index 1338a84a6284bb5a30a5b4ac958d3c7e500beb0d..083fb12db92938c23ae10c6679809459573fa42d 100644
--- a/matlab/kalman/likelihood/univariate_computeDLIK.m
+++ b/matlab/kalman/likelihood/univariate_computeDLIK.m
@@ -1,6 +1,6 @@
 function [Da,DP1,DLIK,D2a,D2P,Hesst] = univariate_computeDLIK(k,indx,Z,Zflag,v,K,PZ,F,Da,DYss,DP,DH,notsteady,D2a,D2Yss,D2P)
 
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -21,12 +21,12 @@ function [Da,DP1,DLIK,D2a,D2P,Hesst] = univariate_computeDLIK(k,indx,Z,Zflag,v,K
 
 persistent DDK DDF DD2K DD2F
 
-if notsteady,
+if notsteady
     if Zflag
         Dv   = -Z*Da(:,:) - Z*DYss(:,:);
         DF = zeros(k,1);
         DK = zeros([rows(K),k]);
-        for j=1:k,
+        for j=1:k
             DF(j)=Z*DP(:,:,j)*Z'+DH;
             DK(:,j) = (DP(:,:,j)*Z')/F-PZ*DF(j)/F^2;
         end
@@ -35,9 +35,9 @@ if notsteady,
             D2v = zeros(k,k);
             D2K = zeros(rows(K),k,k);
             jcount=0;
-            for j=1:k,
+            for j=1:k
                 D2v(:,j)   = -Z*D2a(:,:,j) - Z*D2Yss(:,:,j);
-                for i=1:j,
+                for i=1:j
                     jcount=jcount+1;
                     D2F(j,i)=Z*dyn_unvech(D2P(:,jcount))*Z';
                     D2F(i,j)=D2F(j,i);
@@ -47,7 +47,7 @@ if notsteady,
                 end
             end
         end
-        
+
     else
         Dv   = -Da(Z,:) - DYss(Z,:);
         DF = squeeze(DP(Z,Z,:))+DH';
@@ -57,8 +57,8 @@ if notsteady,
             D2K = zeros(rows(K),k,k);
             D2v   = squeeze(-D2a(Z,:,:) - D2Yss(Z,:,:));
             jcount=0;
-            for j=1:k,
-                for i=1:j,
+            for j=1:k
+                for i=1:j
                     jcount=jcount+1;
                     tmp = dyn_unvech(D2P(:,jcount));
                     D2F(j,i) = tmp(Z,Z);
@@ -67,7 +67,7 @@ if notsteady,
                     D2K(:,i,j) = D2K(:,i,j) -PZ*D2F(j,i)/F^2 - squeeze(DP(:,Z,i))*DF(j)/F^2 - ...
                         squeeze(DP(:,Z,j))*DF(i)'/F^2 + 2/F^3*PZ*DF(i)'*DF(j);
                     D2K(:,j,i) = D2K(:,i,j);
-%                     D2K = squeeze(D2P(:,Z,:,:))/F;
+                    %                     D2K = squeeze(D2P(:,Z,:,:))/F;
                 end
             end
         end
@@ -89,7 +89,7 @@ else
         Dv   = -Z*Da(:,:) - Z*DYss(:,:);
         if nargout>4
             D2v = zeros(k,k);
-            for j=1:k,
+            for j=1:k
                 D2v(:,j)   = -Z*D2a(:,:,j) - Z*D2Yss(:,:,j);
             end
         end
@@ -104,70 +104,68 @@ end
 DLIK = DF/F + 2*Dv'/F*v - v^2/F^2*DF;
 if nargout==6
     Hesst = D2F/F-1/F^2*(DF*DF') + 2*D2v/F*v + 2*(Dv'*Dv)/F - 2*(DF*Dv)*v/F^2 ...
-        - v^2/F^2*D2F - 2*v/F^2*(Dv'*DF') + 2*v^2/F^3*(DF*DF');
-elseif nargout==4,
+            - v^2/F^2*D2F - 2*v/F^2*(Dv'*DF') + 2*v^2/F^3*(DF*DF');
+elseif nargout==4
     D2a = 1/F^2*(DF*DF') + 2*(Dv'*Dv)/F ;
-%     D2a = -1/F^2*(DF*DF') + 2*(Dv'*Dv)/F  + 2*v^2/F^3*(DF*DF') ...
-%         - 2*(DF*Dv)*v/F^2 - 2*v/F^2*(Dv'*DF');
-%     D2a = +2*(Dv'*Dv)/F + (DF' * DF)/F^2;
+    %     D2a = -1/F^2*(DF*DF') + 2*(Dv'*Dv)/F  + 2*v^2/F^3*(DF*DF') ...
+    %         - 2*(DF*Dv)*v/F^2 - 2*v/F^2*(Dv'*DF');
+    %     D2a = +2*(Dv'*Dv)/F + (DF' * DF)/F^2;
 end
 
 Da = Da + DK*v+K*Dv;
 if nargout>4
-    
+
     D2a = D2a + D2K*v;
-    for j=1:k,
+    for j=1:k
         %         D2a(:,:,j) = D2a(:,:,j) + DK*Dv(j) + DK(:,j)*Dv + K*D2v(j,:);
-        for i=1:j,
+        for i=1:j
             D2a(:,j,i) = D2a(:,j,i) + DK(:,i)*Dv(j) + DK(:,j)*Dv(i) + K*D2v(j,i);
             D2a(:,i,j) = D2a(:,j,i);
         end
     end
-    
-    
+
+
 end
 
-if notsteady,
+if notsteady
     DP1 = DP*0;
-    if Zflag,
-        for j=1:k,
+    if Zflag
+        for j=1:k
             DP1(:,:,j)=DP(:,:,j) - (DP(:,:,j)*Z')*K'-PZ*DK(:,j)';
         end
     else
-        for j=1:k,
+        for j=1:k
             DP1(:,:,j)=DP(:,:,j) - (DP(:,Z,j))*K'-PZ*DK(:,j)';
         end
     end
-    if nargout>4,
-        if Zflag,
-            for j=1:k,
-                for i=1:j,
+    if nargout>4
+        if Zflag
+            for j=1:k
+                for i=1:j
                     jcount = jcount+1;
                     tmp = dyn_unvech(D2P(:,jcount));
                     tmp = tmp - (tmp*Z')*K' - (DP(:,:,j)*Z')*DK(:,i)' ...
-                        - (DP(:,:,i)*Z')*DK(:,j)' -PZ*D2K(:,j,i)';
+                          - (DP(:,:,i)*Z')*DK(:,j)' -PZ*D2K(:,j,i)';
                     D2P(:,jcount) = dyn_vech(tmp);
-%                     D2P(:,:,i,j) = D2P(:,:,j,i);
+                    %                     D2P(:,:,i,j) = D2P(:,:,j,i);
                 end
             end
         else
             DPZ = squeeze(DP(:,Z,:));
             jcount = 0;
-            for j=1:k,
-                for i=1:j,
+            for j=1:k
+                for i=1:j
                     jcount = jcount+1;
                     tmp = dyn_unvech(D2P(:,jcount));
                     D2PZ = tmp(:,Z);
                     tmp = tmp - D2PZ*K' - DPZ(:,j)*DK(:,i)'- DPZ(:,i)*DK(:,j)' - PZ*squeeze(D2K(:,j,i))';
                     D2P(:,jcount) = dyn_vech(tmp);
-%                     D2P(:,:,i,j) = D2P(:,:,j,i);
+                    %                     D2P(:,:,i,j) = D2P(:,:,j,i);
                 end
             end
-            
+
         end
     end
 else
     DP1=DP;
 end
-
-
diff --git a/matlab/kalman/likelihood/univariate_computeDstate.m b/matlab/kalman/likelihood/univariate_computeDstate.m
index a535a0a5189919f72000f688f6d11b5e0dac4703..eecee428eb4f3bcf2608e4434dce2c7baf4c4d89 100644
--- a/matlab/kalman/likelihood/univariate_computeDstate.m
+++ b/matlab/kalman/likelihood/univariate_computeDstate.m
@@ -1,6 +1,6 @@
 function [Da1,DP1,D2a,D2P] = univariate_computeDstate(k,a,P,T,Da,DP,DT,DOm,notsteady,D2a,D2P,D2T,D2Om)
 
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -22,35 +22,35 @@ function [Da1,DP1,D2a,D2P] = univariate_computeDstate(k,a,P,T,Da,DP,DT,DOm,notst
 
 DP1=DP*0;
 Da1=Da*0;
-for j=1:k,
+for j=1:k
     Da1(:,j) = T*Da(:,j) + DT(:,:,j)*a;
-    if notsteady,
+    if notsteady
         DP1(:,:,j) = T*DP(:,:,j)*T'+DT(:,:,j)*P*T'+T*P*DT(:,:,j)';
     else
         DP1=DP;
     end
 end
-if notsteady,
+if notsteady
     DP1 = DP1 + DOm;
 end
-if nargout>2,
+if nargout>2
     jcount=0;
-    for j=1:k,
-        for i=1:j,
+    for j=1:k
+        for i=1:j
             jcount=jcount+1;
             D2a(:,j,i) = DT(:,:,i)*Da(:,j) + DT(:,:,j)*Da(:,i) + T*D2a(:,j,i)+ reshape(D2T(:,jcount),size(T))*a;
             D2a(:,i,j) = D2a(:,j,i);
-            if notsteady,
+            if notsteady
                 tmp = dyn_unvech(D2P(:,jcount));
                 tmp = T*tmp*T' +DT(:,:,i)*DP(:,:,j)*T'+T*DP(:,:,j)*DT(:,:,i)' + ...
-                    DT(:,:,j)*DP(:,:,i)*T'+T*DP(:,:,i)*DT(:,:,j)' + ...
-                    DT(:,:,j)*P*DT(:,:,i)'+DT(:,:,i)*P*DT(:,:,j)'+ ...
-                    reshape(D2T(:,jcount),size(T))*P*T'+T*P*reshape(D2T(:,jcount),size(T))' + ...
-                    dyn_unvech(D2Om(:,jcount));
+                      DT(:,:,j)*DP(:,:,i)*T'+T*DP(:,:,i)*DT(:,:,j)' + ...
+                      DT(:,:,j)*P*DT(:,:,i)'+DT(:,:,i)*P*DT(:,:,j)'+ ...
+                      reshape(D2T(:,jcount),size(T))*P*T'+T*P*reshape(D2T(:,jcount),size(T))' + ...
+                      dyn_unvech(D2Om(:,jcount));
                 D2P(:,jcount) = dyn_vech(tmp);
-%                 D2P(:,:,i,j) = D2P(:,:,j,i);
+                %                 D2P(:,:,i,j) = D2P(:,:,j,i);
             end
         end
     end
-    
+
 end
diff --git a/matlab/kalman/likelihood/univariate_kalman_filter.m b/matlab/kalman/likelihood/univariate_kalman_filter.m
index dd4559cd5f7560b4e7a7b86194ed68a7550d68d3..add638a54760dc397a29b7371cf0d752b5170c35 100644
--- a/matlab/kalman/likelihood/univariate_kalman_filter.m
+++ b/matlab/kalman/likelihood/univariate_kalman_filter.m
@@ -37,7 +37,7 @@ function [LIK, lik,a,P] = univariate_kalman_filter(data_index,number_of_observat
 %! @item Q
 %! Matrix (@var{rr}*@var{rr}) of doubles, covariance matrix of the structural innovations (noise in the state equation).
 %! @item R
-%! Matrix (@var{mm}*@var{rr}) of doubles, 
+%! Matrix (@var{mm}*@var{rr}) of doubles,
 %! @item H
 %! Vector (@var{pp}) of doubles, diagonal of covariance matrix of the measurement errors (corelation among measurement errors is handled by a model transformation).
 %! @item Z
@@ -76,15 +76,15 @@ function [LIK, lik,a,P] = univariate_kalman_filter(data_index,number_of_observat
 %! @ref{univariate_kalman_filter_ss}
 %! @end deftypefn
 %@eod:
-% 
+%
 % Algorithm:
-% 
+%
 %   Uses the univariate filter as described in Durbin/Koopman (2012): "Time
 %   Series Analysis by State Space Methods", Oxford University Press,
 %   Second Edition, Ch. 6.4 + 7.2.5
 
 
-% Copyright (C) 2004-2016 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -128,7 +128,7 @@ oldK = Inf;
 K = NaN(mm,pp);
 asy_hess=0;
 
-if  analytic_derivation == 0,
+if  analytic_derivation == 0
     DLIK=[];
     Hess=[];
 else
@@ -136,15 +136,15 @@ else
     DLIK  = zeros(k,1);                             % Initialization of the score.
     Da    = zeros(mm,k);                            % Derivative State vector.
     dlik  = zeros(smpl,k);
-    
-    if Zflag==0,
+
+    if Zflag==0
         C = zeros(pp,mm);
-        for ii=1:pp; C(ii,Z(ii))=1;end         % SELECTION MATRIX IN MEASUREMENT EQ. (FOR WHEN IT IS NOT CONSTANT)
+        for ii=1:pp, C(ii,Z(ii))=1; end         % SELECTION MATRIX IN MEASUREMENT EQ. (FOR WHEN IT IS NOT CONSTANT)
     else
         C=Z;
     end
     dC = zeros(pp,mm,k);   % either selection matrix or schur have zero derivatives
-    if analytic_derivation==2,
+    if analytic_derivation==2
         Hess  = zeros(k,k);                             % Initialization of the Hessian
         D2a    = zeros(mm,k,k);                             % State vector.
         d2C = zeros(pp,mm,k,k);
@@ -155,7 +155,7 @@ else
         D2T=[];
         D2Yss=[];
     end
-    if asy_hess,
+    if asy_hess
         Hess  = zeros(k,k);                             % Initialization of the Hessian
     end
     LIK={inf,DLIK,Hess};
@@ -172,13 +172,13 @@ while notsteady && t<=last %loop over t
     oldP = P(:);
     for i=1:rows(z) %loop over i
         if Zflag
-            prediction_error = Y(d_index(i),t) - z(i,:)*a;  % nu_{t,i} in 6.13 in DK (2012) 
+            prediction_error = Y(d_index(i),t) - z(i,:)*a;  % nu_{t,i} in 6.13 in DK (2012)
             PZ = P*z(i,:)';                                 % Z_{t,i}*P_{t,i}*Z_{t,i}'
-            Fi = z(i,:)*PZ + H(d_index(i));                 % F_{t,i} in 6.13 in DK (2012), relies on H being diagonal 
+            Fi = z(i,:)*PZ + H(d_index(i));                 % F_{t,i} in 6.13 in DK (2012), relies on H being diagonal
         else
-            prediction_error = Y(d_index(i),t) - a(z(i));   % nu_{t,i} in 6.13 in DK (2012) 
+            prediction_error = Y(d_index(i),t) - a(z(i));   % nu_{t,i} in 6.13 in DK (2012)
             PZ = P(:,z(i));                                 % Z_{t,i}*P_{t,i}*Z_{t,i}'
-            Fi = PZ(z(i)) + H(d_index(i));                  % F_{t,i} in 6.13 in DK (2012), relies on H being diagonal 
+            Fi = PZ(z(i)) + H(d_index(i));                  % F_{t,i} in 6.13 in DK (2012), relies on H being diagonal
         end
         if Fi>kalman_tol
             Ki =  PZ/Fi; %K_{t,i} in 6.13 in DK (2012)
@@ -186,15 +186,15 @@ while notsteady && t<=last %loop over t
                 K(:,i) = Ki;
             end
             lik(s,i) = log(Fi) + (prediction_error*prediction_error)/Fi + l2pi; %Top equation p. 175 in DK (2012)
-            if analytic_derivation,
-                if analytic_derivation==2,
+            if analytic_derivation
+                if analytic_derivation==2
                     [Da,DP,DLIKt,D2a,D2P, Hesst] = univariate_computeDLIK(k,i,z(i,:),Zflag,prediction_error,Ki,PZ,Fi,Da,DYss,DP,DH(d_index(i),:),notsteady,D2a,D2Yss,D2P);
                 else
                     [Da,DP,DLIKt,Hesst] = univariate_computeDLIK(k,i,z(i,:),Zflag,prediction_error,Ki,PZ,Fi,Da,DYss,DP,DH(d_index(i),:),notsteady);
                 end
                 if t>presample
                     DLIK = DLIK + DLIKt;
-                    if analytic_derivation==2 || asy_hess,
+                    if analytic_derivation==2 || asy_hess
                         Hess = Hess + Hesst;
                     end
                 end
@@ -207,14 +207,14 @@ while notsteady && t<=last %loop over t
             % p. 157, DK (2012)
         end
     end
-    if analytic_derivation,        
-        if analytic_derivation==2,
+    if analytic_derivation
+        if analytic_derivation==2
             [Da,DP,D2a,D2P] = univariate_computeDstate(k,a,P,T,Da,DP,DT,DOm,notsteady,D2a,D2P,D2T,D2Om);
         else
             [Da,DP] = univariate_computeDstate(k,a,P,T,Da,DP,DT,DOm,notsteady);
         end
     end
-    a = T*a;            %transition according to (6.14) in DK (2012) 
+    a = T*a;            %transition according to (6.14) in DK (2012)
     P = T*P*T' + QQ;    %transition according to (6.14) in DK (2012)
     if t>=no_more_missing_observations
         notsteady = max(abs(K(:)-oldK))>riccati_tol;
@@ -225,29 +225,29 @@ end
 
 % Divide by two.
 lik(1:s,:) = .5*lik(1:s,:);
-if analytic_derivation,
+if analytic_derivation
     DLIK = DLIK/2;
     dlik = dlik/2;
-    if analytic_derivation==2 || asy_hess,
-%         Hess = (Hess + Hess')/2;
+    if analytic_derivation==2 || asy_hess
+        %         Hess = (Hess + Hess')/2;
         Hess = -Hess/2;
     end
 end
 
 % Call steady state univariate kalman filter if needed.
 if t <= last
-    if analytic_derivation,
-        if analytic_derivation==2,
+    if analytic_derivation
+        if analytic_derivation==2
             [tmp, tmp2] = univariate_kalman_filter_ss(Y,t,last,a,P,kalman_tol,T,H,Z,pp,Zflag, ...
-                analytic_derivation,Da,DT,DYss,DP,DH,D2a,D2T,D2Yss,D2P);
+                                                      analytic_derivation,Da,DT,DYss,DP,DH,D2a,D2T,D2Yss,D2P);
         else
             [tmp, tmp2] = univariate_kalman_filter_ss(Y,t,last,a,P,kalman_tol,T,H,Z,pp,Zflag, ...
-                analytic_derivation,Da,DT,DYss,DP,DH,asy_hess);
+                                                      analytic_derivation,Da,DT,DYss,DP,DH,asy_hess);
         end
         lik(s+1:end,:)=tmp2{1};
         dlik(s+1:end,:)=tmp2{2};
         DLIK = DLIK + tmp{2};
-        if analytic_derivation==2 || asy_hess,
+        if analytic_derivation==2 || asy_hess
             Hess = Hess + tmp{3};
         end
     else
@@ -262,8 +262,8 @@ else
     LIK = sum(sum(lik));
 end
 
-if analytic_derivation,
-    if analytic_derivation==2 || asy_hess,
+if analytic_derivation
+    if analytic_derivation==2 || asy_hess
         LIK={LIK, DLIK, Hess};
     else
         LIK={LIK, DLIK};
diff --git a/matlab/kalman/likelihood/univariate_kalman_filter_d.m b/matlab/kalman/likelihood/univariate_kalman_filter_d.m
index ac121ee33861d98c1d476b4940eeadefe64ac587..ce78d2421497d1c570081d334910d611ae21dd55 100644
--- a/matlab/kalman/likelihood/univariate_kalman_filter_d.m
+++ b/matlab/kalman/likelihood/univariate_kalman_filter_d.m
@@ -80,14 +80,14 @@ function [dLIK, dlikk, a, Pstar, llik] = univariate_kalman_filter_d(data_index,
 %! @ref{univariate_kalman_filter_ss}
 %! @end deftypefn
 %@eod:
-% 
+%
 % Algorithm:
-% 
+%
 %   Uses the diffuse univariate filter as described in Durbin/Koopman (2012): "Time
 %   Series Analysis by State Space Methods", Oxford University Press,
 %   Second Edition, Ch. 5, 6.4 + 7.2.5
 
-% Copyright (C) 2004-2016 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -125,15 +125,15 @@ while newRank && (t<=last)
     d_index = data_index{t};
     for i=1:length(d_index)
         Zi = Z(d_index(i),:);
-        prediction_error = Y(d_index(i),t) - Zi*a;      % nu_{t,i} in 6.13 in DK (2012) 
+        prediction_error = Y(d_index(i),t) - Zi*a;      % nu_{t,i} in 6.13 in DK (2012)
         Fstar = Zi*Pstar*Zi' + H(d_index(i));           % F_{*,t} in 5.7 in DK (2012), relies on H being diagonal
-        Finf  = Zi*Pinf*Zi';                            % F_{\infty,t} in 5.7 in DK (2012), relies on H being diagonal 
+        Finf  = Zi*Pinf*Zi';                            % F_{\infty,t} in 5.7 in DK (2012), relies on H being diagonal
         Kstar = Pstar*Zi';
         % Conduct check of rank
-        % Pinf and Finf are always scaled such that their norm=1: Fstar/Pstar, instead, 
+        % Pinf and Finf are always scaled such that their norm=1: Fstar/Pstar, instead,
         % depends on the actual values of std errors in the model and can be badly scaled.
-        % experience is that diffuse_kalman_tol has to be bigger than kalman_tol, to ensure 
-        % exiting the diffuse filter properly, avoiding tests that provide false non-zero rank for Pinf. 
+        % experience is that diffuse_kalman_tol has to be bigger than kalman_tol, to ensure
+        % exiting the diffuse filter properly, avoiding tests that provide false non-zero rank for Pinf.
         % Also the test for singularity is better set coarser for Finf than for Fstar for the same reason
         if Finf>diffuse_kalman_tol && newRank           % F_{\infty,t,i} = 0, use upper part of bracket on p. 175 DK (2012) for w_{t,i}
             Kinf   = Pinf*Zi';
@@ -141,7 +141,7 @@ while newRank && (t<=last)
             a         = a + Kinf_Finf*prediction_error;
             Pstar     = Pstar + Kinf*(Kinf_Finf'*(Fstar/Finf)) - Kstar*Kinf_Finf' - Kinf_Finf*Kstar';
             Pinf      = Pinf - Kinf*Kinf_Finf';
-            llik(s,d_index(i)) = log(Finf) + l2pi;      
+            llik(s,d_index(i)) = log(Finf) + l2pi;
             dlikk(s) = dlikk(s) + llik(s,d_index(i));
         elseif Fstar>kalman_tol
             llik(s,d_index(i)) = log(Fstar) + (prediction_error*prediction_error/Fstar) + l2pi;
diff --git a/matlab/kalman/likelihood/univariate_kalman_filter_ss.m b/matlab/kalman/likelihood/univariate_kalman_filter_ss.m
index cbc1d5775351fc9abf61bdda94c0d17905ef1c45..9d8cbff06fa912f12c69768b34c2f2338ff33c7a 100644
--- a/matlab/kalman/likelihood/univariate_kalman_filter_ss.m
+++ b/matlab/kalman/likelihood/univariate_kalman_filter_ss.m
@@ -54,10 +54,10 @@ function [LIK,likk,a] = univariate_kalman_filter_ss(Y,start,last,a,P,kalman_tol,
 %! @sp 1
 %! @end deftypefn
 %@eod:
-% 
+%
 % Algorithm: See univariate_kalman_filter.m
 
-% Copyright (C) 2011-2016 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -90,18 +90,18 @@ if nargin<12
     analytic_derivation = 0;
 end
 
-if  analytic_derivation == 0,
+if  analytic_derivation == 0
     DLIK=[];
     Hess=[];
 else
     k = size(DT,3);                                 % number of structural parameters
     DLIK  = zeros(k,1);                             % Initialization of the score.
     dlikk = zeros(smpl,k);
-    if analytic_derivation==2,
+    if analytic_derivation==2
         Hess  = zeros(k,k);                             % Initialization of the Hessian
     else
         asy_hess=D2a;
-        if asy_hess,
+        if asy_hess
             Hess  = zeros(k,k);                             % Initialization of the Hessian
         else
             Hess=[];
@@ -113,9 +113,9 @@ end
 while t<=last
     s  = t-start+1;
     PP = P;
-    if analytic_derivation,
+    if analytic_derivation
         DPP = DP;
-        if analytic_derivation==2,
+        if analytic_derivation==2
             D2PP = D2P;
         end
     end
@@ -134,14 +134,14 @@ while t<=last
             a  = a + Ki*prediction_error;
             PP = PP - PPZ*Ki';
             likk(s,i) = log(Fi) + prediction_error*prediction_error/Fi + l2pi;
-            if analytic_derivation,
-                if analytic_derivation==2,
+            if analytic_derivation
+                if analytic_derivation==2
                     [Da,DPP,DLIKt,D2a,D2PP, Hesst] = univariate_computeDLIK(k,i,Z(i,:),Zflag,prediction_error,Ki,PPZ,Fi,Da,DYss,DPP,DH(i,:),0,D2a,D2Yss,D2PP);
                 else
                     [Da,DPP,DLIKt,Hesst] = univariate_computeDLIK(k,i,Z(i,:),Zflag,prediction_error,Ki,PPZ,Fi,Da,DYss,DPP,DH(i,:),0);
                 end
                 DLIK = DLIK + DLIKt;
-                if analytic_derivation==2 || asy_hess,
+                if analytic_derivation==2 || asy_hess
                     Hess = Hess + Hesst;
                 end
                 dlikk(s,:)=dlikk(s,:)+DLIKt';
@@ -151,8 +151,8 @@ while t<=last
             % p. 157, DK (2012)
         end
     end
-    if analytic_derivation,        
-        if analytic_derivation==2,
+    if analytic_derivation
+        if analytic_derivation==2
             [Da,junk,D2a] = univariate_computeDstate(k,a,P,T,Da,DP,DT,[],0,D2a,D2P,D2T);
         else
             Da = univariate_computeDstate(k,a,P,T,Da,DP,DT,[],0);
@@ -165,15 +165,15 @@ end
 likk = .5*likk;
 
 LIK = sum(sum(likk));
-if analytic_derivation,
+if analytic_derivation
     dlikk = dlikk/2;
     DLIK = DLIK/2;
     likk = {likk, dlikk};
 end
-if analytic_derivation==2 || asy_hess,
-%     Hess = (Hess + Hess')/2;
+if analytic_derivation==2 || asy_hess
+    %     Hess = (Hess + Hess')/2;
     Hess = -Hess/2;
     LIK={LIK,DLIK,Hess};
-elseif analytic_derivation==1,
+elseif analytic_derivation==1
     LIK={LIK,DLIK};
 end
\ No newline at end of file
diff --git a/matlab/kalman/steady_state_kalman_gain.m b/matlab/kalman/steady_state_kalman_gain.m
index 460534e1b3b1011ae8aa56e65125a616b1861b10..c40761d4a7b0e9193646dccd12fa24bf60171c22 100644
--- a/matlab/kalman/steady_state_kalman_gain.m
+++ b/matlab/kalman/steady_state_kalman_gain.m
@@ -1,23 +1,23 @@
 function [K,iF,P] = steady_state_kalman_gain(T,R,Q,H,mf)
 % Given the invariant state space representation of a model, this
 % function computes the gain matrix and the covariance matrix of the
-% state vector at the steady state of the kalman filter. 
-% 
-% INPUTS 
-%   T   [double]    m*m transition matrix of the state vector.  
+% state vector at the steady state of the kalman filter.
+%
+% INPUTS
+%   T   [double]    m*m transition matrix of the state vector.
 %   R   [double]    m*q matrix (q is the number of structural innovations).
 %   Q   [double]    q*q covariance matrix of the structural innovations.
 %   H   [double]    p*p covariance matrix of the measurement error.
 %   mf  [integer]   p*1 vector, indices for the observed variables
-%    
-% OUTPUTS 
+%
+% OUTPUTS
 %   K   [double]    kalman gain matrix.
 %   P   [double]    covariance matrix of the state vector.
-%               
+%
 % SPECIAL REQUIREMENTS
 %   Needs a solver for Riccati equations (dare.m)
 
-% Copyright (C) 2004-2009 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/kalman_transition_matrix.m b/matlab/kalman_transition_matrix.m
index 77b3a4d3a7741981a52fbf302f5778f80dfc77fb..f79b436cd09c3d1d99cb50f6b7ab984053d62bdd 100644
--- a/matlab/kalman_transition_matrix.m
+++ b/matlab/kalman_transition_matrix.m
@@ -1,21 +1,21 @@
 function [A,B] = kalman_transition_matrix(dr,iv,ic,exo_nbr)
 %function [A,B] = kalman_transition_matrix(dr,iv,ic,exo_nbr)
 % Builds the transition equation of the state space representation out of ghx and ghu for Kalman filter
-% 
+%
 % INPUTS
 %    dr:      structure of decisions rules for stochastic simulations
 %    iv:      selected variables
 %    ic:      state variables position in the transition matrix columns
 %    exo_nbr: number of exogenous variables
-%    
+%
 % OUTPUTS
 %    A:       matrix of predetermined variables effects in linear solution (ghx)
 %    B:       matrix of shocks effects in linear solution (ghu)
-%        
+%
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2016 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -41,4 +41,3 @@ A(:,ic) = dr.ghx(iv,:);
 if nargout>1
     B = dr.ghu(iv,:);
 end
-
diff --git a/matlab/kernel_density_estimate.m b/matlab/kernel_density_estimate.m
index 172097c870c7bb0acd8614ef717b4f0537758b67..c0492768191bb31b5bf9fbba93885770f451a1b1 100644
--- a/matlab/kernel_density_estimate.m
+++ b/matlab/kernel_density_estimate.m
@@ -1,30 +1,30 @@
-function [abscissa,f] = kernel_density_estimate(data,number_of_grid_points,number_of_draws,bandwidth,kernel_function) 
-% Estimates a continuous density. 
-% 
+function [abscissa,f] = kernel_density_estimate(data,number_of_grid_points,number_of_draws,bandwidth,kernel_function)
+% Estimates a continuous density.
+%
 % INPUTS
 %   data                  [double]  Vector (number_of_draws*1) of draws.
 %   number_of_grid_points [integer] Scalar, number of points where the density is estimated.
-%                                   This (positive) integer must be a power of two.  
+%                                   This (positive) integer must be a power of two.
 %   number_of_draws       [integer] Scalar, number of draws.
-%   bandwidth             [double]  Real positive scalar.                                  
+%   bandwidth             [double]  Real positive scalar.
 %   kernel_function       [string]  Name of the kernel function: 'gaussian', 'triweight',
-%                                   'uniform', 'triangle', 'epanechnikov', 'quartic', 
+%                                   'uniform', 'triangle', 'epanechnikov', 'quartic',
 %                                   'triweight' and 'cosinus'
 %
 % OUTPUTS
 %    abscissa             [double] Vector (number_of_grid_points*1) of values on the abscissa axis.
-%    f:                   [double] Vector (number_of_grid_points*1) of values on the ordinate axis, 
+%    f:                   [double] Vector (number_of_grid_points*1) of values on the ordinate axis,
 %                                  (density estimates).
-%        
+%
 % SPECIAL REQUIREMENTS
 %    none.
 %
 % REFERENCES
 %    A kernel density estimator is used (see Silverman [1986], "Density estimation for statistics and data analysis")
-%    The code is adapted from Anders Holtsberg's matlab toolbox (stixbox). 
+%    The code is adapted from Anders Holtsberg's matlab toolbox (stixbox).
 %
 
-% Copyright (C) 2004-2008 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -53,19 +53,19 @@ if (abs(test-round(test)) > 1e-12)
 end
 
 %% Kernel specification.
-if strcmpi(kernel_function,'gaussian') 
+if strcmpi(kernel_function,'gaussian')
     kernel = @(x) inv(sqrt(2*pi))*exp(-0.5*x.^2);
-elseif strcmpi(kernel_function,'uniform') 
-    kernel = @(x) 0.5*(abs(x) <= 1); 
-elseif strcmpi(kernel_function,'triangle') 
+elseif strcmpi(kernel_function,'uniform')
+    kernel = @(x) 0.5*(abs(x) <= 1);
+elseif strcmpi(kernel_function,'triangle')
     kernel = @(x) (1-abs(x)).*(abs(x) <= 1);
-elseif strcmpi(kernel_function,'epanechnikov') 
+elseif strcmpi(kernel_function,'epanechnikov')
     kernel = @(x) 0.75*(1-x.^2).*(abs(x) <= 1);
-elseif strcmpi(kernel_function,'quartic') 
+elseif strcmpi(kernel_function,'quartic')
     kernel = @(x) 0.9375*((1-x.^2).^2).*(abs(x) <= 1);
-elseif strcmpi(kernel_function,'triweight') 
+elseif strcmpi(kernel_function,'triweight')
     kernel = @(x) 1.09375*((1-x.^2).^3).*(abs(x) <= 1);
-elseif strcmpi(kernel_function,'cosinus') 
+elseif strcmpi(kernel_function,'cosinus')
     kernel = @(x) (pi/4)*cos((pi/2)*x).*(abs(x) <= 1);
 end
 
@@ -73,9 +73,9 @@ end
 lower_bound  = min(data) - (max(data)-min(data))/3;
 upper_bound  = max(data) + (max(data)-min(data))/3;
 abscissa = linspace(lower_bound,upper_bound,number_of_grid_points)';
-inc = abscissa(2)-abscissa(1); 
+inc = abscissa(2)-abscissa(1);
 xi  = zeros(number_of_grid_points,1);
-xa  = (data-lower_bound)/(upper_bound-lower_bound)*number_of_grid_points; 
+xa  = (data-lower_bound)/(upper_bound-lower_bound)*number_of_grid_points;
 for i = 1:number_of_draws
     indx = floor(xa(i));
     temp = xa(i)-indx;
diff --git a/matlab/list_of_functions_to_be_cleared.m b/matlab/list_of_functions_to_be_cleared.m
index e482add52c65e3452b83f2d135ef18fd2fe31fb3..a9d182dae2307d77a79f35668ff9505c1c6b38fd 100644
--- a/matlab/list_of_functions_to_be_cleared.m
+++ b/matlab/list_of_functions_to_be_cleared.m
@@ -1 +1 @@
-list_of_functions = {'discretionary_policy_1', 'dsge_var_likelihood', 'dyn_first_order_solver', 'dyn_waitbar', 'ep_residuals', 'evaluate_likelihood', 'evaluate_smoother', 'prior_draw_gsa', 'identification_analysis', 'computeDLIK', 'univariate_computeDLIK', 'metropolis_draw', 'flag_implicit_skip_nan', 'moment_function', 'non_linear_dsge_likelihood', 'mr_hessian', 'masterParallel', 'auxiliary_initialization', 'auxiliary_particle_filter', 'conditional_filter_proposal', 'conditional_particle_filter', 'gaussian_filter', 'gaussian_filter_bank', 'gaussian_mixture_filter', 'gaussian_mixture_filter_bank', 'Kalman_filter', 'online_auxiliary_filter', 'sequential_importance_particle_filter', 'solve_model_for_online_filter', 'perfect_foresight_simulation', 'prior_draw', 'priordens', 'smm_objective'};
\ No newline at end of file
+list_of_functions = {'discretionary_policy_1', 'dsge_var_likelihood', 'dyn_first_order_solver', 'dyn_waitbar', 'ep_residuals', 'evaluate_likelihood', 'prior_draw_gsa', 'identification_analysis', 'computeDLIK', 'univariate_computeDLIK', 'metropolis_draw', 'flag_implicit_skip_nan', 'moment_function', 'non_linear_dsge_likelihood', 'mr_hessian', 'masterParallel', 'auxiliary_initialization', 'auxiliary_particle_filter', 'conditional_filter_proposal', 'conditional_particle_filter', 'gaussian_filter', 'gaussian_filter_bank', 'gaussian_mixture_filter', 'gaussian_mixture_filter_bank', 'Kalman_filter', 'online_auxiliary_filter', 'sequential_importance_particle_filter', 'solve_model_for_online_filter', 'perfect_foresight_simulation', 'prior_draw', 'priordens', 'smm_objective'};
\ No newline at end of file
diff --git a/matlab/list_of_parameters_calibrated_as_NaN.m b/matlab/list_of_parameters_calibrated_as_NaN.m
index 603a9f2e1f2dd3fb7e77ce498d5c9f21dbd024a2..01964a89a9f21f107163aa76824e1da6b9ce8cb2 100644
--- a/matlab/list_of_parameters_calibrated_as_NaN.m
+++ b/matlab/list_of_parameters_calibrated_as_NaN.m
@@ -1,19 +1,19 @@
 function list = list_of_parameters_calibrated_as_NaN(M_)
 % The name of the function is explicit enough...
-%  
+%
 % INPUTS
 %   M_    [structure]   Description of the (simulated or estimated) model.
-%  
+%
 % OUTPUTS
 %   list  [char]        n*p array of characters, each line is the name of parameter without value.
-%    
+%
 % ALGORITHM
 %   none
-%    
+%
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2010-2011 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/lmmcp/catstruct.m b/matlab/lmmcp/catstruct.m
index 540bc99d7aff0ad6f4581141f63fffdb872429d0..df4a9c05b500bbaac74a356d6aa3eebdd10ad050 100644
--- a/matlab/lmmcp/catstruct.m
+++ b/matlab/lmmcp/catstruct.m
@@ -1,174 +1,171 @@
-function A = catstruct(varargin)
-% CATSTRUCT   Concatenate or merge structures with different fieldnames
-%   X = CATSTRUCT(S1,S2,S3,...) merges the structures S1, S2, S3 ...
-%   into one new structure X. X contains all fields present in the various
-%   structures. An example:
-%
-%     A.name = 'Me' ;
-%     B.income = 99999 ;
-%     X = catstruct(A,B) 
-%     % -> X.name = 'Me' ;
-%     %    X.income = 99999 ;
-%
-%   If a fieldname is not unique among structures (i.e., a fieldname is
-%   present in more than one structure), only the value from the last
-%   structure with this field is used. In this case, the fields are 
-%   alphabetically sorted. A warning is issued as well. An axample:
-%
-%     S1.name = 'Me' ;
-%     S2.age  = 20 ; S3.age  = 30 ; S4.age  = 40 ;
-%     S5.honest = false ;
-%     Y = catstruct(S1,S2,S3,S4,S5) % use value from S4
-%
-%   The inputs can be array of structures. All structures should have the
-%   same size. An example:
-%
-%     C(1).bb = 1 ; C(2).bb = 2 ;
-%     D(1).aa = 3 ; D(2).aa = 4 ;
-%     CD = catstruct(C,D) % CD is a 1x2 structure array with fields bb and aa
-%
-%   The last input can be the string 'sorted'. In this case,
-%   CATSTRUCT(S1,S2, ..., 'sorted') will sort the fieldnames alphabetically. 
-%   To sort the fieldnames of a structure A, you could use
-%   CATSTRUCT(A,'sorted') but I recommend ORDERFIELDS for doing that.
-%
-%   When there is nothing to concatenate, the result will be an empty
-%   struct (0x0 struct array with no fields).
-%
-%   NOTE: To concatenate similar arrays of structs, you can use simple
-%   concatenation: 
-%     A = dir('*.mat') ; B = dir('*.m') ; C = [A ; B] ;
-%
-%   See also CAT, STRUCT, FIELDNAMES, STRUCT2CELL, ORDERFIELDS
-
-% for Matlab R13 and up
-% version 3.0 (mar 2013)
-% Originally downloaded from MATLAB central:
-% http://www.mathworks.com/matlabcentral/fileexchange/7842-catstruct
-
-% Copyright (C) 2005 Jos van der Geest <jos@jasen.nl>
-% Copyright (C) 2013 Christophe Gouel
-% Copyright (C) 2016 Dynare Team
-%
-% Redistribution and use in source and binary forms, with or without
-% modification, are permitted provided that the following conditions are
-% met:
-% 
-%     * Redistributions of source code must retain the above copyright
-%       notice, this list of conditions and the following disclaimer.
-%     * Redistributions in binary form must reproduce the above copyright
-%       notice, this list of conditions and the following disclaimer in
-%       the documentation and/or other materials provided with the distribution
-% 
-% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-% POSSIBILITY OF SUCH DAMAGE.
-
-% History
-% Created in 2005
-% Revisions
-%   2.0 (sep 2007) removed bug when dealing with fields containing cell
-%                  arrays (Thanks to Rene Willemink)
-%   2.1 (sep 2008) added warning and error identifiers
-%   2.2 (oct 2008) fixed error when dealing with empty structs (Thanks to
-%                  Lars Barring)
-%   3.0 (mar 2013) fixed problem when the inputs were array of structures
-%                  (thanks to Tor Inge Birkenes for pointing this out).
-%                  Rephrased the help section as well.
-
-narginchk(1, Inf);
-N = nargin ;
-
-if ~isstruct(varargin{end}),
-    if isequal(varargin{end},'sorted'),
-        sorted = 1 ;
-        N = N-1 ;
-        if N<1
-            error('catstruct: wrong number of input arguments') ;
-        end
-    else
-        error('catstruct:InvalidArgument','Last argument should be a structure, or the string "sorted".') ;
-    end
-else
-    sorted = 0 ;
-end
-
-sz0 = [] ; % used to check that all inputs have the same size
-
-% used to check for a few trivial cases
-NonEmptyInputs = false(N,1) ; 
-NonEmptyInputsN = 0 ;
-
-% used to collect the fieldnames and the inputs
-FN = cell(N,1) ;
-VAL = cell(N,1) ;
-
-% parse the inputs
-for ii=1:N,
-    X = varargin{ii} ;
-    if ~isstruct(X),
-        error('catstruct:InvalidArgument',['Argument #' num2str(ii) ' is not a structure.']) ;
-    end
-    
-    if ~isempty(X),
-        % empty structs are ignored
-        if ii > 1 && ~isempty(sz0)
-            if ~isequal(size(X), sz0)
-                error('catstruct:UnequalSizes','All structures should have the same size.') ;
-            end
-        else
-            sz0 = size(X) ;
-        end
-        NonEmptyInputsN = NonEmptyInputsN + 1 ;
-        NonEmptyInputs(ii) = true ;
-        FN{ii} = fieldnames(X) ;
-        VAL{ii} = struct2cell(X) ;
-    end
-end
-
-if NonEmptyInputsN == 0
-    % all structures were empty
-    A = struct([]) ;
-elseif NonEmptyInputsN == 1,
-    % there was only one non-empty structure
-    A = varargin{NonEmptyInputs} ;
-    if sorted,
-        A = orderfields(A) ;
-    end
-else
-    % there is actually something to concatenate
-    FN = cat(1,FN{:}) ;    
-    VAL = cat(1,VAL{:}) ;    
-    FN = squeeze(FN) ;
-    VAL = squeeze(VAL) ;
-    MatlabVersion = version;
-    if isoctave || str2double(MatlabVersion(end-5:end-2))<2013 % Equivalent to, but faster than if verLessThan('matlab','8.1')
-      [UFN,ind] = unique(FN) ;          
-    else
-      [UFN,ind] = unique(FN,'legacy') ;
-    end
-    
-    if numel(UFN) ~= numel(FN),
-        warning('catstruct:DuplicatesFound','Fieldnames are not unique between structures.') ;
-        sorted = 1 ;
-    end
-    
-    if sorted,
-        VAL = VAL(ind,:) ;
-        FN = FN(ind,:) ;
-    end
-    
-    A = cell2struct(VAL, FN);
-    A = reshape(A, sz0) ; % reshape into original format
-end
-
-
-
+function A = catstruct(varargin)
+% CATSTRUCT   Concatenate or merge structures with different fieldnames
+%   X = CATSTRUCT(S1,S2,S3,...) merges the structures S1, S2, S3 ...
+%   into one new structure X. X contains all fields present in the various
+%   structures. An example:
+%
+%     A.name = 'Me' ;
+%     B.income = 99999 ;
+%     X = catstruct(A,B)
+%     % -> X.name = 'Me' ;
+%     %    X.income = 99999 ;
+%
+%   If a fieldname is not unique among structures (i.e., a fieldname is
+%   present in more than one structure), only the value from the last
+%   structure with this field is used. In this case, the fields are
+%   alphabetically sorted. A warning is issued as well. An axample:
+%
+%     S1.name = 'Me' ;
+%     S2.age  = 20 ; S3.age  = 30 ; S4.age  = 40 ;
+%     S5.honest = false ;
+%     Y = catstruct(S1,S2,S3,S4,S5) % use value from S4
+%
+%   The inputs can be array of structures. All structures should have the
+%   same size. An example:
+%
+%     C(1).bb = 1 ; C(2).bb = 2 ;
+%     D(1).aa = 3 ; D(2).aa = 4 ;
+%     CD = catstruct(C,D) % CD is a 1x2 structure array with fields bb and aa
+%
+%   The last input can be the string 'sorted'. In this case,
+%   CATSTRUCT(S1,S2, ..., 'sorted') will sort the fieldnames alphabetically.
+%   To sort the fieldnames of a structure A, you could use
+%   CATSTRUCT(A,'sorted') but I recommend ORDERFIELDS for doing that.
+%
+%   When there is nothing to concatenate, the result will be an empty
+%   struct (0x0 struct array with no fields).
+%
+%   NOTE: To concatenate similar arrays of structs, you can use simple
+%   concatenation:
+%     A = dir('*.mat') ; B = dir('*.m') ; C = [A ; B] ;
+%
+%   See also CAT, STRUCT, FIELDNAMES, STRUCT2CELL, ORDERFIELDS
+
+% for Matlab R13 and up
+% version 3.0 (mar 2013)
+% Originally downloaded from MATLAB central:
+% http://www.mathworks.com/matlabcentral/fileexchange/7842-catstruct
+
+% Copyright (C) 2005 Jos van der Geest <jos@jasen.nl>
+% Copyright (C) 2013 Christophe Gouel
+% Copyright (C) 2016-2017 Dynare Team
+%
+% Redistribution and use in source and binary forms, with or without
+% modification, are permitted provided that the following conditions are
+% met:
+%
+%     * Redistributions of source code must retain the above copyright
+%       notice, this list of conditions and the following disclaimer.
+%     * Redistributions in binary form must reproduce the above copyright
+%       notice, this list of conditions and the following disclaimer in
+%       the documentation and/or other materials provided with the distribution
+%
+% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+% POSSIBILITY OF SUCH DAMAGE.
+
+% History
+% Created in 2005
+% Revisions
+%   2.0 (sep 2007) removed bug when dealing with fields containing cell
+%                  arrays (Thanks to Rene Willemink)
+%   2.1 (sep 2008) added warning and error identifiers
+%   2.2 (oct 2008) fixed error when dealing with empty structs (Thanks to
+%                  Lars Barring)
+%   3.0 (mar 2013) fixed problem when the inputs were array of structures
+%                  (thanks to Tor Inge Birkenes for pointing this out).
+%                  Rephrased the help section as well.
+
+narginchk(1, Inf);
+N = nargin ;
+
+if ~isstruct(varargin{end})
+    if isequal(varargin{end},'sorted')
+        sorted = 1 ;
+        N = N-1 ;
+        if N<1
+            error('catstruct: wrong number of input arguments') ;
+        end
+    else
+        error('catstruct:InvalidArgument','Last argument should be a structure, or the string "sorted".') ;
+    end
+else
+    sorted = 0 ;
+end
+
+sz0 = [] ; % used to check that all inputs have the same size
+
+% used to check for a few trivial cases
+NonEmptyInputs = false(N,1) ;
+NonEmptyInputsN = 0 ;
+
+% used to collect the fieldnames and the inputs
+FN = cell(N,1) ;
+VAL = cell(N,1) ;
+
+% parse the inputs
+for ii=1:N
+    X = varargin{ii} ;
+    if ~isstruct(X)
+        error('catstruct:InvalidArgument',['Argument #' num2str(ii) ' is not a structure.']) ;
+    end
+
+    if ~isempty(X)
+        % empty structs are ignored
+        if ii > 1 && ~isempty(sz0)
+            if ~isequal(size(X), sz0)
+                error('catstruct:UnequalSizes','All structures should have the same size.') ;
+            end
+        else
+            sz0 = size(X) ;
+        end
+        NonEmptyInputsN = NonEmptyInputsN + 1 ;
+        NonEmptyInputs(ii) = true ;
+        FN{ii} = fieldnames(X) ;
+        VAL{ii} = struct2cell(X) ;
+    end
+end
+
+if NonEmptyInputsN == 0
+    % all structures were empty
+    A = struct([]) ;
+elseif NonEmptyInputsN == 1
+    % there was only one non-empty structure
+    A = varargin{NonEmptyInputs} ;
+    if sorted
+        A = orderfields(A) ;
+    end
+else
+    % there is actually something to concatenate
+    FN = cat(1,FN{:}) ;
+    VAL = cat(1,VAL{:}) ;
+    FN = squeeze(FN) ;
+    VAL = squeeze(VAL) ;
+    MatlabVersion = version;
+    if isoctave || str2double(MatlabVersion(end-5:end-2))<2013 % Equivalent to, but faster than if verLessThan('matlab','8.1')
+        [UFN,ind] = unique(FN) ;
+    else
+        [UFN,ind] = unique(FN,'legacy') ;
+    end
+
+    if numel(UFN) ~= numel(FN)
+        warning('catstruct:DuplicatesFound','Fieldnames are not unique between structures.') ;
+        sorted = 1 ;
+    end
+
+    if sorted
+        VAL = VAL(ind,:) ;
+        FN = FN(ind,:) ;
+    end
+
+    A = cell2struct(VAL, FN);
+    A = reshape(A, sz0) ; % reshape into original format
+end
diff --git a/matlab/lmmcp/dyn_lmmcp_func.m b/matlab/lmmcp/dyn_lmmcp_func.m
index 936f98306dae861e8c01a7d30f90620bdeffb308..0da1f7565fd77c50fb476e6a056f8ba249af0cbd 100644
--- a/matlab/lmmcp/dyn_lmmcp_func.m
+++ b/matlab/lmmcp/dyn_lmmcp_func.m
@@ -3,7 +3,7 @@ function [F,A] = dyn_lmmcp_func(x, model_dynamic, Y0, YT, exo_simul, params, ...
                                 i_cols_A1, i_cols_1, i_cols_T, i_cols_j, ...
                                 nnzA,eq_index)
 
-% Copyright (C) 2014 Dynare Team
+% Copyright (C) 2014-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -20,37 +20,36 @@ function [F,A] = dyn_lmmcp_func(x, model_dynamic, Y0, YT, exo_simul, params, ...
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-    Y = [Y0; x; YT];
-    
-    F = zeros(periods*ny,1);
-    if nargout == 2
-        A = sparse([],[],[],periods*ny,periods*ny,periods*nnzA);
-    end
+Y = [Y0; x; YT];
 
-    i_rows = 1:ny;
-    i_cols = find(lead_lag_incidence');
-    i_cols_A = i_cols;
-
-    for it = 2:(periods+1)
-        
-        [res,jacobian] = model_dynamic(Y(i_cols),exo_simul, params, ...
-                                       steady_state,it);
-        F(i_rows) = res(eq_index);
-        
-        if nargout == 2
-            if it == 2
-                A(i_rows,i_cols_A1) = jacobian(eq_index,i_cols_1);
-            elseif it == periods+1
-                A(i_rows,i_cols_A(i_cols_T)) = jacobian(eq_index,i_cols_T);
-            else
-                A(i_rows,i_cols_A) = jacobian(eq_index,i_cols_j);
-            end
-        end
-        
-        i_rows = i_rows + ny;
-        i_cols = i_cols + ny;
-        if nargout == 2 && it > 2
-            i_cols_A = i_cols_A + ny;
+F = zeros(periods*ny,1);
+if nargout == 2
+    A = sparse([],[],[],periods*ny,periods*ny,periods*nnzA);
+end
+
+i_rows = 1:ny;
+i_cols = find(lead_lag_incidence');
+i_cols_A = i_cols;
+
+for it = 2:(periods+1)
+
+    [res,jacobian] = model_dynamic(Y(i_cols),exo_simul, params, ...
+                                   steady_state,it);
+    F(i_rows) = res(eq_index);
+
+    if nargout == 2
+        if it == 2
+            A(i_rows,i_cols_A1) = jacobian(eq_index,i_cols_1);
+        elseif it == periods+1
+            A(i_rows,i_cols_A(i_cols_T)) = jacobian(eq_index,i_cols_T);
+        else
+            A(i_rows,i_cols_A) = jacobian(eq_index,i_cols_j);
         end
     end
 
+    i_rows = i_rows + ny;
+    i_cols = i_cols + ny;
+    if nargout == 2 && it > 2
+        i_cols_A = i_cols_A + ny;
+    end
+end
diff --git a/matlab/lmmcp/get_complementarity_conditions.m b/matlab/lmmcp/get_complementarity_conditions.m
index d1ea1771fdd2031835f1a0130b8fc4c22b058bc2..fb48ece9a15eb97f365e0ae622bb1433862b734e 100644
--- a/matlab/lmmcp/get_complementarity_conditions.m
+++ b/matlab/lmmcp/get_complementarity_conditions.m
@@ -2,17 +2,17 @@ function [lb,ub,eq_index] = get_complementarity_conditions(M,ramsey_policy)
 % [lb,ub,eq_index] = get_complementarity_conditions(M,ramsey_policy)
 % INPUTS
 %   - M                   [struct] contains a description of the model.
-%   - ramsey_policy       [boolean] indicator whether a Ramsey problem is considered 
+%   - ramsey_policy       [boolean] indicator whether a Ramsey problem is considered
 % OUTPUTS
 %   - lb                  [double] endo_nbr*1 array of lower bounds for
 %                                   endogenous variables
 %   - ub                  [double] endo_nbr*1 array of upper bounds for
 %                                   endogenous variables
-%   - eq_index            [struct] endo_nbr*1 index vector describing residual mapping resulting 
+%   - eq_index            [struct] endo_nbr*1 index vector describing residual mapping resulting
 %                                from complementarity setup used in
 %                                perfect_foresight_mcp_problem.m
 
-% Copyright (C) 2014-16 Dynare Team
+% Copyright (C) 2014-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -55,14 +55,14 @@ for i=1:size(etags,1)
         str = etags{i,3};
         kop = strfind(etags{i,3},'<');
         if ~isempty(kop)
-                k = find(strcmp(strtrim(str(1:kop-1)),cellstr(M.endo_names))); %get variable index with restriction
-                if isempty(k)
-                    error(sprintf(['Complementarity condition %s: variable %s is ' ...
-                                   'not recognized'],etags{i,3},strtrim(str(1:kop-1))))
-                end
-                ub(k) = str2num(str(kop+1:end));
-                eq_index(etags{i,1}) = k;
-                eq_index(k) = etags{i,1};
+            k = find(strcmp(strtrim(str(1:kop-1)),cellstr(M.endo_names))); %get variable index with restriction
+            if isempty(k)
+                error(sprintf(['Complementarity condition %s: variable %s is ' ...
+                               'not recognized'],etags{i,3},strtrim(str(1:kop-1))))
+            end
+            ub(k) = str2num(str(kop+1:end));
+            eq_index(etags{i,1}) = k;
+            eq_index(k) = etags{i,1};
         else
             kop = strfind(etags{i,3},'>');
             if ~isempty(kop)
@@ -81,4 +81,3 @@ for i=1:size(etags,1)
         end
     end
 end
-
diff --git a/matlab/lmmcp/lmmcp.m b/matlab/lmmcp/lmmcp.m
index 1ac1c5e0a444a916ba17bde44212f58d6bc54923..50404ac7c948145c941dd7e07881f49e9d8127cb 100644
--- a/matlab/lmmcp/lmmcp.m
+++ b/matlab/lmmcp/lmmcp.m
@@ -1,625 +1,625 @@
-function [x,FVAL,EXITFLAG,OUTPUT,JACOB] = lmmcp(FUN,x,lb,ub,options,varargin)
-% LMMCP solves a mixed complementarity problem.
-%
-% LMMCP uses a semismooth least squares formulation. The method applies a
-% Levenberg-Marquardt/Gauss-Newton algorithm to a least-squares formulation.
-%
-% X = LMMCP(FUN,X0) tries to solve the system of nonlinear equations F(X)=0 and
-% starts at the vector X0. FUN accepts a vector X and return a vector F of equation
-% values F evaluated at X and, as second output if required, a matrix J, the
-% Jacobian evaluated at X.
-%
-% X = LMMCP(FUN,X0,LB,UB) solves the mixed complementarity problem of the form:
-% LB =X     =>   F(X)>0,
-% LB<=X<=UB =>   F(X)=0,
-%     X =UB =>   F(X)<0.
-%
-% X = LMMCP(FUN,X0,LB,UB,OPTIONS) solves the MCP problem using the options
-% defined in the structure OPTIONS. Main fields are
-%      Display    : control the display of iterations, 'none' (default),
-%                   'iter-detailed' or 'final-detailed'
-%  Switch from phase I to phase II
-%      preprocess : activate preprocessor for phase I (default = 1)
-%      presteps   : number of iterations in phase I (default = 20)
-%  Termination parameters
-%      MaxIter    : Maximum number of iterations (default = 500)
-%      tmin       : safeguard stepsize (default = 1E-12)
-%      TolFun     : Termination tolerance on the function value, a positive 
-%                   scalar (default = sqrt(eps))
-%  Stepsize parameters
-%      m          : number of previous function values to use in the nonmonotone
-%                   line search rule (default = 10)
-%      kwatch     : maximum number of steps (default = 20 and should not be
-%                   smaller than m)
-%      watchdog   : activate the watchdog strategy (default = 1)
-%  Ther are other minor parameters. Please see the code for their default values
-%  and interpretation.
-%
-% [X,FVAL] = LMMCP(FUN,X0,...) returns the value of the equations FUN at X.
-%
-% [X,FVAL,EXITFLAG] = LMMCP(FUN,X0,...) returns EXITFLAG that describes the exit
-% conditions. Possible values are
-%      1         : LMMCP converged to a root
-%      0         : Too many iterations
-%     -1         :
-%
-% [X,FVAL,EXITFLAG,OUTPUT] = LMMCP(FUN,X0,...) returns the structure OUTPUT that
-% contains the number of iterations (OUTPUT.iterations), the value of the merit
-% function (OUTPUT.Psix), and the norm of the derivative of the merit function
-% (OUTPUT.normDPsix).
-%
-% [X,FVAL,EXITFLAG,OUTPUT,JACOB] = LMMCP(FUN,X0,...) returns JACOB the Jacobian
-% of FUN evaluated at X.
-%
-% More details of the main program may be found in the following paper:
-%
-% Christian Kanzow and Stefania Petra: On a semismooth least squares formulation of
-% complementarity problems with gap reduction. Optimization Methods and Software
-% 19, 2004, pp. 507-525.
-%
-% In addition, the current implementation uses a preprocessor which is the
-% projected Levenberg-Marquardt step from the following preprint:
-%
-% Christian Kanzow and Stefania Petra: Projected filter trust region methods for a
-% semismooth least squares formulation of mixed complementarity
-% problems. Optimization Methods and Software
-% 22, 2007, pp. 713-735.
-%
-% A user's guide is also available:
-%
-% Christian Kanzow and Stefania Petra (2005).
-% LMMCP --- A Levenberg-Marquardt-type MATLAB Solver for Mixed Complementarity Problems.
-% University of Wuerzburg.
-% http://www.mathematik.uni-wuerzburg.de/~kanzow/software/UserGuide.pdf
-%
-% This is a modification by Christophe Gouel of the original files, which can be
-% downloaded from:
-% http://www.mathematik.uni-wuerzburg.de/~kanzow/software/LMMCP.zip
-%
-% Written by Christian Kanzow and Stefania Petra
-%            Institute of Applied Mathematics and Statistics
-%            University of Wuerzburg
-%            Am Hubland
-%            97074 Wuerzburg
-%            GERMANY
-%
-%            e-mail: kanzow@mathematik.uni-wuerzburg.de
-%                    petra@mathematik.uni-wuerzburg.de
-%
-% Christian Kanzow sent a private message to Dynare Team on July 8, 2014,
-% confirming the free software status of lmmcp and granting unlimited
-% permission to use, copy, modifiy or redistribute the file.
-
-% Copyright (C) 2005 Christian Kanzow and Stefania Petra
-% Copyright (C) 2013 Christophe Gouel
-% Copyright (C) 2014 Dynare Team
-%
-% Unlimited permission is granted to everyone to use, copy, modify or
-% distribute this software.
-
-%% Initialization
-defaultopt = struct(...
-    'beta',       0.55,...
-    'Big',        1e10,...
-    'delta',      5,...
-    'deltamin',   1,...
-    'Display',    'none',...
-    'epsilon1',   1e-6,...
-    'eta',        0.95,...
-    'kwatch',     20,...
-    'lambda1',    0.1,...
-    'm',          10,...
-    'MaxIter',    500,...
-    'null',       1e-10,...
-    'preprocess', 1,...
-    'presteps',   20,...
-    'sigma',      1e-4,...
-    'sigma1',     0.5,...
-    'sigma2',     2,...
-    'tmin',       1e-12,...
-    'TolFun',     sqrt(eps),...
-    'watchdog',   1);
-
-if nargin < 4
-  ub = inf(size(x));
-  if nargin < 3
-    lb = -inf(size(x));
-  end
-end
-
-if nargin < 5 || isempty(options) || ~isstruct(options)
-  options = defaultopt;
-else
-  warning('off','catstruct:DuplicatesFound')
-  options = catstruct(defaultopt,options);
-end
-
-warning('off','MATLAB:rankDeficientMatrix')
-
-switch options.Display
-  case {'off','none'}
-    verbosity = 0;
-  case {'iter','iter-detailed'}
-    verbosity = 2;
-  case {'final','final-detailed'}
-    verbosity = 1;
-  otherwise
-    verbosity = 0;
-end
-
-% parameter settings
-eps1 = options.epsilon1;
-eps2 = 0.5*options.TolFun^2;
-null = options.null;
-Big  = options.Big;
-
-% maximal number of iterations
-kmax     = options.MaxIter;
-
-% choice of lambda
-lambda1  = options.lambda1;
-lambda2  = 1-lambda1;
-
-% steplength parameters
-beta     = options.beta;
-sigma    = options.sigma;
-tmin     = options.tmin;
-
-% parameters watchdog and nonmonotone line search; redefined later
-m        = options.m;
-kwatch   = options.kwatch;
-watchdog = options.watchdog; % 1=watchdog strategy active, otherwise not
-
-% parameters for preprocessor
-preprocess = options.preprocess; % 1=preprocessor used, otherwise not
-presteps   = options.presteps; % maximum number of preprocessing steps
-
-% trust-region parameters for preprocessor
-delta    = options.delta;
-deltamin = options.deltamin;
-sigma1   = options.sigma1;
-sigma2   = options.sigma2;
-eta      = options.eta;
-
-% initializations
-k        = 0;
-k_main   = 0;
-
-% compute a feasible starting point by projection
-x = max(lb,min(x,ub));
-
-n = length(x);
-OUTPUT.Dim = n;
-
-% definition of index sets I_l, I_u and I_lu
-Indexset       = zeros(n,1);
-I_l            = lb>-Big & ub>Big;
-I_u            = lb<-Big & ub<Big;
-I_lu           = lb>-Big & ub<Big;
-Indexset(I_l)  = 1;
-Indexset(I_u)  = 2;
-Indexset(I_lu) = 3;
-
-% function evaluations
-[Fx,DFx] = feval(FUN,x,varargin{:});
-
-% choice of NCP-function and corresponding evaluations
-Phix      = Phi(x,Fx,lb,ub,lambda1,lambda2,n,Indexset);
-normPhix  = norm(Phix);
-Psix      = 0.5*(Phix'*Phix);
-DPhix     = DPhi(x,Fx,DFx,lb,ub,lambda1,lambda2,n,Indexset);
-DPsix     = DPhix'*Phix;
-normDPsix = norm(DPsix);
-
-% save initial values
-x0         = x;
-Phix0      = Phix;
-Psix0      = Psix;
-DPhix0     = DPhix;
-DPsix0     = DPsix;
-normDPsix0 = normDPsix;
-
-% watchdog strategy
-aux    = zeros(m,1);
-aux(1) = Psix;
-MaxPsi = Psix;
-
-if watchdog==1
-  kbest        = k;
-  xbest        = x;
-  Phibest      = Phix;
-  Psibest      = Psix;
-  DPhibest     = DPhix;
-  DPsibest     = DPsix;
-  normDPsibest = normDPsix;
-end
-
-% initial output
-if verbosity > 1
-  fprintf('   k               Psi(x)                || DPsi(x) ||    stepsize\n');
-  disp('====================================================================')
-  disp('********************* Output at starting point *********************')
-  fprintf('%4.0f %24.5e %24.5e\n',k,Psix,normDPsix);
-end
-
-%% Preprocessor using local method
-
-if preprocess==1
-
-  if verbosity > 1
-    disp('************************** Preprocessor ****************************')
-  end
-  
-  normpLM=1;
-  while (k < presteps) && (Psix > eps2) && (normpLM>null)
-    k = k+1;
-    
-    % choice of Levenberg-Marquardt parameter, note that we do not use
-    % the condition estimator for large-scale problems, although this
-    % may cause numerical problems in some examples
-
-    i  = false;
-    mu = 0;
-    if n<100
-      i = true;
-      mu = 1e-16;
-      if condest(DPhix'*DPhix)>1e25
-        mu = 1e-6/(k+1);
-      end
-    end
-    if i
-      pLM =  [DPhix; sqrt(mu)*speye(n)]\[-Phix; zeros(n,1)];
-    else
-      pLM = -DPhix\Phix;
-    end
-    normpLM = norm(pLM);
-    
-    % compute the projected Levenberg-Marquard step onto box Xk
-    lbnew = max(min(lb-x,0),-delta);
-    ubnew = min(max(ub-x,0),delta);
-    d     = max(lbnew,min(pLM,ubnew));
-    xnew  = x+d;
-
-    % function evaluations etc.
-    [Fxnew,DFxnew] = feval(FUN,xnew,varargin{:});
-    Phixnew        = Phi(xnew,Fxnew,lb,ub,lambda1,lambda2,n,Indexset);
-    Psixnew        = 0.5*(Phixnew'*Phixnew);
-    normPhixnew    = norm(Phixnew);
-    
-    % update of delta
-    if normPhixnew<=eta*normPhix
-      delta = max(deltamin,sigma2*delta);
-    elseif normPhixnew>5*eta*normPhix
-      delta = max(deltamin,sigma1*delta);
-    end
-
-    % update
-    x         = xnew;
-    Fx        = Fxnew;
-    DFx       = DFxnew;
-    Phix      = Phixnew;
-    Psix      = Psixnew;
-    normPhix  = normPhixnew;
-    DPhix     = DPhi(x,Fx,DFx,lb,ub,lambda1,lambda2,n,Indexset);
-    DPsix     = DPhix'*Phix;
-    normDPsix = norm(DPsix,inf);
-    
-    % output at each iteration
-    t=1;
-    if verbosity > 1
-      fprintf('%4.0f %24.5e %24.5e %11.7g\n',k,Psix,normDPsix,t);
-    end
-  end
-end
-
-% terminate program or redefine current iterate as original initial point
-if preprocess==1 && Psix<eps2
-  if verbosity > 0
-    fprintf('Psix = %1.4e\nnormDPsix = %1.4e\n',Psix,normDPsix);
-    disp('Approximate solution found.')
-  end
-  EXITFLAG          = 1;
-  FVAL              = Fx;
-  OUTPUT.iterations = k;
-  OUTPUT.Psix       = Psix;
-  OUTPUT.normDPsix  = normDPsix;
-  JACOB             = DFx;
-  return
-elseif preprocess==1 && Psix>=eps2
-  x=x0;
-  Phix=Phix0;
-  Psix=Psix0;
-  DPhix=DPhix0;
-  DPsix=DPsix0;
-  if verbosity > 1
-    disp('******************** Restart with initial point ********************')
-    fprintf('%4.0f %24.5e %24.5e\n',k_main,Psix0,normDPsix0);
-  end
-end
-
-%%   Main algorithm
-
-if verbosity > 1
-  disp('************************** Main program ****************************')
-end
-
-while (k < kmax) && (Psix > eps2)
-
-  % choice of Levenberg-Marquardt parameter, note that we do not use
-  % the condition estimator for large-scale problems, although this
-  % may cause numerical problems in some examples
-
-  i = false;
-  if n<100
-    i  = true;
-    mu = 1e-16;
-    if condest(DPhix'*DPhix)>1e25
-      mu = 1e-1/(k+1);
-    end
-  end
-  
-  % compute a Levenberg-Marquard direction
-
-  if i
-    d = [DPhix; sqrt(mu)*speye(n)]\[-Phix; zeros(n,1)];
-  else
-    d = -DPhix\Phix;
-  end
-
-  % computation of steplength t using the nonmonotone Armijo-rule
-  % starting with the 6-th iteration
-
-  % computation of steplength t using the monotone Armijo-rule if
-  % d is a 'good' descent direction or k<=5
-
-  t       = 1;
-  xnew    = x+d;
-  Fxnew   = feval(FUN,xnew,varargin{:});
-  Phixnew = Phi(xnew,Fxnew,lb,ub,lambda1,lambda2,n,Indexset);
-  Psixnew = 0.5*(Phixnew'*Phixnew);
-  const   = sigma*DPsix'*d;
-  
-  while (Psixnew > MaxPsi + const*t)  && (t > tmin)
-    t       = t*beta;
-    xnew    = x+t*d;
-    Fxnew   = feval(FUN,xnew,varargin{:});
-    Phixnew = Phi(xnew,Fxnew,lb,ub,lambda1,lambda2,n,Indexset);
-    Psixnew = 0.5*(Phixnew'*Phixnew);
-  end
-
-  % updatings
-  x         = xnew;
-  Fx        = Fxnew;
-  Phix      = Phixnew;
-  Psix      = Psixnew;
-  [junk,DFx]   = feval(FUN,x,varargin{:});
-  DPhix     = DPhi(x,Fx,DFx,lb,ub,lambda1,lambda2,n,Indexset);
-  DPsix     = DPhix'*Phix;
-  normDPsix = norm(DPsix);
-  k         = k+1;
-  k_main    = k_main+1;
-  
-  if k_main<=5
-    aux(mod(k_main,m)+1) = Psix;
-    MaxPsi               = Psix;
-  else
-    aux(mod(k_main,m)+1) = Psix;
-    MaxPsi               = max(aux);
-  end
-  
-  % updatings for the watchdog strategy
-  if watchdog ==1
-    if Psix<Psibest
-      kbest        = k;
-      xbest        = x;
-      Phibest      = Phix;
-      Psibest      = Psix;
-      DPhibest     = DPhix;
-      DPsibest     = DPsix;
-      normDPsibest = normDPsix;
-    elseif k-kbest>kwatch
-      x=xbest;
-      Phix=Phibest;
-      Psix=Psibest;
-      DPhix=DPhibest;
-      DPsix=DPsibest;
-      normDPsix=normDPsibest;
-      MaxPsi=Psix;
-    end
-  end
-
-  if verbosity > 1
-    % output at each iteration
-    fprintf('%4.0f %24.5e %24.5e %11.7g\n',k,Psix,normDPsix,t);
-  end
-end
-
-%% Final output
-if Psix<=eps2
-  EXITFLAG = 1;
-  if verbosity > 0, disp('Approximate solution found.'); end
-elseif k>=kmax
-  EXITFLAG = 0;
-  if verbosity > 0, disp('Maximum iteration number reached.'); end
-elseif normDPsix<=eps1
-  EXITFLAG          = -1; % Provisoire
-  if verbosity > 0, disp('Approximate stationary point found.'); end
-else
-  EXITFLAG          = -1; % Provisoire
-  if verbosity > 0, disp('No solution found.'); end
-end
-
-FVAL              = Fx;
-OUTPUT.iterations = k;
-OUTPUT.Psix       = Psix;
-OUTPUT.normDPsix  = normDPsix;
-JACOB             = DFx;
-
-%% Subfunctions
-
-function y = Phi(x,Fx,lb,ub,lambda1,lambda2,n,Indexset)
-%% PHI
-
-y           = zeros(2*n,1);
-phi_u       = sqrt((ub-x).^2+Fx.^2)-ub+x+Fx;
-LZ          = false(n,1); % logical zero
-
-I0          = Indexset==0;
-y(I0)       = -lambda1*Fx(I0);
-y([LZ; I0]) = -lambda2*Fx(I0);
-
-I1          = Indexset==1;
-y(I1)       = lambda1*(-x(I1)+lb(I1)-Fx(I1)+sqrt((x(I1)-lb(I1)).^2+Fx(I1).^2));
-y([LZ; I1]) = lambda2*max(0,x(I1)-lb(I1)).*max(0,Fx(I1));
-
-I2          = Indexset==2;
-y(I2)       = -lambda1*phi_u(I2);
-y([LZ; I2]) = lambda2*max(0,ub(I2)-x(I2)).*max(0,-Fx(I2));
-
-I3          = Indexset==3;
-y(I3)       = lambda1*(sqrt((x(I3)-lb(I3)).^2+phi_u(I3).^2)-x(I3)+lb(I3)-phi_u(I3));
-y([LZ; I3]) = lambda2*(max(0,x(I3)-lb(I3)).*max(0,Fx(I3))+max(0,ub(I3)-x(I3)).*max(0,-Fx(I3)));
-
-
-function H = DPhi(x,Fx,DFx,lb,ub,lambda1,lambda2,n,Indexset)
-%% DPHI evaluates an element of the C-subdifferential of operator Phi
-
-null       = 1e-8;
-beta_l     = zeros(n,1);
-beta_u     = zeros(n,1);
-alpha_l    = zeros(n,1);
-alpha_u    = zeros(n,1);
-
-
-z          = zeros(n,1);
-H2         = sparse(n,n);
-
-I          = abs(x-lb)<=null & abs(Fx)<=null;
-beta_l(I)  = 1;
-z(I)       = 1;
-
-I          = abs(ub-x)<=null & abs(Fx)<=null;
-beta_u(I)  = 1;
-z(I)       = 1;
-
-I          = x-lb>=-null & Fx>=-null;
-alpha_l(I) = 1;
-
-I          = ub-x>=-null & Fx<=null;
-alpha_u(I) = 1;
-
-Da         = zeros(n,1);
-Db         = zeros(n,1);
-
-I          = 1:n;
-
-I0         = Indexset==0;
-Da(I0)     = 0;
-Db(I0)     = -1;
-H2(I0,:)   = -DFx(I0,:);
-
-I1         = Indexset==1;
-denom1     = zeros(n,1);
-denom2     = zeros(n,1);
-if any(I1)
-  denom1(I1) = max(null,sqrt((x(I1)-lb(I1)).^2+Fx(I1).^2));
-  denom2(I1) = max(null,sqrt(z(I1).^2+(DFx(I1,:)*z).^2));
-end
-
-I1b        = Indexset==1 & beta_l==0;
-Da(I1b)    = (x(I1b)-lb(I1b))./denom1(I1b)-1;
-Db(I1b)    = Fx(I1b)./denom1(I1b)-1;
-I1b        = Indexset==1 & beta_l~=0;
-if any(I1b)
-  Da(I1b)  = z(I1b)./denom2(I1b)-1;
-  Db(I1b)  = (DFx(I1b,:)*z)./denom2(I1b)-1;
-end
-
-I1a         = I(Indexset==1 & alpha_l==1);
-if any(I1a)
-    H2(I1a,:) = spdiags(x(I1a)-lb(I1a), 0, length(I1a), length(I1a))*DFx(I1a,:) +...
-              sparse(1:length(I1a),I1a,Fx(I1a),length(I1a),n,length(I1a));
-end
-
-I2         = Indexset==2;
-denom1     = zeros(n,1);
-denom2     = zeros(n,1);
-if any(I2)
-  denom1(I2) = max(null,sqrt((ub(I2)-x(I2)).^2+Fx(I2).^2));
-  denom2(I2) = max(null,sqrt(z(I2).^2+(DFx(I2,:)*z).^2));
-end
-
-I2b        = Indexset==2 & beta_u==0;
-Da(I2b)    = (ub(I2b)-x(I2b))./denom1(I2b)-1;
-Db(I2b)    = -Fx(I2b)./denom1(I2b)-1;
-I2b        = Indexset==2 & beta_u~=0;
-if any(I2b)
-  Da(I2b)  = -z(I2b)./denom2(I2b)-1;
-  Db(I2b)  = -(DFx(I2b,:)*z)./denom2(I2b)-1;
-end
-
-I2a         = I(Indexset==2 & alpha_u==1);
-if any(I2a)
-  H2(I2a,:) = bsxfun(@times,x(I2a)-ub(I2a),DFx(I2a,:))+...
-              sparse(1:length(I2a),I2a,Fx(I2a),length(I2a),n,length(I2a));
-end
-
-I3         = Indexset==3;
-phi        = zeros(n,1);
-ai         = zeros(n,1);
-bi         = zeros(n,1);
-ci         = zeros(n,1);
-di         = zeros(n,1);
-denom1     = zeros(n,1);
-denom2     = zeros(n,1);
-denom3     = zeros(n,1);
-denom4     = zeros(n,1);
-if any(I3)
-  phi(I3)    = -ub(I3)+x(I3)+Fx(I3)+sqrt((ub(I3)-x(I3)).^2+Fx(I3).^2);
-  denom1(I3) = max(null,sqrt((x(I3)-lb(I3)).^2+phi(I3).^2));
-  denom2(I3) = max(null,sqrt(z(I3).^2+(DFx(I3,:)*z).^2));
-  denom3(I3) = max(null,sqrt((ub(I3)-x(I3)).^2+Fx(I3).^2));
-  denom4(I3) = max(null,sqrt(z(I3).^2));
-end
-
-I3bu       = Indexset==3 & beta_u==0;
-ci(I3bu)   = (x(I3bu)-ub(I3bu))./denom3(I3bu)+1;
-di(I3bu)   = Fx(I3bu)./denom3(I3bu)+1;
-I3bu       = Indexset==3 & beta_u~=0;
-if any(I3bu)
-  ci(I3bu)   = 1+z(I3bu)./denom2(I3bu);
-  di(I3bu)   = 1+(DFx(I3bu,:)*z)./denom2(I3bu);
-end
-
-I3bl       = Indexset==3 & beta_l==0;
-ai(I3bl)   = (x(I3bl)-lb(I3bl))./denom1(I3bl)-1;
-bi(I3bl)   = phi(I3bl)./denom1(I3bl)-1;
-I3bl       = Indexset==3 & beta_l~=0;
-if any(I3bl)
-  ai(I3bl)   = z(I3bl)./denom4(I3bl)-1;
-  bi(I3bl)   = (ci(I3bl).*z(I3bl)+(di(I3bl,ones(1,n)).*DFx(I3bl,:))*z)./denom4(I3bl)-1;
-end
-
-Da(I3)     = ai(I3)+bi(I3).*ci(I3);
-Db(I3)     = bi(I3).*di(I3);
-
-I3a         = I(Indexset==3 & alpha_l==1 & alpha_u==1);
-if any(I3a)
-  H2(I3a,:) = bsxfun(@times,-lb(I3a)-ub(I3a)+2*x(I3a),DFx(I3a,:))+...
-              2*sparse(1:length(I3a),I3a,Fx(I3a),length(I3a),n,length(I3a));
-end
-I3a         = I(Indexset==3 & alpha_l==1 & alpha_u~=1);
-if any(I3a)
-  H2(I3a,:) = bsxfun(@times,x(I3a)-lb(I3a),DFx(I3a,:))+...
-              sparse(1:length(I3a),I3a,Fx(I3a),length(I3a),n,length(I3a));
-end
-I3a         = I(Indexset==3 & alpha_l~=1 & alpha_u==1);
-if any(I3a)
-  H2(I3a,:) = bsxfun(@times,x(I3a)-ub(I3a),DFx(I3a,:))+...
-              sparse(1:length(I3a),I3a,Fx(I3a),length(I3a),n,length(I3a));
-end
-
-H1 = spdiags(Db,0,length(Db),length(Db))*DFx;
-H1 = H1 + spdiags(Da, 0, length(Da), length(Da));
-
-H  = [lambda1*H1; lambda2*H2];
+function [x,FVAL,EXITFLAG,OUTPUT,JACOB] = lmmcp(FUN,x,lb,ub,options,varargin)
+% LMMCP solves a mixed complementarity problem.
+%
+% LMMCP uses a semismooth least squares formulation. The method applies a
+% Levenberg-Marquardt/Gauss-Newton algorithm to a least-squares formulation.
+%
+% X = LMMCP(FUN,X0) tries to solve the system of nonlinear equations F(X)=0 and
+% starts at the vector X0. FUN accepts a vector X and return a vector F of equation
+% values F evaluated at X and, as second output if required, a matrix J, the
+% Jacobian evaluated at X.
+%
+% X = LMMCP(FUN,X0,LB,UB) solves the mixed complementarity problem of the form:
+% LB =X     =>   F(X)>0,
+% LB<=X<=UB =>   F(X)=0,
+%     X =UB =>   F(X)<0.
+%
+% X = LMMCP(FUN,X0,LB,UB,OPTIONS) solves the MCP problem using the options
+% defined in the structure OPTIONS. Main fields are
+%      Display    : control the display of iterations, 'none' (default),
+%                   'iter-detailed' or 'final-detailed'
+%  Switch from phase I to phase II
+%      preprocess : activate preprocessor for phase I (default = 1)
+%      presteps   : number of iterations in phase I (default = 20)
+%  Termination parameters
+%      MaxIter    : Maximum number of iterations (default = 500)
+%      tmin       : safeguard stepsize (default = 1E-12)
+%      TolFun     : Termination tolerance on the function value, a positive
+%                   scalar (default = sqrt(eps))
+%  Stepsize parameters
+%      m          : number of previous function values to use in the nonmonotone
+%                   line search rule (default = 10)
+%      kwatch     : maximum number of steps (default = 20 and should not be
+%                   smaller than m)
+%      watchdog   : activate the watchdog strategy (default = 1)
+%  Ther are other minor parameters. Please see the code for their default values
+%  and interpretation.
+%
+% [X,FVAL] = LMMCP(FUN,X0,...) returns the value of the equations FUN at X.
+%
+% [X,FVAL,EXITFLAG] = LMMCP(FUN,X0,...) returns EXITFLAG that describes the exit
+% conditions. Possible values are
+%      1         : LMMCP converged to a root
+%      0         : Too many iterations
+%     -1         :
+%
+% [X,FVAL,EXITFLAG,OUTPUT] = LMMCP(FUN,X0,...) returns the structure OUTPUT that
+% contains the number of iterations (OUTPUT.iterations), the value of the merit
+% function (OUTPUT.Psix), and the norm of the derivative of the merit function
+% (OUTPUT.normDPsix).
+%
+% [X,FVAL,EXITFLAG,OUTPUT,JACOB] = LMMCP(FUN,X0,...) returns JACOB the Jacobian
+% of FUN evaluated at X.
+%
+% More details of the main program may be found in the following paper:
+%
+% Christian Kanzow and Stefania Petra: On a semismooth least squares formulation of
+% complementarity problems with gap reduction. Optimization Methods and Software
+% 19, 2004, pp. 507-525.
+%
+% In addition, the current implementation uses a preprocessor which is the
+% projected Levenberg-Marquardt step from the following preprint:
+%
+% Christian Kanzow and Stefania Petra: Projected filter trust region methods for a
+% semismooth least squares formulation of mixed complementarity
+% problems. Optimization Methods and Software
+% 22, 2007, pp. 713-735.
+%
+% A user's guide is also available:
+%
+% Christian Kanzow and Stefania Petra (2005).
+% LMMCP --- A Levenberg-Marquardt-type MATLAB Solver for Mixed Complementarity Problems.
+% University of Wuerzburg.
+% http://www.mathematik.uni-wuerzburg.de/~kanzow/software/UserGuide.pdf
+%
+% This is a modification by Christophe Gouel of the original files, which can be
+% downloaded from:
+% http://www.mathematik.uni-wuerzburg.de/~kanzow/software/LMMCP.zip
+%
+% Written by Christian Kanzow and Stefania Petra
+%            Institute of Applied Mathematics and Statistics
+%            University of Wuerzburg
+%            Am Hubland
+%            97074 Wuerzburg
+%            GERMANY
+%
+%            e-mail: kanzow@mathematik.uni-wuerzburg.de
+%                    petra@mathematik.uni-wuerzburg.de
+%
+% Christian Kanzow sent a private message to Dynare Team on July 8, 2014,
+% confirming the free software status of lmmcp and granting unlimited
+% permission to use, copy, modifiy or redistribute the file.
+
+% Copyright (C) 2005 Christian Kanzow and Stefania Petra
+% Copyright (C) 2013 Christophe Gouel
+% Copyright (C) 2014-2017 Dynare Team
+%
+% Unlimited permission is granted to everyone to use, copy, modify or
+% distribute this software.
+
+%% Initialization
+defaultopt = struct(...
+    'beta',       0.55,...
+    'Big',        1e10,...
+    'delta',      5,...
+    'deltamin',   1,...
+    'Display',    'none',...
+    'epsilon1',   1e-6,...
+    'eta',        0.95,...
+    'kwatch',     20,...
+    'lambda1',    0.1,...
+    'm',          10,...
+    'MaxIter',    500,...
+    'null',       1e-10,...
+    'preprocess', 1,...
+    'presteps',   20,...
+    'sigma',      1e-4,...
+    'sigma1',     0.5,...
+    'sigma2',     2,...
+    'tmin',       1e-12,...
+    'TolFun',     sqrt(eps),...
+    'watchdog',   1);
+
+if nargin < 4
+    ub = inf(size(x));
+    if nargin < 3
+        lb = -inf(size(x));
+    end
+end
+
+if nargin < 5 || isempty(options) || ~isstruct(options)
+    options = defaultopt;
+else
+    warning('off','catstruct:DuplicatesFound')
+    options = catstruct(defaultopt,options);
+end
+
+warning('off','MATLAB:rankDeficientMatrix')
+
+switch options.Display
+  case {'off','none'}
+    verbosity = 0;
+  case {'iter','iter-detailed'}
+    verbosity = 2;
+  case {'final','final-detailed'}
+    verbosity = 1;
+  otherwise
+    verbosity = 0;
+end
+
+% parameter settings
+eps1 = options.epsilon1;
+eps2 = 0.5*options.TolFun^2;
+null = options.null;
+Big  = options.Big;
+
+% maximal number of iterations
+kmax     = options.MaxIter;
+
+% choice of lambda
+lambda1  = options.lambda1;
+lambda2  = 1-lambda1;
+
+% steplength parameters
+beta     = options.beta;
+sigma    = options.sigma;
+tmin     = options.tmin;
+
+% parameters watchdog and nonmonotone line search; redefined later
+m        = options.m;
+kwatch   = options.kwatch;
+watchdog = options.watchdog; % 1=watchdog strategy active, otherwise not
+
+% parameters for preprocessor
+preprocess = options.preprocess; % 1=preprocessor used, otherwise not
+presteps   = options.presteps; % maximum number of preprocessing steps
+
+% trust-region parameters for preprocessor
+delta    = options.delta;
+deltamin = options.deltamin;
+sigma1   = options.sigma1;
+sigma2   = options.sigma2;
+eta      = options.eta;
+
+% initializations
+k        = 0;
+k_main   = 0;
+
+% compute a feasible starting point by projection
+x = max(lb,min(x,ub));
+
+n = length(x);
+OUTPUT.Dim = n;
+
+% definition of index sets I_l, I_u and I_lu
+Indexset       = zeros(n,1);
+I_l            = lb>-Big & ub>Big;
+I_u            = lb<-Big & ub<Big;
+I_lu           = lb>-Big & ub<Big;
+Indexset(I_l)  = 1;
+Indexset(I_u)  = 2;
+Indexset(I_lu) = 3;
+
+% function evaluations
+[Fx,DFx] = feval(FUN,x,varargin{:});
+
+% choice of NCP-function and corresponding evaluations
+Phix      = Phi(x,Fx,lb,ub,lambda1,lambda2,n,Indexset);
+normPhix  = norm(Phix);
+Psix      = 0.5*(Phix'*Phix);
+DPhix     = DPhi(x,Fx,DFx,lb,ub,lambda1,lambda2,n,Indexset);
+DPsix     = DPhix'*Phix;
+normDPsix = norm(DPsix);
+
+% save initial values
+x0         = x;
+Phix0      = Phix;
+Psix0      = Psix;
+DPhix0     = DPhix;
+DPsix0     = DPsix;
+normDPsix0 = normDPsix;
+
+% watchdog strategy
+aux    = zeros(m,1);
+aux(1) = Psix;
+MaxPsi = Psix;
+
+if watchdog==1
+    kbest        = k;
+    xbest        = x;
+    Phibest      = Phix;
+    Psibest      = Psix;
+    DPhibest     = DPhix;
+    DPsibest     = DPsix;
+    normDPsibest = normDPsix;
+end
+
+% initial output
+if verbosity > 1
+    fprintf('   k               Psi(x)                || DPsi(x) ||    stepsize\n');
+    disp('====================================================================')
+    disp('********************* Output at starting point *********************')
+    fprintf('%4.0f %24.5e %24.5e\n',k,Psix,normDPsix);
+end
+
+%% Preprocessor using local method
+
+if preprocess==1
+
+    if verbosity > 1
+        disp('************************** Preprocessor ****************************')
+    end
+
+    normpLM=1;
+    while (k < presteps) && (Psix > eps2) && (normpLM>null)
+        k = k+1;
+
+        % choice of Levenberg-Marquardt parameter, note that we do not use
+        % the condition estimator for large-scale problems, although this
+        % may cause numerical problems in some examples
+
+        i  = false;
+        mu = 0;
+        if n<100
+            i = true;
+            mu = 1e-16;
+            if condest(DPhix'*DPhix)>1e25
+                mu = 1e-6/(k+1);
+            end
+        end
+        if i
+            pLM =  [DPhix; sqrt(mu)*speye(n)]\[-Phix; zeros(n,1)];
+        else
+            pLM = -DPhix\Phix;
+        end
+        normpLM = norm(pLM);
+
+        % compute the projected Levenberg-Marquard step onto box Xk
+        lbnew = max(min(lb-x,0),-delta);
+        ubnew = min(max(ub-x,0),delta);
+        d     = max(lbnew,min(pLM,ubnew));
+        xnew  = x+d;
+
+        % function evaluations etc.
+        [Fxnew,DFxnew] = feval(FUN,xnew,varargin{:});
+        Phixnew        = Phi(xnew,Fxnew,lb,ub,lambda1,lambda2,n,Indexset);
+        Psixnew        = 0.5*(Phixnew'*Phixnew);
+        normPhixnew    = norm(Phixnew);
+
+        % update of delta
+        if normPhixnew<=eta*normPhix
+            delta = max(deltamin,sigma2*delta);
+        elseif normPhixnew>5*eta*normPhix
+            delta = max(deltamin,sigma1*delta);
+        end
+
+        % update
+        x         = xnew;
+        Fx        = Fxnew;
+        DFx       = DFxnew;
+        Phix      = Phixnew;
+        Psix      = Psixnew;
+        normPhix  = normPhixnew;
+        DPhix     = DPhi(x,Fx,DFx,lb,ub,lambda1,lambda2,n,Indexset);
+        DPsix     = DPhix'*Phix;
+        normDPsix = norm(DPsix,inf);
+
+        % output at each iteration
+        t=1;
+        if verbosity > 1
+            fprintf('%4.0f %24.5e %24.5e %11.7g\n',k,Psix,normDPsix,t);
+        end
+    end
+end
+
+% terminate program or redefine current iterate as original initial point
+if preprocess==1 && Psix<eps2
+    if verbosity > 0
+        fprintf('Psix = %1.4e\nnormDPsix = %1.4e\n',Psix,normDPsix);
+        disp('Approximate solution found.')
+    end
+    EXITFLAG          = 1;
+    FVAL              = Fx;
+    OUTPUT.iterations = k;
+    OUTPUT.Psix       = Psix;
+    OUTPUT.normDPsix  = normDPsix;
+    JACOB             = DFx;
+    return
+elseif preprocess==1 && Psix>=eps2
+    x=x0;
+    Phix=Phix0;
+    Psix=Psix0;
+    DPhix=DPhix0;
+    DPsix=DPsix0;
+    if verbosity > 1
+        disp('******************** Restart with initial point ********************')
+        fprintf('%4.0f %24.5e %24.5e\n',k_main,Psix0,normDPsix0);
+    end
+end
+
+%%   Main algorithm
+
+if verbosity > 1
+    disp('************************** Main program ****************************')
+end
+
+while (k < kmax) && (Psix > eps2)
+
+    % choice of Levenberg-Marquardt parameter, note that we do not use
+    % the condition estimator for large-scale problems, although this
+    % may cause numerical problems in some examples
+
+    i = false;
+    if n<100
+        i  = true;
+        mu = 1e-16;
+        if condest(DPhix'*DPhix)>1e25
+            mu = 1e-1/(k+1);
+        end
+    end
+
+    % compute a Levenberg-Marquard direction
+
+    if i
+        d = [DPhix; sqrt(mu)*speye(n)]\[-Phix; zeros(n,1)];
+    else
+        d = -DPhix\Phix;
+    end
+
+    % computation of steplength t using the nonmonotone Armijo-rule
+    % starting with the 6-th iteration
+
+    % computation of steplength t using the monotone Armijo-rule if
+    % d is a 'good' descent direction or k<=5
+
+    t       = 1;
+    xnew    = x+d;
+    Fxnew   = feval(FUN,xnew,varargin{:});
+    Phixnew = Phi(xnew,Fxnew,lb,ub,lambda1,lambda2,n,Indexset);
+    Psixnew = 0.5*(Phixnew'*Phixnew);
+    const   = sigma*DPsix'*d;
+
+    while (Psixnew > MaxPsi + const*t)  && (t > tmin)
+        t       = t*beta;
+        xnew    = x+t*d;
+        Fxnew   = feval(FUN,xnew,varargin{:});
+        Phixnew = Phi(xnew,Fxnew,lb,ub,lambda1,lambda2,n,Indexset);
+        Psixnew = 0.5*(Phixnew'*Phixnew);
+    end
+
+    % updatings
+    x         = xnew;
+    Fx        = Fxnew;
+    Phix      = Phixnew;
+    Psix      = Psixnew;
+    [junk,DFx]   = feval(FUN,x,varargin{:});
+    DPhix     = DPhi(x,Fx,DFx,lb,ub,lambda1,lambda2,n,Indexset);
+    DPsix     = DPhix'*Phix;
+    normDPsix = norm(DPsix);
+    k         = k+1;
+    k_main    = k_main+1;
+
+    if k_main<=5
+        aux(mod(k_main,m)+1) = Psix;
+        MaxPsi               = Psix;
+    else
+        aux(mod(k_main,m)+1) = Psix;
+        MaxPsi               = max(aux);
+    end
+
+    % updatings for the watchdog strategy
+    if watchdog ==1
+        if Psix<Psibest
+            kbest        = k;
+            xbest        = x;
+            Phibest      = Phix;
+            Psibest      = Psix;
+            DPhibest     = DPhix;
+            DPsibest     = DPsix;
+            normDPsibest = normDPsix;
+        elseif k-kbest>kwatch
+            x=xbest;
+            Phix=Phibest;
+            Psix=Psibest;
+            DPhix=DPhibest;
+            DPsix=DPsibest;
+            normDPsix=normDPsibest;
+            MaxPsi=Psix;
+        end
+    end
+
+    if verbosity > 1
+        % output at each iteration
+        fprintf('%4.0f %24.5e %24.5e %11.7g\n',k,Psix,normDPsix,t);
+    end
+end
+
+%% Final output
+if Psix<=eps2
+    EXITFLAG = 1;
+    if verbosity > 0, disp('Approximate solution found.'); end
+elseif k>=kmax
+    EXITFLAG = 0;
+    if verbosity > 0, disp('Maximum iteration number reached.'); end
+elseif normDPsix<=eps1
+    EXITFLAG          = -1; % Provisoire
+    if verbosity > 0, disp('Approximate stationary point found.'); end
+else
+    EXITFLAG          = -1; % Provisoire
+    if verbosity > 0, disp('No solution found.'); end
+end
+
+FVAL              = Fx;
+OUTPUT.iterations = k;
+OUTPUT.Psix       = Psix;
+OUTPUT.normDPsix  = normDPsix;
+JACOB             = DFx;
+
+%% Subfunctions
+
+function y = Phi(x,Fx,lb,ub,lambda1,lambda2,n,Indexset)
+%% PHI
+
+y           = zeros(2*n,1);
+phi_u       = sqrt((ub-x).^2+Fx.^2)-ub+x+Fx;
+LZ          = false(n,1); % logical zero
+
+I0          = Indexset==0;
+y(I0)       = -lambda1*Fx(I0);
+y([LZ; I0]) = -lambda2*Fx(I0);
+
+I1          = Indexset==1;
+y(I1)       = lambda1*(-x(I1)+lb(I1)-Fx(I1)+sqrt((x(I1)-lb(I1)).^2+Fx(I1).^2));
+y([LZ; I1]) = lambda2*max(0,x(I1)-lb(I1)).*max(0,Fx(I1));
+
+I2          = Indexset==2;
+y(I2)       = -lambda1*phi_u(I2);
+y([LZ; I2]) = lambda2*max(0,ub(I2)-x(I2)).*max(0,-Fx(I2));
+
+I3          = Indexset==3;
+y(I3)       = lambda1*(sqrt((x(I3)-lb(I3)).^2+phi_u(I3).^2)-x(I3)+lb(I3)-phi_u(I3));
+y([LZ; I3]) = lambda2*(max(0,x(I3)-lb(I3)).*max(0,Fx(I3))+max(0,ub(I3)-x(I3)).*max(0,-Fx(I3)));
+
+
+function H = DPhi(x,Fx,DFx,lb,ub,lambda1,lambda2,n,Indexset)
+%% DPHI evaluates an element of the C-subdifferential of operator Phi
+
+null       = 1e-8;
+beta_l     = zeros(n,1);
+beta_u     = zeros(n,1);
+alpha_l    = zeros(n,1);
+alpha_u    = zeros(n,1);
+
+
+z          = zeros(n,1);
+H2         = sparse(n,n);
+
+I          = abs(x-lb)<=null & abs(Fx)<=null;
+beta_l(I)  = 1;
+z(I)       = 1;
+
+I          = abs(ub-x)<=null & abs(Fx)<=null;
+beta_u(I)  = 1;
+z(I)       = 1;
+
+I          = x-lb>=-null & Fx>=-null;
+alpha_l(I) = 1;
+
+I          = ub-x>=-null & Fx<=null;
+alpha_u(I) = 1;
+
+Da         = zeros(n,1);
+Db         = zeros(n,1);
+
+I          = 1:n;
+
+I0         = Indexset==0;
+Da(I0)     = 0;
+Db(I0)     = -1;
+H2(I0,:)   = -DFx(I0,:);
+
+I1         = Indexset==1;
+denom1     = zeros(n,1);
+denom2     = zeros(n,1);
+if any(I1)
+    denom1(I1) = max(null,sqrt((x(I1)-lb(I1)).^2+Fx(I1).^2));
+    denom2(I1) = max(null,sqrt(z(I1).^2+(DFx(I1,:)*z).^2));
+end
+
+I1b        = Indexset==1 & beta_l==0;
+Da(I1b)    = (x(I1b)-lb(I1b))./denom1(I1b)-1;
+Db(I1b)    = Fx(I1b)./denom1(I1b)-1;
+I1b        = Indexset==1 & beta_l~=0;
+if any(I1b)
+    Da(I1b)  = z(I1b)./denom2(I1b)-1;
+    Db(I1b)  = (DFx(I1b,:)*z)./denom2(I1b)-1;
+end
+
+I1a         = I(Indexset==1 & alpha_l==1);
+if any(I1a)
+    H2(I1a,:) = spdiags(x(I1a)-lb(I1a), 0, length(I1a), length(I1a))*DFx(I1a,:) +...
+        sparse(1:length(I1a),I1a,Fx(I1a),length(I1a),n,length(I1a));
+end
+
+I2         = Indexset==2;
+denom1     = zeros(n,1);
+denom2     = zeros(n,1);
+if any(I2)
+    denom1(I2) = max(null,sqrt((ub(I2)-x(I2)).^2+Fx(I2).^2));
+    denom2(I2) = max(null,sqrt(z(I2).^2+(DFx(I2,:)*z).^2));
+end
+
+I2b        = Indexset==2 & beta_u==0;
+Da(I2b)    = (ub(I2b)-x(I2b))./denom1(I2b)-1;
+Db(I2b)    = -Fx(I2b)./denom1(I2b)-1;
+I2b        = Indexset==2 & beta_u~=0;
+if any(I2b)
+    Da(I2b)  = -z(I2b)./denom2(I2b)-1;
+    Db(I2b)  = -(DFx(I2b,:)*z)./denom2(I2b)-1;
+end
+
+I2a         = I(Indexset==2 & alpha_u==1);
+if any(I2a)
+    H2(I2a,:) = bsxfun(@times,x(I2a)-ub(I2a),DFx(I2a,:))+...
+        sparse(1:length(I2a),I2a,Fx(I2a),length(I2a),n,length(I2a));
+end
+
+I3         = Indexset==3;
+phi        = zeros(n,1);
+ai         = zeros(n,1);
+bi         = zeros(n,1);
+ci         = zeros(n,1);
+di         = zeros(n,1);
+denom1     = zeros(n,1);
+denom2     = zeros(n,1);
+denom3     = zeros(n,1);
+denom4     = zeros(n,1);
+if any(I3)
+    phi(I3)    = -ub(I3)+x(I3)+Fx(I3)+sqrt((ub(I3)-x(I3)).^2+Fx(I3).^2);
+    denom1(I3) = max(null,sqrt((x(I3)-lb(I3)).^2+phi(I3).^2));
+    denom2(I3) = max(null,sqrt(z(I3).^2+(DFx(I3,:)*z).^2));
+    denom3(I3) = max(null,sqrt((ub(I3)-x(I3)).^2+Fx(I3).^2));
+    denom4(I3) = max(null,sqrt(z(I3).^2));
+end
+
+I3bu       = Indexset==3 & beta_u==0;
+ci(I3bu)   = (x(I3bu)-ub(I3bu))./denom3(I3bu)+1;
+di(I3bu)   = Fx(I3bu)./denom3(I3bu)+1;
+I3bu       = Indexset==3 & beta_u~=0;
+if any(I3bu)
+    ci(I3bu)   = 1+z(I3bu)./denom2(I3bu);
+    di(I3bu)   = 1+(DFx(I3bu,:)*z)./denom2(I3bu);
+end
+
+I3bl       = Indexset==3 & beta_l==0;
+ai(I3bl)   = (x(I3bl)-lb(I3bl))./denom1(I3bl)-1;
+bi(I3bl)   = phi(I3bl)./denom1(I3bl)-1;
+I3bl       = Indexset==3 & beta_l~=0;
+if any(I3bl)
+    ai(I3bl)   = z(I3bl)./denom4(I3bl)-1;
+    bi(I3bl)   = (ci(I3bl).*z(I3bl)+(di(I3bl,ones(1,n)).*DFx(I3bl,:))*z)./denom4(I3bl)-1;
+end
+
+Da(I3)     = ai(I3)+bi(I3).*ci(I3);
+Db(I3)     = bi(I3).*di(I3);
+
+I3a         = I(Indexset==3 & alpha_l==1 & alpha_u==1);
+if any(I3a)
+    H2(I3a,:) = bsxfun(@times,-lb(I3a)-ub(I3a)+2*x(I3a),DFx(I3a,:))+...
+        2*sparse(1:length(I3a),I3a,Fx(I3a),length(I3a),n,length(I3a));
+end
+I3a         = I(Indexset==3 & alpha_l==1 & alpha_u~=1);
+if any(I3a)
+    H2(I3a,:) = bsxfun(@times,x(I3a)-lb(I3a),DFx(I3a,:))+...
+        sparse(1:length(I3a),I3a,Fx(I3a),length(I3a),n,length(I3a));
+end
+I3a         = I(Indexset==3 & alpha_l~=1 & alpha_u==1);
+if any(I3a)
+    H2(I3a,:) = bsxfun(@times,x(I3a)-ub(I3a),DFx(I3a,:))+...
+        sparse(1:length(I3a),I3a,Fx(I3a),length(I3a),n,length(I3a));
+end
+
+H1 = spdiags(Db,0,length(Db),length(Db))*DFx;
+H1 = H1 + spdiags(Da, 0, length(Da), length(Da));
+
+H  = [lambda1*H1; lambda2*H2];
diff --git a/matlab/lnsrch1.m b/matlab/lnsrch1.m
index 6457793c766f9375210878807a6646795cc13e22..09b128b918f4ae7abb9e899fccf7873cd1c49389 100644
--- a/matlab/lnsrch1.m
+++ b/matlab/lnsrch1.m
@@ -20,11 +20,11 @@ function [x,f,fvec,check]=lnsrch1(xold, fold, g, p, stpmax, func, j1, j2, tolx,
 %   fvec:     residuals vector
 %   check=1:  problem of the looping which continues indefinitely
 %
-% 
+%
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2001-2016 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -48,7 +48,7 @@ x = xold;
 nn = length(j2);
 summ = sqrt(p'*p);
 
-if ~isfinite(summ) 
+if ~isfinite(summ)
     if ~isequal(func,@perfect_foresight_problem)
         eq_number_string=[];
         for ii=1:length(j1)-1
@@ -61,13 +61,13 @@ if ~isfinite(summ)
             var_string=[var_string, deblank(Model.endo_names(j2(ii),:)), ', '];
         end
         var_string=[var_string, deblank(Model.endo_names(j2(end),:))];
-        fprintf('\nAn infinite element was encountered when trying to solve equation(s) %s \n',eq_number_string) 
+        fprintf('\nAn infinite element was encountered when trying to solve equation(s) %s \n',eq_number_string)
         fprintf('with respect to the variable(s): %s.\n',var_string)
         fprintf('The values of the endogenous variables when the problem was encountered were:\n')
         for ii=1:length(xold)
             fprintf('%-s % 8.4g \n',Model.endo_names(ii,:),xold(ii));
         end
-        skipline();    
+        skipline();
     end
     error(['Some element of Newton direction isn''t finite. Jacobian maybe' ...
            ' singular or there is a problem with initial values'])
@@ -103,7 +103,7 @@ while 1
     else
         if f <= fold+alf*alam*slope
             check = 0;
-            break ;
+            break
         else
             if alam == 1
                 tmplam = -slope/(2*(f-fold-slope)) ;
diff --git a/matlab/lnsrch1_wrapper_one_boundary.m b/matlab/lnsrch1_wrapper_one_boundary.m
index 22485104681cb7639e1fc975cc48365bebe2984c..8ac9c14d0cb8c0d16cf2234d3fd908cfbc273dd3 100644
--- a/matlab/lnsrch1_wrapper_one_boundary.m
+++ b/matlab/lnsrch1_wrapper_one_boundary.m
@@ -12,16 +12,16 @@ function r = lnsrch1_wrapper_one_boundary(ya, y_index, fname, y, x, params, stea
 %   x                   [matrix]        All the exogenous variables of the model
 %   params              [vector]        All the parameters of the model
 % OUTPUTS
-%   r                   [vector]        The residuals of the current block      
-%  
+%   r                   [vector]        The residuals of the current block
+%
 % ALGORITHM
 %   none.
-%    
+%
 % SPECIAL REQUIREMENTS
 %   none.
-%  
+%
 
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/lnsrch1_wrapper_two_boundaries.m b/matlab/lnsrch1_wrapper_two_boundaries.m
index 3b55ca70351a1f992f714936ca33078577fc6ee5..05c396c77fcd32f93d4437cd4fe3c8f8509fe9bd 100644
--- a/matlab/lnsrch1_wrapper_two_boundaries.m
+++ b/matlab/lnsrch1_wrapper_two_boundaries.m
@@ -17,16 +17,16 @@ function ra = lnsrch1_wrapper_two_boundaries(ya, fname, y, y_index, x, ...
 %   y_size              [int]           The number of endogenous variables
 %                                       in the current block
 % OUTPUTS
-%   ra                  [vector]        The residuals of the current block      
-%  
+%   ra                  [vector]        The residuals of the current block
+%
 % ALGORITHM
 %   none.
-%    
+%
 % SPECIAL REQUIREMENTS
 %   none.
-%  
+%
 
-% Copyright (C) 2009-2015 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/load_first_mh_history_file.m b/matlab/load_first_mh_history_file.m
index 3177fafe4590b3c74d645c749de1acd72a2de261..b99c8ccbfa724c1700917e992aee82b0abe60946 100644
--- a/matlab/load_first_mh_history_file.m
+++ b/matlab/load_first_mh_history_file.m
@@ -1,8 +1,8 @@
 function info = load_first_mh_history_file(MetropolisFolder, ModelName)
 
 % This routine requires that the MCMC draws were obtained with a dynare version greater than 4.3.3.
- 
-% Copyright (C) 2013 Dynare Team
+
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/load_last_mh_history_file.m b/matlab/load_last_mh_history_file.m
index 92bf059dbb80a08844ce810bd3cddfa385544ae5..2874dbffd22921c3a7223925e817ac5991ca5379 100644
--- a/matlab/load_last_mh_history_file.m
+++ b/matlab/load_last_mh_history_file.m
@@ -4,13 +4,13 @@ function info = load_last_mh_history_file(MetropolisFolder, ModelName)
 % Inputs:
 %   MetropolisFolder    [char]      Name of the metropolis subfolder
 %   ModelName           [char]      Name of the mod-file
-% Outputs:  
+% Outputs:
 %   info                [struct]    structure storing the MH history
-% 
+%
 % Notes: The record structure is written to the caller workspace via an
 % assignin statement.
 
-% Copyright (C) 2013-2016 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -37,7 +37,7 @@ mh_history_files = dir([BaseName '_mh_history_*.mat']);
 % Consistency with older versions of Dynare.
 if isequal(length(mh_history_files),0)
     if exist([BaseName '_mh_history.mat'])
-        format_mh_history_file = 1; % old Dynare format 
+        format_mh_history_file = 1; % old Dynare format
     else
         error(['Estimation::load_mh_file: I cannot find any mh-history file in ' MetropolisFolder '!'])
     end
@@ -63,7 +63,7 @@ else
     load([BaseName '_mh_history_' num2str(length(mh_history_files)-1) '.mat']);
     % add fields that have later been introduced
     if ~isfield(record,'MCMCConcludedSuccessfully')
-        record.MCMCConcludedSuccessfully = NaN; % This information is forever lost...    
+        record.MCMCConcludedSuccessfully = NaN; % This information is forever lost...
     end
     if ~isfield(record,'MAX_nruns')
         record.MAX_nruns=NaN(size(record.MhDraws,1),1); % This information is forever lost...
diff --git a/matlab/load_m_file_data_legacy.m b/matlab/load_m_file_data_legacy.m
index 9442abfac94db2ca2e65cbb69b13c4784747de8a..9d4b8e34c8155bc27d52a5811e376ecf00afcdd5 100644
--- a/matlab/load_m_file_data_legacy.m
+++ b/matlab/load_m_file_data_legacy.m
@@ -1,6 +1,6 @@
-function data  = load_m_file_data_legacy(datafile, varobs)
+function o2WysrOISH  = load_m_file_data_legacy(datafile, U7ORsJ0vy3) % --*-- Unitary tests --*--
 
-% Copyright (C) 2014 Dynare Team
+% Copyright (C) 2014-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -21,27 +21,142 @@ cXDHdrXnqo5KwwVpTRuc6OprAW = datafile(1:end-2);
 [pathtocXDHdrXnqo5KwwVpTRuc6OprAW,cXDHdrXnqo5KwwVpTRuc6OprAW,junk] = fileparts(cXDHdrXnqo5KwwVpTRuc6OprAW);
 
 if ~isempty(pathtocXDHdrXnqo5KwwVpTRuc6OprAW)
+    % We need to change directory, first we keep the current directory in memory...
     OvMuQsJgjwzYG5Pni0TzU8Acb2YBJva = pwd();
+    % Then we move in the directory where the data file is saved.
     cd(pathtocXDHdrXnqo5KwwVpTRuc6OprAW);
 end
 
+% We evaluate the matlab script defining the data. All the variables in the
+% variables defined in this script are loaded in the current workspace.
 eval(cXDHdrXnqo5KwwVpTRuc6OprAW);
 
 if ~isempty(pathtocXDHdrXnqo5KwwVpTRuc6OprAW)
+    % If we previously changed directory, we go back to the initial directory.
     cd(OvMuQsJgjwzYG5Pni0TzU8Acb2YBJva);
+    clear OvMuQsJgjwzYG5Pni0TzU8Acb2YBJva;
 end
 
+% Clear all the variables except the ones defined in the script.
+clear('pathtocXDHdrXnqo5KwwVpTRuc6OprAW', 'cXDHdrXnqo5KwwVpTRuc6OprAW', 'junk');
+
+% Get the list of variables in the script.
+mj6F4eU1BN = whos();
+Z3s1ZFBffw = {mj6F4eU1BN(:).name};
+
+% Check that the variables in varobs are available.
+if ~isequal(sort(intersect(Z3s1ZFBffw, U7ORsJ0vy3)), sort(U7ORsJ0vy3))
+    qtvUkxKk6b = setdiff(U7ORsJ0vy3, intersect(Z3s1ZFBffw, U7ORsJ0vy3));
+    qtvUkxKk6b = sprintf('%s ', qtvUkxKk6b{:});
+    qtvUkxKk6b = qtvUkxKk6b(1:end-1);
+    error('Some variables are missing (%s)!', qtvUkxKk6b)
+end
+
+% Check that the variables are provided as vectors.
+N5L9sgRHIu = {};
+for uAiwEPcc3Q=1:length(U7ORsJ0vy3)
+    if ~isvector(eval(U7ORsJ0vy3{uAiwEPcc3Q}))
+        N5L9sgRHIu(end+1) = {U7ORsJ0vy3{uAiwEPcc3Q}};
+    end
+end
+if ~isempty(N5L9sgRHIu)
+    N5L9sgRHIu = sprintf('%s ', N5L9sgRHIu{:});
+    N5L9sgRHIu = N5L9sgRHIu(1:end-1);
+    error('Observed variables should be provided as vectors (%s are not vectors)!')
+end
+
+% Check that all the vectors have the same number of elements.
+RXZzmKFPFK = numel(eval(U7ORsJ0vy3{1}));
+for uAiwEPcc3Q=2:length(U7ORsJ0vy3)
+    if ~isequal(numel(eval(U7ORsJ0vy3{1})), RXZzmKFPFK)
+        error('All vectors must have the same number of elements (%s has %i elements while %s has %i elements)!', U7ORsJ0vy3{1}, numel(eval(U7ORsJ0vy3{1})), U7ORsJ0vy3{uAiwEPcc3Q}, numel(eval(U7ORsJ0vy3{uAiwEPcc3Q})));
+    end
+end
+
+% Put the observed variables in data
+JSmvfqTSXT = repmat(' vec(%s) ', 1, length(U7ORsJ0vy3));
+VbO4y7zOlh = sprintf('[%s]', JSmvfqTSXT);
+o2WysrOISH = dseries(eval(sprintf(VbO4y7zOlh, U7ORsJ0vy3{:})), [], U7ORsJ0vy3);
+
+return
+
+%@test:1
+% Write a data file
+fid = fopen('example.m','w');
+fwriten(fid, 'a = randn(100,1);');
+fwriten(fid, 'b = randn(100,1);');
+fwriten(fid, 'c = transpose(randn(100,1));');
+fwriten(fid, 'd = randn(100,1);');
+fwriten(fid, 'e = randn(100,2);');
+fwriten(fid, ' ');
+fwriten(fid, 'f = NaN(100,1);');
+fwriten(fid, 'for i=1:100');
+fwriten(fid, '  f(i) = log(rand());')
+fwriten(fid, 'end');
+fclose(fid);
+% Define a set of variables to be loaded.
+listofvariablestobeloaded = {'b', 'a'};
+% Test if we can load the data.
 try
-    data = dseries(eval(cellofstring4eval(varobs)),[],varobs);
+    data = load_m_file_data_legacy('example.m', listofvariablestobeloaded);
+    delete example.m
+    t(1) = 1;
 catch
-    errmsg = sprintf('makedataset: Check that all the variables listed in varobs exist in %s and have the same number of observations.',datafile);
-    error(errmsg)
+    t(1) = 0;
 end
+T = all(t);
+%@eof:1
 
-function str = cellofstring4eval(A)
-    n = length(A);
-    str = '[';
-    for i=1:n-1
-        str = [str, A{i}, ','];
-    end
-    str = [str, A{n}, ']'];
\ No newline at end of file
+%@test:2
+% Write a data file
+fid = fopen('example.m','w');
+fwriten(fid, 'a = randn(100,1);');
+fwriten(fid, 'b = randn(100,1);');
+fwriten(fid, 'c = transpose(randn(100,1));');
+fwriten(fid, 'd = randn(100,1);');
+fwriten(fid, 'e = randn(100,2);');
+fwriten(fid, ' ');
+fwriten(fid, 'f = NaN(100,1);');
+fwriten(fid, 'for i=1:100');
+fwriten(fid, '  f(i) = log(rand());')
+fwriten(fid, 'end');
+fclose(fid);
+% Define a set of variables to be loaded.
+listofvariablestobeloaded = {'e', 'a'};
+% Test if we can load the data.
+try
+    data = load_m_file_data_legacy('example.m', listofvariablestobeloaded);
+    delete example.m
+    t(1) = 0;
+catch
+    t(1) = 1;
+end
+T = all(t);
+%@eof:2
+
+%@test:3
+% Write a data file
+fid = fopen('example.m','w');
+fwriten(fid, 'a = randn(100,1);');
+fwriten(fid, 'b = randn(100,1);');
+fwriten(fid, 'c = transpose(randn(100,1));');
+fwriten(fid, 'd = randn(100,1);');
+fwriten(fid, 'e = randn(100,2);');
+fwriten(fid, ' ');
+fwriten(fid, 'f = NaN(100,1);');
+fwriten(fid, 'for i=1:100');
+fwriten(fid, '  f(i) = log(rand());')
+fwriten(fid, 'end');
+fclose(fid);
+% Define a set of variables to be loaded.
+listofvariablestobeloaded = {'c', 'a'};
+% Test if we can load the data.
+try
+    data = load_m_file_data_legacy('example.m', listofvariablestobeloaded);
+    delete example.m
+    t(1) = 1;
+catch
+    t(1) = 0;
+end
+T = all(t);
+%@eof:3
diff --git a/matlab/load_mat_file_data_legacy.m b/matlab/load_mat_file_data_legacy.m
new file mode 100644
index 0000000000000000000000000000000000000000..356c57237049c6d21737be67d75f0781ef3ced26
--- /dev/null
+++ b/matlab/load_mat_file_data_legacy.m
@@ -0,0 +1,42 @@
+function data  = load_mat_file_data_legacy(datafile, varobs)
+
+% Copyright (C) 2017 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/>.
+
+data_file=load(datafile);
+
+names=fieldnames(data_file);
+
+if ~all(ismember(varobs',names))
+    missing_variables=varobs(~ismember(varobs',names))';
+    disp_string=[missing_variables{1,:}];
+    for ii=2:size(missing_variables,1)
+        disp_string=[disp_string,', ',missing_variables{ii,:}];
+    end
+    error('makedataset: The variable(s) %s listed in varobs are not contained in the dataset %s',disp_string);
+else
+    data_mat=[];
+    for var_iter=1:length(varobs)
+        try
+            data_mat=[data_mat vec(data_file.(varobs{1,var_iter}))];
+        catch
+            error('makedataset: The variable %s does not have dimensions conformable with the previous one',varobs{1,var_iter});
+        end
+    end
+end
+
+data = dseries(data_mat,[],varobs);
\ No newline at end of file
diff --git a/matlab/lpdfgam.m b/matlab/lpdfgam.m
index b82e43234d87f3f5910c434d0f16fa9d618dd8e7..7dbcf2579ee907433f4a6f52bcd35e26a1c5f030 100644
--- a/matlab/lpdfgam.m
+++ b/matlab/lpdfgam.m
@@ -1,19 +1,19 @@
-function  [ldens,Dldens,D2ldens] = lpdfgam(x,a,b);
+function  [ldens,Dldens,D2ldens] = lpdfgam(x,a,b)
 % Evaluates the logged GAMMA PDF at x.
 %
-% INPUTS     
+% INPUTS
 %    x     [double]  m*n matrix of locations,
 %    a     [double]  m*n matrix or scalar, First GAMMA distribution parameters (shape),
 %    b     [double]  m*n matrix or scalar, Second GAMMA distribution parameters (scale),
 %
 % OUTPUTS
 %    ldens [double]  m*n matrix of logged GAMMA densities evaluated at x.
-%     
-%        
+%
+%
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2016 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -41,7 +41,7 @@ end
 
 
 
-if nargout >1 
+if nargout >1
     if length(a)==1
         Dldens(idx) = (a-1)./(x(idx)) - ones(length(idx),1)/b ;
     else
diff --git a/matlab/lpdfgbeta.m b/matlab/lpdfgbeta.m
index e8d8af521d78f7b681675359b1e3ea36cef113f3..6f0dd0fd876b0d9d87bd3cb8e836e8ea028dcd81 100644
--- a/matlab/lpdfgbeta.m
+++ b/matlab/lpdfgbeta.m
@@ -1,20 +1,20 @@
-function [ldens,Dldens,D2ldens] = lpdfgbeta(x,a,b,aa,bb);
-% Evaluates the logged BETA PDF at x. 
+function [ldens,Dldens,D2ldens] = lpdfgbeta(x,a,b,aa,bb)
+% Evaluates the logged BETA PDF at x.
 %
-% INPUTS 
+% INPUTS
 %    x     [double]  m*n matrix of loactions,
-%    a     [double]  m*n matrix of First BETA distribution parameters, 
-%    b     [double]  m*n matrix of Second BETA distribution parameters, 
-%    aa    [double]  m*n matrix of lower bounds for (generalized) distribution, 
+%    a     [double]  m*n matrix of First BETA distribution parameters,
+%    b     [double]  m*n matrix of Second BETA distribution parameters,
+%    aa    [double]  m*n matrix of lower bounds for (generalized) distribution,
 %    bb    [double]  m*n matrix of upper bounds for (generalized) distribution
 %
-% OUTPUTS 
+% OUTPUTS
 %    ldens [double]  m*n matrix of logged (generalized) BETA densities.
-%        
+%
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2011 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -41,7 +41,7 @@ else
 end
 
 
-if nargout >1 
+if nargout >1
     if length(a)==1
         Dldens(idx) = (a-1)./(x(idx)-aa) - (b-1)./(bb-x(idx)) ;
     else
@@ -50,7 +50,7 @@ if nargout >1
 end
 
 
-if nargout == 3 
+if nargout == 3
     if length(a)==1
         D2ldens(idx) = -(a-1)./(x(idx)-aa).^2 - (b-1)./(bb-x(idx)).^2 ;
     else
diff --git a/matlab/lpdfig1.m b/matlab/lpdfig1.m
index 5aeb05f90c95e5352b42d608fe6075e579e9b752..2b14c8fabbbae82e3e0bcdae82475c5a867e6235 100644
--- a/matlab/lpdfig1.m
+++ b/matlab/lpdfig1.m
@@ -1,15 +1,15 @@
 function [ldens,Dldens,D2ldens] = lpdfig1(x,s,nu)
 % Evaluates the logged INVERSE-GAMMA-1 PDF at x.
 %
-% X ~ IG1(s,nu) if X = sqrt(Y) where Y ~ IG2(s,nu) and Y = inv(Z) with Z ~ G(nu/2,2/s) (Gamma distribution) 
+% X ~ IG1(s,nu) if X = sqrt(Y) where Y ~ IG2(s,nu) and Y = inv(Z) with Z ~ G(nu/2,2/s) (Gamma distribution)
 %
 % See L. Bauwens, M. Lubrano and J-F. Richard [1999, appendix A] for more details.
 %
 %
-% INPUTS     
+% INPUTS
 %    x     [double]  m*n matrix of locations,
-%    s     [double]  m*n matrix or scalar, First INVERSE-GAMMA-1 distribution parameters, 
-%    nu    [double]  m*n matrix or scalar, Second INVERSE-GAMMA-1 distribution parameters. 
+%    s     [double]  m*n matrix or scalar, First INVERSE-GAMMA-1 distribution parameters,
+%    nu    [double]  m*n matrix or scalar, Second INVERSE-GAMMA-1 distribution parameters.
 %
 % OUTPUTS
 %    ldens [double]  m*n matrix of logged INVERSE-GAMMA-1 densities evaluated at x.
@@ -17,7 +17,7 @@ function [ldens,Dldens,D2ldens] = lpdfig1(x,s,nu)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2004-2011 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -35,7 +35,7 @@ function [ldens,Dldens,D2ldens] = lpdfig1(x,s,nu)
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 ldens = -Inf( size(x) ) ;
-idx = find( x>0 ) ;    
+idx = find( x>0 ) ;
 
 if length(s)==1
     ldens(idx) = log(2) - gammaln(.5*nu) - .5*nu*(log(2)-log(s)) - (nu+1)*log(x(idx)) - .5*s./(x(idx).*x(idx)) ;
@@ -43,7 +43,7 @@ else
     ldens(idx) = log(2) - gammaln(.5*nu(idx)) - .5*nu(idx).*(log(2)-log(s(idx))) - (nu(idx)+1).*log(x(idx)) - .5*s(idx)./(x(idx).*x(idx)) ;
 end
 
-if nargout >1 
+if nargout >1
     if length(s)==1
         Dldens(idx) = - (nu+1)./(x(idx)) + s./(x(idx).^3) ;
     else
@@ -51,11 +51,10 @@ if nargout >1
     end
 end
 
-if nargout == 3 
+if nargout == 3
     if length(s)==1
         D2ldens(idx) =  (nu+1)./(x(idx).^2) - 3*s(idx)./(x(idx).^4) ;
     else
         D2ldens(idx) =  (nu(idx)+1)./(x(idx).^2) - 3*s(idx)./(x(idx).^4) ;
     end
 end
-
diff --git a/matlab/lpdfig2.m b/matlab/lpdfig2.m
index 00de3abb12746e3396812d651d6216af2a460369..e1b3ca2a139f71867ec1798d7de8221929ed0ff5 100644
--- a/matlab/lpdfig2.m
+++ b/matlab/lpdfig2.m
@@ -1,15 +1,15 @@
 function [ldens,Dldens,D2ldens] = lpdfig2(x,s,nu)
 % Evaluates the logged INVERSE-GAMMA-2 PDF at x.
 %
-% X ~ IG2(s,nu) if X = inv(Z) where Z ~ G(nu/2,2/s) (Gamma distribution) 
+% X ~ IG2(s,nu) if X = inv(Z) where Z ~ G(nu/2,2/s) (Gamma distribution)
 %
 % See L. Bauwens, M. Lubrano and J-F. Richard [1999, appendix A] for more details.
 %
 %
-% INPUTS     
+% INPUTS
 %    x     [double]  m*n matrix of locations,
-%    s     [double]  m*n matrix or scalar, First INVERSE-GAMMA-2 distribution parameters, 
-%    nu    [double]  m*n matrix or scalar, Second INVERSE-GAMMA-2 distribution parameters. 
+%    s     [double]  m*n matrix or scalar, First INVERSE-GAMMA-2 distribution parameters,
+%    nu    [double]  m*n matrix or scalar, Second INVERSE-GAMMA-2 distribution parameters.
 %
 % OUTPUTS
 %    ldens [double]  m*n matrix of logged INVERSE-GAMMA-2 densities evaluated at x.
@@ -17,7 +17,7 @@ function [ldens,Dldens,D2ldens] = lpdfig2(x,s,nu)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2004-2011 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -35,7 +35,7 @@ function [ldens,Dldens,D2ldens] = lpdfig2(x,s,nu)
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 ldens = -Inf( size(x) ) ;
-idx = find( x>0 ) ;    
+idx = find( x>0 ) ;
 
 if length(s)==1
     ldens(idx) = -gammaln(.5*nu) - (.5*nu)*(log(2)-log(s)) - .5*(nu+2)*log(x(idx)) -.5*s./x(idx);
@@ -43,7 +43,7 @@ else
     ldens(idx) = -gammaln(.5*nu(idx)) - (.5*nu(idx)).*(log(2)-log(s(idx))) - .5*(nu(idx)+2).*log(x(idx)) -.5*s(idx)./x(idx);
 end
 
-if nargout >1 
+if nargout >1
     if length(s)==1
         Dldens(idx) = - .5*(nu+2)./(x(idx)) + .5*s./x(idx).^2;
     else
@@ -51,7 +51,7 @@ if nargout >1
     end
 end
 
-if nargout == 3 
+if nargout == 3
     if length(s)==1
         D2ldens(idx) = .5*(nu+2)./(x(idx)).^2 - s./x(idx).^3;
     else
diff --git a/matlab/lpdfnorm.m b/matlab/lpdfnorm.m
index bb9da98d8e64ff4f522bda0feba1867e6e73bcb8..2c1249996456a33bb7da3d826adc1754764e10a0 100644
--- a/matlab/lpdfnorm.m
+++ b/matlab/lpdfnorm.m
@@ -1,19 +1,19 @@
 function  [ldens,Dldens,D2ldens] = lpdfnorm(x,a,b)
 % Evaluates the logged UNIVARIATE GAUSSIAN PDF at x.
 %
-% INPUTS 
+% INPUTS
 %    x     [double]  m*n matrix of locations,
-%    a     [double]  m*n matrix or scalar, First GAUSSIAN distribution parameters (expectation) 
-%    b     [double]  m*n matrix or scalar, Second GAUSSIAN distribution parameters (standard deviation). 
+%    a     [double]  m*n matrix or scalar, First GAUSSIAN distribution parameters (expectation)
+%    b     [double]  m*n matrix or scalar, Second GAUSSIAN distribution parameters (standard deviation).
 %
-% OUTPUTS 
+% OUTPUTS
 %    ldens [double]  m*n matrix of logged GAUSSIAN densities evaluated at x.
-%     
-%        
+%
+%
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2012 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -34,10 +34,10 @@ if nargin<3, b=1; end
 if nargin<2, a=0; end
 ldens = -log(b) -.5*log(2*pi) - .5*((x-a)./b).*((x-a)./b) ;
 
-if nargout >1 
+if nargout >1
     Dldens =  - (1./b).*((x-a)./b) ;
 end
 
-if nargout == 3 
+if nargout == 3
     D2ldens =  - (1./b).^2 ;
 end
\ No newline at end of file
diff --git a/matlab/lyapunov_solver.m b/matlab/lyapunov_solver.m
index a7b96c997a4fa3e354048d451b345bf98ba5a283..98d782cdf30d7ef239bd7968f9cc875b75217ba8 100644
--- a/matlab/lyapunov_solver.m
+++ b/matlab/lyapunov_solver.m
@@ -1,14 +1,14 @@
 function P=lyapunov_solver(T,R,Q,DynareOptions) % --*-- Unitary tests --*--
 % function P=lyapunov_solver(T,R,Q,DynareOptions)
 % Solves the Lyapunov equation P-T*P*T' = R*Q*R' arising in a state-space
-% system, where P is the variance of the states 
+% system, where P is the variance of the states
 %
 % Inputs
 %   T               [double]    n*n matrix.
 %   R               [double]    n*m matrix.
 %   Q               [double]    m*m matrix.
 %   DynareOptions   [structure] Dynare options
-% 
+%
 % Outputs
 %   P               [double]    n*n matrix.
 %
@@ -20,10 +20,10 @@ function P=lyapunov_solver(T,R,Q,DynareOptions) % --*-- Unitary tests --*--
 %   DynareOptions.lyapunov_db == 1
 %       doubling algorithm
 %   DynareOptions.lyapunov_srs == 1
-%       Square-root solver for discrete-time Lyapunov equations (requires Matlab System Control toolbox 
+%       Square-root solver for discrete-time Lyapunov equations (requires Matlab System Control toolbox
 %       or Octave control package)
 
-% Copyright (C) 2016 Dynare Team
+% Copyright (C) 2016-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -60,10 +60,10 @@ elseif DynareOptions.lyapunov_srs == 1
     end
     chol_Q = R*chol(Q,'lower');
     R_P = dlyapchol(T,chol_Q);
-    P = R_P' * R_P;    
+    P = R_P' * R_P;
 else
     P = lyapunov_symm(T,R*Q*R',DynareOptions.lyapunov_fixed_point_tol,DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold, [], DynareOptions.debug);
-end;
+end
 
 %@test:1
 %$ t = NaN(10,1);
@@ -81,7 +81,7 @@ end;
 %$ tmp2=randn(m_small,m_small);
 %$ Q_small=tmp2*tmp2';
 %$ R_small=randn(n_small,m_small);
-%$ 
+%$
 %$ n_large=9;
 %$ m_large=11;
 %$ T_large=randn(n_large,n_large);
@@ -89,7 +89,7 @@ end;
 %$ tmp2=randn(m_large,m_large);
 %$ Q_large=tmp2*tmp2';
 %$ R_large=randn(n_large,m_large);
-%$ 
+%$
 %$ % DynareOptions.lyapunov_fp == 1
 %$ options_.lyapunov_fp = 1;
 %$ try
diff --git a/matlab/lyapunov_symm.m b/matlab/lyapunov_symm.m
index 694415d714c08e86e9aac90263830da40cf10dc3..53eaf9e4c1810645ffb91bd09fb67ed57794807c 100644
--- a/matlab/lyapunov_symm.m
+++ b/matlab/lyapunov_symm.m
@@ -1,22 +1,22 @@
 function [x,u] = lyapunov_symm(a,b,lyapunov_fixed_point_tol,qz_criterium,lyapunov_complex_threshold,method,debug)  % --*-- Unitary tests --*--
 % Solves the Lyapunov equation x-a*x*a' = b, for b and x symmetric matrices.
 % If a has some unit roots, the function computes only the solution of the stable subsystem.
-%  
+%
 % INPUTS:
 %   a                           [double]    n*n matrix.
 %   b                           [double]    n*n matrix.
 %   qz_criterium                [double]    unit root threshold for eigenvalues
 %   lyapunov_fixed_point_tol    [double]    convergence criteria for fixed_point algorithm.
 %   lyapunov_complex_threshold  [double]    scalar, complex block threshold for the upper triangular matrix T.
-%   method                      [integer]   Scalar, if method=0 [default] then U, T, n and k are not persistent.  
-%                                                      method=1 then U, T, n and k are declared as persistent 
-%                                                               variables and the Schur decomposition is triggered.    
-%                                                      method=2 then U, T, n and k are declared as persistent 
+%   method                      [integer]   Scalar, if method=0 [default] then U, T, n and k are not persistent.
+%                                                      method=1 then U, T, n and k are declared as persistent
+%                                                               variables and the Schur decomposition is triggered.
+%                                                      method=2 then U, T, n and k are declared as persistent
 %                                                               variables and the Schur decomposition is not performed.
 %                                                      method=3 fixed point method
 % OUTPUTS
 %   x:      [double]    m*m solution matrix of the lyapunov equation, where m is the dimension of the stable subsystem.
-%   u:      [double]    Schur vectors associated with unit roots  
+%   u:      [double]    Schur vectors associated with unit roots
 %
 % ALGORITHM
 %   Uses reordered Schur decomposition (Bartels-Stewart algorithm)
@@ -25,7 +25,7 @@ function [x,u] = lyapunov_symm(a,b,lyapunov_fixed_point_tol,qz_criterium,lyapuno
 % SPECIAL REQUIREMENTS
 %   None
 
-% Copyright (C) 2006-2016 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -54,7 +54,7 @@ if method == 3
     persistent X method1;
     if ~isempty(method1)
         method = method1;
-    end;
+    end
     if debug
         fprintf('lyapunov_symm:: [method=%d] \n',method);
     end
@@ -67,16 +67,16 @@ if method == 3
             max_it_fp = 2000;
         else
             max_it_fp = 300;
-        end;
+        end
         at = a';
         %fixed point iterations
-        while evol >  lyapunov_fixed_point_tol && it_fp < max_it_fp;
+        while evol >  lyapunov_fixed_point_tol && it_fp < max_it_fp
             X_old = X;
             X = a * X * at + b;
             evol = max(sum(abs(X - X_old))); %norm_1
-            %evol = max(sum(abs(X - X_old)')); %norm_inf
+                                             %evol = max(sum(abs(X - X_old)')); %norm_inf
             it_fp = it_fp + 1;
-        end;
+        end
         if debug
             fprintf('lyapunov_symm:: lyapunov fixed_point iterations=%d norm=%g\n',it_fp,evol);
         end
@@ -87,9 +87,9 @@ if method == 3
         else
             method1 = 3;
             x = X;
-            return;
-        end;
-    end;
+            return
+        end
+    end
 end
 
 if method
@@ -110,7 +110,7 @@ end
 if method<2
     [U,T] = schur(a);
     e1 = abs(ordeig(T)) > 2-qz_criterium;
-    k = sum(e1);       % Number of unit roots. 
+    k = sum(e1);       % Number of unit roots.
     n = length(e1)-k;  % Number of stationary variables.
     if k > 0
         % Selects stable roots
diff --git a/matlab/marginal_density.m b/matlab/marginal_density.m
index 32880f34aee563103446d43e03be5747d7411021..e5683da2c1a06e209ccfc259854e7031c165a602 100644
--- a/matlab/marginal_density.m
+++ b/matlab/marginal_density.m
@@ -15,7 +15,7 @@ function [marginal,oo_] = marginal_density(M_, options_, estim_params_, oo_, bay
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2005-2011 Dynare Team
+% Copyright (C) 2005-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -58,14 +58,15 @@ lpost_mode = posterior_kernel_at_the_mode;
 xparam1 = posterior_mean;
 hh = inv(SIGMA);
 fprintf(' Done!\n');
-if ~isfield(oo_,'posterior_mode')
+if ~isfield(oo_,'posterior_mode') || (options_.mh_replic && isequal(options_.posterior_sampler_options.posterior_sampling_method,'slice'))
     oo_=fill_mh_mode(posterior_mode',NaN(npar,1),M_,options_,estim_params_,bayestopt_,oo_,'posterior');
 end
 
 % save the posterior mean and the inverse of the covariance matrix
 % (usefull if the user wants to perform some computations using
-% the posterior mean instead of the posterior mode ==> ). 
-save([M_.fname '_mean.mat'],'xparam1','hh','SIGMA');
+% the posterior mean instead of the posterior mode ==> ).
+parameter_names = bayestopt_.name;
+save([M_.fname '_mean.mat'],'xparam1','hh','parameter_names','SIGMA');
 
 fprintf('Estimation::marginal density: I''m computing the posterior log marginal density (modified harmonic mean)... ');
 logdetSIGMA = log(det(SIGMA));
@@ -75,7 +76,7 @@ linee = 0;
 check_coverage = 1;
 increase = 1;
 while check_coverage
-    for p = 0.1:0.1:0.9;
+    for p = 0.1:0.1:0.9
         critval = chi2inv(p,npar);
         ifil = FirstLine;
         tmp = 0;
@@ -105,7 +106,7 @@ while check_coverage
             disp('Estimation::marginal density: The support of the weighting density function is not large enough...')
             disp('Estimation::marginal density: I increase the variance of this distribution.')
             increase = 1.2*increase;
-            linee    = 0;   
+            linee    = 0;
         else
             disp('Estimation::marginal density: Let me try again.')
             increase = 1.2*increase;
@@ -113,9 +114,9 @@ while check_coverage
             if increase > 20
                 check_coverage = 0;
                 clear invSIGMA detSIGMA increase;
-                disp('Estimation::marginal density: There''s probably a problem with the modified harmonic mean estimator.')    
+                disp('Estimation::marginal density: There''s probably a problem with the modified harmonic mean estimator.')
             end
-        end  
+        end
     else
         check_coverage = 0;
         clear invSIGMA detSIGMA increase;
@@ -129,17 +130,17 @@ return
 
 function oo_=fill_mh_mode(xparam1,stdh,M_,options_,estim_params_,bayestopt_,oo_, field_name)
 %function oo_=fill_mh_mode(xparam1,stdh,M_,options_,estim_params_,bayestopt_,oo_, field_name)
-% 
-% INPUTS 
+%
+% INPUTS
 %   o xparam1       [double]   (p*1) vector of estimate parameters.
 %   o stdh          [double]   (p*1) vector of estimate parameters.
-%   o M_                        Matlab's structure describing the Model (initialized by dynare, see @ref{M_}).          
+%   o M_                        Matlab's structure describing the Model (initialized by dynare, see @ref{M_}).
 %   o estim_params_             Matlab's structure describing the estimated_parameters (initialized by dynare, see @ref{estim_params_}).
 %   o options_                  Matlab's structure describing the options (initialized by dynare, see @ref{options_}).
 %   o bayestopt_                Matlab's structure describing the priors (initialized by dynare, see @ref{bayesopt_}).
 %   o oo_                       Matlab's structure gathering the results (initialized by dynare, see @ref{oo_}).
-%  
-% OUTPUTS 
+%
+% OUTPUTS
 %   o oo_                       Matlab's structure gathering the results
 %
 % SPECIAL REQUIREMENTS
@@ -171,8 +172,8 @@ if nvx
         eval(['oo_.' field_name '_std_at_mode.shocks_std.' name ' = stdh(ip);']);
         ip = ip+1;
     end
- end
- if nvn
+end
+if nvn
     ip = nvx+1;
     for i=1:nvn
         name = options_.varobs{estim_params_.nvn_observable_correspondence(i,1)};
@@ -180,7 +181,7 @@ if nvx
         eval(['oo_.' field_name '_std_at_mode.measurement_errors_std.' name ' = stdh(ip);']);
         ip = ip+1;
     end
- end
+end
 
 if ncx
     ip = nvx+nvn+1;
diff --git a/matlab/matlab_ver_less_than.m b/matlab/matlab_ver_less_than.m
index 53dd8d7ef5f6a0b92d0155d4d2b7df903790cee5..10cd640d2461f32d25669e82e8dca04c307844ea 100644
--- a/matlab/matlab_ver_less_than.m
+++ b/matlab/matlab_ver_less_than.m
@@ -8,14 +8,14 @@ function r = matlab_ver_less_than(verstr)
 %
 % INPUTS
 %    verstr: a string of the format 'x.y' or 'x.y.z'
-%    
+%
 % OUTPUTS
 %    r: 0 or 1
 %
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2008-2014 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/maximize_prior_density.m b/matlab/maximize_prior_density.m
index 72df861a4768cd76436c740acd00241224392716..9f79e44a4ab80a4d058fac6179ad391bfbe065af 100644
--- a/matlab/maximize_prior_density.m
+++ b/matlab/maximize_prior_density.m
@@ -1,21 +1,21 @@
 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 
+%
+% INPUTS
 %   iparams                        [double]   vector of initial parameters.
 %   prior_shape                    [integer]  vector specifying prior densities shapes.
 %   prior_hyperparameter_1         [double]   vector, first hyperparameter.
 %   prior_hyperparameter_2         [double]   vector, second hyperparameter.
 %   prior_inf_bound                [double]   vector, prior's lower bound.
-%   prior_sup_bound                [double]   vector, prior's upper bound. 
+%   prior_sup_bound                [double]   vector, prior's upper bound.
 %
-% OUTPUTS 
+% OUTPUTS
 %   xparams       [double]  vector, prior mode.
 %   lpd           [double]  scalar, value of the logged prior density at the mode.
 %   hessian_mat   [double]  matrix, Hessian matrix at the prior mode.
 
-% Copyright (C) 2009-2015 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/mcforecast3.m b/matlab/mcforecast3.m
index 3e1de2888f89cc03e7e97460a396bc3323e38056..b318d46f4b144c16a5111ef96d9f4a3f6f32261b 100644
--- a/matlab/mcforecast3.m
+++ b/matlab/mcforecast3.m
@@ -2,7 +2,7 @@ function [forcs, e]= mcforecast3(cL,H,mcValue,shocks,forcs,T,R,mv,mu)
 % forcs = mcforecast3(cL,H,mcValue,shocks,forcs,T,R,mv,mu)
 % Computes the shock values for constrained forecasts necessary to keep
 % endogenous variables at their constrained paths
-% 
+%
 % INPUTS
 %  o cL             [scalar]                            number of controlled periods
 %  o H              [scalar]                            number of forecast periods
@@ -14,7 +14,7 @@ function [forcs, e]= mcforecast3(cL,H,mcValue,shocks,forcs,T,R,mv,mu)
 %  o mv             [n_controlled_exo by n_endovars boolean]        indicator vector  selecting constrained endogenous variables
 %  o mu             [n_controlled_vars by nexo boolean]             indicator vector
 %                                                   selecting controlled exogenous variables
-% 
+%
 % Algorithm:
 %   Relies on state-space form:
 %       y_t=T*y_{t-1}+R*shocks(:,t)
@@ -30,8 +30,8 @@ function [forcs, e]= mcforecast3(cL,H,mcValue,shocks,forcs,T,R,mv,mu)
 %   After obtaining the shocks, and for uncontrolled periods, the state-space representation
 %       y_t=T*y_{t-1}+R*shocks(:,t)
 %   is used for forecasting
-%  
-% Copyright (C) 2006-2013 Dynare Team
+%
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/mcompare.m b/matlab/mcompare.m
index 9bf0f1713f644d6ddf5603d5ed98d855f07de68d..f3f052f689ebec7d43ca67bba0dfc8d9b94c2c83 100644
--- a/matlab/mcompare.m
+++ b/matlab/mcompare.m
@@ -1,7 +1,7 @@
 function mcompare(s1,s2)
-% MCOMPARE :    MCOMPARE ( [ 'file1' ; 'file2' ] , [ 'var1' ; 'var2' ...] )     
+% MCOMPARE :    MCOMPARE ( [ 'file1' ; 'file2' ] , [ 'var1' ; 'var2' ...] )
 %               This optional command plots the relative differences between
-%               two different simulations for a list of variables. One plot 
+%               two different simulations for a list of variables. One plot
 %               is drawn for each variable. The trajectories must have been
 %               previously saved by the instruction DYNASAVE. The simulation
 %               in file1 serves as the base simulation and the ploted quantity
@@ -10,7 +10,7 @@ function mcompare(s1,s2)
 %               value of the base simulation, the absolute difference is ploted
 %               instead of the relative one.
 
-% Copyright (C) 2001-2011 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/mcp_func.m b/matlab/mcp_func.m
index 424b9203f9a187f0dc950a181757c5f3743060b3..30494b95a73fc20dc88aa9433d504562819f2ce6 100644
--- a/matlab/mcp_func.m
+++ b/matlab/mcp_func.m
@@ -1,17 +1,17 @@
 function [res,fjac,domer] = mcp_func(x,jacflag)
 % function [res,fjac,domer] = mcp_func(x,jacflag)
 % wrapper function for mixed complementarity problem when using PATH
-% 
-% INPUTS 
+%
+% INPUTS
 % - x                   [double] N*T array, paths for the endogenous variables (initial guess).
 % - jacflag             [scalar] indicator whether Jacobian is requested
 %
-% OUTPUTS 
+% OUTPUTS
 %  - res                [double] (N*T)*1 array, residuals of the stacked problem
 %  - fjac               [double] (N*T)*(N*T) array, Jacobian of the stacked problem
 %  - domer              [scalar] errorflag that is 1 if solution is not real
 
-% Copyright (C) 2016 Dynare Team
+% Copyright (C) 2016-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/metropolis_draw.m b/matlab/metropolis_draw.m
index f0fcf49bd969524ef1cd883983d125c4ac67980a..94c4212783b81cc30ca46c926deaa63d96ca7000 100644
--- a/matlab/metropolis_draw.m
+++ b/matlab/metropolis_draw.m
@@ -1,12 +1,12 @@
 function [xparams, logpost, options_]=metropolis_draw(init,options_,estim_params_,M_)
-% function [xparams, logpost]=metropolis_draw(init) 
+% function [xparams, logpost]=metropolis_draw(init)
 % Builds draws from metropolis
 %
 % INPUTS:
-%   init:              scalar equal to 
-%                      1: first call to store the required information 
-%                           on files, lines, and chains to be read 
-%                           in persistent variables to make them available 
+%   init:              scalar equal to
+%                      1: first call to store the required information
+%                           on files, lines, and chains to be read
+%                           in persistent variables to make them available
 %                           for future calls
 %                      0: load a parameter draw
 % Additional Inputs required for initialization
@@ -19,12 +19,12 @@ function [xparams, logpost, options_]=metropolis_draw(init,options_,estim_params
 %                      if init==1: error flaog
 %   logpost:           log of posterior density
 %   options_:          [structure]     Matlab's structure describing the options (initialized by dynare, see @ref{options_}).
-%   
+%
 % SPECIAL REQUIREMENTS
 %
 %   Requires CutSample to be run before in order to set up mh_history-file
 
-% Copyright (C) 2003-2015 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -61,20 +61,20 @@ if init
     %load mh_history-file with info on what to load
     load_last_mh_history_file(MetropolisFolder, FileName);
     FirstMhFile = record.KeepedDraws.FirstMhFile;
-    FirstLine = record.KeepedDraws.FirstLine; 
-    TotalNumberOfMhFiles = sum(record.MhDraws(:,2)); 
-    LastMhFile = TotalNumberOfMhFiles; 
+    FirstLine = record.KeepedDraws.FirstLine;
+    TotalNumberOfMhFiles = sum(record.MhDraws(:,2));
+    LastMhFile = TotalNumberOfMhFiles;
     TotalNumberOfMhDraws = sum(record.MhDraws(:,1));
     NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws);
     MAX_nruns = ceil(options_.MaxNumberOfBytes/(npar+2)/8); %number of parameters plus posterior plus ?
     mh_nblck = options_.mh_nblck;
     % set sub_draws option if empty
     if isempty(options_.sub_draws)
-        options_.sub_draws = min(options_.posterior_max_subsample_draws, round(.25*NumberOfDraws));
+        options_.sub_draws = min(options_.posterior_max_subsample_draws, ceil(.25*NumberOfDraws));
     else
-        if options_.sub_draws>NumberOfDraws
+        if options_.sub_draws>NumberOfDraws*mh_nblck
             skipline()
-            disp(['Estimation::mcmc: The value of option sub_draws (' num2str(options_.sub_draws) ') is greater than the number of available draws in the MCMC (' num2str(NumberOfDraws) ')!'])
+            disp(['Estimation::mcmc: The value of option sub_draws (' num2str(options_.sub_draws) ') is greater than the number of available draws in the MCMC (' num2str(NumberOfDraws*mh_nblck) ')!'])
             disp('Estimation::mcmc: You can either change the value of sub_draws, reduce the value of mh_drop, or run another mcmc (with the load_mh_file option).')
             skipline()
             xparams = 1; % xparams is interpreted as an error flag
@@ -82,16 +82,16 @@ if init
     end
     return
 else %not initialization, return one draw
-    %get random draw from random chain
+     %get random draw from random chain
     ChainNumber = ceil(rand*mh_nblck);
     DrawNumber  = ceil(rand*NumberOfDraws);
 
     if DrawNumber <= MAX_nruns-FirstLine+1 %draw in first file, needs to account for first line
         MhFilNumber = FirstMhFile;
         MhLine = FirstLine+DrawNumber-1;
-    else %draw in other file 
+    else %draw in other file
         DrawNumber  = DrawNumber-(MAX_nruns-FirstLine+1);
-        MhFilNumber = FirstMhFile+ceil(DrawNumber/MAX_nruns); 
+        MhFilNumber = FirstMhFile+ceil(DrawNumber/MAX_nruns);
         MhLine = DrawNumber-(MhFilNumber-FirstMhFile-1)*MAX_nruns;
     end
     %load parameters and posterior
diff --git a/matlab/metropolis_hastings_initialization.m b/matlab/metropolis_hastings_initialization.m
index e18ea098a4f13b50d443b55437b72a3c1c672da7..e9d97a0ea26d956b4f89a22f388823e2ae8dc6ea 100644
--- a/matlab/metropolis_hastings_initialization.m
+++ b/matlab/metropolis_hastings_initialization.m
@@ -3,13 +3,13 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa
 % function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npar, NumberOfBlocks, 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 
+%
+% INPUTS
 %   o TargetFun  [char]     string specifying the name of the objective
 %                           function (posterior kernel).
 %   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 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
@@ -17,17 +17,17 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa
 %   o estim_params_         estimated parameters structure
 %   o bayestopt_            estimation options structure
 %   o oo_                   outputs structure
-%  
-% OUTPUTS 
+%
+% OUTPUTS
 %   o ix2                   [double]   (NumberOfBlocks*npar) vector of starting points for different chains
 %   o ilogpo2               [double]   (NumberOfBlocks*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 FirstBlock            [scalar]    number of the first MH chain to be run (not equal to 1 in case of recovery)   
-%   o FirstLine             [double]   (NumberOfBlocks*1) vector of first draw in each chain (not equal to 1 in case of recovery)   
+%   o FirstBlock            [scalar]    number of the first MH chain to be run (not equal to 1 in case of recovery)
+%   o FirstLine             [double]   (NumberOfBlocks*1) vector of first draw in each chain (not equal to 1 in case of recovery)
 %   o npar                  [scalar]    number of parameters estimated
-%   o NumberOfBlocks        [scalar]    Number of MCM chains requested   
-%   o nruns                 [double]   (NumberOfBlocks*1) number of draws in each chain 
+%   o NumberOfBlocks        [scalar]    Number of MCM chains requested
+%   o nruns                 [double]   (NumberOfBlocks*1) number of draws in each chain
 %   o NewFile               [scalar]    (NumberOfBlocks*1) vector storing the number
 %                                       of the first MH-file to created for each chain when saving additional
 %                                       draws
@@ -37,7 +37,7 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2006-2016 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -57,7 +57,7 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa
 %Initialize outputs
 ix2 = [];
 ilogpo2 = [];
-ModelName = []; 
+ModelName = [];
 MetropolisFolder = [];
 FirstBlock = [];
 FirstLine = [];
@@ -124,7 +124,7 @@ if ~options_.load_mh_file && ~options_.mh_recover
             trial = 1;
             while validate == 0 && trial <= 10
                 candidate = rand_multivariate_normal( transpose(xparam1), d * options_.mh_init_scale, npar);
-                if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub) 
+                if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub)
                     ix2(j,:) = candidate;
                     ilogpo2(j) = - feval(TargetFun,ix2(j,:)',dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_);
                     if ~isfinite(ilogpo2(j)) % if returned log-density is
@@ -167,7 +167,7 @@ if ~options_.load_mh_file && ~options_.mh_recover
     else% Case 2: one chain (we start from the posterior mode)
         fprintf(fidlog,['  Initial values of the parameters:\n']);
         candidate = transpose(xparam1(:));%
-        if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub) 
+        if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub)
             ix2 = candidate;
             ilogpo2 = - feval(TargetFun,ix2',dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_);
             disp('Estimation::mcmc: Initialization at the posterior mode.')
@@ -223,7 +223,7 @@ if ~options_.load_mh_file && ~options_.mh_recover
     fprintf(fidlog,['    Expected number of files per block.......: ' int2str(AnticipatedNumberOfFiles) '.\n']);
     fprintf(fidlog,['    Expected number of lines in the last file: ' int2str(AnticipatedNumberOfLinesInTheLastFile) '.\n']);
     fprintf(fidlog,['\n']);
-    for j = 1:NumberOfBlocks,
+    for j = 1:NumberOfBlocks
         fprintf(fidlog,['    Initial state of the Gaussian random number generator for chain number ',int2str(j),':\n']);
         for i=1:length(record.InitialSeeds(j).Normal)
             fprintf(fidlog,['      ' num2str(record.InitialSeeds(j).Normal(i)') '\n']);
@@ -232,7 +232,7 @@ if ~options_.load_mh_file && ~options_.mh_recover
         for i=1:length(record.InitialSeeds(j).Unifor)
             fprintf(fidlog,['      ' num2str(record.InitialSeeds(j).Unifor(i)') '\n']);
         end
-    end,
+    end
     fprintf(fidlog,' \n');
     fclose(fidlog);
 elseif options_.load_mh_file && ~options_.mh_recover
@@ -281,7 +281,7 @@ elseif options_.load_mh_file && ~options_.mh_recover
     NumberOfDrawsWrittenInThePastLastFile = MAX_nruns - LastLineNumber;
     NumberOfDrawsToBeSaved = nruns(1) - NumberOfDrawsWrittenInThePastLastFile;
     AnticipatedNumberOfFiles = ceil(NumberOfDrawsToBeSaved/MAX_nruns);
-    AnticipatedNumberOfLinesInTheLastFile = NumberOfDrawsToBeSaved - (AnticipatedNumberOfFiles-1)*MAX_nruns;  
+    AnticipatedNumberOfLinesInTheLastFile = NumberOfDrawsToBeSaved - (AnticipatedNumberOfFiles-1)*MAX_nruns;
     record.LastFileNumber = LastFileNumber + AnticipatedNumberOfFiles;
     record.LastLineNumber = AnticipatedNumberOfLinesInTheLastFile;
     record.MhDraws(end,1) = nruns(1);
@@ -300,15 +300,15 @@ elseif options_.mh_recover
     load_last_mh_history_file(MetropolisFolder, ModelName);
     NumberOfBlocks = record.Nblck;% Number of "parallel" mcmc chains.
     options_.mh_nblck = NumberOfBlocks;
-    
+
     %% check consistency of options
     if record.MhDraws(end,1)~=options_.mh_replic
         fprintf('\nEstimation::mcmc: You cannot specify a different mh_replic than in the chain you are trying to recover\n')
         fprintf('Estimation::mcmc: I am resetting mh_replic to %u\n',record.MhDraws(end,1))
         options_.mh_replic=record.MhDraws(end,1);
         nruns = ones(NumberOfBlocks,1)*options_.mh_replic;
-    end    
-    
+    end
+
     if ~isnan(record.MAX_nruns(end,1)) %field exists
         if record.MAX_nruns(end,1)~=MAX_nruns
             fprintf('\nEstimation::mcmc: You cannot specify a different MaxNumberOfBytes than in the chain you are trying to recover\n')
@@ -335,9 +335,9 @@ elseif options_.mh_recover
     if OldMhExists
         LastLineNumberInThePreviousMh = record.MhDraws(end-1,3);% Number of lines in the last mh files of the previous session.
         LastFileNumberInThePreviousMh = sum(record.MhDraws(1:end-1,2),1);% Number of mh files in the the previous sessions.
-        %Test if the last mh files of the previous session were not full yet 
-        if LastLineNumberInThePreviousMh < MAX_nruns%not full 
-            %store starting point if whole chain needs to be redone
+                                                                         %Test if the last mh files of the previous session were not full yet
+        if LastLineNumberInThePreviousMh < MAX_nruns%not full
+                                                    %store starting point if whole chain needs to be redone
             NewFile = ones(NumberOfBlocks,1)*LastFileNumberInThePreviousMh;
             FirstLine = ones(NumberOfBlocks,1)*(LastLineNumberInThePreviousMh+1);
             LastFileFullIndicator=0;
@@ -354,9 +354,9 @@ elseif options_.mh_recover
         FirstLine = ones(NumberOfBlocks,1);
         LastFileFullIndicator=1;
     end
-    
+
     %% Now find out what exactly needs to be redone
-    % 1. Check if really something needs to be done 
+    % 1. Check if really something needs to be done
     % How many mh files should we have ?
     ExpectedNumberOfMhFilesPerBlock = sum(record.MhDraws(:,2),1);
     ExpectedNumberOfMhFiles = ExpectedNumberOfMhFilesPerBlock*NumberOfBlocks;
@@ -366,7 +366,7 @@ elseif options_.mh_recover
     % Quit if no crashed mcmc chain can be found as there are as many files as expected
     if (TotalNumberOfMhFiles==ExpectedNumberOfMhFiles)
         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('                  You have to edit the mod file and remove the mh_recover option')
         disp('                  in the estimation command')
         error('Estimation::mcmc: mh_recover option not required!')
     end
@@ -389,15 +389,15 @@ elseif options_.mh_recover
         end
         FirstBlock = FirstBlock+1;
     end
-    
-    %% 3. Overwrite default settings for 
+
+    %% 3. Overwrite default settings for
     % How many mh-files are saved in this block?
     NumberOfSavedMhFilesInTheCrashedBlck = NumberOfMhFilesPerBlock(FirstBlock);
     ExistingDrawsInLastMCFile=0; %initialize: no MCMC draws of current MCMC are in file from last run
-    % Check whether last present file is a file included in the last MCMC run
-    if ~LastFileFullIndicator 
+                                 % Check whether last present file is a file included in the last MCMC run
+    if ~LastFileFullIndicator
         if NumberOfSavedMhFilesInTheCrashedBlck==NewFile(FirstBlock) %only that last file exists, but no files from current MCMC
-            loaded_results=load([BaseName '_mh' int2str(NewFile(FirstBlock)) '_blck' int2str(FirstBlock) '.mat']);    
+            loaded_results=load([BaseName '_mh' int2str(NewFile(FirstBlock)) '_blck' int2str(FirstBlock) '.mat']);
             %check whether that last file was filled
             if size(loaded_results.x2,1)==MAX_nruns %file is full
                 NewFile(FirstBlock)=NewFile(FirstBlock)+1; %set first file to be created to next one
@@ -407,20 +407,20 @@ elseif options_.mh_recover
                 ExistingDrawsInLastMCFile=0;
             end
         end
-    elseif LastFileFullIndicator 
+    elseif LastFileFullIndicator
         ExistingDrawsInLastMCFile=0;
         if NumberOfSavedMhFilesInTheCrashedBlck==NewFile(FirstBlock) %only the last file exists, but no files from current MCMC
             NewFile(FirstBlock)=NewFile(FirstBlock)+1; %set first file to be created to next one
         end
     end
-%     % 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 OldMhExists
-%         NumberOfSavedMhFilesInTheCrashedBlck = NumberOfSavedMhFilesInTheCrashedBlck - LastFileNumberInThePreviousMh;
-%     end
-%     NumberOfSavedMhFiles = NumberOfSavedMhFilesInTheCrashedBlck+LastFileNumberInThePreviousMh;
-    
+    %     % 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 OldMhExists
+    %         NumberOfSavedMhFilesInTheCrashedBlck = NumberOfSavedMhFilesInTheCrashedBlck - LastFileNumberInThePreviousMh;
+    %     end
+    %     NumberOfSavedMhFiles = NumberOfSavedMhFilesInTheCrashedBlck+LastFileNumberInThePreviousMh;
+
     % Correct initial conditions.
     if NumberOfSavedMhFilesInTheCrashedBlck<ExpectedNumberOfMhFilesPerBlock
         loaded_results=load([BaseName '_mh' int2str(NumberOfSavedMhFilesInTheCrashedBlck) '_blck' int2str(FirstBlock) '.mat']);
diff --git a/matlab/metropolis_run_analysis.m b/matlab/metropolis_run_analysis.m
index 99b589c820b0d2a2aeb086ea7654266650ab29a6..acdfe3b337ca451e69ae5fc3b4e0a48905f91758 100644
--- a/matlab/metropolis_run_analysis.m
+++ b/matlab/metropolis_run_analysis.m
@@ -1,19 +1,19 @@
 function metropolis_run_analysis(M,basetopt,j)
 %function metropolis_run_analysis(M)
 % analizes Metropolis runs
-%  
+%
 % INPUTS
 %   M:         (struct)  Model structure
 %   basetopt:  (struct)  Estimated parameters structure
 %   j:         (int)     Index of estimated paramter
-%  
+%
 % OUTPUTS
 %   none
 %
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2003-2011 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -39,7 +39,7 @@ params = [];
 blck = 1;
 for i=1:record.LastFileNumber
     fname = [M.fname '/metropolis/' M.fname '_mh' int2str(i) '_blck' ...
-            int2str(blck) '.mat'];
+             int2str(blck) '.mat'];
     if exist(fname,'file')
         o=load(fname);
         logPost = [logPost; o.logpo2];
diff --git a/matlab/mex/k_order_perturbation.m b/matlab/mex/k_order_perturbation.m
index 96b7ba5f6b879b624fd530d38b3de8e0beba6f0b..7c10d0efdf86ac44d765b331cf6fc9a86d81f4b7 100644
--- a/matlab/mex/k_order_perturbation.m
+++ b/matlab/mex/k_order_perturbation.m
@@ -37,7 +37,7 @@
 %                         The Taylor coefficient (1/6) is
 %                         included. Inside the tensor, the variables are in
 %                         dr.order_var order of state endogenous variables
-%                         and shocks 
+%                         and shocks
 % derivs        struct    contains the original derivatives of the
 %                         decision function (ghx, ghu, ghxx, ghxu, ghuu,
 %                         ghs2, ghxxx, ghxxu, ghxuu,ghuuu, ghxss, ghuss),
@@ -52,7 +52,7 @@
 % dynare/mex/sources/k_order_perturbation.cc and it uses code provided by
 % dynare++
 
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/mex/qmc_sequence.m b/matlab/mex/qmc_sequence.m
index aa26ae2d3cc962b05f59e46ceeaf47c72ceb9b29..1b934927312f037ee5323a9130d9b6025b304d66 100644
--- a/matlab/mex/qmc_sequence.m
+++ b/matlab/mex/qmc_sequence.m
@@ -16,7 +16,7 @@
 %!  @sp 1
 %!  @table @ @samp
 %!  @item @var{t}=0
-%!  Uniform numbers in a n-dimensional (unit by default) hypercube 
+%!  Uniform numbers in a n-dimensional (unit by default) hypercube
 %!  @item @var{t}=1
 %!  Gaussian numbers
 %!  @item @var{t}=2
@@ -55,7 +55,7 @@
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -125,7 +125,7 @@
 %$
 %$ [draws1, S] = qmc_sequence(d,s,0,n,[0 , 2; -1, 2]);
 %$ [draws2, Q] = qmc_sequence(d,s,0,n);
-%$ 
+%$
 %$ draws3 = draws2;
 %$ draws3(1,:) = 2*draws2(1,:);
 %$ draws3(2,:) = 3*draws2(2,:)-1;
diff --git a/matlab/mh_autocorrelation_function.m b/matlab/mh_autocorrelation_function.m
index 96b4c5875f3b76b824d02fc2edc85647e7ead450..377de19786043a2d0f8e0312b8ea6e713f13473f 100644
--- a/matlab/mh_autocorrelation_function.m
+++ b/matlab/mh_autocorrelation_function.m
@@ -1,9 +1,9 @@
 function mh_autocorrelation_function(options_,M_,estim_params_,type,blck,name1,name2)
 % This function plots the autocorrelation of the sampled draws in the
 % posterior distribution.
-% 
 %
-% INPUTS 
+%
+% INPUTS
 %
 %   options_        [structure]    Dynare structure.
 %   M_              [structure]    Dynare structure (related to model definition).
@@ -11,14 +11,14 @@ function mh_autocorrelation_function(options_,M_,estim_params_,type,blck,name1,n
 %   type            [string]       'DeepParameter', 'MeasurementError' (for measurement equation error) or 'StructuralShock' (for structural shock).
 %   blck            [integer]      Number of the mh chain.
 %   name1           [string]       Object name.
-%   name2           [string]       Object name. 
-%    
-% OUTPUTS 
+%   name2           [string]       Object name.
+%
+% OUTPUTS
 %   None
-%        
+%
 % SPECIAL REQUIREMENTS
 
-% Copyright (C) 2003-2013 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -36,7 +36,7 @@ function mh_autocorrelation_function(options_,M_,estim_params_,type,blck,name1,n
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 % Cet the column index:
-if nargin<7    
+if nargin<7
     column = name2index(options_, M_, estim_params_, type, name1);
 else
     column = name2index(options_, M_, estim_params_, type, name1, name2);
@@ -88,10 +88,10 @@ else
 end
 
 if options_.mh_nblck>1
-    FigureName = [ FigureName , ' (block number' int2str(blck)  ').']; 
+    FigureName = [ FigureName , ' (block number' int2str(blck)  ').'];
 end
 
-hh=dyn_figure(options_,'Name',FigureName);
+hh=dyn_figure(options_.nodisplay,'Name',FigureName);
 
 bar(0:options_.mh_autocorrelation_function_size,autocor,'k');
 axis tight
@@ -104,4 +104,4 @@ if ~exist([M_.fname filesep 'graphs'])
 end
 
 plot_name=get_the_name(column,0,M_,estim_params_,options_);
-dyn_saveas(hh,[M_.fname, filesep, 'graphs', filesep, 'MH_Autocorrelation_' plot_name],options_)
+dyn_saveas(hh,[M_.fname, filesep, 'graphs', filesep, 'MH_Autocorrelation_' plot_name],options_.nodisplay,options_.graph_format)
diff --git a/matlab/mh_optimal_bandwidth.m b/matlab/mh_optimal_bandwidth.m
index 7355fddbdb169f17845d97e2ac3a04168ef0adbc..0a827c5ac9c8ab6c376f8277651dee11ece972b5 100644
--- a/matlab/mh_optimal_bandwidth.m
+++ b/matlab/mh_optimal_bandwidth.m
@@ -1,30 +1,30 @@
-function optimal_bandwidth = mh_optimal_bandwidth(data,number_of_draws,bandwidth,kernel_function) 
+function optimal_bandwidth = mh_optimal_bandwidth(data,number_of_draws,bandwidth,kernel_function)
 % This function gives the optimal bandwidth parameter of a kernel estimator
-% used to estimate a posterior univariate density from realisations of a 
-% Metropolis-Hastings algorithm. 
+% used to estimate a posterior univariate density from realisations of a
+% Metropolis-Hastings algorithm.
 %
 % INPUTS:
 %   data               [double]  Vector (number_of_draws*1) of draws.
 %   number_of_draws    [integer] Scalar, number of draws.
-%   bandwidth          [integer] Scalar equal to 0,-1 or -2.    
+%   bandwidth          [integer] Scalar equal to 0,-1 or -2.
 %                                bandwidth =  0 => Silverman [1986] rule of thumb.
 %                                bandwidth = -1 => Sheather and Jones [1991].
-%                                bandwidth = -2 => Local bandwith parameters.                              
+%                                bandwidth = -2 => Local bandwith parameters.
 %   kernel_function    [string]  Name of the kernel function: 'gaussian', 'triweight',
-%                                'uniform', 'triangle', 'epanechnikov', 'quartic', 
+%                                'uniform', 'triangle', 'epanechnikov', 'quartic',
 %                                'triweight' and 'cosinus'
 %
 % OUTPUTS:
 %   optimal_bandwidth: [double]  Scalar or vector, optimal window width.
-%   
+%
 % SPECIAL REQUIREMENTS:
 %   none.
 %
 % REFERENCES:
-%   [1] M. Skoeld and G.O. Roberts [2003], "Density estimation for the Metropolis-Hastings algorithm". 
-%   [2] Silverman [1986], "Density estimation for statistics and data analysis". 
+%   [1] M. Skoeld and G.O. Roberts [2003], "Density estimation for the Metropolis-Hastings algorithm".
+%   [2] Silverman [1986], "Density estimation for statistics and data analysis".
 
-% Copyright (C) 2004-2015 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -41,7 +41,7 @@ function optimal_bandwidth = mh_optimal_bandwidth(data,number_of_draws,bandwidth
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-%% Kernel specifications.
+% Kernel specifications.
 if strcmpi(kernel_function,'gaussian')
     % Kernel definition
     k    = @(x)inv(sqrt(2*pi))*exp(-0.5*x.^2);
@@ -53,30 +53,30 @@ if strcmpi(kernel_function,'gaussian')
     k6   = @(x)inv(sqrt(2*pi))*(-15*exp(-0.5*x.^2)+45*(x.^2).*exp(-0.5*x.^2)-15*(x.^4).*exp(-0.5*x.^2)+(x.^6).*exp(-0.5*x.^2));
     mu02 = inv(2*sqrt(pi));
     mu21 = 1;
-elseif strcmpi(kernel_function,'uniform') 
+elseif strcmpi(kernel_function,'uniform')
     k    = @(x)0.5*(abs(x) <= 1);
     mu02 = 0.5;
     mu21 = 1/3;
-elseif strcmpi(kernel_function,'triangle') 
+elseif strcmpi(kernel_function,'triangle')
     k    = @(x)(1-abs(x)).*(abs(x) <= 1);
     mu02 = 2/3;
     mu21 = 1/6;
-elseif strcmpi(kernel_function,'epanechnikov') 
+elseif strcmpi(kernel_function,'epanechnikov')
     k    = @(x)0.75*(1-x.^2).*(abs(x) <= 1);
     mu02 = 3/5;
     mu21 = 1/5;
-elseif strcmpi(kernel_function,'quartic') 
+elseif strcmpi(kernel_function,'quartic')
     k    = @(x)0.9375*((1-x.^2).^2).*(abs(x) <= 1);
     mu02 = 15/21;
     mu21 = 1/7;
-elseif strcmpi(kernel_function,'triweight') 
+elseif strcmpi(kernel_function,'triweight')
     k    = @(x)1.09375*((1-x.^2).^3).*(abs(x) <= 1);
     k2   = @(x)(105/4*(1-x.^2).*x.^2-105/16*(1-x.^2).^2).*(abs(x) <= 1);
     k4   = @(x)(-1575/4*x.^2+315/4).*(abs(x) <= 1);
     k6   = @(x)(-1575/2).*(abs(x) <= 1);
     mu02 = 350/429;
     mu21 = 1/9;
-elseif strcmpi(kernel_function,'cosinus') 
+elseif strcmpi(kernel_function,'cosinus')
     k    = @(x)(pi/4)*cos((pi/2)*x).*(abs(x) <= 1);
     k2   = @(x)(-1/16*cos(pi*x/2)*pi^3).*(abs(x) <= 1);
     k4   = @(x)(1/64*cos(pi*x/2)*pi^5).*(abs(x) <= 1);
@@ -89,32 +89,34 @@ else
 end
 
 
-%% Get the Skold and Roberts' correction.
+% Get the Skold and Roberts' correction.
 if bandwidth==0 || bandwidth==-1
     correction = correction_for_repeated_draws(data,number_of_draws);
 else
     correction = 0;
 end
-%% Compute the standard deviation of the draws.
+
+% Compute the standard deviation of the draws.
 sigma = std(data);
-%% Optimal bandwidth parameter.
-if bandwidth == 0;  % Rule of thumb bandwidth parameter (Silverman [1986].
+
+% Optimal bandwidth parameter.
+if bandwidth == 0  % Rule of thumb bandwidth parameter (Silverman [1986].
     h = 2*sigma*(sqrt(pi)*mu02/(12*(mu21^2)*number_of_draws))^(1/5);
     h = h*correction^(1/5);
-elseif bandwidth == -1; % Sheather and Jones [1991] plug-in estimation of the optimal bandwidth parameter. 
-    if strcmp(kernel_function,'uniform')      || ... 
-            strcmp(kernel_function,'triangle')     || ... 
-            strcmp(kernel_function,'epanechnikov') || ... 
+elseif bandwidth == -1 % Sheather and Jones [1991] plug-in estimation of the optimal bandwidth parameter.
+    if strcmp(kernel_function,'uniform')      || ...
+            strcmp(kernel_function,'triangle')     || ...
+            strcmp(kernel_function,'epanechnikov') || ...
             strcmp(kernel_function,'quartic')
         error(['I can''t compute the optimal bandwidth with this kernel...' ...
                'Try the gaussian, triweight or cosinus kernels.']);
-    end 
+    end
     Itilda4 = 8*7*6*5/(((2*sigma)^9)*sqrt(pi));
     g3      = abs(2*correction*k6(0)/(mu21*Itilda4*number_of_draws))^(1/9);
     Ihat3   = 0;
     for i=1:number_of_draws
         Ihat3 = Ihat3 + sum(k6((data(i,1)-data)/g3));
-    end     
+    end
     Ihat3 = - Ihat3/((number_of_draws^2)*g3^7);
     g2    = abs(2*correction*k4(0)/(mu21*Ihat3*number_of_draws))^(1/7);
     Ihat2 = 0;
@@ -122,40 +124,40 @@ elseif bandwidth == -1; % Sheather and Jones [1991] plug-in estimation of the op
         Ihat2 = Ihat2 + sum(k4((data(i)-data)/g2));
     end
     Ihat2 = Ihat2/((number_of_draws^2)*g2^5);
-    h     = (correction*mu02/(number_of_draws*Ihat2*mu21^2))^(1/5); % equation (22) in Skold and Roberts [2003]. 
-elseif bandwidth == -2;     % Bump killing... I compute local bandwith parameters in order to remove 
-                            % spurious bumps introduced by long rejecting periods.   
-    if strcmp(kernel_function,'uniform')      || ... 
-            strcmp(kernel_function,'triangle')     || ... 
-            strcmp(kernel_function,'epanechnikov') || ... 
+    h     = (correction*mu02/(number_of_draws*Ihat2*mu21^2))^(1/5); % equation (22) in Skold and Roberts [2003].
+elseif bandwidth == -2     % Bump killing... I compute local bandwith parameters in order to remove
+                           % spurious bumps introduced by long rejecting periods.
+    if strcmp(kernel_function,'uniform')      || ...
+            strcmp(kernel_function,'triangle')     || ...
+            strcmp(kernel_function,'epanechnikov') || ...
             strcmp(kernel_function,'quartic')
         error(['I can''t compute the optimal bandwidth with this kernel...' ...
                'Try the gaussian, triweight or cosinus kernels.']);
     end
-    T = zeros(n,1);
-    for i=1:n
+    T = zeros(number_of_draws, 1);
+    for i=1:number_of_draws
         j = i;
-        while j<= n && (data(j,1)-data(i,1))<2*eps;
+        while j<=number_of_draws && (data(j,1)-data(i,1))<2*eps
             j = j+1;
-        end     
+        end
         T(i) = (j-i);
         correction = correction + 2*T(i) - 1;
     end
     correction = correction/number_of_draws;
     Itilda4 = 8*7*6*5/(((2*sigma)^9)*sqrt(pi));
-    g3      = abs(2*correction*k6(0)/(mu21*Itilda4*correction))^(1/9);
+    g3      = abs(2*correction*k6(0)/(mu21*Itilda4*number_of_draws))^(1/9);
     Ihat3   = 0;
     for i=1:number_of_draws
         Ihat3 = Ihat3 + sum(k6((data(i,1)-data)/g3));
     end
     Ihat3 = -Ihat3/((n^2)*g3^7);
-    g2    = abs(2*correction*k4(0)/(mu21*Ihat3*n))^(1/7);
+    g2    = abs(2*correction*k4(0)/(mu21*Ihat3*number_of_draws))^(1/7);
     Ihat2 = 0;
-    for i=1:number_of_draws;
+    for i=1:number_of_draws
         Ihat2 = Ihat2 + sum(k4((data(i)-data)/g2));
-    end     
+    end
     Ihat2 = Ihat2/((number_of_draws^2)*g2^5);
-    h = ((2*T-1)*mu02/(number_of_draws*Ihat2*mu21^2)).^(1/5); % h is a column vector (local banwidth parameters). 
+    h = ((2*T-1)*mu02/(number_of_draws*Ihat2*mu21^2)).^(1/5); % h is a column vector (local banwidth parameters).
 else
     disp('mh_optimal_bandwidth:: ');
     error('Parameter bandwidth must be equal to 0, -1 or -2.');
@@ -169,7 +171,7 @@ function correction = correction_for_repeated_draws(draws,n)
 correction = 0;
 for i=1:n
     j = i;
-    while j<=n && ( draws(j,1) - draws(i,1) )<2*eps; 
+    while j<=n && ( draws(j,1) - draws(i,1) )<2*eps
         j = j+1;
     end
     correction = correction + 2*(j-i) - 1;
diff --git a/matlab/minus_logged_prior_density.m b/matlab/minus_logged_prior_density.m
index 38662541e1bfb192cbc8f0456b33ca0e1086b9c3..0b5b1e8152f252bff2cc22bd36e47dc5144d87bd 100644
--- a/matlab/minus_logged_prior_density.m
+++ b/matlab/minus_logged_prior_density.m
@@ -1,19 +1,19 @@
 function [fval,info,exit_flag,fake_1,fake_2] = minus_logged_prior_density(xparams,pshape,p6,p7,p3,p4,DynareOptions,DynareModel,EstimatedParams,DynareResults)
 % Evaluates minus the logged prior density.
-% 
-% INPUTS 
+%
+% INPUTS
 %   xparams    [double]   vector of parameters.
 %   pshape     [integer]  vector specifying prior densities shapes.
 %   p6         [double]   vector, first hyperparameter.
 %   p7         [double]   vector, second hyperparameter.
 %   p3         [double]   vector, prior's lower bound.
-%   p4         [double]   vector, prior's upper bound. 
+%   p4         [double]   vector, prior's upper bound.
 %
-% OUTPUTS 
+% OUTPUTS
 %   f          [double]  value of minus the logged prior density.
 %   info       [double]  vector: second entry stores penalty, first entry the error code.
 %
-% Copyright (C) 2009-2016 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -128,8 +128,8 @@ M_ = set_all_parameters(xparams,EstimatedParams,DynareModel);
 % Return, with endogenous penalty when possible, if dynare_resolve issues an error code (defined in resol).
 if info(1)
     if info(1) == 3 || info(1) == 4 || info(1) == 5 || info(1)==6 ||info(1) == 19 ...
-            info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1) == 26 || ...
-            info(1) == 81 || info(1) == 84 ||  info(1) == 85
+                info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1) == 26 || ...
+                info(1) == 81 || info(1) == 84 ||  info(1) == 85
         %meaningful second entry of output that can be used
         fval = Inf;
         info(4) = info(2);
@@ -138,7 +138,7 @@ if info(1)
     else
         fval = Inf;
         info(4) = 0.1;
-        exit_flag = 0;        
+        exit_flag = 0;
         return
     end
 end
diff --git a/matlab/missing/corrcoef/corrcoef.m b/matlab/missing/corrcoef/corrcoef.m
index c918c61043ddf89d11f1556f2ec315b651389859..893fd7c57dbb52a431d2b3131ffb71be8221d296 100644
--- a/matlab/missing/corrcoef/corrcoef.m
+++ b/matlab/missing/corrcoef/corrcoef.m
@@ -25,28 +25,28 @@ function [R,sig,ci1,ci2,nan_sig] = corrcoef(X,Y,varargin)
 %               This replaces RANKCORR.M
 %
 % [...] = CORRCOEF(..., param1, value1, param2, value2, ... );
-%	param       value
-%	'Mode'		type of correlation
-%		'Pearson','parametric'
-%		'Spearman'
-%		'rank'
-%	'rows'		how do deal with missing values encoded as NaN's.
-%		'complete': remove all rows with at least one NaN
-%		'pairwise': [default]
-%	'alpha'		0.01	: significance level to compute confidence interval
+%       param       value
+%       'Mode'          type of correlation
+%               'Pearson','parametric'
+%               'Spearman'
+%               'rank'
+%       'rows'          how do deal with missing values encoded as NaN's.
+%               'complete': remove all rows with at least one NaN
+%               'pairwise': [default]
+%       'alpha'         0.01    : significance level to compute confidence interval
 %
 % [R,p,ci1,ci2,nansig] = CORRCOEF(...);
 %   R is the correlation matrix
-%	R(i,j) is the correlation coefficient r between X(:,i) and Y(:,j)
+%       R(i,j) is the correlation coefficient r between X(:,i) and Y(:,j)
 %  p    gives the significance of R
-%	It tests the null hypothesis that the product moment correlation coefficient is zero
+%       It tests the null hypothesis that the product moment correlation coefficient is zero
 %       using Student's t-test on the statistic t = r*sqrt(N-2)/sqrt(1-r^2)
 %       where N is the number of samples (Statistics, M. Spiegel, Schaum series).
 %  p > alpha: do not reject the Null hypothesis: 'R is zero'.
 %  p < alpha: The alternative hypothesis 'R is larger than zero' is true with probability (1-alpha).
-%  ci1	lower (1-alpha) confidence interval
-%  ci2	upper (1-alpha) confidence interval
-%	If no alpha is provided, the default alpha is 0.01. This can be changed with function flag_implicit_significance.
+%  ci1  lower (1-alpha) confidence interval
+%  ci2  upper (1-alpha) confidence interval
+%       If no alpha is provided, the default alpha is 0.01. This can be changed with function flag_implicit_significance.
 %  nan_sig  p-value whether H0: 'NaN''s are not correlated' could be correct
 %       if nan_sig < alpha, H1 ('NaNs are correlated') is very likely.
 %
@@ -65,7 +65,7 @@ function [R,sig,ci1,ci2,nan_sig] = corrcoef(X,Y,varargin)
 % Further recommandation related to the correlation coefficient:
 % + LOOK AT THE SCATTERPLOTS to make sure that the relationship is linear
 % + Correlation is not causation because
-%	it is not clear which parameter is 'cause' and which is 'effect' and
+%       it is not clear which parameter is 'cause' and which is 'effect' and
 %       the observed correlation between two variables might be due to the action of other, unobserved variables.
 %
 % see also: SUMSKIPNAN, COVM, COV, COR, SPEARMAN, RANKCORR, RANKS,
@@ -91,7 +91,7 @@ function [R,sig,ci1,ci2,nan_sig] = corrcoef(X,Y,varargin)
 
 %       $Id: corrcoef.m 9387 2011-12-15 10:42:14Z schloegl $
 %       Copyright (C) 2000-2004,2008,2009,2011 by Alois Schloegl <alois.schloegl@gmail.com>
-%       Copyright (C) 2014 Dynare Team
+%       Copyright (C) 2014-2017 Dynare Team
 %       This function is part of the NaN-toolbox
 %       http://pub.ist.ac.at/~schloegl/matlab/NaN/
 
@@ -124,59 +124,59 @@ function [R,sig,ci1,ci2,nan_sig] = corrcoef(X,Y,varargin)
 
 global FLAG_NANS_OCCURED;
 
-NARG = nargout;	% needed because nargout is not reentrant in Octave, and corrcoef is recursive
+NARG = nargout; % needed because nargout is not reentrant in Octave, and corrcoef is recursive
 mode = [];
 
 if nargin==1
-        Y = [];
-        Mode='Pearson';
+    Y = [];
+    Mode='Pearson';
 elseif nargin==0
-        fprintf(2,'Error CORRCOEF: Missing argument(s)\n');
+    fprintf(2,'Error CORRCOEF: Missing argument(s)\n');
 elseif nargin>1
-        if ischar(Y)
-                varg = [Y,varargin];
-                Y=[];
-        else
-                varg = varargin;
-        end;
+    if ischar(Y)
+        varg = [Y,varargin];
+        Y=[];
+    else
+        varg = varargin;
+    end
 
-        if length(varg)<1,
-                Mode = 'Pearson';
-        elseif length(varg)==1,
-                Mode = varg{1};
-        else
-                for k = 2:2:length(varg),
-                        mode = setfield(mode,lower(varg{k-1}),varg{k});
-                end;
-                if isfield(mode,'mode')
-                        Mode = mode.mode;
-                end;
-        end;
-end;
-if isempty(Mode) Mode='pearson'; end;
+    if length(varg)<1
+        Mode = 'Pearson';
+    elseif length(varg)==1
+        Mode = varg{1};
+    else
+        for k = 2:2:length(varg)
+            mode = setfield(mode,lower(varg{k-1}),varg{k});
+        end
+        if isfield(mode,'mode')
+            Mode = mode.mode;
+        end
+    end
+end
+if isempty(Mode), Mode='pearson'; end
 Mode=[Mode,'        '];
 
 
 
-FLAG_WARNING = warning;		% save warning status
+FLAG_WARNING = warning;         % save warning status
 warning('off');
 
 [r1,c1]=size(X);
 if ~isempty(Y)
-        [r2,c2]=size(Y);
-        if r1~=r2,
-                fprintf(2,'Error CORRCOEF: X and Y must have the same number of observations (rows).\n');
-                return;
-        end;
-        NN = real(~isnan(X)')*real(~isnan(Y));
+    [r2,c2]=size(Y);
+    if r1~=r2
+        fprintf(2,'Error CORRCOEF: X and Y must have the same number of observations (rows).\n');
+        return
+    end
+    NN = real(~isnan(X)')*real(~isnan(Y));
 else
-        [r2,c2]=size(X);
-        NN = real(~isnan(X)')*real(~isnan(X));
-end;
+    [r2,c2]=size(X);
+    NN = real(~isnan(X)')*real(~isnan(X));
+end
 
 %%%%% generate combinations using indices for pairwise calculation of the correlation
 YESNAN = any(isnan(X(:))) | any(isnan(Y(:)));
-if YESNAN,
+if YESNAN
     FLAG_NANS_OCCURED=(1==1);
     if isfield(mode,'rows')
         if strcmp(mode.rows,'complete')
@@ -184,7 +184,7 @@ if YESNAN,
             X = X(ix,:);
             if ~isempty(Y)
                 Y = Y(ix,:);
-            end;
+            end
             YESNAN = 0;
             NN = size(X,1);
         elseif strcmp(mode.rows,'all')
@@ -192,175 +192,175 @@ if YESNAN,
             %%NN(NN < size(X,1)) = NaN;
         elseif strcmp(mode.rows,'pairwise')
             %%% default
-        end;
-    end;
-end;
-if isempty(Y),
-        IX = ones(c1)-diag(ones(c1,1));
-        [jx, jy ] = find(IX);
-        [jxo,jyo] = find(IX);
+        end
+    end
+end
+if isempty(Y)
+    IX = ones(c1)-diag(ones(c1,1));
+    [jx, jy ] = find(IX);
+    [jxo,jyo] = find(IX);
     R = eye(c1);
 else
-        IX = sparse([],[],[],c1+c2,c1+c2,c1*c2);
-        IX(1:c1,c1+(1:c2)) = 1;
-        [jx,jy] = find(IX);
+    IX = sparse([],[],[],c1+c2,c1+c2,c1*c2);
+    IX(1:c1,c1+(1:c2)) = 1;
+    [jx,jy] = find(IX);
 
-        IX = ones(c1,c2);
-        [jxo,jyo] = find(IX);
+    IX = ones(c1,c2);
+    [jxo,jyo] = find(IX);
     R = zeros(c1,c2);
-end;
-
-if strcmp(lower(Mode(1:7)),'pearson');
-        % see http://mathworld.wolfram.com/CorrelationCoefficient.html
-    if ~YESNAN,
-                [S,N,SSQ] = sumskipnan(X,1);
-                if ~isempty(Y),
-                    [S2,N2,SSQ2] = sumskipnan(Y,1);
-                        CC = X'*Y;
-                        M1 = S./N;
-                        M2 = S2./N2;
-                        cc = CC./NN - M1'*M2;
-                        R  = cc./sqrt((SSQ./N-M1.*M1)'*(SSQ2./N2-M2.*M2));
-                else
-                        CC = X'*X;
-                        M  = S./N;
-                        cc = CC./NN - M'*M;
-                        v  = SSQ./N - M.*M; %max(N-1,0);
-                        R  = cc./sqrt(v'*v);
-                end;
+end
+
+if strcmp(lower(Mode(1:7)),'pearson')
+    % see http://mathworld.wolfram.com/CorrelationCoefficient.html
+    if ~YESNAN
+        [S,N,SSQ] = sumskipnan(X,1);
+        if ~isempty(Y)
+            [S2,N2,SSQ2] = sumskipnan(Y,1);
+            CC = X'*Y;
+            M1 = S./N;
+            M2 = S2./N2;
+            cc = CC./NN - M1'*M2;
+            R  = cc./sqrt((SSQ./N-M1.*M1)'*(SSQ2./N2-M2.*M2));
         else
-                if ~isempty(Y),
-                        X  = [X,Y];
-                end;
-                for k = 1:length(jx),
-                        %ik = ~any(isnan(X(:,[jx(k),jy(k)])),2);
-                        ik = ~isnan(X(:,jx(k))) & ~isnan(X(:,jy(k)));
-                        [s,n,s2] = sumskipnan(X(ik,[jx(k),jy(k)]),1);
-                        v  = (s2-s.*s./n)./n;
-                        cc = X(ik,jx(k))'*X(ik,jy(k));
-                        cc = cc/n(1) - prod(s./n);
-                        %r(k) = cc./sqrt(prod(v));
-                        R(jxo(k),jyo(k)) = cc./sqrt(prod(v));
-                end;
+            CC = X'*X;
+            M  = S./N;
+            cc = CC./NN - M'*M;
+            v  = SSQ./N - M.*M; %max(N-1,0);
+            R  = cc./sqrt(v'*v);
+        end
+    else
+        if ~isempty(Y)
+            X  = [X,Y];
+        end
+        for k = 1:length(jx)
+            %ik = ~any(isnan(X(:,[jx(k),jy(k)])),2);
+            ik = ~isnan(X(:,jx(k))) & ~isnan(X(:,jy(k)));
+            [s,n,s2] = sumskipnan(X(ik,[jx(k),jy(k)]),1);
+            v  = (s2-s.*s./n)./n;
+            cc = X(ik,jx(k))'*X(ik,jy(k));
+            cc = cc/n(1) - prod(s./n);
+            %r(k) = cc./sqrt(prod(v));
+            R(jxo(k),jyo(k)) = cc./sqrt(prod(v));
+        end
     end
 
-elseif strcmp(lower(Mode(1:4)),'rank');
-        % see [ 6] http://mathworld.wolfram.com/SpearmanRankCorrelationCoefficient.html
-    if ~YESNAN,
-                if isempty(Y)
-                    R = corrcoef(ranks(X));
-                else
-                        R = corrcoef(ranks(X),ranks(Y));
-                end;
+elseif strcmp(lower(Mode(1:4)),'rank')
+    % see [ 6] http://mathworld.wolfram.com/SpearmanRankCorrelationCoefficient.html
+    if ~YESNAN
+        if isempty(Y)
+            R = corrcoef(ranks(X));
         else
-                if ~isempty(Y),
-                        X = [X,Y];
-                end;
-                for k = 1:length(jx),
-                        %ik = ~any(isnan(X(:,[jx(k),jy(k)])),2);
-                        ik = ~isnan(X(:,jx(k))) & ~isnan(X(:,jy(k)));
-                        il = ranks(X(ik,[jx(k),jy(k)]));
-                        R(jxo(k),jyo(k)) = corrcoef(il(:,1),il(:,2));
-                end;
+            R = corrcoef(ranks(X),ranks(Y));
+        end
+    else
+        if ~isempty(Y)
+            X = [X,Y];
+        end
+        for k = 1:length(jx)
+            %ik = ~any(isnan(X(:,[jx(k),jy(k)])),2);
+            ik = ~isnan(X(:,jx(k))) & ~isnan(X(:,jy(k)));
+            il = ranks(X(ik,[jx(k),jy(k)]));
+            R(jxo(k),jyo(k)) = corrcoef(il(:,1),il(:,2));
+        end
         X = ranks(X);
-    end;
-
-elseif strcmp(lower(Mode(1:8)),'spearman');
-        % see [ 6] http://mathworld.wolfram.com/SpearmanRankCorrelationCoefficient.html
-        if ~isempty(Y),
-                X = [X,Y];
-        end;
-
-        n = repmat(nan,c1,c2);
+    end
 
-        if ~YESNAN,
-                iy = ranks(X);	%  calculates ranks;
+elseif strcmp(lower(Mode(1:8)),'spearman')
+    % see [ 6] http://mathworld.wolfram.com/SpearmanRankCorrelationCoefficient.html
+    if ~isempty(Y)
+        X = [X,Y];
+    end
 
-                for k = 1:length(jx),
-                        [R(jxo(k),jyo(k)),n(jxo(k),jyo(k))] = sumskipnan((iy(:,jx(k)) - iy(:,jy(k))).^2);	% NN is the number of non-missing values
-                end;
-        else
-                for k = 1:length(jx),
-                        %ik = ~any(isnan(X(:,[jx(k),jy(k)])),2);
-                        ik = ~isnan(X(:,jx(k))) & ~isnan(X(:,jy(k)));
-                        il = ranks(X(ik,[jx(k),jy(k)]));
-                        % NN is the number of non-missing values
-                        [R(jxo(k),jyo(k)),n(jxo(k),jyo(k))] = sumskipnan((il(:,1) - il(:,2)).^2);
-                end;
+    n = repmat(nan,c1,c2);
+
+    if ~YESNAN
+        iy = ranks(X);  %  calculates ranks;
+
+        for k = 1:length(jx)
+            [R(jxo(k),jyo(k)),n(jxo(k),jyo(k))] = sumskipnan((iy(:,jx(k)) - iy(:,jy(k))).^2);       % NN is the number of non-missing values
+        end
+    else
+        for k = 1:length(jx)
+            %ik = ~any(isnan(X(:,[jx(k),jy(k)])),2);
+            ik = ~isnan(X(:,jx(k))) & ~isnan(X(:,jy(k)));
+            il = ranks(X(ik,[jx(k),jy(k)]));
+            % NN is the number of non-missing values
+            [R(jxo(k),jyo(k)),n(jxo(k),jyo(k))] = sumskipnan((il(:,1) - il(:,2)).^2);
+        end
         X = ranks(X);
-        end;
-        R = 1 - 6 * R ./ (n.*(n.*n-1));
+    end
+    R = 1 - 6 * R ./ (n.*(n.*n-1));
 
-elseif strcmp(lower(Mode(1:7)),'partial');
-        fprintf(2,'Error CORRCOEF: use PARTCORRCOEF \n',Mode);
+elseif strcmp(lower(Mode(1:7)),'partial')
+    fprintf(2,'Error CORRCOEF: use PARTCORRCOEF \n',Mode);
 
-        return;
+    return
 
-elseif strcmp(lower(Mode(1:7)),'kendall');
-        fprintf(2,'Error CORRCOEF: mode ''%s'' not implemented yet.\n',Mode);
+elseif strcmp(lower(Mode(1:7)),'kendall')
+    fprintf(2,'Error CORRCOEF: mode ''%s'' not implemented yet.\n',Mode);
 
-        return;
+    return
 else
-        fprintf(2,'Error CORRCOEF: unknown mode ''%s''\n',Mode);
-end;
+    fprintf(2,'Error CORRCOEF: unknown mode ''%s''\n',Mode);
+end
 
-if (NARG<2),
-        warning(FLAG_WARNING);  % restore warning status
-        return;
-end;
+if (NARG<2)
+    warning(FLAG_WARNING);  % restore warning status
+    return
+end
 
 
 % CONFIDENCE INTERVAL
 if isfield(mode,'alpha')
     alpha = mode.alpha;
-elseif exist('flag_implicit_significance','file'),
-        alpha = flag_implicit_significance;
+elseif exist('flag_implicit_significance','file')
+    alpha = flag_implicit_significance;
 else
     alpha = 0.01;
-end;
+end
 % fprintf(1,'CORRCOEF: confidence interval is based on alpha=%f\n',alpha);
 
 
 % SIGNIFICANCE TEST
 R(isnan(R))=0;
 tmp = 1 - R.*R;
-tmp(tmp<0) = 0;		% prevent tmp<0 i.e. imag(t)~=0
+tmp(tmp<0) = 0;         % prevent tmp<0 i.e. imag(t)~=0
 t   = R.*sqrt(max(NN-2,0)./tmp);
 
-if exist('t_cdf','file');
-        sig = t_cdf(t,NN-2);
-elseif exist('tcdf','file')>1;
-        sig = tcdf(t,NN-2);
+if exist('t_cdf','file')
+    sig = t_cdf(t,NN-2);
+elseif exist('tcdf','file')>1
+    sig = tcdf(t,NN-2);
 else
-        fprintf('CORRCOEF: significance test not completed because of missing TCDF-function\n')
-        sig = repmat(nan,size(R));
-end;
+    fprintf('CORRCOEF: significance test not completed because of missing TCDF-function\n')
+    sig = repmat(nan,size(R));
+end
 sig  = 2 * min(sig,1 - sig);
 
 
-if NARG<3,
+if NARG<3
     warning(FLAG_WARNING);  % restore warning status
-        return;
-end;
+    return
+end
 
 
 tmp = R;
-%tmp(ix1 | ix2) = nan;		% avoid division-by-zero warning
+%tmp(ix1 | ix2) = nan;          % avoid division-by-zero warning
 z   = log((1+tmp)./(1-tmp))/2;  % Fisher transformation [21]
-%sz = 1./sqrt(NN-3);		% standard error of z
-sz  = sqrt(2)*erfinv(1-alpha)./sqrt(NN-3);	% confidence interval for alpha of z
+                                %sz = 1./sqrt(NN-3);            % standard error of z
+sz  = sqrt(2)*erfinv(1-alpha)./sqrt(NN-3);      % confidence interval for alpha of z
 
 ci1 = tanh(z-sz);
 ci2 = tanh(z+sz);
 
-%ci1(isnan(ci1))=R(isnan(ci1));	% in case of isnan(ci), the interval limits are exactly the R value
+%ci1(isnan(ci1))=R(isnan(ci1)); % in case of isnan(ci), the interval limits are exactly the R value
 %ci2(isnan(ci2))=R(isnan(ci2));
 
-if (NARG<5) || ~YESNAN,
+if (NARG<5) || ~YESNAN
     nan_sig = repmat(NaN,size(R));
     warning(FLAG_WARNING);  % restore warning status
-    return;
-end;
+    return
+end
 
 %%%%% ----- check independence of NaNs (missing values) -----
 [nan_R, nan_sig] = corrcoef(X,double(isnan(X)));
@@ -370,18 +370,16 @@ nan_sig(isnan(nan_R)) = nan;
 % remove diagonal elements, because these have not any meaning %
 nan_R(isnan(nan_R)) = 0;
 
-if 0, any(nan_sig(:) < alpha),
-        tmp = nan_sig(:);			% Hack to skip NaN's in MIN(X)
-        min_sig = min(tmp(~isnan(tmp)));    % Necessary, because Octave returns NaN rather than min(X) for min(NaN,X)
-        fprintf(1,'CORRCOFF Warning: Missing Values (i.e. NaNs) are not independent of data (p-value=%f)\n', min_sig);
-        fprintf(1,'   Its recommended to remove all samples (i.e. rows) with any missing value (NaN).\n');
-        fprintf(1,'   The null-hypotheses (NaNs are uncorrelated) is rejected for the following parameter pair(s).\n');
-        [ix,iy] = find(nan_sig < alpha);
-        disp([ix,iy])
-end;
+if 0, any(nan_sig(:) < alpha)
+    tmp = nan_sig(:);                       % Hack to skip NaN's in MIN(X)
+    min_sig = min(tmp(~isnan(tmp)));    % Necessary, because Octave returns NaN rather than min(X) for min(NaN,X)
+    fprintf(1,'CORRCOFF Warning: Missing Values (i.e. NaNs) are not independent of data (p-value=%f)\n', min_sig);
+    fprintf(1,'   Its recommended to remove all samples (i.e. rows) with any missing value (NaN).\n');
+    fprintf(1,'   The null-hypotheses (NaNs are uncorrelated) is rejected for the following parameter pair(s).\n');
+    [ix,iy] = find(nan_sig < alpha);
+    disp([ix,iy])
+end
 
 %%%%% ----- end of independence check ------
 
 warning(FLAG_WARNING);  % restore warning status
-return;
-
diff --git a/matlab/missing/corrcoef/flag_implicit_skip_nan.m b/matlab/missing/corrcoef/flag_implicit_skip_nan.m
index 409b9f69648ea224f956bdcbb1b968b8f3bcc652..e8fd0fec6e8fa16c2a0900129e8d334a33b3b700 100644
--- a/matlab/missing/corrcoef/flag_implicit_skip_nan.m
+++ b/matlab/missing/corrcoef/flag_implicit_skip_nan.m
@@ -1,6 +1,6 @@
 function FLAG = flag_implicit_skip_nan(i)
 % FLAG_IMPLICIT_SKIP_NAN sets and gets default mode for handling NaNs
-%	1 skips NaN's (the default mode if no mode is set)
+%       1 skips NaN's (the default mode if no mode is set)
 %   0 NaNs are propagated; input NaN's give NaN's at the output
 %
 % FLAG = flag_implicit_skip_nan()
@@ -9,15 +9,15 @@ function FLAG = flag_implicit_skip_nan(i)
 % flag_implicit_skip_nan(FLAG)    % sets mode
 %
 % prevFLAG = flag_implicit_skip_nan(nextFLAG)
-%	gets previous set FLAG and sets FLAG for the future
+%       gets previous set FLAG and sets FLAG for the future
 % flag_implicit_skip_nan(prevFLAG)
-%	resets FLAG to previous mode
+%       resets FLAG to previous mode
 %
 % It is used in:
-%	SUMSKIPNAN, MEDIAN, QUANTILES, TRIMEAN
+%       SUMSKIPNAN, MEDIAN, QUANTILES, TRIMEAN
 % and affects many other functions like:
-%	CENTER, KURTOSIS, MAD, MEAN, MOMENT, RMS, SEM, SKEWNESS,
-%	STATISTIC, STD, VAR, ZSCORE etc.
+%       CENTER, KURTOSIS, MAD, MEAN, MOMENT, RMS, SEM, SKEWNESS,
+%       STATISTIC, STD, VAR, ZSCORE etc.
 %
 % The mode is stored in the global variable FLAG_implicit_skip_nan
 % It is recommended to use flag_implicit_skip_nan(1) as default and
@@ -40,27 +40,28 @@ function FLAG = flag_implicit_skip_nan(i)
 %    along with this program; if not, write to the Free Software
 %    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 
-%	$Id: flag_implicit_skip_nan.m 8351 2011-06-24 17:35:07Z carandraug $
+%       $Id: flag_implicit_skip_nan.m 8351 2011-06-24 17:35:07Z carandraug $
+
 %   Copyright (C) 2001-2003,2009 by Alois Schloegl <alois.schloegl@gmail.com>
-%   Copyright (C) 2014 Dynare Team
+%   Copyright (C) 2014-2017 Dynare Team
+%
 %       This function is part of the NaN-toolbox
 %       http://pub.ist.ac.at/~schloegl/matlab/NaN/
 
 
 persistent FLAG_implicit_skip_nan;
 
-%% if strcmp(version,'3.6'), FLAG_implicit_skip_nan=(1==1); end;	%% hack for the use with Freemat3.6
+%% if strcmp(version,'3.6'), FLAG_implicit_skip_nan=(1==1); end;        %% hack for the use with Freemat3.6
 
 %%% set DEFAULT value of FLAG
-if isempty(FLAG_implicit_skip_nan),
+if isempty(FLAG_implicit_skip_nan)
     FLAG_implicit_skip_nan = (1==1); %logical(1); % logical.m not available on 2.0.16
-end;
+end
 
 FLAG = FLAG_implicit_skip_nan;
-if nargin>0,
+if nargin>0
     FLAG_implicit_skip_nan = (i~=0); %logical(i); %logical.m not available in 2.0.16
     if (~i)
         warning('flag_implicit_skipnan(0): You are warned!!! You have turned off skipping NaN in sumskipnan. This is not recommended. Make sure you really know what you do.')
-    end;
-end;
-
+    end
+end
diff --git a/matlab/missing/corrcoef/sumskipnan.m b/matlab/missing/corrcoef/sumskipnan.m
index 78f8ecbc1e40854d7c96083f11d7315b5947b6c1..a1054c3f8d83f563c43e65aa9851c7d23386e32e 100644
--- a/matlab/missing/corrcoef/sumskipnan.m
+++ b/matlab/missing/corrcoef/sumskipnan.m
@@ -13,13 +13,13 @@ function [o,count,SSQ] = sumskipnan(x, DIM, W)
 % [Y,N,SSQ] = sumskipnan(x [,DIM])
 % [...] = sumskipnan(x, DIM, W)
 %
-% x	input data
-% DIM	dimension (default: [])
-%	empty DIM sets DIM to first non singleton dimension
-% W	weight vector for weighted sum, numel(W) must fit size(x,DIM)
-% Y	resulting sum
-% N	number of valid (not missing) elements
-% SSQ	sum of squares
+% x     input data
+% DIM   dimension (default: [])
+%       empty DIM sets DIM to first non singleton dimension
+% W     weight vector for weighted sum, numel(W) must fit size(x,DIM)
+% Y     resulting sum
+% N     number of valid (not missing) elements
+% SSQ   sum of squares
 %
 % the function FLAG_NANS_OCCURED() returns whether any value in x
 %  is a not-a-number (NaN)
@@ -47,21 +47,22 @@ function [o,count,SSQ] = sumskipnan(x, DIM, W)
 %    You should have received a copy of the GNU General Public License
 %    along with this program; If not, see <http://www.gnu.org/licenses/>.
 
-%	$Id: sumskipnan.m 9033 2011-11-08 20:58:07Z schloegl $
+%       $Id: sumskipnan.m 9033 2011-11-08 20:58:07Z schloegl $
+%
 %       Copyright (C) 2000-2005,2009,2011 by Alois Schloegl <alois.schloegl@gmail.com>
-%       Copyright (C) 2014 Dynare Team
+%       Copyright (C) 2014-2017 Dynare Team
 %       This function is part of the NaN-toolbox
 %       http://pub.ist.ac.at/~schloegl/matlab/NaN/
 
 
 global FLAG_NANS_OCCURED;
 
-if nargin<2,
-        DIM = [];
-end;
-if nargin<3,
-        W = [];
-end;
+if nargin<2
+    DIM = [];
+end
+if nargin<3
+    W = [];
+end
 
 % an efficient implementation in C of the following lines
 % could significantly increase performance
@@ -73,24 +74,24 @@ end;
 %   if ~isnan(i(k))
 %   {   o     += x(k);
 %               count += 1;
-%		tmp    = x(k)*x(k)
-%		o2    += tmp;
-%		o3    += tmp.*tmp;
+%               tmp    = x(k)*x(k)
+%               o2    += tmp;
+%               o3    += tmp.*tmp;
 %       };
 
-if isempty(DIM),
-        DIM = find(size(x)>1,1);
-        if isempty(DIM), DIM = 1; end;
+if isempty(DIM)
+    DIM = find(size(x)>1,1);
+    if isempty(DIM), DIM = 1; end
 end
-if (DIM<1), DIM = 1; end; %% Hack, because min([])=0 for FreeMat v3.5
+if (DIM<1), DIM = 1; end %% Hack, because min([])=0 for FreeMat v3.5
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 % non-float data
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-if  (isempty(W) && (~(isa(x,'float') || isa(x,'double')))) || ~flag_implicit_skip_nan(), %%% skip always NaN's
+if  (isempty(W) && (~(isa(x,'float') || isa(x,'double')))) || ~flag_implicit_skip_nan() %%% skip always NaN's
     if ~isempty(W)
         error('SUMSKIPNAN: weighted sum of integers not supported, yet');
-    end;
+    end
     x = double(x);
     o = sum(x,DIM);
     if nargout>1
@@ -101,16 +102,16 @@ if  (isempty(W) && (~(isa(x,'float') || isa(x,'double')))) || ~flag_implicit_ski
         if nargout>2
             x = x.*x;
             SSQ = sum(x,DIM);
-        end;
-    end;
-    return;
-end;
+        end
+    end
+    return
+end
 
 if (length(size(x))<DIM)
     error('SUMSKIPNAN: DIM argument larger than number of dimensions of x');
 elseif ~isempty(W) && (size(x,DIM)~=numel(W))
     error('SUMSKIPNAN: size of weight vector does not match size(x,DIM)');
-end;
+end
 
 %% mex and oct files expect double
 x = double(x);
@@ -124,18 +125,18 @@ try
     %% using sumskipnan_mex.mex
 
     %% !!! hack: FLAG_NANS_OCCURED is an output argument, reserve memory !!!
-    if isempty(FLAG_NANS_OCCURED),
+    if isempty(FLAG_NANS_OCCURED)
         FLAG_NANS_OCCURED = logical(0);  % default value
-    end;
+    end
 
-    if (nargout<2),
+    if (nargout<2)
         o = sumskipnan_mex(real(x),DIM,FLAG_NANS_OCCURED,W);
         if (~isreal(x))
             io = sumskipnan_mex(imag(x),DIM,FLAG_NANS_OCCURED,W);
             o  = o + i*io;
-        end;
-        return;
-    elseif (nargout==2),
+        end
+        return
+    elseif (nargout==2)
         [o,count] = sumskipnan_mex(real(x),DIM,FLAG_NANS_OCCURED,W);
         if (~isreal(x))
             [io,icount] = sumskipnan_mex(imag(x),DIM,FLAG_NANS_OCCURED,W);
@@ -143,10 +144,10 @@ try
                 error('Number of NaNs differ for REAL and IMAG part');
             else
                 o  = o+i*io;
-            end;
-        end;
-        return;
-    elseif (nargout>=3),
+            end
+        end
+        return
+    elseif (nargout>=3)
         [o,count,SSQ] = sumskipnan_mex(real(x),DIM,FLAG_NANS_OCCURED,W);
         if (~isreal(x))
             [io,icount,iSSQ] = sumskipnan_mex(imag(x),DIM,FLAG_NANS_OCCURED,W);
@@ -155,23 +156,23 @@ try
             else
                 o  = o+i*io;
                 SSQ = SSQ+iSSQ;
-            end;
-        end;
-        return;
-    end;
-end;
+            end
+        end
+        return
+    end
+end
 
 if ~isempty(W)
     error('weighted sumskipnan requires sumskipnan_mex');
-end;
+end
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 % count non-NaN's
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-if nargout>1,
-        count = sum(x==x,DIM);
+if nargout>1
+    count = sum(x==x,DIM);
     FLAG_NANS_OCCURED = any(count(:)<size(x,DIM));
-end;
+end
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 % replace NaN's with zero
@@ -179,16 +180,13 @@ end;
 x(x~=x) = 0;
 o = sum(x,DIM);
 
-if nargout>2,
-        x = real(x).^2 + imag(x).^2;
-        SSQ = sum(x,DIM);
-end;
+if nargout>2
+    x = real(x).^2 + imag(x).^2;
+    SSQ = sum(x,DIM);
+end
 
 %!assert(sumskipnan([1,2],1),[1,2])
 %!assert(sumskipnan([1,NaN],2),1)
 %!assert(sumskipnan([1,NaN],2),1)
 %!assert(sumskipnan([nan,1,4,5]),10)
 %!assert(sumskipnan([nan,1,4,5]',1,[3;2;1;0]),6)
-
-
-
diff --git a/matlab/missing/corrcoef/tcdf.m b/matlab/missing/corrcoef/tcdf.m
index c282e0a1745c80b660f4a56425d08898f55ecbfb..8d76f765762716fcac36c8a4b9adbe00bf8fedf8 100644
--- a/matlab/missing/corrcoef/tcdf.m
+++ b/matlab/missing/corrcoef/tcdf.m
@@ -11,9 +11,11 @@ function p = tcdf(x,n)
 
 % Reference(s):
 
-%	$Id: tcdf.m 9033 2011-11-08 20:58:07Z schloegl $
-%	Copyright (C) 2000-2003,2009 by Alois Schloegl <alois.schloegl@gmail.com>
-%   Copyright (C) 2014 Dynare Team
+%       $Id: tcdf.m 9033 2011-11-08 20:58:07Z schloegl $
+
+%   Copyright (C) 2000-2003,2009 by Alois Schloegl <alois.schloegl@gmail.com>
+%   Copyright (C) 2014-2017 Dynare Team
+%
 %       This is part of the NaN-toolbox. For more details see
 %       http://pub.ist.ac.at/~schloegl/matlab/NaN/
 
@@ -37,10 +39,10 @@ if all(size(x)==1)
 elseif all(size(n)==1)
     n = repmat(n,size(x));
 elseif all(size(x)==size(n))
-    ;	%% OK, do nothing
+    % OK, do nothing
 else
     error('size of input arguments must be equal or scalar')
-end;
+end
 
 % allocate memory
 p = zeros(size(x));
diff --git a/matlab/missing/ilu/ilu.m b/matlab/missing/ilu/ilu.m
index 4b4fe233829b1ba8d1a7f82a44c670cdbd9d5078..6e53e59dfeb5b071ac3994f3b5787044b8789707 100644
--- a/matlab/missing/ilu/ilu.m
+++ b/matlab/missing/ilu/ilu.m
@@ -1,7 +1,7 @@
 function [L, U, P] = ilu(A, setup)
 % Partially implement function ilu using the (now deprecated) luinc
 
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -18,20 +18,20 @@ function [L, U, P] = ilu(A, setup)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-  if nargout ~= 2
-      error('Only two output arguments supported')
-  end
-  if nargin ~= 2
-      error('Only two input arguments supported')
-  end
+if nargout ~= 2
+    error('Only two output arguments supported')
+end
+if nargin ~= 2
+    error('Only two input arguments supported')
+end
+
+if isfield(setup, 'milu')
+    if setup.milu == 'off'
+        setup.milu = 0;
+    else
+        error(['Unsupported milu: ' setup.milu ])
+    end
+end
 
-  if isfield(setup, 'milu')
-      if setup.milu == 'off'
-          setup.milu = 0;
-      else
-          error(['Unsupported milu: ' setup.milu ])
-      end
-  end
-  
-  [L, U] = luinc(A, setup);
+[L, U] = luinc(A, setup);
 end
diff --git a/matlab/missing/issquare/issquare.m b/matlab/missing/issquare/issquare.m
index 4d4eb2b572c8a771080d57d35f8ffdc0904131af..0b28884a021c55fae95f1ff8de5ba32126b14b4e 100644
--- a/matlab/missing/issquare/issquare.m
+++ b/matlab/missing/issquare/issquare.m
@@ -27,7 +27,7 @@ function i = issquare(A)
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -46,7 +46,7 @@ function i = issquare(A)
 
 d = size(A);
 if (length(d)==2) && (d(1)==d(2))
-  i = d(1);
+    i = d(1);
 else
-  i = 0;
+    i = 0;
 end
diff --git a/matlab/missing/ordeig/ordeig.m b/matlab/missing/ordeig/ordeig.m
index 6004fd86f3bad770a517099c72326f99817a30cf..e7ddfd744f9a876a348fa103ce472961420c49fc 100644
--- a/matlab/missing/ordeig/ordeig.m
+++ b/matlab/missing/ordeig/ordeig.m
@@ -11,7 +11,7 @@ function eigs = ordeig(t)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2009 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -34,7 +34,7 @@ i = 1;
 while i <= n
     if i == n
         eigs(n) = t(n,n);
-        break;
+        break
     elseif t(i+1,i) == 0
         eigs(i) = t(i,i);
         i = i+1;
diff --git a/matlab/missing/stats/betacdf.m b/matlab/missing/stats/betacdf.m
index 2ba7cc53ebfd183c7ab454a85a97d26b02e229bd..d1ac509f789495695e172be064052e5e7139d5e8 100644
--- a/matlab/missing/stats/betacdf.m
+++ b/matlab/missing/stats/betacdf.m
@@ -10,7 +10,7 @@ function cdf = betacdf (x, a, b)
 % Original author: KH <Kurt.Hornik@wu-wien.ac.at>
 
 % Copyright (C) 1995, 1996, 1997, 2005, 2006, 2007 Kurt Hornik
-% Copyright (C) 2008-2009 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -61,4 +61,3 @@ if (any (k))
 end
 
 end
-
diff --git a/matlab/missing/stats/betainv.m b/matlab/missing/stats/betainv.m
index 8273fc356f355e887c0387a11ab04638d1049467..a7300d1b19c8ffd298821e84b0519674e9a80f91 100644
--- a/matlab/missing/stats/betainv.m
+++ b/matlab/missing/stats/betainv.m
@@ -84,7 +84,7 @@ if (any (k))
         end
         h = y_old - y_new;
         if (max (abs (h)) < sqrt (eps))
-            break;
+            break
         end
         y_old = y_new;
     end
diff --git a/matlab/missing/stats/betarnd.m b/matlab/missing/stats/betarnd.m
index f27fca4413447169311e3287bb13818a2254baf3..a2d0c9fe889fdf0ff2daef2765b21a14f934ae2d 100644
--- a/matlab/missing/stats/betarnd.m
+++ b/matlab/missing/stats/betarnd.m
@@ -1,19 +1,19 @@
 function rnd = betarnd(a, b)
 % This function produces independent random variates from the Beta distribution.
 %
-%  INPUTS 
+%  INPUTS
 %    a       [double]    n*1 vector of positive parameters.
 %    b       [double]    n*1 vector of positive parameters.
 %
-%  OUTPUT 
+%  OUTPUT
 %    rnd     [double]    n*1 vector of independent variates from the beta(a,b) distribution.
-%                        rnd(i) is beta distributed with variance a(i)/(a(i)+b(i)) and 
-%                        variance a(i)b(i)/(a(i)+b(i))^2/(a(i)+b(i)+1).    
-%  
-%  ALGORITHMS     
+%                        rnd(i) is beta distributed with variance a(i)/(a(i)+b(i)) and
+%                        variance a(i)b(i)/(a(i)+b(i))^2/(a(i)+b(i)+1).
+%
+%  ALGORITHMS
 %    Described and Devroye (1986, chapter 9).
 
-% Copyright (C) 2008-2009 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/missing/stats/corr.m b/matlab/missing/stats/corr.m
index 21cdda767e6620fb3c08f072e7d5277576ed7692..ec2f719a18f6202791a1ad96e94140de235c6731 100644
--- a/matlab/missing/stats/corr.m
+++ b/matlab/missing/stats/corr.m
@@ -25,7 +25,7 @@ function retval = corr(x, y) % --*-- Unitary tests --*--
 %! the correlation between the columns of @var{x}.
 %! @end deftypefn
 %@eod:
-% 
+%
 % Notes:    - the original Octave code has been rewritten to avoid calling cov, since
 %               there is a long-standing incompatiblity between Matlab's cov and Octave's cov
 %               (see https://savannah.gnu.org/bugs/?40751)
@@ -39,7 +39,7 @@ function retval = corr(x, y) % --*-- Unitary tests --*--
 % Copyright (C) 1993-1996 Kurt Hornik
 % Copyright (C) 1996-2015 John W. Eaton
 % Copyright (C) 2013-2015 Julien Bect
-% Copyright (C) 2016 Dynare Team
+% Copyright (C) 2016-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -63,12 +63,12 @@ end
 
 % Input validation
 if (nargin==1 && ~(isnumeric (x) || islogical (x))) || ...
-    (nargin==2 && ~(isnumeric (x) || islogical (x) || isnumeric (y) || islogical (y)))
+           (nargin==2 && ~(isnumeric (x) || islogical (x) || isnumeric (y) || islogical (y)))
     error ('corr: X and Y must be numeric matrices or vectors');
 end
 
 if (nargin==1 && ~ismatrix(x)) || (nargin==2 && (~ismatrix(y) || ~ismatrix(x)))
-error ('corr: X and Y must be 2-D matrices or vectors');
+    error ('corr: X and Y must be 2-D matrices or vectors');
 end
 
 if (nargin == 2)
@@ -82,14 +82,14 @@ if isscalar(x)
     if nargin==1
         retval = NaN;
     else
-        retval = NaN(size(y));    
+        retval = NaN(size(y));
     end
-    return;
+    return
 end
 
 if nargin==2 && isscalar(y)
-    retval = NaN(size(x'));    
-    return;
+    retval = NaN(size(x'));
+    return
 end
 
 n = size (x, 1);
diff --git a/matlab/missing/stats/exprnd.m b/matlab/missing/stats/exprnd.m
index 65855db6e37a1c9bf1e840b44259df8b5d438b15..b59daf904990a85051a6f21bca270672e140a50f 100644
--- a/matlab/missing/stats/exprnd.m
+++ b/matlab/missing/stats/exprnd.m
@@ -2,22 +2,22 @@ function rnd = exprnd(a)
 %  Random samples from the exponential distribution with expectation a
 %  and variance a^2.
 %
-%  INPUTS 
+%  INPUTS
 %    a       [double]    m*n matrix of positive parameters
 %
-%  OUTPUT 
+%  OUTPUT
 %    rnd     [double]    m*n matrix, independent draws from the exponential
-%                        distribution rnd(j,j) has expectation a(i,j) and     
-%                        variance a(i,j)^2.   
+%                        distribution rnd(j,j) has expectation a(i,j) and
+%                        variance a(i,j)^2.
 %
-%  ALGORITHM  
+%  ALGORITHM
 %    Inverse transform sampling.
 %
 %  SPECIAL REQUIREMENTS
 %    None.
-%    
+%
 
-% Copyright (C) 2009 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/missing/stats/gaminv.m b/matlab/missing/stats/gaminv.m
index e879616c42d9154e360495257378b2466dd4cf51..96c4a0a3f0974e96f7d1c0a52b9f1ae58361cdae 100644
--- a/matlab/missing/stats/gaminv.m
+++ b/matlab/missing/stats/gaminv.m
@@ -76,7 +76,7 @@ if (any (k))
             h = y_old - y_new;
         end
         if (max (abs (h)) < sqrt (eps))
-            break;
+            break
         end
         y_old = y_new;
     end
diff --git a/matlab/missing/stats/gamrnd.m b/matlab/missing/stats/gamrnd.m
index b75b7868fd987e08ebfea913767ca91630085fed..af212475355ce0a98d6488e4d3fe2a7fbc2b75ca 100644
--- a/matlab/missing/stats/gamrnd.m
+++ b/matlab/missing/stats/gamrnd.m
@@ -1,19 +1,19 @@
 function rnd = gamrnd(a,b,method)
 % This function produces independent random variates from the Gamma distribution.
 %
-%  INPUTS 
+%  INPUTS
 %    a       [double]    n*1 vector of positive parameters.
-%    b       [double]    n*1 vector of positive parameters.    
+%    b       [double]    n*1 vector of positive parameters.
 %    method  [string]    'BawensLubranoRichard' or anything else (see below).
 %
-%  OUTPUT 
+%  OUTPUT
 %    rnd     [double]    n*1 vector of independent variates from the gamma(a,b) distribution.
 %                        rnd(i) is gamma distributed with mean a(i)b(i) and variance a(i)b(i)^2.
-%  
-%  ALGORITHMS     
+%
+%  ALGORITHMS
 %    Described in Bauwens, Lubrano and Richard (1999, page 316) and Devroye (1986, chapter 9).
 
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -39,13 +39,13 @@ if nargin==2
     if any(a<1)
         method = 'Devroye';
         Devroye.small = 'Best'; % 'Weibull' , 'Johnk' , 'Berman' , 'GS' , 'Best'
-                                % REMARK: The first algorithm (Weibull) is producing too much extreme values. 
+                                % REMARK: The first algorithm (Weibull) is producing too much extreme values.
     end
     if ~strcmpi(method,'BauwensLubranoRichard')
-        Devroye.big = 'Best'; % 'Cheng' , 'Best' 
+        Devroye.big = 'Best'; % 'Cheng' , 'Best'
                               % REMARK 1: The first algorithm (Cheng) is still producing obviously wrong simulations.
-                              % REMARK 2: The second algorithm seems slightly slower than the algorithm advocated by Bauwens, 
-                              %           Lubrano and Richard, but the comparison depends on the value of a (this should be 
+                              % REMARK 2: The second algorithm seems slightly slower than the algorithm advocated by Bauwens,
+                              %           Lubrano and Richard, but the comparison depends on the value of a (this should be
                               %           investigated further).
     end
 else
@@ -96,7 +96,7 @@ if number_of_double_a
     if strcmpi(method,'BauwensLubranoRichard')
         % Algorithm given in Bauwens, Lubrano & Richard (1999) page 316.
         rnd(double_idx) = knuth_algorithm(a(double_idx),b(double_idx));
-    else% Algorithm given in  Devroye (1986, chapter 9) 
+    else% Algorithm given in  Devroye (1986, chapter 9)
         small_idx = find(a(double_idx)<1);
         big_idx = find(a(double_idx)>1);
         number_of_small_a = length(small_idx);
@@ -180,7 +180,7 @@ end
 gamma_variates = exprnd(ones(nn,1)).*X./(X+Y);
 
 
-function gamma_variates = berman_algorithm(a,b)    
+function gamma_variates = berman_algorithm(a,b)
 nn = length(a);
 mm = nn;
 aa = 1./a ;
@@ -206,7 +206,7 @@ Z = gamrnd(2*ones(nn,1),ones(nn,1));
 gamma_variates = Z.*X.*b ;
 
 
-function gamma_variates = ahrens_dieter_algorithm(a,b)    
+function gamma_variates = ahrens_dieter_algorithm(a,b)
 nn = length(a);
 mm = nn;
 bb = (exp(1)+a)/exp(1);
@@ -246,7 +246,7 @@ end
 gamma_variates = X.*b ;
 
 
-function gamma_variates = best_1983_algorithm(a,b)    
+function gamma_variates = best_1983_algorithm(a,b)
 nn = length(a);
 mm = nn;
 tt = .07 + .75*sqrt(1-a);
diff --git a/matlab/missing/stats/quantile.m b/matlab/missing/stats/quantile.m
index ec7dbfa64f08b7eb188cdc7096452ab0f0cc0798..a63baada00ed09511ebeb8df9317d8315eba4e2d 100644
--- a/matlab/missing/stats/quantile.m
+++ b/matlab/missing/stats/quantile.m
@@ -8,18 +8,18 @@ function [q,N] = quantile(X, p, dim, method, weights) % --*-- Unitary tests --*-
 %   a matrix, the i-th row of Q contains the P(i)-th quantiles of each
 %   column of X.  For N-D arrays, QUANTILE2 operates along the first
 %   non-singleton dimension.
-% 
+%
 %   Q = QUANTILE2(X,P,DIM) calculates quantiles along dimension DIM.  The
 %   DIM'th dimension of Q has length LENGTH(P).
-% 
+%
 %   Q = QUANTILE2(X,P,DIM,METHOD) calculates quantiles using one of the
 %   methods described in http://en.wikipedia.org/wiki/Quantile. The method
 %   are designated 'R-1'...'R-9'; the default is R-8 as described in
 %   http://bit.ly/1kX4NcT, whereas Matlab uses 'R-5'.
-%   
+%
 %   Q = QUANTILE2(X,P,[],METHOD) uses the specified METHOD, but calculates
 %   quantiles along the first non-singleton dimension.
-% 
+%
 %   Q = QUANTILE2(X,P,[],METHOD,WEIGHTS) and QUANTILE2(X,P,[],[],WEIGHTS)
 %   uses the array WEIGHTS to weight the values in X when calculating
 %   quantiles. If no weighting is specified, the method determines the
@@ -33,12 +33,12 @@ function [q,N] = quantile(X, p, dim, method, weights) % --*-- Unitary tests --*-
 %   equal, then the weighted and unweighted index (and correpsonding
 %   quantile) are identical. The default method R-8 is used if METHOD is
 %   specified as an empty array ([]).
-% 
+%
 %   [Q,N] = QUANTILE2(...) returns an array that is the same size as Q such
 %   that N(i) is the number of points used to calculate Q(i).
-% 
+%
 %   Further reading
-%   
+%
 %   Hyndman, R.J.; Fan, Y. (November 1996). "Sample Quantiles in
 %     Statistical Packages". The American Statistician 50 (4): 361-365.
 %   Frigge, Michael; Hoaglin, David C.; Iglewicz, Boris (February 1989).
@@ -47,9 +47,9 @@ function [q,N] = quantile(X, p, dim, method, weights) % --*-- Unitary tests --*-
 
 % Original file downloaded from:
 % http://fr.mathworks.com/matlabcentral/fileexchange/46555-quantile-calculation
-% 
-% Copyright (C) 2014-2016 University of Surrey (Christopher Hummersone) 
-% Copyright (C) 2016 Dynare Team
+%
+% Copyright (C) 2014-2016 University of Surrey (Christopher Hummersone)
+% Copyright (C) 2016-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -205,34 +205,34 @@ if numel(p)==numel(q)
 end
 
 function cumweights = accumulateWeights(weights, ind, n, N)
-   % ACCUMULATEWEIGHTS accumulate the weights
-    wSorted = weights(ind,n); % sort weights
-    wSorted = wSorted*N/sum(wSorted); % normalize weights to sum to N
-    cumweights = cumsum(wSorted); % cumulative weights
+% ACCUMULATEWEIGHTS accumulate the weights
+wSorted = weights(ind,n); % sort weights
+wSorted = wSorted*N/sum(wSorted); % normalize weights to sum to N
+cumweights = cumsum(wSorted); % cumulative weights
 
 function hw = weightedIndex(huw, cumweights)
-    % WEIGHTEDINDEX calculate index from cumulative weights
-    ii = find(sign(cumweights-huw)<0,1,'last');
-    jj = find(sign(cumweights-huw)>0,1,'first');
-    if isempty(ii) || isempty(jj)
-        hw = huw;
-    else
-        hw = ii + (huw-cumweights(ii))/(cumweights(jj)-cumweights(ii)); % weighted index
-    end
+% WEIGHTEDINDEX calculate index from cumulative weights
+ii = find(sign(cumweights-huw)<0,1,'last');
+jj = find(sign(cumweights-huw)>0,1,'first');
+if isempty(ii) || isempty(jj)
+    hw = huw;
+else
+    hw = ii + (huw-cumweights(ii))/(cumweights(jj)-cumweights(ii)); % weighted index
+end
 
 function y = isint(x)
-    % ISINT check if input is whole number
-    y = x==round(x);
+% ISINT check if input is whole number
+y = x==round(x);
 
 function y = rearrange(x,order,shape)
-    %REARRANGE reshape and permute to make target dim column
-    y = permute(x,order);
-    y = reshape(y,shape);
+%REARRANGE reshape and permute to make target dim column
+y = permute(x,order);
+y = reshape(y,shape);
 
 function y = irearrange(x,order,shape)
-    %IREARRANGE reshape and permute to original size
-    y = reshape(x,shape);
-    y = ipermute(y,order);
+%IREARRANGE reshape and permute to original size
+y = reshape(x,shape);
+y = ipermute(y,order);
 
 
 %@test:1
diff --git a/matlab/missing/stats/stdnormal_inv.m b/matlab/missing/stats/stdnormal_inv.m
index bc52845a562c105858abe3cf38baecbd81471167..9859efde700496be0b49b88bb01a7228ad52ad31 100644
--- a/matlab/missing/stats/stdnormal_inv.m
+++ b/matlab/missing/stats/stdnormal_inv.m
@@ -10,7 +10,7 @@ function inv = stdnormal_inv (x)
 
 % Copyright (C) 1995, 1996, 1997, 1998, 2000, 2002, 2005, 2006, 2007
 %               Kurt Hornik
-% Copyright (C) 2008-2009 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -34,4 +34,3 @@ end
 inv = sqrt (2) * erfinv (2 * x - 1);
 
 end
-
diff --git a/matlab/missing/stats/wblcdf.m b/matlab/missing/stats/wblcdf.m
index 14b0fc8e8fdeb85c8ffed3fd582ef844a933f2f9..6246a01cf99f69c86dd8ca120ff7ceb1e609d9bd 100644
--- a/matlab/missing/stats/wblcdf.m
+++ b/matlab/missing/stats/wblcdf.m
@@ -2,15 +2,15 @@ function p = wblcdf(x, scale, shape)   % --*-- Unitary tests --*--
 
 % Cumulative distribution function for the Weibull distribution.
 %
-% INPUTS 
+% INPUTS
 % - x     [double] Positive real scalar.
 % - scale [double] Positive hyperparameter.
 % - shape [double] Positive hyperparameter.
 %
-% OUTPUTS 
-% - p     [double] Positive scalar between 
+% OUTPUTS
+% - p     [double] Positive scalar between
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -58,7 +58,7 @@ if isinf(x)
     return
 end
 
-% Evaluate the CDF. 
+% Evaluate the CDF.
 
 p = 1-exp(-(x/scale)^shape);
 
@@ -146,4 +146,3 @@ p = 1-exp(-(x/scale)^shape);
 %$ end
 %$ T = all(t);
 %@eof:4
-
diff --git a/matlab/missing/stats/wblinv.m b/matlab/missing/stats/wblinv.m
index 1b87c9fcb88f51bf9578b7ceba94f5c8fb383243..363d5180192bdb0262bad5c57f743790dc4dadca 100644
--- a/matlab/missing/stats/wblinv.m
+++ b/matlab/missing/stats/wblinv.m
@@ -2,15 +2,15 @@ function t = wblinv(proba, scale, shape)   % --*-- Unitary tests --*--
 
 % Inverse cumulative distribution function.
 %
-% INPUTS 
+% INPUTS
 % - proba [double] Probability, scalar between 0 and 1.
 % - scale [double] Positive hyperparameter.
 % - shape [double] Positive hyperparameter.
 %
-% OUTPUTS 
+% OUTPUTS
 % - t     [double] scalar such that P(X<=t)=proba
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -156,7 +156,7 @@ t = exp(log(scale)+log(-log(1-proba))/shape);
 %$               [s, abs(p-s)]
 %$           end
 %$         if isoctave
-%$           t(k) = abs(p-s)<1e-10;  
+%$           t(k) = abs(p-s)<1e-10;
 %$         else
 %$           t(k) = abs(p-s)<1e-12;
 %$         end
@@ -165,4 +165,3 @@ t = exp(log(scale)+log(-log(1-proba))/shape);
 %$ end
 %$ T = all(t);
 %@eof:4
-
diff --git a/matlab/missing/stats/wblrnd.m b/matlab/missing/stats/wblrnd.m
index 2f55bc8b7709286efa2b94c9a43b8001e7be0275..e2a6911d9a54e143a1932a1cc51d297ebafdd633 100644
--- a/matlab/missing/stats/wblrnd.m
+++ b/matlab/missing/stats/wblrnd.m
@@ -1,14 +1,14 @@
 function rnd = wblrnd(a, b)
 % This function produces independent random variates from the Weibull distribution.
 %
-%  INPUTS 
+%  INPUTS
 %    a       [double]    m*n matrix of positive parameters (scale).
 %    b       [double]    m*n matrix of positive parameters (shape).
 %
-%  OUTPUT 
+%  OUTPUT
 %    rnd     [double]    m*n matrix of independent variates from the beta(a,b) distribution.
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/missing/struct2array/struct2array.m b/matlab/missing/struct2array/struct2array.m
new file mode 100644
index 0000000000000000000000000000000000000000..92aaab35fe5801fe68ec66cc5b3a12551d0a7882
--- /dev/null
+++ b/matlab/missing/struct2array/struct2array.m
@@ -0,0 +1,29 @@
+function a = struct2array(s)
+
+% INPUTS
+% - s  [struct]  with N fields, field i contains a n_i*m_i array of doubles.
+%
+% OUPUTS
+% - a  [double]  column vector with sum(n_i*m_i, i=1,...,N) elements.
+
+% Copyright (C) 2017 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(isstruct(s), 'struct2array:: Argument has to be a structure!')
+
+c = cellfun(@vec, struct2cell(s), 'UniformOutput', false);
+a = vertcat(c{:});
\ No newline at end of file
diff --git a/matlab/missing/vec/vec.m b/matlab/missing/vec/vec.m
index 225c5f9ec1e910bda2bd0f15013aa479f73e94a1..fd9e36b7908168ee4431193742ff9e3731078738 100644
--- a/matlab/missing/vec/vec.m
+++ b/matlab/missing/vec/vec.m
@@ -1,13 +1,13 @@
 function Vector = vec(Matrix)
 % This function implements the vec operator.
-% 
-% INPUTS 
+%
+% INPUTS
 %   Matrix             [double]   a squared n*n matrix.
-%    
-% OUTPUTS 
+%
+% OUTPUTS
 %   Vector             [double]   a n*n vector.
 
-% Copyright (C) 2009 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/missing_DiffuseKalmanSmootherH1_Z.m b/matlab/missing_DiffuseKalmanSmootherH1_Z.m
index a19d3fff6392455391fc18d332add47d3d04d14e..5ba614f945c059768ff3204063b8708da84e2ae0 100644
--- a/matlab/missing_DiffuseKalmanSmootherH1_Z.m
+++ b/matlab/missing_DiffuseKalmanSmootherH1_Z.m
@@ -5,10 +5,10 @@ function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,decomp,V] = missing_DiffuseK
 %
 % INPUTS
 %    T:        mm*mm matrix
-%    Z:        pp*mm matrix  
+%    Z:        pp*mm matrix
 %    R:        mm*rr matrix
 %    Q:        rr*rr matrix
-%    H:        pp*pp matrix variance of measurement errors    
+%    H:        pp*pp matrix variance of measurement errors
 %    Pinf1:    mm*mm diagonal matrix with with q ones and m-q zeros
 %    Pstar1:   mm*mm variance-covariance matrix with stationary variables
 %    Y:        pp*1 vector
@@ -22,7 +22,7 @@ function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,decomp,V] = missing_DiffuseK
 %    decomp_flag  if true, compute filter decomposition
 %    state_uncertainty_flag     if true, compute uncertainty about smoothed
 %                               state estimate
-%             
+%
 % OUTPUTS
 %    alphahat: smoothed variables (a_{t|T})
 %    epsilonhat:smoothed measurement errors
@@ -36,20 +36,20 @@ function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,decomp,V] = missing_DiffuseK
 %              matrices (meaningless for periods 1:d)
 %    decomp:   decomposition of the effect of shocks on filtered values
 %    V:        3D array of state uncertainty matrices
-%  
+%
 % Notes:
 %   Outputs are stored in decision-rule order, i.e. to get variables in order of declaration
 %   as in M_.endo_names, ones needs code along the lines of:
 %   variables_declaration_order(dr.order_var,:) = alphahat
-% 
+%
 % SPECIAL REQUIREMENTS
 %   See "Filtering and Smoothing of State Vector for Diffuse State Space
-%   Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series 
-%   Analysis, vol. 24(1), pp. 85-98). 
+%   Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
+%   Analysis, vol. 24(1), pp. 85-98).
 %   Durbin/Koopman (2012): "Time Series Analysis by State Space Methods", Oxford University Press,
 %   Second Edition, Ch. 5
 
-% Copyright (C) 2004-2016 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -70,7 +70,7 @@ function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,decomp,V] = missing_DiffuseK
 % new output argument aK (1-step to k-step predictions)
 % new options_.nk: the max step ahed prediction in aK (default is 4)
 % new crit1 value for rank of Pinf
-% it is assured that P is symmetric 
+% it is assured that P is symmetric
 
 d = 0;
 decomp = [];
@@ -92,9 +92,9 @@ Lstar           = zeros(mm,mm,smpl);
 Kstar           = zeros(mm,pp,smpl);
 Kinf            = zeros(mm,pp,smpl);
 P               = zeros(mm,mm,smpl+1);
-Pstar           = zeros(spstar(1),spstar(2),smpl+1); 
+Pstar           = zeros(spstar(1),spstar(2),smpl+1);
 Pstar(:,:,1)    = Pstar1;
-Pinf            = zeros(spinf(1),spinf(2),smpl+1); 
+Pinf            = zeros(spinf(1),spinf(2),smpl+1);
 Pinf(:,:,1)     = Pinf1;
 rr              = size(Q,1);
 QQ              = R*Q*transpose(R);
@@ -127,9 +127,9 @@ while rank(Pinf(:,:,t+1),diffuse_kalman_tol) && t<smpl
         ZZ = Z(di,:);                                                       %span selector matrix
         v(di,t)= Y(di,t) - ZZ*a(:,t);                                       %get prediction error v^(0) in (5.13) DK (2012)
         Finf = ZZ*Pinf(:,:,t)*ZZ';                                          % (5.7) in DK (2012)
-        if rcond(Finf) < diffuse_kalman_tol                                 %F_{\infty,t} = 0 
+        if rcond(Finf) < diffuse_kalman_tol                                 %F_{\infty,t} = 0
             if ~all(abs(Finf(:)) < diffuse_kalman_tol)                      %rank-deficient but not rank 0
-                % The univariate diffuse kalman filter should be used.
+                                                                            % The univariate diffuse kalman filter should be used.
                 alphahat = Inf;
                 return
             else                                                            %rank of F_{\infty,t} is 0
@@ -200,13 +200,13 @@ while notsteady && t<smpl
         if any(diag(F)<kalman_tol) || rcond(F./(sig*sig')) < kalman_tol
             alphahat = Inf;
             return
-        end    
+        end
         iF(di,di,t)   = inv(F./(sig*sig'))./(sig*sig');
         PZI         = P(:,:,t)*ZZ'*iF(di,di,t);
         atilde(:,t) = a(:,t) + PZI*v(di,t);
         K(:,di,t)    = T*PZI;
         L(:,:,t)    = T-K(:,di,t)*ZZ;
-		P(:,:,t+1)  = T*P(:,:,t)*L(:,:,t)' + QQ;
+        P(:,:,t+1)  = T*P(:,:,t)*L(:,:,t)' + QQ;
     end
     a(:,t+1)    = T*atilde(:,t);
     Pf          = P(:,:,t);
@@ -267,8 +267,8 @@ while t>d+1
     end
 end
 if d %diffuse periods
-    % initialize r_d^(0) and r_d^(1) as below DK (2012), eq. 5.23
-    r0 = zeros(mm,d+1); 
+     % initialize r_d^(0) and r_d^(1) as below DK (2012), eq. 5.23
+    r0 = zeros(mm,d+1);
     r0(:,d+1) = r(:,d+1);   %set r0_{d}, i.e. shifted by one period
     r1 = zeros(mm,d+1);     %set r1_{d}, i.e. shifted by one period
     if state_uncertainty_flag
@@ -284,7 +284,7 @@ if d %diffuse periods
             if ~Finf_singular(1,t)
                 r0(:,t) = Linf(:,:,t)'*r0(:,t+1);                                   % DK (2012), eq. 5.21 where L^(0) is named Linf
                 r1(:,t) = Z(di,:)'*(iFinf(di,di,t)*v(di,t)-Kstar(:,di,t)'*T'*r0(:,t+1)) ...
-                    + Linf(:,:,t)'*r1(:,t+1);                                       % DK (2012), eq. 5.21, noting that i) F^(1)=(F^Inf)^(-1)(see 5.10), ii) where L^(0) is named Linf, and iii) Kstar=T^{-1}*K^(1)
+                          + Linf(:,:,t)'*r1(:,t+1);                                       % DK (2012), eq. 5.21, noting that i) F^(1)=(F^Inf)^(-1)(see 5.10), ii) where L^(0) is named Linf, and iii) Kstar=T^{-1}*K^(1)
                 if state_uncertainty_flag
                     L_1=(-T*Kstar(:,di,t)*Z(di,:));                                     % noting that Kstar=T^{-1}*K^(1)
                     N(:,:,t)=Linf(:,:,t)'*N(:,:,t+1)*Linf(:,:,t);                       % DK (2012), eq. 5.19, noting that L^(0) is named Linf
@@ -301,7 +301,7 @@ if d %diffuse periods
                 r1(:,t) = T'*r1(:,t+1);                                             % DK (2003), eq. (14)
                 if state_uncertainty_flag
                     N(:,:,t)=Z(di,:)'*iFstar(di,di,t)*Z(di,:)...
-                        +Lstar(:,:,t)'*N(:,:,t+1)*Lstar(:,:,t);                     % DK (2003), eq. (14)
+                             +Lstar(:,:,t)'*N(:,:,t+1)*Lstar(:,:,t);                     % DK (2003), eq. (14)
                     N_1(:,:,t)=T'*N_1(:,:,t+1)*Lstar(:,:,t);                            % DK (2003), eq. (14)
                     N_2(:,:,t)=T'*N_2(:,:,t+1)*T';                                      % DK (2003), eq. (14)
                 end
@@ -311,9 +311,9 @@ if d %diffuse periods
         etahat(:,t)     = QRt*r0(:,t);                                              % DK (2012), p. 135
         if state_uncertainty_flag
             V(:,:,t)=Pstar(:,:,t)-Pstar(:,:,t)*N(:,:,t)*Pstar(:,:,t)...
-                -(Pinf(:,:,t)*N_1(:,:,t)*Pstar(:,:,t))'...
-                - Pinf(:,:,t)*N_1(:,:,t)*Pstar(:,:,t)...
-                - Pinf(:,:,t)*N_2(:,:,t)*Pinf(:,:,t);                                   % DK (2012), eq. 5.30
+                     -(Pinf(:,:,t)*N_1(:,:,t)*Pstar(:,:,t))'...
+                     - Pinf(:,:,t)*N_1(:,:,t)*Pstar(:,:,t)...
+                     - Pinf(:,:,t)*N_2(:,:,t)*Pinf(:,:,t);                                   % DK (2012), eq. 5.30
         end
     end
 end
diff --git a/matlab/missing_DiffuseKalmanSmootherH3_Z.m b/matlab/missing_DiffuseKalmanSmootherH3_Z.m
index c5beeedc735b38970dd4487c2922d080ebef54cf..de40741fcf29f4d0c203c1d61b6c12437700e9a6 100644
--- a/matlab/missing_DiffuseKalmanSmootherH3_Z.m
+++ b/matlab/missing_DiffuseKalmanSmootherH3_Z.m
@@ -43,20 +43,20 @@ function [alphahat,epsilonhat,etahat,a,P,aK,PK,decomp,V] = missing_DiffuseKalman
 %   variables_declaration_order(dr.order_var,:) = alphahat
 %
 % Algorithm:
-% 
+%
 %   Uses the univariate filter as described in Durbin/Koopman (2012): "Time
 %   Series Analysis by State Space Methods", Oxford University Press,
 %   Second Edition, Ch. 6.4 + 7.2.5
-%   and 
+%   and
 %   Koopman/Durbin (2000): "Fast Filtering and Smoothing for Multivariatze State Space
 %   Models", in Journal of Time Series Analysis, vol. 21(3), pp. 281-296.
 %
 % SPECIAL REQUIREMENTS
 %   See "Filtering and Smoothing of State Vector for Diffuse State Space
-%   Models", S.J. Koopman and J. Durbin (2003), in Journal of Time Series 
-%   Analysis, vol. 24(1), pp. 85-98. 
+%   Models", S.J. Koopman and J. Durbin (2003), in Journal of Time Series
+%   Analysis, vol. 24(1), pp. 85-98.
 
-% Copyright (C) 2004-2016 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -78,10 +78,10 @@ function [alphahat,epsilonhat,etahat,a,P,aK,PK,decomp,V] = missing_DiffuseKalman
 % New input argument nk: max order of predictions in aK
 
 
-if size(H,2)>1 
+if size(H,2)>1
     error('missing_DiffuseKalmanSmootherH3_Z:: H is not a vector. This must not happens')
 end
-    
+
 d = 0;
 decomp = [];
 spinf           = size(Pinf1);
@@ -100,9 +100,9 @@ Kinf            = zeros(spstar(1),pp,smpl);
 P               = zeros(mm,mm,smpl+1);
 P1              = P;
 PK              = zeros(nk,mm,mm,smpl+nk);
-Pstar           = zeros(spstar(1),spstar(2),smpl); 
+Pstar           = zeros(spstar(1),spstar(2),smpl);
 Pstar(:,:,1)    = Pstar1;
-Pinf            = zeros(spinf(1),spinf(2),smpl); 
+Pinf            = zeros(spinf(1),spinf(2),smpl);
 Pinf(:,:,1)     = Pinf1;
 Pstar1          = Pstar;
 Pinf1           = Pinf;
@@ -122,7 +122,11 @@ end
 
 t = 0;
 icc=0;
-newRank = rank(Pinf(:,:,1),diffuse_kalman_tol);
+if ~isempty(Pinf(:,:,1))
+    newRank = rank(Z*Pinf(:,:,1)*Z',diffuse_kalman_tol);
+else
+    newRank = rank(Pinf(:,:,1),diffuse_kalman_tol);
+end
 while newRank && t < smpl
     t = t+1;
     a(:,t) = a1(:,t);
@@ -131,13 +135,13 @@ while newRank && t < smpl
     di = data_index{t}';
     for i=di
         Zi = Z(i,:);
-        v(i,t)      = Y(i,t)-Zi*a(:,t);                                     % nu_{t,i} in 6.13 in DK (2012) 
+        v(i,t)      = Y(i,t)-Zi*a(:,t);                                     % nu_{t,i} in 6.13 in DK (2012)
         Fstar(i,t)  = Zi*Pstar(:,:,t)*Zi' +H(i);                            % F_{*,t} in 5.7 in DK (2012), relies on H being diagonal
         Finf(i,t)   = Zi*Pinf(:,:,t)*Zi';                                   % F_{\infty,t} in 5.7 in DK (2012)
         Kstar(:,i,t) = Pstar(:,:,t)*Zi';                                    % KD (2000), eq. (15)
         if Finf(i,t) > diffuse_kalman_tol && newRank                        % F_{\infty,t,i} = 0, use upper part of bracket on p. 175 DK (2012) for w_{t,i}
             icc=icc+1;
-            Kinf(:,i,t)       = Pinf(:,:,t)*Zi';                            % KD (2000), eq. (15)                         
+            Kinf(:,i,t)       = Pinf(:,:,t)*Zi';                            % KD (2000), eq. (15)
             Kinf_Finf         = Kinf(:,i,t)/Finf(i,t);
             a(:,t)            = a(:,t) + Kinf_Finf*v(i,t);                  % KD (2000), eq. (16)
             Pstar(:,:,t)      = Pstar(:,:,t) + ...
@@ -145,33 +149,41 @@ while newRank && t < smpl
                 Kstar(:,i,t)*Kinf_Finf' - ...
                 Kinf_Finf*Kstar(:,i,t)';                                    % KD (2000), eq. (16)
             Pinf(:,:,t)       = Pinf(:,:,t) - Kinf(:,i,t)*Kinf(:,i,t)'/Finf(i,t); % KD (2000), eq. (16)
-        elseif Fstar(i,t) > kalman_tol 
+        elseif Fstar(i,t) > kalman_tol
             a(:,t)            = a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t);    % KD (2000), eq. (17)
             Pstar(:,:,t)      = Pstar(:,:,t) - Kstar(:,i,t)*Kstar(:,i,t)'/Fstar(i,t);   % KD (2000), eq. (17)
-            % Pinf is passed through unaltered, see eq. (17) of
-            % Koopman/Durbin (2000)
+                                                                                        % Pinf is passed through unaltered, see eq. (17) of
+                                                                                        % Koopman/Durbin (2000)
         else
             % do nothing as a_{t,i+1}=a_{t,i} and P_{t,i+1}=P_{t,i}, see
-            % p. 157, DK (2012)        
+            % p. 157, DK (2012)
         end
     end
     if newRank
-        oldRank = rank(Pinf(:,:,t),diffuse_kalman_tol);
+        if ~isempty(Pinf(:,:,t))
+            oldRank = rank(Z*Pinf(:,:,t)*Z',diffuse_kalman_tol);
+        else
+            oldRank = rank(Pinf(:,:,t),diffuse_kalman_tol);
+        end
     else
         oldRank = 0;
     end
     a1(:,t+1) = T*a(:,t);
-    aK(1,:,t+1) = a1(:,t+1); 
+    aK(1,:,t+1) = a1(:,t+1);
     for jnk=2:nk
         aK(jnk,:,t+jnk) = T*dynare_squeeze(aK(jnk-1,:,t+jnk-1));
     end
     Pstar(:,:,t+1) = T*Pstar(:,:,t)*T'+ QQ;
     Pinf(:,:,t+1) = T*Pinf(:,:,t)*T';
     if newRank
-        newRank       = rank(Pinf(:,:,t+1),diffuse_kalman_tol);
+        if ~isempty(Pinf(:,:,t+1))
+            newRank = rank(Z*Pinf(:,:,t+1)*Z',diffuse_kalman_tol);
+        else
+            newRank = rank(Pinf(:,:,t+1),diffuse_kalman_tol);
+        end
     end
     if oldRank ~= newRank
-        disp('univariate_diffuse_kalman_filter:: T does influence the rank of Pinf!')   
+        disp('univariate_diffuse_kalman_filter:: T does influence the rank of Pinf!')
     end
 end
 
@@ -194,7 +206,7 @@ while notsteady && t<smpl
     for i=di
         Zi = Z(i,:);
         v(i,t)  = Y(i,t) - Zi*a(:,t);                                       % nu_{t,i} in 6.13 in DK (2012)
-        Fi(i,t) = Zi*P(:,:,t)*Zi' + H(i);                                   % F_{t,i} in 6.13 in DK (2012), relies on H being diagonal 
+        Fi(i,t) = Zi*P(:,:,t)*Zi' + H(i);                                   % F_{t,i} in 6.13 in DK (2012), relies on H being diagonal
         Ki(:,i,t) = P(:,:,t)*Zi';                                           % K_{t,i}*F_(i,t) in 6.13 in DK (2012)
         if Fi(i,t) > kalman_tol
             a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t);                     %filtering according to (6.13) in DK (2012)
@@ -204,18 +216,18 @@ while notsteady && t<smpl
             % p. 157, DK (2012)
         end
     end
-    a1(:,t+1) = T*a(:,t);                                                   %transition according to (6.14) in DK (2012) 
+    a1(:,t+1) = T*a(:,t);                                                   %transition according to (6.14) in DK (2012)
     Pf          = P(:,:,t);
-    aK(1,:,t+1) = a1(:,t+1); 
+    aK(1,:,t+1) = a1(:,t+1);
     for jnk=1:nk
         Pf = T*Pf*T' + QQ;
         PK(jnk,:,:,t+jnk) = Pf;
         if jnk>1
-            aK(jnk,:,t+jnk) = T*dynare_squeeze(aK(jnk-1,:,t+jnk-1));    
+            aK(jnk,:,t+jnk) = T*dynare_squeeze(aK(jnk-1,:,t+jnk-1));
         end
     end
-    P(:,:,t+1) = T*P(:,:,t)*T' + QQ;                                        %transition according to (6.14) in DK (2012) 
-    %  notsteady   = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<kalman_tol);
+    P(:,:,t+1) = T*P(:,:,t)*T' + QQ;                                        %transition according to (6.14) in DK (2012)
+                                                                            %  notsteady   = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<kalman_tol);
 end
 % $$$ P_s=tril(P(:,:,t))+tril(P(:,:,t),-1)';
 % $$$ P1_s=tril(P1(:,:,t))+tril(P1(:,:,t),-1)';
@@ -267,18 +279,18 @@ while t > d+1
             end
         end
     end
-    r(:,t) = ri;                                                            % DK (2012), below 6.15, r_{t-1}=r_{t,0} 
+    r(:,t) = ri;                                                            % DK (2012), below 6.15, r_{t-1}=r_{t,0}
     alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t);
     etahat(:,t) = QRt*r(:,t);
-    ri = T'*ri;                                                             % KD (2003), eq. (23), equation for r_{t-1,p_{t-1}} 
+    ri = T'*ri;                                                             % KD (2003), eq. (23), equation for r_{t-1,p_{t-1}}
     if state_uncertainty_flag
-        N(:,:,t) = Ni;                                                          % DK (2012), below 6.15, N_{t-1}=N_{t,0} 
+        N(:,:,t) = Ni;                                                          % DK (2012), below 6.15, N_{t-1}=N_{t,0}
         V(:,:,t) = P1(:,:,t)-P1(:,:,t)*N(:,:,t)*P1(:,:,t);                      % KD (2000), eq. (7) with N_{t-1} stored in N(:,:,t)
-        Ni = T'*Ni*T;                                                           % KD (2000), eq. (23), equation for N_{t-1,p_{t-1}} 
+        Ni = T'*Ni*T;                                                           % KD (2000), eq. (23), equation for N_{t-1,p_{t-1}}
     end
 end
 if d
-    r0 = zeros(mm,d); 
+    r0 = zeros(mm,d);
     r0(:,d) = ri;
     r1 = zeros(mm,d);
     if state_uncertainty_flag
@@ -292,10 +304,10 @@ if d
         di = flipud(data_index{t})';
         for i = di
             if Finf(i,t) > diffuse_kalman_tol
-                % recursions need to be from highest to lowest term in order to not 
+                % recursions need to be from highest to lowest term in order to not
                 % overwrite lower terms still needed in this step
                 Linf    = eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t);
-                L0      = (Kinf(:,i,t)*(Fstar(i,t)/Finf(i,t))-Kstar(:,i,t))*Z(i,:)/Finf(i,t);            
+                L0      = (Kinf(:,i,t)*(Fstar(i,t)/Finf(i,t))-Kstar(:,i,t))*Z(i,:)/Finf(i,t);
                 r1(:,t) = Z(i,:)'*v(i,t)/Finf(i,t) + ...
                           L0'*r0(:,t) + ...
                           Linf'*r1(:,t);   % KD (2000), eq. (25) for r_1
@@ -323,9 +335,9 @@ if d
         etahat(:,t)   = QRt*r(:,t);                                         % KD (2000), eq. (27)
         if state_uncertainty_flag
             V(:,:,t)=Pstar(:,:,t)-Pstar(:,:,t)*N_0(:,:,t)*Pstar(:,:,t)...
-                -(Pinf(:,:,t)*N_1(:,:,t)*Pstar(:,:,t))'...
-                - Pinf(:,:,t)*N_1(:,:,t)*Pstar(:,:,t)...
-                - Pinf(:,:,t)*N_2(:,:,t)*Pinf(:,:,t);                       % DK (2012), eq. 5.30
+                     -(Pinf(:,:,t)*N_1(:,:,t)*Pstar(:,:,t))'...
+                     - Pinf(:,:,t)*N_1(:,:,t)*Pstar(:,:,t)...
+                     - Pinf(:,:,t)*N_2(:,:,t)*Pinf(:,:,t);                       % DK (2012), eq. 5.30
         end
         if t > 1
             r0(:,t-1) = T'*r0(:,t);                                         % KD (2000), below eq. (25) r_{t-1,p_{t-1}}=T'*r_{t,0}
@@ -350,11 +362,11 @@ if decomp_flag
                 ri_d = Z(i,:)'/Fi(i,t)*v(i,t)+ri_d-Ki(:,i,t)'*ri_d/Fi(i,t)*Z(i,:)';
             end
         end
-        
+
         % calculate eta_tm1t
         eta_tm1t = QRt*ri_d;
         % calculate decomposition
-        Ttok = eye(mm,mm); 
+        Ttok = eye(mm,mm);
         AAA = P1(:,:,t)*Z'*ZRQinv*Z*R;
         for h = 1:nk
             BBB = Ttok*AAA;
@@ -367,3 +379,9 @@ if decomp_flag
 end
 
 epsilonhat = Y - Z*alphahat;
+
+
+if (d==smpl)
+    warning(['missing_DiffuseKalmanSmootherH3_Z:: There isn''t enough information to estimate the initial conditions of the nonstationary variables']);
+    return
+end
diff --git a/matlab/mode_check.m b/matlab/mode_check.m
index 8d216bcbfe3ab13dd654a4ae674afc5453b7d7b6..2df26ff0c520a20b90e07a988c427e862ed922eb 100644
--- a/matlab/mode_check.m
+++ b/matlab/mode_check.m
@@ -40,7 +40,7 @@ function mode_check(fun,x,hessian_mat,DynareDataset,DatasetInfo,DynareOptions,Mo
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2003-2016 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -58,13 +58,13 @@ function mode_check(fun,x,hessian_mat,DynareDataset,DatasetInfo,DynareOptions,Mo
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 TeX = DynareOptions.TeX;
-if ~isempty(hessian_mat);
+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_mat);
+if ~isempty(hessian_mat)
     skipline()
     disp('MODE CHECK')
     skipline()
@@ -85,18 +85,18 @@ if TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
 end
 
 ll = DynareOptions.mode_check.neighbourhood_size;
-if isinf(ll),
+if isinf(ll)
     DynareOptions.mode_check.symmetric_plots = 0;
 end
 
 mcheck = struct('cross',struct(),'emode',struct());
 
-for plt = 1:nbplt,
+for plt = 1:nbplt
     if TeX
         NAMES = [];
         TeXNAMES = [];
     end
-    hh = dyn_figure(DynareOptions,'Name','Mode check plots');
+    hh = dyn_figure(DynareOptions.nodisplay,'Name','Mode check plots');
     for k=1:min(nstar,length(x)-(plt-1)*nstar)
         subplot(nr,nc,k)
         kk = (plt-1)*nstar+k;
@@ -121,7 +121,7 @@ for plt = 1:nbplt,
         elseif isequal(x(kk),BoundsInfo.ub(kk))
             binding_upper_bound=1;
             bound_value=BoundsInfo.ub(kk);
-        end      
+        end
         if DynareOptions.mode_check.symmetric_plots && ~binding_lower_bound && ~binding_upper_bound
             if l2<(1+ll)*x(kk) %test whether upper bound is too small due to prior binding
                 l1 = x(kk) - (l2-x(kk)); %adjust lower bound to become closer
@@ -134,7 +134,7 @@ for plt = 1:nbplt,
         z1 = l1:((x(kk)-l1)/(DynareOptions.mode_check.number_of_points/2)):x(kk);
         z2 = x(kk):((l2-x(kk))/(DynareOptions.mode_check.number_of_points/2)):l2;
         z  = union(z1,z2);
-        if DynareOptions.mode_check.nolik==0,
+        if DynareOptions.mode_check.nolik==0
             y = zeros(length(z),2);
             dy = priordens(xx,BayesInfo.pshape,BayesInfo.p6,BayesInfo.p7,BayesInfo.p3,BayesInfo.p4);
         end
@@ -174,7 +174,7 @@ for plt = 1:nbplt,
         hold off
         drawnow
     end
-    if DynareOptions.mode_check.nolik==0,
+    if DynareOptions.mode_check.nolik==0
         if isoctave
             axes('outerposition',[0.3 0.93 0.42 0.07],'box','on'),
         else
@@ -187,7 +187,7 @@ for plt = 1:nbplt,
         text(0.25,0.5,'log-post')
         text(0.69,0.5,'log-lik kernel')
     end
-    dyn_saveas(hh,[ Model.fname '_CheckPlots' int2str(plt) ],DynareOptions);
+    dyn_saveas(hh,[ Model.fname '_CheckPlots' int2str(plt) ],DynareOptions.nodisplay,DynareOptions.graph_format);
     if TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
         % TeX eps loader file
         fprintf(fidTeX,'\\begin{figure}[H]\n');
@@ -203,7 +203,7 @@ for plt = 1:nbplt,
     end
 end
 if TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
-        fclose(fidTeX);
+    fclose(fidTeX);
 end
 
 OutputDirectoryName = CheckPath('modecheck',Model.dname);
diff --git a/matlab/model_comparison.m b/matlab/model_comparison.m
index fd179b454030846539911c8da97e9b3dd702a781..07935af6f79ba0adac85a35d6767379a0a11a08f 100644
--- a/matlab/model_comparison.m
+++ b/matlab/model_comparison.m
@@ -5,9 +5,9 @@ function oo = model_comparison(ModelNames,ModelPriors,oo,options_,fname)
 %
 % INPUTS
 %    ModelNames       [string]     m*1 cell array of string.
-%    ModelPriors      [double]     m*1 vector of prior probabilities 
+%    ModelPriors      [double]     m*1 vector of prior probabilities
 %    oo               [struct]     Dynare results structure
-%    options_         [struct]     Dynare options structure 
+%    options_         [struct]     Dynare options structure
 %    fname            [string]     name of the current mod-file
 %
 % OUTPUTS
@@ -20,7 +20,7 @@ function oo = model_comparison(ModelNames,ModelPriors,oo,options_,fname)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2007-2015 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -61,14 +61,14 @@ if isfield(options_,'mc_marginal_density')
     type = options_.mc_marginal_density;
     if strcmp(type,'laplace') || strcmp(type,'Laplace')
         type = 'LaplaceApproximation';
-        title = 'Model Comparison (based on Laplace approximation)'; 
-    elseif strcmp(type,'modifiedharmonicmean') || strcmp(type,'ModifiedHarmonicMean') 
+        title = 'Model Comparison (based on Laplace approximation)';
+    elseif strcmp(type,'modifiedharmonicmean') || strcmp(type,'ModifiedHarmonicMean')
         type = 'ModifiedHarmonicMean';
-        title = 'Model Comparison (based on Modified Harmonic Mean Estimator)'; 
+        title = 'Model Comparison (based on Modified Harmonic Mean Estimator)';
     end
 else
     type = 'LaplaceApproximation';
-    title = 'Model Comparison (based on Laplace approximation)'; 
+    title = 'Model Comparison (based on Laplace approximation)';
 end
 
 % Get the estimated logged marginal densities.
@@ -87,7 +87,7 @@ for i=1:NumberOfModels
         end
     end
     try
-        eval(['MarginalLogDensity(i) = mstruct.oo_.MarginalDensity.' type ';']) 
+        eval(['MarginalLogDensity(i) = mstruct.oo_.MarginalDensity.' type ';'])
     catch
         if strcmpi(type,'LaplaceApproximation')
             if isfield(mstruct.oo_,'mle_mode')
@@ -119,13 +119,13 @@ if prior_flag
     labels = char('Priors','Log Marginal Density','Bayes Ratio', ...
                   'Posterior Model Probability');
     field_labels={'Prior','Log_Marginal_Density','Bayes_Ratio', ...
-                  'Posterior_Model_Probability'};          
+                  'Posterior_Model_Probability'};
     values = [ModelPriors';MarginalLogDensity';exp(lmpd-lmpd(1))'; ...
               elmpd'/sum(elmpd)];
 else
     labels = char('Priors','Log Marginal Density','Bayes Ratio','Posterior Odds Ratio', ...
                   'Posterior Model Probability');
-    field_labels={'Prior','Log_Marginal_Density','Bayes_Ratio','Posterior_Odds_Ratio','Posterior_Model_Probability'};          
+    field_labels={'Prior','Log_Marginal_Density','Bayes_Ratio','Posterior_Odds_Ratio','Posterior_Model_Probability'};
     values = [ModelPriors';MarginalLogDensity'; exp(MarginalLogDensity-MarginalLogDensity(1))'; ...
               exp(lmpd-lmpd(1))'; elmpd'/sum(elmpd)];
 end
@@ -148,7 +148,7 @@ if options_.TeX
     for ii=1:size(labels,1)
         labels_tex=strvcat(labels_tex,strrep(labels(ii,:),' ', '\ '));
     end
-    
+
     dyn_latex_table(M_temp,options_,title,['model_comparison',type],headers_tex,labels_tex,values,0,16,6);
 end
 
diff --git a/matlab/model_diagnostics.m b/matlab/model_diagnostics.m
index 32a01725d5ce875b7485a7932fa398278fdec847..6734291150c15a64b4f3de89f829fb1aa44a6db5 100644
--- a/matlab/model_diagnostics.m
+++ b/matlab/model_diagnostics.m
@@ -1,22 +1,22 @@
 function model_diagnostics(M,options,oo)
 % function model_diagnostics(M,options,oo)
-%   computes various diagnostics on the model 
+%   computes various diagnostics on the model
 % INPUTS
-%   M         [matlab structure] Definition of the model.           
+%   M         [matlab structure] Definition of the model.
 %   options   [matlab structure] Global options.
-%   oo        [matlab structure] Results 
-%    
+%   oo        [matlab structure] Results
+%
 % OUTPUTS
 %   none
-%    
+%
 % ALGORITHM
 %   ...
-%    
+%
 % SPECIAL REQUIREMENTS
 %   none.
-%  
+%
 
-% Copyright (C) 1996-2013 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -67,7 +67,7 @@ end
 info=test_for_deep_parameters_calibration(M);
 if info
     problem_dummy=1;
-end;
+end
 
 % check if ys is steady state
 options.debug=1; %locally set debug option to 1
@@ -83,7 +83,7 @@ if check1(1)
     if any(isinf(dr.ys))
         disp(['MODEL_DIAGNOSTICS: Steady state contains Inf'])
     end
-    return;
+    return
 end
 
 if ~isreal(dr.ys)
@@ -108,7 +108,7 @@ for b=1:nb
     if options.bytecode
         if nb == 1
             [chk, res, jacob] = bytecode(dr.ys, exo, M.params, dr.ys, 1, exo, ...
-                                    'evaluate', 'static');
+                                         'evaluate', 'static');
         else
             [chk, res, jacob] = bytecode(dr.ys, exo, M.params, dr.ys, 1, exo, ...
                                          'evaluate', 'static',['block=' ...
@@ -173,8 +173,8 @@ for b=1:nb
         end
     end
 end
-    
-if singularity_problem 
+
+if singularity_problem
     try
         options_check=options;
         options_check.noprint=1;
@@ -205,29 +205,29 @@ if ~options.block
     if options.order == 1
         if (options.bytecode)
             [chck, junk, loc_dr] = bytecode('dynamic','evaluate', z,exo_simul, ...
-                M.params, dr.ys, 1);
+                                            M.params, dr.ys, 1);
             jacobia_ = [loc_dr.g1 loc_dr.g1_x loc_dr.g1_xd];
         else
             [junk,jacobia_] = feval([M.fname '_dynamic'],z(iyr0),exo_simul, ...
-                M.params, dr.ys, it_);
-        end;
+                                    M.params, dr.ys, it_);
+        end
     elseif options.order >= 2
         if (options.bytecode)
             [chck, junk, loc_dr] = bytecode('dynamic','evaluate', z,exo_simul, ...
-                M.params, dr.ys, 1);
+                                            M.params, dr.ys, 1);
             jacobia_ = [loc_dr.g1 loc_dr.g1_x];
         else
             [junk,jacobia_,hessian1] = feval([M.fname '_dynamic'],z(iyr0),...
-                exo_simul, ...
-                M.params, dr.ys, it_);
-        end;
+                                             exo_simul, ...
+                                             M.params, dr.ys, it_);
+        end
         if options.use_dll
             % In USE_DLL mode, the hessian is in the 3-column sparse representation
             hessian1 = sparse(hessian1(:,1), hessian1(:,2), hessian1(:,3), ...
-                size(jacobia_, 1), size(jacobia_, 2)*size(jacobia_, 2));
+                              size(jacobia_, 1), size(jacobia_, 2)*size(jacobia_, 2));
         end
     end
-    
+
     if any(any(isinf(jacobia_) | isnan(jacobia_)))
         problem_dummy=1;
         [infrow,infcol]=find(isinf(jacobia_) | isnan(jacobia_));
@@ -245,7 +245,7 @@ if ~options.block
             problem_dummy=1;
             fprintf('\nMODEL_DIAGNOSTICS: The Hessian of the dynamic model contains Inf or NaN.\n')
         end
-    end    
+    end
 else
     fprintf('\nMODEL_DIAGNOSTICS: This command currently does not support the block option for checking.\n')
     fprintf('\nMODEL_DIAGNOSTICS: the dynamic model. You may want to disable it for doing model_diagnostics. Skipping this part.\n')
@@ -254,4 +254,3 @@ end
 if problem_dummy==0
     fprintf('MODEL_DIAGNOSTICS:  No obvious problems with this mod-file were detected.\n')
 end
-
diff --git a/matlab/model_info.m b/matlab/model_info.m
index d99ca48078556c0b21d07cfa4ce9dc0ea2106159..e277792253b1a842d9af335dd94bdbdcad45408c 100644
--- a/matlab/model_info.m
+++ b/matlab/model_info.m
@@ -1,7 +1,7 @@
-function model_info(varargin);
+function model_info(varargin)
 %function model_info;
 
-% Copyright (C) 2008-2012 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -23,27 +23,27 @@ if sum(strcmp(varargin,'static')) > 0
     static_ = 1;
 else
     static_ = 0;
-end;
+end
 if sum(strcmp(varargin,'incidence')) > 0
     incidence = 1;
 else
     incidence = 0;
-end;
+end
 if static_
-        fprintf('                                          Informations about %s (static model)\n',M_.fname);
-        block_structre_str = 'block_structure_stat';
-        nb_leadlag = 1;
-    else
-        fprintf('                                          Informations about %s (dynamic model)\n',M_.fname);
-        block_structre_str = 'block_structure';
-        nb_leadlag = 3;
-    end;
+    fprintf('                                          Informations about %s (static model)\n',M_.fname);
+    block_structre_str = 'block_structure_stat';
+    nb_leadlag = 1;
+else
+    fprintf('                                          Informations about %s (dynamic model)\n',M_.fname);
+    block_structre_str = 'block_structure';
+    nb_leadlag = 3;
+end
 if(isfield(M_,block_structre_str))
     if static_
         block_structure = M_.block_structure_stat;
     else
         block_structure = M_.block_structure;
-    end;
+    end
     fprintf(strcat('                                          ===================',char(ones(1,length(M_.fname))*'='),'\n\n'));
     nb_blocks=length(block_structure.block);
     fprintf('The model has %d equations and is decomposed in %d blocks as follow:\n',M_.endo_nbr,nb_blocks);
@@ -54,15 +54,15 @@ if(isfield(M_,block_structre_str))
         size_block=length(block_structure.block(i).equation);
         if(i>1)
             fprintf('|------------|------------|--------------------------------|----------------|---------------------------------|\n');
-        end;
+        end
         for j=1:size_block
             if(j==1)
                 fprintf('| %10d | %10d | %30s | %14d | %-6d %24s |\n',i,size_block,Sym_type(block_structure.block(i).Simulation_Type),block_structure.block(i).equation(j),block_structure.block(i).variable(j),M_.endo_names(block_structure.block(i).variable(j),:));
             else
                 fprintf('| %10s | %10s | %30s | %14d | %-6d %24s |\n','','','',block_structure.block(i).equation(j),block_structure.block(i).variable(j),M_.endo_names(block_structure.block(i).variable(j),:));
-            end;
-        end;
-    end;
+            end
+        end
+    end
     fprintf('===============================================================================================================\n');
     fprintf('\n');
     if static_
@@ -71,16 +71,16 @@ if(isfield(M_,block_structre_str))
             IM=sortrows(block_structure.incidence.sparse_IM,2);
         else
             IM=[];
-        end;
+        end
         size_IM=size(IM,1);
         last=99999999;
         for i=1:size_IM
             if(last~=IM(i,2))
                 fprintf('\n%-30s',M_.endo_names(IM(i,2),:));
-            end;
+            end
             fprintf(' %5d',IM(i,1));
             last=IM(i,2);
-        end;
+        end
         fprintf('\n\n');
     else
         for k=1:M_.maximum_endo_lag+M_.maximum_endo_lead+1
@@ -90,25 +90,25 @@ if(isfield(M_,block_structre_str))
                 fprintf('%-30s %s %d','the variable','is used in equations with lag ',M_.maximum_endo_lag+1-k);
             else
                 fprintf('%-30s %s %d','the variable','is used in equations with lead ',k-(M_.maximum_endo_lag+1));
-            end;
+            end
             if(size(block_structure.incidence(k).sparse_IM,1)>0)
                 IM=sortrows(block_structure.incidence(k).sparse_IM,2);
             else
                 IM=[];
-            end;
+            end
             size_IM=size(IM,1);
             last=99999999;
             for i=1:size_IM
                 if(last~=IM(i,2))
                     fprintf('\n%-30s',M_.endo_names(IM(i,2),:));
-                end;
+                end
                 fprintf(' %5d',IM(i,1));
                 last=IM(i,2);
-            end;
+            end
             fprintf('\n\n');
-        end;
-    end;
-    
+        end
+    end
+
     %printing the gross incidence matrix
     IM_star = char([kron(ones(M_.endo_nbr, M_.endo_nbr-1), double(blanks(3))) double(blanks(M_.endo_nbr)')]);
     for i = 1:nb_leadlag
@@ -118,9 +118,9 @@ if(isfield(M_,block_structre_str))
                 IM_star(block_structure.incidence(i).sparse_IM(j,1), 3 * (block_structure.incidence(i).sparse_IM(j,2) - 1) + 1) = 'X';
             else
                 IM_star(block_structure.incidence(i).sparse_IM(j,1), 3 * (block_structure.incidence(i).sparse_IM(j,2) - 1) + 1) = '1';
-            end;
-        end;
-    end;
+            end
+        end
+    end
     seq = 1: M_.endo_nbr;
     blank = [ blanks(size(M_.endo_names,2)); blanks(size(M_.endo_names,2))];
     for i = 1:M_.endo_nbr
@@ -128,15 +128,15 @@ if(isfield(M_,block_structre_str))
             var_names = [blank; M_.endo_names(i,:)];
         else
             var_names = [var_names; blank; M_.endo_names(i,:)];
-        end;
-    end;
+        end
+    end
     if incidence
         topp = [char(kron(double(blanks(ceil(log10(M_.endo_nbr)))),ones(size(M_.endo_names,2),1))) var_names' ];
         bott = [int2str(seq') blanks(M_.endo_nbr)' blanks(M_.endo_nbr)' IM_star];
         fprintf('\n                                          Gross incidence matrix\n');
         fprintf('                                          =======================\n');
         disp([topp; bott]);
-    
+
         %printing the reordered incidence matrix
         IM_star_reordered = char([kron(ones(M_.endo_nbr, M_.endo_nbr-1), double(blanks(3))) double(blanks(M_.endo_nbr)')]);
         eq(block_structure.equation_reordered) = seq;
@@ -145,9 +145,9 @@ if(isfield(M_,block_structre_str))
         cur_block = 1;
         for i = 1:M_.endo_nbr
             past_block = cur_block;
-            while ismember(block_structure.variable_reordered(i), block_structure.block(cur_block).variable) == 0;
+            while ismember(block_structure.variable_reordered(i), block_structure.block(cur_block).variable) == 0
                 cur_block = cur_block + 1;
-            end;
+            end
             if i == 1
                 var_names = [blank; M_.endo_names(block_structure.variable_reordered(i),:)];
             else
@@ -156,8 +156,8 @@ if(isfield(M_,block_structre_str))
                 else
                     var_names = [var_names; blank; M_.endo_names(block_structure.variable_reordered(i),:)];
                 end
-            end;
-        end;
+            end
+        end
         topp = [char(kron(double(blanks(ceil(log10(M_.endo_nbr)))),ones(size(M_.endo_names,2),1))) var_names' ];
         n_state_var = length(M_.state_var);
         IM_state_var = zeros(n_state_var, n_state_var);
@@ -172,49 +172,49 @@ if(isfield(M_,block_structre_str))
                     [tfi, loci] = ismember(block_structure.incidence(i).sparse_IM(j,1), state_equation);
                     if tfi
                         IM_state_var(loci, loc) = 1;
-                    end;
+                    end
                 else
                     IM_star_reordered(eq(block_structure.incidence(i).sparse_IM(j,1)), 3 * (va(block_structure.incidence(i).sparse_IM(j,2)) - 1) + 1) = '1';
-                end;
-            end;
-        end;
+                end
+            end
+        end
         fprintf('1: non nul element, X: non nul element related to a state variable\n');
-        
+
         cur_block = 1;
         i_last = 0;
         block = {};
-        for i = 1:n_state_var;
+        for i = 1:n_state_var
             past_block = cur_block;
-            while ismember(M_.state_var(i), block_structure.block(cur_block).variable) == 0;
+            while ismember(M_.state_var(i), block_structure.block(cur_block).variable) == 0
                 cur_block = cur_block + 1;
-            end;
+            end
             if (past_block ~= cur_block) || (past_block == cur_block && i == n_state_var)
                 block(past_block).IM_state_var(1:(i - 1 - i_last), 1:i - 1) = IM_state_var(i_last+1:i - 1, 1:i - 1);
                 i_last = i - 1;
-            end;
-        end;
+            end
+        end
         cur_block = 1;
         for i = 1:M_.endo_nbr
             past_block = cur_block;
-            while ismember(block_structure.variable_reordered(i), block_structure.block(cur_block).variable) == 0;
+            while ismember(block_structure.variable_reordered(i), block_structure.block(cur_block).variable) == 0
                 cur_block = cur_block + 1;
-            end;
+            end
             if past_block ~= cur_block
                 for j = 1:i-1
-                   IM_star_reordered(j, 3 * (i - 1) - 1) = '|';
-                end;
-            end;
+                    IM_star_reordered(j, 3 * (i - 1) - 1) = '|';
+                end
+            end
         end
-        
+
         bott = [int2str(block_structure.equation_reordered') blanks(M_.endo_nbr)' blanks(M_.endo_nbr)' IM_star_reordered];
         fprintf('\n                                          Reordered incidence matrix\n');
         fprintf('                                          ==========================\n');
         disp([topp; bott]);
         fprintf('1: non nul element, X: non nul element related to a state variable\n');
-     end;
+    end
 else
     fprintf('There is no block decomposition of the model.\nUse ''block'' model''s option.\n');
-end;
+end
 
 function ret=Sym_type(type)
 UNKNOWN=0;
@@ -229,33 +229,30 @@ SOLVE_TWO_BOUNDARIES_COMPLETE=8;
 EVALUATE_FORWARD_R=9;
 EVALUATE_BACKWARD_R=10;
 switch (type)
-  case (UNKNOWN),
+  case (UNKNOWN)
     ret='UNKNOWN                     ';
-  case {EVALUATE_FORWARD,EVALUATE_FORWARD_R},
+  case {EVALUATE_FORWARD,EVALUATE_FORWARD_R}
     ret='EVALUATE FORWARD            ';
-  case {EVALUATE_BACKWARD,EVALUATE_BACKWARD_R},
+  case {EVALUATE_BACKWARD,EVALUATE_BACKWARD_R}
     ret='EVALUATE BACKWARD            ';
-  case SOLVE_FORWARD_SIMPLE,
+  case SOLVE_FORWARD_SIMPLE
     ret='SOLVE FORWARD SIMPLE        ';
-  case SOLVE_BACKWARD_SIMPLE,
+  case SOLVE_BACKWARD_SIMPLE
     ret='SOLVE BACKWARD SIMPLE        ';
-  case SOLVE_TWO_BOUNDARIES_SIMPLE,
+  case SOLVE_TWO_BOUNDARIES_SIMPLE
     ret='SOLVE TWO BOUNDARIES SIMPLE  ';
-  case SOLVE_FORWARD_COMPLETE,
+  case SOLVE_FORWARD_COMPLETE
     ret='SOLVE FORWARD COMPLETE      ';
-  case SOLVE_BACKWARD_COMPLETE,
+  case SOLVE_BACKWARD_COMPLETE
     ret='SOLVE BACKWARD COMPLETE      ';
-  case SOLVE_TWO_BOUNDARIES_COMPLETE,
+  case SOLVE_TWO_BOUNDARIES_COMPLETE
     ret='SOLVE TWO BOUNDARIES COMPLETE';
-end;
+end
 
 
 function ret = barre(n)
 s = [];
-for i=1:n;
+for i=1:n
     s = [s '|'];
-end;
+end
 ret = s;
-
-
-
diff --git a/matlab/model_inversion.m b/matlab/model_inversion.m
new file mode 100644
index 0000000000000000000000000000000000000000..4d01412f98d1306af26b539ae98b8f5140af0240
--- /dev/null
+++ b/matlab/model_inversion.m
@@ -0,0 +1,106 @@
+function [endogenousvariables, exogenousvariables] = model_inversion(constraints, ...
+                                                  exogenousvariables, ...
+                                                  initialconditions, DynareModel, DynareOptions, DynareOutput)
+
+% INPUTS
+% - constraints         [dseries]        with N constrained endogenous variables from t1 to t2.
+% - exogenousvariables  [dseries]        with Q exogenous variables.
+% - initialconditions   [dseries]        with M endogenous variables starting before t1 (M initialcond must contain at least the state variables).
+% - DynareModel         [struct]         M_, Dynare global structure containing informations related to the model.
+% - DynareOptions       [struct]         options_, Dynare global structure containing all the options.
+%
+% OUTPUTS
+% - endogenous          [dseries]
+% - exogenous           [dseries]
+%
+% REMARKS
+
+% Copyright (C) 2017 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+if ~isequal(nargin, 6)
+    error('model_inversion: This routine require six input arguments!')
+end
+
+if ~isdseries(constraints)
+    error('model_inversion: First input argument must be a dseries object!')
+end
+
+if ~isdseries(exogenousvariables)
+    error('model_inversion: Second input argument must be a dseries object!')
+end
+
+if ~isdseries(initialconditions)
+    error('model_inversion: Third input argument must be a dseries object!')
+end
+
+if ~isstruct(DynareModel)
+    error('model_inversion: Last input argument must be structures (M_)!')
+end
+
+% Set range where the endogenous variables are constrained.
+crange = constraints.dates;
+
+% Check that the number of instruments match the number of constrained endogenous variables.
+instruments = exogenousvariables(crange);
+freeinnovations = instruments.name(find(all(isnan(instruments))));
+if ~isequal(length(freeinnovations), constraints.vobs)
+    error('model_inversion: The number of instruments must be equal to the number of constrained variables!')
+end
+
+% Check if some of the exogenous variables are given.
+observed_exogenous_variables_flag = false;
+if exogenousvariables.vobs>constraints.vobs
+    observed_exogenous_variables_flag = true;
+end
+
+% Get the list of endogenous and exogenous variables.
+endo_names = cellstr(DynareModel.endo_names);
+exo_names = cellstr(DynareModel.exo_names);
+
+% Use specidalized routine if the model is backward looking.
+if ~DynareModel.maximum_lead
+    [endogenousvariables, exogenousvariables] = ...
+        backward_model_inversion(constraints, exogenousvariables, initialconditions, ...
+                                 endo_names, exo_names, freeinnovations, ...
+                                 DynareModel, DynareOptions, DynareOutput);
+    return
+end
+
+% Initialize fplan
+fplan = init_plan(crange);
+
+% Set the exogenous observed variables.
+if observed_exogenous_variables_flag
+    list_of_observed_exogenous_variables = setdiff(exo_names, freeinnovations);
+    observed_exogenous_variables = exogenousvariables{list_of_observed_exogenous_variables{:}};
+    for i=1:length(list_of_observed_exogenous_variables)
+        fplan = basic_plan(fplan, list_of_observed_exogenous_variables{i}, ...
+                           'surprise', crange, observed_exogenous_variables{list_of_observed_exogenous_variables{i}}.data(2:length(crange)+1));
+    end
+end
+
+% Set constrained path for the endogenous variables.
+for i = 1:constraints.vobs
+    fplan = flip_plan(fplan, constraints.name{i}, freeinnovations{i}, 'surprise', crange, transpose(constraints.data(:,i)));
+end
+
+% Identify the innovations (model inversion)
+f = det_cond_forecast(fplan, initialconditions, crange);
+
+endogenousvariables = f{endo_names{:}};
+exogenousvariables = f{exo_names{:}};
\ No newline at end of file
diff --git a/matlab/modules/dates b/matlab/modules/dates
index f37d5230207dc4ddcb5a8fbe9c2ee21721db8e7c..f1dd6aa1e166f5dee77241737252260f7ea50946 160000
--- a/matlab/modules/dates
+++ b/matlab/modules/dates
@@ -1 +1 @@
-Subproject commit f37d5230207dc4ddcb5a8fbe9c2ee21721db8e7c
+Subproject commit f1dd6aa1e166f5dee77241737252260f7ea50946
diff --git a/matlab/modules/dseries b/matlab/modules/dseries
index 280a93467913c001ec1db68bfb699123e44b34b3..6b77c21cd8d57935ff5aea121e2e3818264ce43f 160000
--- a/matlab/modules/dseries
+++ b/matlab/modules/dseries
@@ -1 +1 @@
-Subproject commit 280a93467913c001ec1db68bfb699123e44b34b3
+Subproject commit 6b77c21cd8d57935ff5aea121e2e3818264ce43f
diff --git a/matlab/modules/reporting b/matlab/modules/reporting
index ac6a420a28feeb68b43a8fdb7a6ea9e0bec0b7ae..bc59736f5b50454cea925c99b98a757a0494f3e8 160000
--- a/matlab/modules/reporting
+++ b/matlab/modules/reporting
@@ -1 +1 @@
-Subproject commit ac6a420a28feeb68b43a8fdb7a6ea9e0bec0b7ae
+Subproject commit bc59736f5b50454cea925c99b98a757a0494f3e8
diff --git a/matlab/moment_function.m b/matlab/moment_function.m
index af0488a594da38a1454019e6faff2b6195b6c6c3..fb42db9e888f99380249493ab75abb258ac49226 100644
--- a/matlab/moment_function.m
+++ b/matlab/moment_function.m
@@ -3,19 +3,19 @@ function [g,grad,hess,flag] = moment_function(xparams,sample_moments,dataset,opt
 % ).
 %
 % INPUTS:
-%  xparams          [double]  p*1 vector of estimated parameters. 
+%  xparams          [double]  p*1 vector of estimated parameters.
 %  sample_moments   [double]  n*1 vector of sample moments (n>=p).
 %  options          [      ]  Structure defining options for SMM.
 %  parallel         [      ]  Structure defining the parallel mode settings (optional).
 %
-% OUTPUTS: 
+% OUTPUTS:
 %  g                [double]  n*1 vector, the gap between simulated and sample moments.
 %  flag             [intger]  empty matrix.
 %
 % SPECIAL REQUIREMENTS
 %  The user has to provide a file where the moment conditions are defined.
 
-% Copyright (C) 2010-2012 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -30,7 +30,7 @@ function [g,grad,hess,flag] = moment_function(xparams,sample_moments,dataset,opt
 % 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/>.
 
 global M_ options_
 persistent mainStream mainState
@@ -61,7 +61,7 @@ end
 
 if penalty>0
     flag = 0;
-    return;
+    return
 end
 
 save('estimated_parameters.mat','xparams');
@@ -106,7 +106,7 @@ else% parallel mode.
             end
         end
         for j=1:parallel(i).number_of_jobs
-            if (strcmpi(hostname,machine) && j>1) || ~strcmpi(hostname,machine)  
+            if (strcmpi(hostname,machine) && j>1) || ~strcmpi(hostname,machine)
                 job_number = job_number + 1;
                 unix(['ssh -A ' parallel(i).login '@' machine ' ./call_matlab_session.sh job' int2str(job_number) '.m &']);
             end
@@ -117,7 +117,7 @@ else% parallel mode.
     eval('job1;')
     tElapsedMasterJob = etime(clock, tStartMasterJob);
     TimeLimit = tElapsedMasterJob*1.2;
-    % Master waits for the  slaves' output... 
+    % Master waits for the  slaves' output...
     tStart = clock;
     tElapsed = 0;
     while tElapsed<TimeLimit
@@ -132,7 +132,7 @@ else% parallel mode.
             simulated_moments = load(['./intermediary_results_from_master_and_slaves/simulated_moments_slave_' int2str(i) '.dat'],'-ascii');
             tmp = tmp + simulated_moments;
         end
-        simulated_moments = tmp / job_number;        
+        simulated_moments = tmp / job_number;
     catch
         flag = 0;
         return
diff --git a/matlab/moments.m b/matlab/moments.m
index f295336aa3e4aa206d7ebd758cb33a96421145bb..9103321184923384f8d77aa11d96e6b1c1ba4fdd 100644
--- a/matlab/moments.m
+++ b/matlab/moments.m
@@ -1,7 +1,7 @@
 function m = moments(X,order)
 % Returns the central sample moment of X specified by the positive integer order.
 %
-% Note that the cross moments are only computed if order=2, in this case the 
+% Note that the cross moments are only computed if order=2, in this case the
 % output is a matrix.
 %
 % INPUTS
@@ -14,7 +14,7 @@ function m = moments(X,order)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2009-2010 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/ms-sbvar/auto/sbvar_identification.el b/matlab/ms-sbvar/auto/sbvar_identification.el
deleted file mode 100644
index 637bf66f677393610bb3a170e5a647c14c8c6c58..0000000000000000000000000000000000000000
--- a/matlab/ms-sbvar/auto/sbvar_identification.el
+++ /dev/null
@@ -1,8 +0,0 @@
-(TeX-add-style-hook "sbvar_identification"
- (lambda ()
-    (TeX-run-style-hooks
-     "latex2e"
-     "art10"
-     "article"
-     "")))
-
diff --git a/matlab/ms-sbvar/check_datafile_years_assigned.m b/matlab/ms-sbvar/check_datafile_years_assigned.m
index 7df9611dc909217610987b5fbde0490856b24481..36eb671d57dccc600b78c018ee2bef8630818fef 100644
--- a/matlab/ms-sbvar/check_datafile_years_assigned.m
+++ b/matlab/ms-sbvar/check_datafile_years_assigned.m
@@ -8,7 +8,7 @@ function [final_year,final_subperiod]=check_datafile_years_assigned(options_)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2013 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/ms-sbvar/clean_files_for_second_type_of_mex.m b/matlab/ms-sbvar/clean_files_for_second_type_of_mex.m
index d29b532bfaff3b021d2182938344794355cd5efa..b1361a49b43e52672db6b29860e15dc7ea06d699 100644
--- a/matlab/ms-sbvar/clean_files_for_second_type_of_mex.m
+++ b/matlab/ms-sbvar/clean_files_for_second_type_of_mex.m
@@ -11,7 +11,7 @@ function clean_files_for_second_type_of_mex(M_, options_, type)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -34,12 +34,12 @@ if ~strcmp(tagtouse, options_.ms.output_file_tag)
 end
 
 switch type
-    case 'irf'
-        clean_ms_irf_files(tagtouse);
-    case 'forecast'
-        clean_ms_forecast_files(tagtouse);
-    case 'variance_decomposition'
-        clean_ms_variance_decomposition_files(tagtouse);
-    otherwise
-        error('clean_files_for_second_type_of_mex: should not arrive here');
+  case 'irf'
+    clean_ms_irf_files(tagtouse);
+  case 'forecast'
+    clean_ms_forecast_files(tagtouse);
+  case 'variance_decomposition'
+    clean_ms_variance_decomposition_files(tagtouse);
+  otherwise
+    error('clean_files_for_second_type_of_mex: should not arrive here');
 end
diff --git a/matlab/ms-sbvar/clean_ms_simulation_files.m b/matlab/ms-sbvar/clean_ms_simulation_files.m
index b6a8078597b37971081ea6eb4c072cd77833995b..19ec8480bf2f660560027bea5e230d79696177cb 100644
--- a/matlab/ms-sbvar/clean_ms_simulation_files.m
+++ b/matlab/ms-sbvar/clean_ms_simulation_files.m
@@ -11,7 +11,7 @@ function clean_ms_simulation_files(file_tag)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2013 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/ms-sbvar/dyn_save_graph.m b/matlab/ms-sbvar/dyn_save_graph.m
index e3ae96326bba91498c109d393e8e6baa0b200829..46623f7c94ee7c8656cd877bb3674459fbfac5e2 100644
--- a/matlab/ms-sbvar/dyn_save_graph.m
+++ b/matlab/ms-sbvar/dyn_save_graph.m
@@ -9,11 +9,11 @@ function dyn_save_graph(dirname,graph_name,graph_formats,TeX,names,texnames,capt
 %
 % OUTPUTS
 %   none
-%    
+%
 % SPECIAL REQUIREMENTS
 %    none
 %
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -30,40 +30,40 @@ function dyn_save_graph(dirname,graph_name,graph_formats,TeX,names,texnames,capt
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-    create_dir(dirname);
-    graph_name = [dirname filesep regexprep(graph_name,' ','_')];
-    if nargin <= 2
-        TeX = 0;
-    elseif nargin <= 4
-        names = {};
-        texnames = {};
-    elseif nargin <= 6
-        caption = '';
-    end
-    
-    if graph_formats.eps || TeX
-        print([ graph_name '.eps' ],'-depsc2');
-    end
-    if graph_formats.pdf && ~isoctave
-        print(graph_name,'-dpdf');
-    end
-    if graph_formats.fig && ~isoctave
-        print(graph_name,'-dfig');
+create_dir(dirname);
+graph_name = [dirname filesep regexprep(graph_name,' ','_')];
+if nargin <= 2
+    TeX = 0;
+elseif nargin <= 4
+    names = {};
+    texnames = {};
+elseif nargin <= 6
+    caption = '';
+end
+
+if graph_formats.eps || TeX
+    print([ graph_name '.eps' ],'-depsc2');
+end
+if graph_formats.pdf && ~isoctave
+    print(graph_name,'-dpdf');
+end
+if graph_formats.fig && ~isoctave
+    print(graph_name,'-dfig');
+end
+
+if TeX
+    fh = fopen([graph_name '.tex'],'w');
+    for i=1:length(names)
+        fprintf(fh,'\\psfrag{%s}[1][][0.5][0]{%s}\n',names{i},texnames{i});
     end
-    
-    if TeX
-        fh = fopen([graph_name '.tex'],'w');
-        for i=1:length(names)
-            fprintf(fh,'\\psfrag{%s}[1][][0.5][0]{%s}\n',names{i},texnames{i});
-        end
-        fprintf(fh,'\\centering \n');
-        fprintf(fh,'\\includegraphics[width=0.8\\textwidth]{%s}\n',graph_name);
-        if caption
-            fprintf(fh,'\\caption{%s}',caption);
-        end
-        fprintf(fh,'\\label{Fig:%s}\n',graph_name);
-        fprintf(fh,'\\end{figure}\n');
-        fprintf(fh,'\n');
-        fprintf(fh,'%% End of TeX file.\n');
-        fclose(fh);
+    fprintf(fh,'\\centering \n');
+    fprintf(fh,'\\includegraphics[width=0.8\\textwidth]{%s}\n',graph_name);
+    if caption
+        fprintf(fh,'\\caption{%s}',caption);
     end
+    fprintf(fh,'\\label{Fig:%s}\n',graph_name);
+    fprintf(fh,'\\end{figure}\n');
+    fprintf(fh,'\n');
+    fprintf(fh,'%% End of TeX file.\n');
+    fclose(fh);
+end
diff --git a/matlab/ms-sbvar/identification/exclusions.m b/matlab/ms-sbvar/identification/exclusions.m
index 5e7d3ef5c040da64ece9eb203f2e32bedd2b2fb7..5361c2ef4c1cea22e7143c12b622a08124f809b0 100644
--- a/matlab/ms-sbvar/identification/exclusions.m
+++ b/matlab/ms-sbvar/identification/exclusions.m
@@ -16,7 +16,7 @@ function [Ui,Vi,n0,np,ixmC0Pres,Qi,Ri] = exclusions(nvar,nexo,options_ms)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -47,25 +47,25 @@ np = zeros(nvar,1);
 k = nlags*nvar+1;
 
 for n=1:nvar
- Qi{n} = zeros(nvar,nvar);
- sQ = size(Qi1{n});
- if all(sQ) > 0
-     Qi{n}(1:sQ(1),1:sQ(2)) = Qi1{n};
- end
- Ri{n} = zeros(k,k);
- sR = size(Ri1{n});
- if all(sR) > 0
-     Ri{n}(1:sR(1),1:sR(2)) = Ri1{n};
- end
+    Qi{n} = zeros(nvar,nvar);
+    sQ = size(Qi1{n});
+    if all(sQ) > 0
+        Qi{n}(1:sQ(1),1:sQ(2)) = Qi1{n};
+    end
+    Ri{n} = zeros(k,k);
+    sR = size(Ri1{n});
+    if all(sR) > 0
+        Ri{n}(1:sR(1),1:sR(2)) = Ri1{n};
+    end
 
- if options_ms.constants_exclusion
+    if options_ms.constants_exclusion
         Ri{n}(sR(1)+1,k) = 1;
- end
+    end
 
- Ui{n} = null(Qi{n});
- Vi{n} = null(Ri{n});
- n0(n) = size(Ui{n},2);
- np(n) = size(Vi{n},2);
+    Ui{n} = null(Qi{n});
+    Vi{n} = null(Ri{n});
+    n0(n) = size(Ui{n},2);
+    np(n) = size(Vi{n},2);
 end
 
 ixmC0Pres = NaN;
\ No newline at end of file
diff --git a/matlab/ms-sbvar/identification/lower_cholesky.m b/matlab/ms-sbvar/identification/lower_cholesky.m
index 2af96ca9b7b732011d0f2831eb02470293262c6e..a88954091d2083bed726e83e17af13862560540c 100644
--- a/matlab/ms-sbvar/identification/lower_cholesky.m
+++ b/matlab/ms-sbvar/identification/lower_cholesky.m
@@ -16,7 +16,7 @@ function [Ui,Vi,n0,np,ixmC0Pres] = lower_cholesky(nvar,nexo,options_ms)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -41,11 +41,11 @@ Vi = cell(nvar,1);
 n0 = zeros(nvar,1);
 np = zeros(nvar,1);
 if (nargin==2)
-   nexo = 1; 
+    nexo = 1;
 elseif (nargin==3)
-   indxC0Pres = 0;
+    indxC0Pres = 0;
 end
-k = lags*nvar+nexo; 
+k = lags*nvar+nexo;
 Qi = zeros(nvar,nvar,nvar);
 Ri = zeros(k,k,nvar);
 
@@ -61,11 +61,11 @@ if options_ms.constants_exclusion
     end
 end
 
-for n=1:nvar 
-   Ui{n} = null(Qi(:,:,n));
-   Vi{n} = null(Ri(:,:,n));
-   n0(n) = size(Ui{n},2);
-   np(n) = size(Vi{n},2);
+for n=1:nvar
+    Ui{n} = null(Qi(:,:,n));
+    Vi{n} = null(Ri(:,:,n));
+    n0(n) = size(Ui{n},2);
+    np(n) = size(Vi{n},2);
 end
 
 ixmC0Pres = NaN;
\ No newline at end of file
diff --git a/matlab/ms-sbvar/identification/upper_cholesky.m b/matlab/ms-sbvar/identification/upper_cholesky.m
index 7f4d2027c56b854b64fe1e8274eeb1170a65fa99..8645214b183e2d08f1acc034035e18bfae48ccb5 100644
--- a/matlab/ms-sbvar/identification/upper_cholesky.m
+++ b/matlab/ms-sbvar/identification/upper_cholesky.m
@@ -16,7 +16,7 @@ function [Ui,Vi,n0,np,ixmC0Pres] = upper_cholesky(nvar,nexo,options_ms)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -42,9 +42,9 @@ n0 = zeros(nvar,1);
 np = zeros(nvar,1);
 
 if (nargin==2)
-   nexo = 1;
+    nexo = 1;
 elseif (nargin==3)
-   indxC0Pres = 0;
+    indxC0Pres = 0;
 end
 
 k = lags*nvar+nexo;
@@ -52,8 +52,8 @@ Qi = zeros(nvar,nvar,nvar);
 Ri = zeros(k,k,nvar);
 
 for ii=2:nvar
-  Qi(ii-1,ii-1,ii)=1;
-  Qi(:,:,ii)=Qi(:,:,ii)+Qi(:,:,ii-1);
+    Qi(ii-1,ii-1,ii)=1;
+    Qi(:,:,ii)=Qi(:,:,ii)+Qi(:,:,ii-1);
 end
 
 if options_ms.constants_exclusion
@@ -62,11 +62,11 @@ if options_ms.constants_exclusion
     end
 end
 
-for n=1:nvar 
-   Ui{n} = null(Qi(:,:,n));
-   Vi{n} = null(Ri(:,:,n));
-   n0(n) = size(Ui{n},2);
-   np(n) = size(Vi{n},2);
+for n=1:nvar
+    Ui{n} = null(Qi(:,:,n));
+    Vi{n} = null(Ri(:,:,n));
+    n0(n) = size(Ui{n},2);
+    np(n) = size(Vi{n},2);
 end
 
 ixmC0Pres = NaN;
\ No newline at end of file
diff --git a/matlab/ms-sbvar/initialize_ms_sbvar_options.m b/matlab/ms-sbvar/initialize_ms_sbvar_options.m
index 61255652b5cc9434bc7e08c25cbb188c6aec11b3..b618aef3cd7b41d18b49e757dc506e56e0010b26 100644
--- a/matlab/ms-sbvar/initialize_ms_sbvar_options.m
+++ b/matlab/ms-sbvar/initialize_ms_sbvar_options.m
@@ -12,7 +12,7 @@ function options_=initialize_ms_sbvar_options(M_, options_)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2013 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/ms-sbvar/ms_estimation.m b/matlab/ms-sbvar/ms_estimation.m
index 6d5eec32d704d61ff4de834515ab2cd9701788dc..495a483eed3a00cbcc6e8821ddd10b4288353bbe 100644
--- a/matlab/ms-sbvar/ms_estimation.m
+++ b/matlab/ms-sbvar/ms_estimation.m
@@ -14,7 +14,7 @@ function [options_, oo_]=ms_estimation(M_, options_, oo_)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -45,7 +45,7 @@ else
             exist(['matlab_' options_.ms.file_tag '.prn'],'file') ~= 2 || ...
             exist([options_.ms.file_tag '_markov_file.dat'],'file') ~= 2
         error(['You must run ms_estimation without no_create_init as '...
-            'you are missing an initialization file it needs.']);
+               'you are missing an initialization file it needs.']);
     end
     if ~strcmp(options_.ms.file_tag, options_.ms.output_file_tag)
         clean_ms_estimation_files(options_.ms.output_file_tag);
diff --git a/matlab/ms-sbvar/ms_forecast.m b/matlab/ms-sbvar/ms_forecast.m
index 55030c9021729dcbde0a1110f920c86cf4ea9eab..e8949c9ae287d83700ad307f507752c3009094bb 100644
--- a/matlab/ms-sbvar/ms_forecast.m
+++ b/matlab/ms-sbvar/ms_forecast.m
@@ -14,7 +14,7 @@ function [options_, oo_]=ms_forecast(M_, options_, oo_)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011-2016 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -89,30 +89,30 @@ if options_.ms.regimes
     for regime_i=1:n_regimes
         forecast_title = ['Forecast, Regimes ' num2str(regime_i)];
         forecast_data = load([forecastdir filesep 'forecasts_percentiles_regime_' ...
-            num2str(regime_i-1) '_' options_.ms.output_file_tag ...
-            '.out'], '-ascii');
+                            num2str(regime_i-1) '_' options_.ms.output_file_tag ...
+                            '.out'], '-ascii');
         forecast_data = reshape_ascii_forecast_data(M_.endo_nbr, ...
-            percentiles_size, options_.ms.horizon, forecast_data);
+                                                    percentiles_size, options_.ms.horizon, forecast_data);
         save([forecastdir filesep 'forecast_regime_' num2str(regime_i-1) '.mat'], ...
-            'forecast_data');
+             'forecast_data');
         plot_ms_forecast(M_, options_, forecast_data, forecast_title);
     end
 else
     if options_.ms.regime
         forecast_data = load([forecastdir filesep 'forecasts_percentiles_regime_' ...
-            num2str(options_.ms.regime-1) '_' options_.ms.output_file_tag ...
-            '.out'], '-ascii');
+                            num2str(options_.ms.regime-1) '_' options_.ms.output_file_tag ...
+                            '.out'], '-ascii');
         forecast_title = ['Forecast, Regime ' num2str(options_.ms.regime)];
         save_filename = ['forecast_regime_' num2str(options_.ms.regime-1) '.mat'];
     else
         forecast_data = load([forecastdir filesep 'forecasts_percentiles_' ...
-            options_.ms.output_file_tag '.out'], '-ascii');
+                            options_.ms.output_file_tag '.out'], '-ascii');
         forecast_title = 'Forecast';
         save_filename = 'forecast.mat';
     end
 
     forecast_data = reshape_ascii_forecast_data(M_.endo_nbr, ...
-        percentiles_size, options_.ms.horizon, forecast_data);
+                                                percentiles_size, options_.ms.horizon, forecast_data);
     save([forecastdir filesep save_filename], 'forecast_data');
     plot_ms_forecast(M_, options_, forecast_data, forecast_title);
 end
diff --git a/matlab/ms-sbvar/ms_irf.m b/matlab/ms-sbvar/ms_irf.m
index 32718aa29c4473515c07d477cccf5498d5ce7364..47d1a8490be13cde4d972f36c46cb66821f9aae0 100644
--- a/matlab/ms-sbvar/ms_irf.m
+++ b/matlab/ms-sbvar/ms_irf.m
@@ -15,7 +15,7 @@ function [options_, oo_]=ms_irf(varlist, M_, options_, oo_)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011-2016 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -91,34 +91,34 @@ if options_.ms.regimes
     for regime_i=1:n_regimes
         irf_title = ['Impulse Responses, Regime ' num2str(regime_i)];
         irf_data = load([irfdir filesep 'ir_percentiles_regime_' ...
-            num2str(regime_i-1) '_' options_.ms.output_file_tag ...
-            '.out'], '-ascii');
+                         num2str(regime_i-1) '_' options_.ms.output_file_tag ...
+                         '.out'], '-ascii');
         irf_data = reshape_ascii_irf_data(M_.endo_nbr, percentiles_size, ...
-            options_.ms.horizon, irf_data);
+                                          options_.ms.horizon, irf_data);
         save([irfdir filesep 'irf_regime_' num2str(regime_i-1) '.mat'], 'irf_data');
         plot_ms_irf(M_, options_, irf_data, irf_title, varlist);
     end
 else
     if options_.ms.regime
         irf_data = load([irfdir filesep 'ir_percentiles_regime_' ...
-            num2str(options_.ms.regime-1) '_' options_.ms.output_file_tag ...
-            '.out'], '-ascii');
+                         num2str(options_.ms.regime-1) '_' options_.ms.output_file_tag ...
+                         '.out'], '-ascii');
         irf_title = ['Impulse Response, Regime ' num2str(options_.ms.regime)];
         save_filename = ['irf_regime_' num2str(options_.ms.regime-1) '.mat'];
     elseif options_.ms.filtered_probabilities
         irf_data = load([irfdir filesep 'ir_percentiles_filtered_' ...
-            options_.ms.output_file_tag '.out'], '-ascii');
+                         options_.ms.output_file_tag '.out'], '-ascii');
         irf_title = 'Impulse Response Filtered';
         save_filename = 'irf.mat';
     else
         irf_data = load([irfdir filesep 'ir_percentiles_ergodic_' ...
-            options_.ms.output_file_tag '.out'], '-ascii');
+                         options_.ms.output_file_tag '.out'], '-ascii');
         irf_title = 'Impulse Response Ergodic';
         save_filename = 'irf.mat';
     end
 
     irf_data = reshape_ascii_irf_data(M_.endo_nbr, percentiles_size, ...
-        options_.ms.horizon, irf_data);
+                                      options_.ms.horizon, irf_data);
     save([irfdir filesep save_filename], 'irf_data');
     plot_ms_irf(M_, options_, irf_data, irf_title, varlist);
 end
diff --git a/matlab/ms-sbvar/ms_mardd.m b/matlab/ms-sbvar/ms_mardd.m
index 9932f0186a38c5bd44decd28eced194f31b666cd..bd522807d1cd116d0da96af0410fce2fdc5209e5 100644
--- a/matlab/ms-sbvar/ms_mardd.m
+++ b/matlab/ms-sbvar/ms_mardd.m
@@ -6,7 +6,7 @@ function ms_mardd(options_)
 %
 % Tao Zha, September 1999.  Quick revisions, May 2003.  Final revision, September 2004.
 
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -25,26 +25,26 @@ function ms_mardd(options_)
 
 msstart2     % start the program in which everyhting is initialized through msstart2.m
 if ~options_.ms.indxestima
-   warning(' ')
-   disp('You must set IxEstima=1 in msstart to run this program')
-	disp('Press ctrl-c to abort now')
-	pause
+    warning(' ')
+    disp('You must set IxEstima=1 in msstart to run this program')
+    disp('Press ctrl-c to abort now')
+    pause
 end
 
 A0xhat = zeros(size(A0hat));
 Apxhat = zeros(size(Aphat));
 if (0)
-   %Robustness check to see if the same result is obtained with the purterbation of the parameters.
-   for k=1:nvar
-      bk = Uiconst{k}'*A0hat(:,k);
-      gk = Viconst{k}'*Aphat(:,k);
-      A0xhat(:,k) =  Uiconst{k}*(bk + 5.2*randn(size(bk)));   % Perturbing the posterior estimate.
-      Apxhat(:,k) = Viconst{k}*(gk + 5.2*randn(size(gk)));      % Perturbing the posterior estimate.
-   end
+    %Robustness check to see if the same result is obtained with the purterbation of the parameters.
+    for k=1:nvar
+        bk = Uiconst{k}'*A0hat(:,k);
+        gk = Viconst{k}'*Aphat(:,k);
+        A0xhat(:,k) =  Uiconst{k}*(bk + 5.2*randn(size(bk)));   % Perturbing the posterior estimate.
+        Apxhat(:,k) = Viconst{k}*(gk + 5.2*randn(size(gk)));      % Perturbing the posterior estimate.
+    end
 else
-   %At the posterior estimate.
-   A0xhat = A0hat;   % ML estimate of A0
-   Apxhat = Aphat;      % ML estimate of A+
+    %At the posterior estimate.
+    A0xhat = A0hat;   % ML estimate of A0
+    Apxhat = Aphat;      % ML estimate of A+
 end
 %--- Rename variables.
 YatYa = yty;
@@ -59,40 +59,40 @@ XatXa = xtx;
 vlog_a0p = 0;
 Yexpt=0;  % exponential term for Y in p(Y|A0,A+) at some point such as the peak
 Apexpt=0.0;  % 0.0 because we have chosen posterior estimate of A+ as A+*.  Exponential term for A+ conditional on A0 and Y
-%======= Computing the log prior pdf of a0a+ and the exponential term for Y in p(Y|A0,A+).
+             %======= Computing the log prior pdf of a0a+ and the exponential term for Y in p(Y|A0,A+).
 for k=1:nvar
-   a0k = A0xhat(:,k);  % meaningful parameters in the kth equation.
-   apk = Apxhat(:,k);  % meaningful parameters in the kth equation.
-
-   %--- Prior settings.
-   S0bar = H0invtld{k};  %See Claim 2 on p.69b.
-   Spbar = Hpinvtld{k};
-   bk = Uiconst{k}'*a0k;  % free parameters in the kth equation.
-   gk = Viconst{k}'*apk;  % free parameters in the kth equation.
-   gbark = Ptld{k}*bk;   % bar: prior
-
-   %--- The exponential term for Y in p(Y|A0,A+)
-   Yexpt = Yexpt - 0.5*(a0k'*YatYa*a0k - 2*apk'*XatYa*a0k + apk'*XatXa*apk);
-   %--- The log prior pdf.
-   vlog_a0p = vlog_a0p - 0.5*(size(Uiconst{k},2)+size(Viconst{k},2))*log(2*pi) + 0.5*log(abs(det(S0bar))) + ...
-         0.5*log(abs(det(Spbar))) - 0.5*(bk'*S0bar*bk+(gk-gbark)'*Spbar*(gk-gbark));
-   %--- For p(A+|Y,a0) only.
-   tmpd = gk - Pmat{k}*bk;
-   Apexpt = Apexpt - 0.5*tmpd'*(Hpinv{k}*tmpd);
+    a0k = A0xhat(:,k);  % meaningful parameters in the kth equation.
+    apk = Apxhat(:,k);  % meaningful parameters in the kth equation.
+
+    %--- Prior settings.
+    S0bar = H0invtld{k};  %See Claim 2 on p.69b.
+    Spbar = Hpinvtld{k};
+    bk = Uiconst{k}'*a0k;  % free parameters in the kth equation.
+    gk = Viconst{k}'*apk;  % free parameters in the kth equation.
+    gbark = Ptld{k}*bk;   % bar: prior
+
+    %--- The exponential term for Y in p(Y|A0,A+)
+    Yexpt = Yexpt - 0.5*(a0k'*YatYa*a0k - 2*apk'*XatYa*a0k + apk'*XatXa*apk);
+    %--- The log prior pdf.
+    vlog_a0p = vlog_a0p - 0.5*(size(Uiconst{k},2)+size(Viconst{k},2))*log(2*pi) + 0.5*log(abs(det(S0bar))) + ...
+        0.5*log(abs(det(Spbar))) - 0.5*(bk'*S0bar*bk+(gk-gbark)'*Spbar*(gk-gbark));
+    %--- For p(A+|Y,a0) only.
+    tmpd = gk - Pmat{k}*bk;
+    Apexpt = Apexpt - 0.5*tmpd'*(Hpinv{k}*tmpd);
 end
 vlog_a0p
 
 %--------- The log value of p(Y|A0,A+) at some point such as the peak. ----------
 %--------- Note that logMarLHres is the same as vlog_Y_a, just to double check. ----------
 vlog_Y_a = -0.5*nvar*fss*log(2*pi) + fss*log(abs(det(A0xhat))) + Yexpt
-                 % a: given a0 and a+
+% a: given a0 and a+
 logMarLHres = 0;   % Initialize log of the marginal likelihood (restricted or constant parameters).
 for ki=1:fss   %ndobs+1:fss     % Forward recursion to get the marginal likelihood.  See F on p.19 and pp. 48-49.
-   %----  Restricted log marginal likelihood function (constant parameters).
-   [A0l,A0u] = lu(A0xhat);
-   ada = sum(log(abs(diag(A0u))));   % log|A0|
-   termexp = y(ki,:)*A0xhat - phi(ki,:)*Apxhat;   % 1-by-nvar
-   logMarLHres = logMarLHres - (0.5*nvar)*log(2*pi) + ada - 0.5*termexp*termexp';  % log value
+               %----  Restricted log marginal likelihood function (constant parameters).
+    [A0l,A0u] = lu(A0xhat);
+    ada = sum(log(abs(diag(A0u))));   % log|A0|
+    termexp = y(ki,:)*A0xhat - phi(ki,:)*Apxhat;   % 1-by-nvar
+    logMarLHres = logMarLHres - (0.5*nvar)*log(2*pi) + ada - 0.5*termexp*termexp';  % log value
 end
 logMarLHres
 
@@ -101,8 +101,8 @@ logMarLHres
 totparsp = 0.0;
 tmpd = 0.0;
 for k=1:nvar
-   totparsp = totparsp + size(Viconst{k},2);
-   tmpd = tmpd + 0.5*log(abs(det(Hpinv{k})));
+    totparsp = totparsp + size(Viconst{k},2);
+    tmpd = tmpd + 0.5*log(abs(det(Hpinv{k})));
 end
 vlog_ap_Ya0 = -0.5*totparsp*log(2*pi) + tmpd + Apexpt;
 
@@ -117,65 +117,65 @@ vlog_ap_Ya0 = -0.5*totparsp*log(2*pi) + tmpd + Apexpt;
 [Tinv,UT] = fn_gibbsrvar_setup(H0inv, Uiconst, Hpinv, Pmat, Viconst, nvar, fss);
 %
 vlog_a0_Yao = zeros(nvar,1);
-  % the log value of p(a0k|Y,ao) where ao: other a's at some point such as the peak of ONLY some a0's
+% the log value of p(a0k|Y,ao) where ao: other a's at some point such as the peak of ONLY some a0's
 vlog=zeros(ndraws2,1);
 for k=1:nvar
-   bk = Uiconst{k}'*A0xhat(:,k);
-   indx_ks=[k:nvar];  % the columns that exclude 1-(k-1)th columns
-   A0gbs0 = A0hat;   % starting at some point such as the peak
-   nk = n0(k);
-
-   if k<nvar
-      %--------- The 1st set of draws to be tossed away. ------------------
-      for draws = 1:ndraws1
-         if ~mod(draws,nbuffer)
-            skipline()
-            disp(sprintf('The %dth column or equation in A0 with %d 1st tossed-away draws in Gibbs',k,draws))
-         end
-         A0gbs1 = fn_gibbsrvar(A0gbs0,UT,nvar,fss,n0,indx_ks);
-         A0gbs0=A0gbs1;    % repeat the Gibbs sampling
-      end
-
-
-      %--------- The 2nd set of draws to be used. ------------------
-      for draws = 1:ndraws2
-         if ~mod(draws,nbuffer)
-            skipline()
-            disp(sprintf('The %dth column or equation in A0 with %d usable draws in Gibbs',k,draws))
-         end
-         [A0gbs1, Wcell] = fn_gibbsrvar(A0gbs0,UT,nvar,fss,n0,indx_ks);
-         %------ See p.71, Forecast (II).
-         %------ Computing p(a0_k|Y,a_others) at some point such as the peak along the dimensions of indx_ks.
-         Vk = Tinv{k}\Wcell{k};  %V_k on p.71 of Forecast (II).
-         gbeta = Vk\bk;  % inv(V_k)*b_k on p.71 of Forecast (II) where alpha_k = b_k in our notation.
-         [Vtq,Vtr]=qr(Vk',0);  %To get inv(V_k)'*inv(V_k) in (*) on p.71 of Forecast (II).
-         %
-         vlog(draws) = 0.5*(fss+nk)*log(fss)-log(abs(det(Vk)))-0.5*(nk-1)*log(2*pi)-...
-                  0.5*(fss+1)*log(2)-gammaln(0.5*(fss+1))+fss*log(abs(gbeta(1)))-...
-                  0.5*fss*bk'*(Vtr\(Vtr'\bk));
-
-         A0gbs0=A0gbs1;    % repeat the Gibbs sampling
-      end
-      vlogm=max(vlog);
-      qlog=vlog-vlogm;
-      vlogxhat=vlogm-log(ndraws2)+log(sum(exp(qlog)));
-      vlog_a0_Yao(k) = vlogxhat;
-         % The log value of p(a0_k|Y,a_others) where a_others: other a's at some point such as the peak of ONLY some a0's
-   else
-      skipline()
-      disp(sprintf('The last(6th) column or equation in A0 with no Gibbs draws'))
-      [A0gbs1, Wcell] = fn_gibbsrvar(A0gbs0,UT,nvar,fss,n0,indx_ks)
-      %------ See p.71, Forecast (II).
-      %------ Computing p(a0_k|Y,a_others) at some point such as the peak along the dimensions of indx_ks.
-      Vk = Tinv{k}\Wcell{k};  %V_k on p.71 of Forecast (II).
-      gbeta = Vk\bk;  % inv(V_k)*b_k on p.71 of Forecast (II) where alpha_k = b_k in our notation.
-      [Vtq,Vtr]=qr(Vk',0);  %To get inv(V_k)'*inv(V_k) in (*) on p.71 of Forecast (II).
-      %
-      vloglast = 0.5*(fss+nk)*log(fss)-log(abs(det(Vk)))-0.5*(nk-1)*log(2*pi)-...
-               0.5*(fss+1)*log(2)-gammaln(0.5*(fss+1))+fss*log(abs(gbeta(1)))-...
-               0.5*fss*bk'*(Vtr\(Vtr'\bk));
-      vlog_a0_Yao(k) = vloglast;
-   end
+    bk = Uiconst{k}'*A0xhat(:,k);
+    indx_ks=[k:nvar];  % the columns that exclude 1-(k-1)th columns
+    A0gbs0 = A0hat;   % starting at some point such as the peak
+    nk = n0(k);
+
+    if k<nvar
+        %--------- The 1st set of draws to be tossed away. ------------------
+        for draws = 1:ndraws1
+            if ~mod(draws,nbuffer)
+                skipline()
+                disp(sprintf('The %dth column or equation in A0 with %d 1st tossed-away draws in Gibbs',k,draws))
+            end
+            A0gbs1 = fn_gibbsrvar(A0gbs0,UT,nvar,fss,n0,indx_ks);
+            A0gbs0=A0gbs1;    % repeat the Gibbs sampling
+        end
+
+
+        %--------- The 2nd set of draws to be used. ------------------
+        for draws = 1:ndraws2
+            if ~mod(draws,nbuffer)
+                skipline()
+                disp(sprintf('The %dth column or equation in A0 with %d usable draws in Gibbs',k,draws))
+            end
+            [A0gbs1, Wcell] = fn_gibbsrvar(A0gbs0,UT,nvar,fss,n0,indx_ks);
+            %------ See p.71, Forecast (II).
+            %------ Computing p(a0_k|Y,a_others) at some point such as the peak along the dimensions of indx_ks.
+            Vk = Tinv{k}\Wcell{k};  %V_k on p.71 of Forecast (II).
+            gbeta = Vk\bk;  % inv(V_k)*b_k on p.71 of Forecast (II) where alpha_k = b_k in our notation.
+            [Vtq,Vtr]=qr(Vk',0);  %To get inv(V_k)'*inv(V_k) in (*) on p.71 of Forecast (II).
+                                  %
+            vlog(draws) = 0.5*(fss+nk)*log(fss)-log(abs(det(Vk)))-0.5*(nk-1)*log(2*pi)-...
+                0.5*(fss+1)*log(2)-gammaln(0.5*(fss+1))+fss*log(abs(gbeta(1)))-...
+                0.5*fss*bk'*(Vtr\(Vtr'\bk));
+
+            A0gbs0=A0gbs1;    % repeat the Gibbs sampling
+        end
+        vlogm=max(vlog);
+        qlog=vlog-vlogm;
+        vlogxhat=vlogm-log(ndraws2)+log(sum(exp(qlog)));
+        vlog_a0_Yao(k) = vlogxhat;
+        % The log value of p(a0_k|Y,a_others) where a_others: other a's at some point such as the peak of ONLY some a0's
+    else
+        skipline()
+        disp(sprintf('The last(6th) column or equation in A0 with no Gibbs draws'))
+        [A0gbs1, Wcell] = fn_gibbsrvar(A0gbs0,UT,nvar,fss,n0,indx_ks)
+        %------ See p.71, Forecast (II).
+        %------ Computing p(a0_k|Y,a_others) at some point such as the peak along the dimensions of indx_ks.
+        Vk = Tinv{k}\Wcell{k};  %V_k on p.71 of Forecast (II).
+        gbeta = Vk\bk;  % inv(V_k)*b_k on p.71 of Forecast (II) where alpha_k = b_k in our notation.
+        [Vtq,Vtr]=qr(Vk',0);  %To get inv(V_k)'*inv(V_k) in (*) on p.71 of Forecast (II).
+                              %
+        vloglast = 0.5*(fss+nk)*log(fss)-log(abs(det(Vk)))-0.5*(nk-1)*log(2*pi)-...
+            0.5*(fss+1)*log(2)-gammaln(0.5*(fss+1))+fss*log(abs(gbeta(1)))-...
+            0.5*fss*bk'*(Vtr\(Vtr'\bk));
+        vlog_a0_Yao(k) = vloglast;
+    end
 end
 ndraws2
 
diff --git a/matlab/ms-sbvar/ms_sbvar_setup.m b/matlab/ms-sbvar/ms_sbvar_setup.m
index 181a6f7d2e54029b363ec2896756374a56403f57..a195cc49137e0756fdde3c59bbde470808cd8ceb 100644
--- a/matlab/ms-sbvar/ms_sbvar_setup.m
+++ b/matlab/ms-sbvar/ms_sbvar_setup.m
@@ -11,7 +11,7 @@ function ms_sbvar_setup(options_)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2012 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -29,7 +29,7 @@ function ms_sbvar_setup(options_)
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 options_.data = read_variables(options_.datafile, ...
-    options_.varobs, [], options_.xls_sheet, options_.xls_range);
+                               options_.varobs, [], options_.xls_sheet, options_.xls_range);
 [options_.ms.final_year,options_.ms.final_subperiod] = check_datafile_years_assigned(options_);
 
 if options_.ms.upper_cholesky
@@ -243,10 +243,10 @@ if indxPrior
     else
         [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti] = fn_rnrprior(nvar,q_m,options_.ms.nlags,xdgel,mu);
     end
-    
+
     %*** Combines asymmetric prior with linear restrictions
     [Ptld,H0invtld,Hpinvtld] = fn_rlrprior(Ui,Vi,Pi,H0multi,Hpmulti,nvar);
-    
+
     %*** Obtains the posterior matrices for estimation and inference
     [Pmat,H0inv,Hpinv] = fn_rlrpostr(xtx,xty,yty,Ptld,H0invtld,Hpinvtld,Ui,Vi);
 else
@@ -258,7 +258,7 @@ if Rform
     %*** Obtain the ML estimate
     A0hatinv = chol(H0inv{1}/fss);   % upper triangular but lower triangular choleski
     A0hat=inv(A0hatinv);
-    
+
     Aphat = Pmat{1}*A0hat;
 else
     %*** Obtain the ML estimate
@@ -271,16 +271,16 @@ else
     [fhat,xhat,grad,Hhat,itct,fcount,retcodehat] = csminwel('fn_a0freefun',x,H0,'fn_a0freegrad',crit,nit,Ui,nvar,n0,fss,H0inv);
 
     A0hat = fn_tran_b2a(xhat,Ui,nvar,n0);
-    
+
     xhat = fn_tran_a2b(A0hat,Ui,nvar,n0);
     [Aphat,ghat] = fn_gfmean(xhat,Pmat,Vi,nvar,ncoef,n0,np);
     if indxC0Pres
         Fhatur0P = Fhat;  % ur: unrestriced across A0 and A+
         for ki = 1:size(ixmC0Pres,1)   % loop through the number of equations in which
-            % cross-A0-A+ restrictions occur. See St. Louis Note p.5.
+                                       % cross-A0-A+ restrictions occur. See St. Louis Note p.5.
             ixeq = ixmC0Pres{ki}(1,1);   % index for the jth equation in consideration.
             Lit = Vi{ixeq}(ixmC0Pres{ki}(:,2),:);  % transposed restriction matrix Li
-            % V_j(i,:) in f_j(i) = V_j(i,:)*g_j
+                                                   % V_j(i,:) in f_j(i) = V_j(i,:)*g_j
             ci = ixmC0Pres{ki}(:,4) .* A0hat(ixmC0Pres{ki}(:,3),ixeq);
             % s * a_j(h) in the restriction f_j(i) = s * a_j(h).
             LtH = Lit/Hpinv{ixeq};
diff --git a/matlab/ms-sbvar/ms_simulation.m b/matlab/ms-sbvar/ms_simulation.m
index 04a2e1eea15f2e84ce94ff336a5855b82bc7ba2e..f7832e035f372de8a683b0be133ff7c74790cc65 100644
--- a/matlab/ms-sbvar/ms_simulation.m
+++ b/matlab/ms-sbvar/ms_simulation.m
@@ -14,7 +14,7 @@ function [options_, oo_]=ms_simulation(M_, options_, oo_)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2013 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/ms-sbvar/ms_variance_decomposition.m b/matlab/ms-sbvar/ms_variance_decomposition.m
index 553488acd184828aabc0f1b836df2601a7b1de84..1fe73ddbc4edab37d68b145527974818635e158b 100644
--- a/matlab/ms-sbvar/ms_variance_decomposition.m
+++ b/matlab/ms-sbvar/ms_variance_decomposition.m
@@ -14,7 +14,7 @@ function [options_, oo_]=ms_variance_decomposition(M_, options_, oo_)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011-2016 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -85,7 +85,7 @@ if options_.ms.regime || options_.ms.regimes
     outfile = [outfile 'regime_'];
     if options_.ms.regime
         outfile = [outfile num2str(options_.ms.regime-1) ...
-            '_' options_.ms.output_file_tag '.out'];
+                   '_' options_.ms.output_file_tag '.out'];
     end
 elseif options_.ms.filtered_probabilities
     outfile = [outfile 'filtered_' options_.ms.output_file_tag '.out'];
@@ -103,7 +103,7 @@ if options_.ms.regimes
     for regime_i=1:n_regimes
         vd_title = ['Variance Decomposition, Regime ' num2str(regime_i)];
         vd_data = load([outfile num2str(regime_i-1) '_' ...
-            options_.ms.output_file_tag '.out'], '-ascii');
+                        options_.ms.output_file_tag '.out'], '-ascii');
         vd_data = reshape_ascii_variance_decomposition_data( ...
             M_.endo_nbr, percentiles_size, options_.ms.horizon, vd_data);
         save([vddir filesep 'variance_decomposition_regime_' num2str(regime_i-1) '.mat'], 'vd_data');
diff --git a/matlab/ms-sbvar/ms_write_markov_file.m b/matlab/ms-sbvar/ms_write_markov_file.m
index 02b934a3e79ed358bff1baa051a9ec7c2c83b0f5..7eaa5925fd98e2cb93582138c8af537afae7810a 100644
--- a/matlab/ms-sbvar/ms_write_markov_file.m
+++ b/matlab/ms-sbvar/ms_write_markov_file.m
@@ -10,7 +10,7 @@ function ms_write_markov_file(fname, options)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -27,136 +27,136 @@ function ms_write_markov_file(fname, options)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-    n_chains = length(options.ms.ms_chain);
-    nvars = length(options.varobs);
-    
-    fh = fopen(fname,'w');
-    %/******************************************************************************/
-    %/********************* Markov State Variable Information **********************/
-    %/******************************************************************************/
-    
-    fprintf(fh,'//== Markov State Variables with Simple Restrictions ==//\n\n');
-    
-    
-    %//This number is NOT used but read in.
-    fprintf(fh,'//== Number Observations ==//\n');
-    fprintf(fh,'0\n\n');
-
-    fprintf(fh,'//== Number independent state variables ==//\n');
-    fprintf(fh,'%d\n\n',n_chains);
+n_chains = length(options.ms.ms_chain);
+nvars = length(options.varobs);
 
-    for i_chain = 1:n_chains
+fh = fopen(fname,'w');
+%/******************************************************************************/
+%/********************* Markov State Variable Information **********************/
+%/******************************************************************************/
 
-        %//=====================================================//
-        %//== state_variable[i] (1 <= i <= n_state_variables) ==//
-        %//=====================================================//
-        fprintf(fh,'//== Number of states for state_variable[%d] ==//\n', ...
-                i_chain);
-        n_states = length(options.ms.ms_chain(i_chain).regime);
-        fprintf(fh,'%d\n\n',n_states);
-
-        %//== 03/15/06: DW TVBVAR code reads the data below and overwrite the prior data read somewhere else if any.
-        %//== Each column contains the parameters for a Dirichlet prior on the corresponding
-        %//== column of the transition matrix.  Each element must be positive.  For each column,
-        %//== the relative size of the prior elements determine the relative size of the elements
-        %//== of the transition matrix and overall larger sizes implies a tighter prior.
-        fprintf(fh,['//== Transition matrix prior for state_variable[%d] ==//\n'], ...
-          i_chain);
-        Alpha = ones(n_states,n_states);
-        for i_state = 1:n_states
-            p = 1-1/options.ms.ms_chain(i_chain).regime(i_state).duration;
-            Alpha(i_state,i_state) = p*(n_states-1)/(1-p);
-            fprintf(fh,'%22.16f',Alpha(i_state,:));
-            fprintf(fh,'\n');
+fprintf(fh,'//== Markov State Variables with Simple Restrictions ==//\n\n');
+
+
+%//This number is NOT used but read in.
+fprintf(fh,'//== Number Observations ==//\n');
+fprintf(fh,'0\n\n');
+
+fprintf(fh,'//== Number independent state variables ==//\n');
+fprintf(fh,'%d\n\n',n_chains);
+
+for i_chain = 1:n_chains
+
+    %//=====================================================//
+    %//== state_variable[i] (1 <= i <= n_state_variables) ==//
+    %//=====================================================//
+    fprintf(fh,'//== Number of states for state_variable[%d] ==//\n', ...
+            i_chain);
+    n_states = length(options.ms.ms_chain(i_chain).regime);
+    fprintf(fh,'%d\n\n',n_states);
+
+    %//== 03/15/06: DW TVBVAR code reads the data below and overwrite the prior data read somewhere else if any.
+    %//== Each column contains the parameters for a Dirichlet prior on the corresponding
+    %//== column of the transition matrix.  Each element must be positive.  For each column,
+    %//== the relative size of the prior elements determine the relative size of the elements
+    %//== of the transition matrix and overall larger sizes implies a tighter prior.
+    fprintf(fh,['//== Transition matrix prior for state_variable[%d] ==//\n'], ...
+            i_chain);
+    Alpha = ones(n_states,n_states);
+    for i_state = 1:n_states
+        p = 1-1/options.ms.ms_chain(i_chain).regime(i_state).duration;
+        Alpha(i_state,i_state) = p*(n_states-1)/(1-p);
+        fprintf(fh,'%22.16f',Alpha(i_state,:));
+        fprintf(fh,'\n');
+    end
+
+    fprintf(fh,['\n//== Dirichlet dimensions for state_variable[%d] ' ...
+                '==//\n'],i_chain);
+    %        fprintf(fh,'%d ',repmat(n_states,1,n_states));
+    fprintf(fh,'%d ',repmat(2,1,n_states));
+    fprintf(fh,'\n\n');
+
+    %//== The jth restriction matrix is n_states-by-free[j].  Each row of the restriction
+    %//== matrix has exactly one non-zero entry and the sum of each column must be one.
+    fprintf(fh,['//== Column restrictions for state_variable[%d] ' ...
+                '==//\n'],i_chain);
+    for i_state = 1:n_states
+        if i_state == 1
+            M = eye(n_states,2);
+        elseif i_state == n_states
+            M = [zeros(n_states-2,2); eye(2)];
+        else
+            M = zeros(n_states,2);
+            M(i_state+[-1 1],1) = ones(2,1)/2;
+            M(i_state,2) = 1;
+            disp(M)
         end
- 
-        fprintf(fh,['\n//== Dirichlet dimensions for state_variable[%d] ' ...
-                    '==//\n'],i_chain);
-        %        fprintf(fh,'%d ',repmat(n_states,1,n_states));
-        fprintf(fh,'%d ',repmat(2,1,n_states));
-        fprintf(fh,'\n\n');
-
-        %//== The jth restriction matrix is n_states-by-free[j].  Each row of the restriction
-        %//== matrix has exactly one non-zero entry and the sum of each column must be one.
-        fprintf(fh,['//== Column restrictions for state_variable[%d] ' ...
-                    '==//\n'],i_chain);
-        for i_state = 1:n_states
-            if i_state == 1
-                M = eye(n_states,2);
-            elseif i_state == n_states
-                M = [zeros(n_states-2,2); eye(2)];
-            else
-                M = zeros(n_states,2);
-                M(i_state+[-1 1],1) = ones(2,1)/2;
-                M(i_state,2) = 1;
-                disp(M)
-            end
-            for j_state = 1:n_states
-                fprintf(fh,'%f ',M(j_state,:));
-                fprintf(fh,'\n');
-            end
+        for j_state = 1:n_states
+            fprintf(fh,'%f ',M(j_state,:));
             fprintf(fh,'\n');
         end
+        fprintf(fh,'\n');
     end
+end
+
+%/******************************************************************************/
+%/******************************* VAR Parameters *******************************/
+%/******************************************************************************/
+%//NOT read
+fprintf(fh,'//== Number Variables ==//\n');
+fprintf(fh,'%d\n\n',nvars);
+
+%//NOT read
+fprintf(fh,'//== Number Lags ==//\n');
+fprintf(fh,'%d\n\n',options.ms.nlags);
+
+%//NOT read
+fprintf(fh,'//== Exogenous Variables ==//\n');
+fprintf(fh,'1\n\n');
+
+
+%//== nvar x n_state_variables matrix.  In the jth row, a non-zero value implies that
+%this state variable controls the jth column of A0 and Aplus
+fprintf(fh,['//== Controlling states variables for coefficients ==//\' ...
+            'n']);
 
-    %/******************************************************************************/
-    %/******************************* VAR Parameters *******************************/
-    %/******************************************************************************/
-    %//NOT read
-    fprintf(fh,'//== Number Variables ==//\n');
-    fprintf(fh,'%d\n\n',nvars);
-
-    %//NOT read
-    fprintf(fh,'//== Number Lags ==//\n');
-    fprintf(fh,'%d\n\n',options.ms.nlags);
-
-    %//NOT read
-    fprintf(fh,'//== Exogenous Variables ==//\n');
-    fprintf(fh,'1\n\n');
-
-
-    %//== nvar x n_state_variables matrix.  In the jth row, a non-zero value implies that
-    %this state variable controls the jth column of A0 and Aplus
-    fprintf(fh,['//== Controlling states variables for coefficients ==//\' ...
-                'n']);
-    
-    for i_var = 1:nvars
-        for i_chain = 1:n_chains
-            if ~isfield(options.ms.ms_chain(i_chain),'svar_coefficients') ...
-                    || isempty(options.ms.ms_chain(i_chain).svar_coefficients)
-                i_equations = 0;
-            else
-                i_equations = ...
-                    options.ms.ms_chain(i_chain).svar_coefficients.equations; 
-            end
-            if strcmp(i_equations,'ALL') || any(i_equations == i_var)
-                fprintf(fh,'%d ',1);
-            else
-                fprintf(fh,'%d ',0);
-            end
+for i_var = 1:nvars
+    for i_chain = 1:n_chains
+        if ~isfield(options.ms.ms_chain(i_chain),'svar_coefficients') ...
+                || isempty(options.ms.ms_chain(i_chain).svar_coefficients)
+            i_equations = 0;
+        else
+            i_equations = ...
+                options.ms.ms_chain(i_chain).svar_coefficients.equations;
+        end
+        if strcmp(i_equations,'ALL') || any(i_equations == i_var)
+            fprintf(fh,'%d ',1);
+        else
+            fprintf(fh,'%d ',0);
         end
-        fprintf(fh,'\n');
     end
+    fprintf(fh,'\n');
+end
 
-    %//== nvar x n_state_variables matrix.  In the jth row, a non-zero value implies that
-    %this state variable controls the jth diagonal element of Xi
-    fprintf(fh,'\n//== Controlling states variables for variance ==//\n');
-    for i_var = 1:nvars
-        for i_chain = 1:n_chains
-            if ~isfield(options.ms.ms_chain(i_chain),'svar_variances') ...
-                    || isempty(options.ms.ms_chain(i_chain).svar_variances)
-                    i_equations = 0;
-            else
-                i_equations = ...
-                    options.ms.ms_chain(i_chain).svar_variances.equations; 
-            end
-            if strcmp(i_equations,'ALL') || any(i_equations == i_var)
-                fprintf(fh,'%d ',1);
-            else
-                fprintf(fh,'%d ',0);
-            end
+%//== nvar x n_state_variables matrix.  In the jth row, a non-zero value implies that
+%this state variable controls the jth diagonal element of Xi
+fprintf(fh,'\n//== Controlling states variables for variance ==//\n');
+for i_var = 1:nvars
+    for i_chain = 1:n_chains
+        if ~isfield(options.ms.ms_chain(i_chain),'svar_variances') ...
+                || isempty(options.ms.ms_chain(i_chain).svar_variances)
+            i_equations = 0;
+        else
+            i_equations = ...
+                options.ms.ms_chain(i_chain).svar_variances.equations;
+        end
+        if strcmp(i_equations,'ALL') || any(i_equations == i_var)
+            fprintf(fh,'%d ',1);
+        else
+            fprintf(fh,'%d ',0);
         end
-        fprintf(fh,'\n');
     end
+    fprintf(fh,'\n');
+end
 
-    fclose(fh);
+fclose(fh);
diff --git a/matlab/ms-sbvar/ms_write_mhm_input.m b/matlab/ms-sbvar/ms_write_mhm_input.m
index 57854d59ae3f6958fb3ca785859467f73a2b3f51..26ec655cd9c23e0bf68355c4a5390d19aacacdd7 100644
--- a/matlab/ms-sbvar/ms_write_mhm_input.m
+++ b/matlab/ms-sbvar/ms_write_mhm_input.m
@@ -11,7 +11,7 @@ function ms_write_mhm_input(fname, options_ms)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -28,41 +28,41 @@ function ms_write_mhm_input(fname, options_ms)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-    fh = fopen(fname,'w');
+fh = fopen(fname,'w');
 
 
-    fprintf(fh,'/**********************************************************\n');
-    fprintf(fh,' *** This input file is read by swzmsbvar_mhm_1 and swzmsbvar_mhm_1.exe only, NOT by swzmsbvar_printdraws.exe.\n');
-    fprintf(fh,' ***\n');
-    fprintf(fh,' **********************************************************/\n');
+fprintf(fh,'/**********************************************************\n');
+fprintf(fh,' *** This input file is read by swzmsbvar_mhm_1 and swzmsbvar_mhm_1.exe only, NOT by swzmsbvar_printdraws.exe.\n');
+fprintf(fh,' ***\n');
+fprintf(fh,' **********************************************************/\n');
 
-    fprintf(fh,'\n\n//------------- 1st set of posterior draws to find optimal scales for Metropolis (30000). ---------------\n');
-    fprintf(fh,'//== number draws for first burn-in ==//  //For determining the Metropolis scales only.\n');
-    fprintf(fh,'%d\n\n',options_ms.draws_nbr_burn_in_1);
+fprintf(fh,'\n\n//------------- 1st set of posterior draws to find optimal scales for Metropolis (30000). ---------------\n');
+fprintf(fh,'//== number draws for first burn-in ==//  //For determining the Metropolis scales only.\n');
+fprintf(fh,'%d\n\n',options_ms.draws_nbr_burn_in_1);
 
-    fprintf(fh,'//------------- MCMC burn-in draws once the Metropolis scales (previous stage) are fixed. --------------\n');
-    fprintf(fh,'//------------- 2nd set of standard burn-in posterior draws to throw away the initial draws (10000). ---------------\n');
-    fprintf(fh,'//== number draws for second burn-in ==//\n');
-    fprintf(fh,'%d\n\n',options_ms.draws_nbr_burn_in_2);
+fprintf(fh,'//------------- MCMC burn-in draws once the Metropolis scales (previous stage) are fixed. --------------\n');
+fprintf(fh,'//------------- 2nd set of standard burn-in posterior draws to throw away the initial draws (10000). ---------------\n');
+fprintf(fh,'//== number draws for second burn-in ==//\n');
+fprintf(fh,'%d\n\n',options_ms.draws_nbr_burn_in_2);
 
-    fprintf(fh,'//--------------- 1st set of posterior draws to compute the mean and variance for the weighting function in the MHM (200000) ----------------\n');
-    fprintf(fh,'//== number draws to estimate mean and variance ==//\n');
-    fprintf(fh,'%d\n\n',options_ms.draws_nbr_mean_var_estimate);
+fprintf(fh,'//--------------- 1st set of posterior draws to compute the mean and variance for the weighting function in the MHM (200000) ----------------\n');
+fprintf(fh,'//== number draws to estimate mean and variance ==//\n');
+fprintf(fh,'%d\n\n',options_ms.draws_nbr_mean_var_estimate);
 
-    fprintf(fh,'//--------------- Only applied to mhm_2 process: total number of MCMC draws = thinning factor * 2nd set of saved posterior draws ----------------\n');
-    fprintf(fh,'//== thinning factor for modified harmonic mean process ==//\n');
-    fprintf(fh,'%d\n\n',options_ms.thinning_factor);
+fprintf(fh,'//--------------- Only applied to mhm_2 process: total number of MCMC draws = thinning factor * 2nd set of saved posterior draws ----------------\n');
+fprintf(fh,'//== thinning factor for modified harmonic mean process ==//\n');
+fprintf(fh,'%d\n\n',options_ms.thinning_factor);
 
-    fprintf(fh,'//--------------- 2nd set of saved posterior draws from MHM_2 (second stage): saved draws AFTER thinning (1000000) ----------------\n');
-    fprintf(fh,'//== number draws for modified harmonic mean process ==//\n');
-    fprintf(fh,'%d\n\n',options_ms.draws_nbr_modified_harmonic_mean);
+fprintf(fh,'//--------------- 2nd set of saved posterior draws from MHM_2 (second stage): saved draws AFTER thinning (1000000) ----------------\n');
+fprintf(fh,'//== number draws for modified harmonic mean process ==//\n');
+fprintf(fh,'%d\n\n',options_ms.draws_nbr_modified_harmonic_mean);
 
-    fprintf(fh,'//------- 1st stage: computing all three tightness factors for Dirichlet.  ---------\n');
-    fprintf(fh,'//------- 2nd stage: hard-code the second scale factor (in principle, we can do all three). ---------\n');
-    fprintf(fh,'//------- It seems that Dan''s code only use the first element of the following scales.  The scale applies to the Dirichlet''s hyperparameter alpha for the diagonal of the transition matrix in the weighting function.  Note that the weighting function for the transition matrix parameters is Dirichlet. ---------\n');
-            
-    fprintf(fh,'//== scale values for Dirichlet distribution ==//\n');
-    fprintf(fh,'3\n\n');
-    fprintf(fh,'%f ',options_ms.dirichlet_scale);
-    fprintf(fh,'\n');
-    fclose(fh);
\ No newline at end of file
+fprintf(fh,'//------- 1st stage: computing all three tightness factors for Dirichlet.  ---------\n');
+fprintf(fh,'//------- 2nd stage: hard-code the second scale factor (in principle, we can do all three). ---------\n');
+fprintf(fh,'//------- It seems that Dan''s code only use the first element of the following scales.  The scale applies to the Dirichlet''s hyperparameter alpha for the diagonal of the transition matrix in the weighting function.  Note that the weighting function for the transition matrix parameters is Dirichlet. ---------\n');
+
+fprintf(fh,'//== scale values for Dirichlet distribution ==//\n');
+fprintf(fh,'3\n\n');
+fprintf(fh,'%f ',options_ms.dirichlet_scale);
+fprintf(fh,'\n');
+fclose(fh);
\ No newline at end of file
diff --git a/matlab/ms-sbvar/msstart2.m b/matlab/ms-sbvar/msstart2.m
index 6fa5861cd9cb981536c1fc0b21b0ca00d0f0e21c..d02a2338dcd49aa8e65391f2f2aa0c31d0f9b916 100644
--- a/matlab/ms-sbvar/msstart2.m
+++ b/matlab/ms-sbvar/msstart2.m
@@ -12,7 +12,7 @@
 %
 % February 2004
 
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -45,17 +45,17 @@ msstart_setup
 %options_.ms.Indxcol = [1:nvar];  % a vector of random columns in which MC draws are made.
 %
 %options_.ms.indxparr = 1;  % 1: parameters random;  0: no randomness in parameters
-               % Note, when 0, there is no effect from the values of options_.ms.IndxAp, options_.ms.Aband, etc.
+% Note, when 0, there is no effect from the values of options_.ms.IndxAp, options_.ms.Aband, etc.
 %options_.ms.indxovr = 0;   % 1: distributions for other variables of interest; 0: no distribution.
-               % Example:  joint distribution of a(1) and a(2).  Only for specific purposes
+% Example:  joint distribution of a(1) and a(2).  Only for specific purposes
 %options_.ms.Aband = 1;     % 1: error bands with only A0 and A+ random.
 %options_.ms.IndxAp = 1;    % 1: generate draws of A+; 0: no such draws.
-               % Note: when options_.ms.IndxAp=0, there is no effect from the values of options_.ms.options_.ms.options_.ms.options_.ms.indximf, IndxFore,
-               %         or options_.ms.apband.
+% Note: when options_.ms.IndxAp=0, there is no effect from the values of options_.ms.options_.ms.options_.ms.options_.ms.indximf, IndxFore,
+%         or options_.ms.apband.
 %options_.ms.apband = 1;    % 1: error bands for A+; 0: no error bands for A+.
 %*** The following (impulse responses and forecasts) is used only if options_.ms.IndxAp=1
 %options_.ms.indximf = 1;   % 1: generate draws of impulse responses; 0: no such draws (thus no effect
-               %      from options_.ms.imfband)
+%      from options_.ms.imfband)
 %options_.ms.imfband = 1;   % 1: error bands for impulse responses; 0: no error bands
 %options_.ms.indxfore = 0;  % 1: generate draws of forecasts; 0: no such draws (thus no effect from options_.ms.foreband)
 %options_.ms.foreband = 0;  % 1: error bands for out-of-sample forecasts; 0: no error bands
@@ -64,23 +64,23 @@ msstart_setup
 rnum = nvar;      % number of rows in the graph
 cnum = 1;      % number of columns in the graph
 if rnum*cnum<nvar
-   warning('rnum*cnum must be at least as large as nvar')
-   disp('Hit any key to continue, or ctrl-c to abort')
-   pause
+    warning('rnum*cnum must be at least as large as nvar')
+    disp('Hit any key to continue, or ctrl-c to abort')
+    pause
 end
 %options_.ms.indxgimfhat = 1;  % 1: plot ML impulse responses; 0: no plot
 %options_.ms.indxestima = 1;  %1: ML estimation; 0: no estimation and data only
 %
 IndxNmlr = [1 0 0 0 0 0];  % imported by nmlzvar.m
-    % Index for which normalization rule to choose
-    % Only one of the elments in IndxNmlr can be non-zero
-    % IndxNmlr(1): ML A distance rule (supposed to be the best)
-    % IndxNmlr(2): ML Ahat distance rule (to approximate IndxNmlr(1))
-    % IndxNmlr(3): ML Euclidean distance rule (not invariant to scale)
-    % IndxNmlr(4): Positive diagonal rule
-    % IndxNmlr(5): Positive inv(A) diagonal rule (if ~IndxNmlr(5), no need for A0inu,
-    %                                      so let A0inu=[])
-    % IndxNmlr(6): Assigned postive rule (such as off-diagonal elements).  Added 1/3/00
+                           % Index for which normalization rule to choose
+                           % Only one of the elments in IndxNmlr can be non-zero
+                           % IndxNmlr(1): ML A distance rule (supposed to be the best)
+                           % IndxNmlr(2): ML Ahat distance rule (to approximate IndxNmlr(1))
+                           % IndxNmlr(3): ML Euclidean distance rule (not invariant to scale)
+                           % IndxNmlr(4): Positive diagonal rule
+                           % IndxNmlr(5): Positive inv(A) diagonal rule (if ~IndxNmlr(5), no need for A0inu,
+                           %                                      so let A0inu=[])
+                           % IndxNmlr(6): Assigned postive rule (such as off-diagonal elements).  Added 1/3/00
 
 
 %%%%----------------------------------------
@@ -90,7 +90,7 @@ IndxNmlr = [1 0 0 0 0 0];  % imported by nmlzvar.m
 nconstr1=nfqm;      % number of the 1st set of constraints
 nconstr2=options_.forecast ;     % number of the 2nd set of constraints
 nconstr=nconstr1+nconstr2;   % q: 4 years -- 4*12 months.
-                         % When 0, no conditions directly on variables <<>>
+                             % When 0, no conditions directly on variables <<>>
 nconstr=0 ;  %6*nconstr1;
 options_.ms.eq_ms = [];      % location of MS equation; if [], all shocks
 PorR = [4*ones(nconstr1,1);2*ones(nconstr1,1);3*ones(nconstr1,1)];   % the variable conditioned.  1: Pcm; 3: FFR; 4: CPI
@@ -102,32 +102,32 @@ PorR = [PorR;1*ones(nconstr1,1);5*ones(nconstr1,1);6*ones(nconstr1,1)];
 % Conditions directly on future shocks
 %
 %options_.ms.cms = 0     % 1: condition on ms shocks; 0: disable this and "fidcnderr.m" gives
-             %   unconditional forecasts if nconstr = 0 as well;  <<>>
+%   unconditional forecasts if nconstr = 0 as well;  <<>>
 %options_.ms.ncms = 0;   % number of the stance of policy; 0 if no tightening or loosening
 %options_.ms.eq_cms = 1;  % location of MS shocks
 options_.ms.tlindx = 1*ones(1,options_.ms.ncms);  % 1-by-options_.ms.ncms vector; 1: tightening; 0: loosen
 options_.ms.tlnumber = [0.5 0.5 0 0];  %94:4 % [2 2 1.5 1.5]; %79:9  %[1.5 1.5 1 1]; 90:9
-                          % 1-by-options_.ms.ncms vector; cut-off point for MS shocks
+                                       % 1-by-options_.ms.ncms vector; cut-off point for MS shocks
 TLmean = zeros(1,options_.ms.ncms);
-              % unconditional, i.e., 0 mean, for the final report in the paper
+% unconditional, i.e., 0 mean, for the final report in the paper
 if options_.ms.cms
-   options_.ms.eq_ms = [];
-   % At least at this point, it makes no sense to have DLS type of options_.ms.eq_ms; 10/12/98
-   if all(isfinite(options_.ms.tlnumber))
-      for k=1:options_.ms.ncms
-         TLmean(k) = lcnmean(options_.ms.tlnumber(k),options_.ms.tlindx(k));
-                      % shock mean magnitude. 1: tight; 0: loose
-                      % Never used for any subsequent computation but
-                      %   simply used for the final report in the paper.
-         %options_.ms.tlnumber(k) = fzero('lcutoff',0,[],[],TLmean(k))
-                % get an idea about the cutoff point given TLmean instead
-
-      end
-   end
+    options_.ms.eq_ms = [];
+    % At least at this point, it makes no sense to have DLS type of options_.ms.eq_ms; 10/12/98
+    if all(isfinite(options_.ms.tlnumber))
+        for k=1:options_.ms.ncms
+            TLmean(k) = lcnmean(options_.ms.tlnumber(k),options_.ms.tlindx(k));
+            % shock mean magnitude. 1: tight; 0: loose
+            % Never used for any subsequent computation but
+            %   simply used for the final report in the paper.
+            %options_.ms.tlnumber(k) = fzero('lcutoff',0,[],[],TLmean(k))
+            % get an idea about the cutoff point given TLmean instead
+
+        end
+    end
 else
-   options_.ms.ncms = 0;   % only for the use of the graph by msprobg.m
-   options_.ms.tlnumber = NaN*ones(1,options_.ms.ncms);
-               % -infinity, only for the use of the graph by msprobg.m
+    options_.ms.ncms = 0;   % only for the use of the graph by msprobg.m
+    options_.ms.tlnumber = NaN*ones(1,options_.ms.ncms);
+    % -infinity, only for the use of the graph by msprobg.m
 end
 
 
@@ -135,22 +135,22 @@ end
 % Soft conditions on variables
 %
 %cnum = 0  % # of band condtions; when 0, disable this option
-  % Note (different from "fidencon") that each condition corres. to variable
+% Note (different from "fidencon") that each condition corres. to variable
 %options_.ms.banact = 1;    % 1: use infor on actual; 0:  preset without infor on actual
 if cnum
-   banindx = cell(cnum,1);  % index for each variable or conditon
-   banstp = cell(cnum,1);    % steps:  annual in general
-   banvar = zeros(cnum,1);    % varables:  annual in general
-   banval = cell(cnum,1);    % band value (each variable occupy a cell)
-   badval{1} = zeros(length(banstp{1}),2);   % 2: lower or higher bound
-
-   banstp{1} = 1:4;      % 3 or 4 years
-   banvar(1) = 3;      % 3: FFR; 5: CPI
-   if ~options_.ms.banact
-      for i=1:length(banstp{1})
-         banval{1}(i,:) = [5.0 10.0];
-      end
-   end
+    banindx = cell(cnum,1);  % index for each variable or conditon
+    banstp = cell(cnum,1);    % steps:  annual in general
+    banvar = zeros(cnum,1);    % varables:  annual in general
+    banval = cell(cnum,1);    % band value (each variable occupy a cell)
+    badval{1} = zeros(length(banstp{1}),2);   % 2: lower or higher bound
+
+    banstp{1} = 1:4;      % 3 or 4 years
+    banvar(1) = 3;      % 3: FFR; 5: CPI
+    if ~options_.ms.banact
+        for i=1:length(banstp{1})
+            banval{1}(i,:) = [5.0 10.0];
+        end
+    end
 end
 %
 pause(1)
@@ -171,60 +171,60 @@ pause(1)
 %(1)--------------------------------------
 %
 if (options_.ms.freq==12)
-   nStart=(yrStart-options_.ms.initial_year )*12+qmStart-options_.ms.initial_subperiod ;  % positive number of months at the start
-   nEnd=(yrEnd-options_.ms.final_year )*12+qmEnd-options_.ms.final_subperiod ;     % negative number of months towards end
+    nStart=(yrStart-options_.ms.initial_year )*12+qmStart-options_.ms.initial_subperiod ;  % positive number of months at the start
+    nEnd=(yrEnd-options_.ms.final_year )*12+qmEnd-options_.ms.final_subperiod ;     % negative number of months towards end
 elseif (options_.ms.freq==4)
-   nStart=(yrStart-options_.ms.initial_year )*4+qmStart-options_.ms.initial_subperiod ;  % positive number of months at the start
-   nEnd=(yrEnd-options_.ms.final_year )*4+qmEnd-options_.ms.final_subperiod ;     % negative number of months towards end
+    nStart=(yrStart-options_.ms.initial_year )*4+qmStart-options_.ms.initial_subperiod ;  % positive number of months at the start
+    nEnd=(yrEnd-options_.ms.final_year )*4+qmEnd-options_.ms.final_subperiod ;     % negative number of months towards end
 elseif (options_.ms.freq==1)
-   nStart=(yrStart-options_.ms.initial_year )*1+qmStart-options_.ms.initial_subperiod ;  % positive number of months at the start
-   nEnd=(yrEnd-options_.ms.final_year )*1+qmEnd-options_.ms.final_subperiod ;     % negative number of months towards end
+    nStart=(yrStart-options_.ms.initial_year )*1+qmStart-options_.ms.initial_subperiod ;  % positive number of months at the start
+    nEnd=(yrEnd-options_.ms.final_year )*1+qmEnd-options_.ms.final_subperiod ;     % negative number of months towards end
 else
-   error('Error: this code is only good for monthly/quarterly/yearly data!!!')
-   return
+    error('Error: this code is only good for monthly/quarterly/yearly data!!!')
+    return
 end
 %
 if nEnd>0 || nStart<0
-   disp('Warning: this particular sample consider is out of bounds of the data!!!')
-   return
+    disp('Warning: this particular sample consider is out of bounds of the data!!!')
+    return
 end
 %***  Note, both xdgel and xdata have the same start with the specific sample
 xdgel=options_.data(nStart+1:nData+nEnd,options_.ms.vlist);
-      % gel: general options_.data within sample (nSample)
+% gel: general options_.data within sample (nSample)
 if ~(nSample==size(xdgel,1))
-   warning('The sample size (including options_.ms.nlags ) and data are incompatible')
-   disp('Check to make sure nSample and size(xdgel,1) are the same')
-   return
+    warning('The sample size (including options_.ms.nlags ) and data are incompatible')
+    disp('Check to make sure nSample and size(xdgel,1) are the same')
+    return
 end
 %
 baddata = find(isnan(xdgel));
 if ~isempty(baddata)
-   warning('Some data for this selected sample are actually unavailable.')
-   disp('Hit any key to continue, or ctrl-c to abort')
-   pause
+    warning('Some data for this selected sample are actually unavailable.')
+    disp('Hit any key to continue, or ctrl-c to abort')
+    pause
 end
 %
 if options_.ms.initial_subperiod ==1
-   yrB = options_.ms.initial_year ; qmB = options_.ms.initial_subperiod ;
+    yrB = options_.ms.initial_year ; qmB = options_.ms.initial_subperiod ;
 else
-   yrB = options_.ms.initial_year +1; qmB = 1;
+    yrB = options_.ms.initial_year +1; qmB = 1;
 end
 yrF = options_.ms.final_year ; qmF = options_.ms.final_subperiod ;
 [Mdate,tmp] = fn_calyrqm(options_.ms.freq,[options_.ms.initial_year  options_.ms.initial_subperiod ],[options_.ms.final_year options_.ms.final_subperiod ]);
 xdatae=[Mdate options_.data(1:nData,options_.ms.vlist)];
-      % beyond sample into forecast horizon until the end of the data options_.ms.final_year :options_.ms.final_subperiod 
-      % Note: may contain NaN data.  So must be careful about its use
+% beyond sample into forecast horizon until the end of the data options_.ms.final_year :options_.ms.final_subperiod
+% Note: may contain NaN data.  So must be careful about its use
 
 %=========== Obtain prior-period, period-to-last period, and annual growth rates
 [yactyrge,yactyre,yactqmyge,yactqmge,yactqme] = fn_datana(xdatae,options_.ms.freq,options_.ms.log_var,options_.ms.percent_var,[yrB qmB],[yrF qmF]);
 qdates = zeros(size(yactqmyge,1),1);
 for ki=1:length(qdates)
-   qdates(ki) = yactqmyge(1,1) + (yactqmyge(1,2)+ki-2)/options_.ms.freq;
+    qdates(ki) = yactqmyge(1,1) + (yactqmyge(1,2)+ki-2)/options_.ms.freq;
 end
 for ki=1:nvar
-   figure
-   plot(qdates, yactqmyge(:,2+ki)/100)
-   xlabel(options_.ms.varlist{ki})
+    figure
+    plot(qdates, yactqmyge(:,2+ki)/100)
+    xlabel(options_.ms.varlist{ki})
 end
 save outactqmygdata.prn yactqmyge -ascii
 
@@ -236,11 +236,11 @@ spstr1 = 'disp([sprintf(';
 spstr2 = '%4.0f %2.0f';
 yactyrget=yactyrge';
 for ki=1:length(options_.ms.vlist)
-   if ki==length(options_.ms.vlist)
-      spstr2 = [spstr2 ' %8.3f\n'];
-   else
-      spstr2 = [spstr2 ' %8.3f'];
-   end
+    if ki==length(options_.ms.vlist)
+        spstr2 = [spstr2 ' %8.3f\n'];
+    else
+        spstr2 = [spstr2 ' %8.3f'];
+    end
 end
 spstr = [spstr1 'spstr2' ', yactyrget)])'];
 eval(spstr)
@@ -251,11 +251,11 @@ fid = fopen('outyrqm.prn','w');
 fpstr1 = 'fprintf(fid,';
 fpstr2 = '%4.0f %2.0f';
 for ki=1:nvar
-   if ki==nvar
-      fpstr2 = [fpstr2 ' %8.3f\n'];
-   else
-      fpstr2 = [fpstr2 ' %8.3f'];
-   end
+    if ki==nvar
+        fpstr2 = [fpstr2 ' %8.3f\n'];
+    else
+        fpstr2 = [fpstr2 ' %8.3f'];
+    end
 end
 fpstr = [fpstr1 'fpstr2' ', yactyrget);'];
 eval(fpstr)
@@ -264,479 +264,479 @@ fclose(fid);
 
 
 if options_.ms.indxestima
-   %(2)----------------------------------------------------------------------------
-   % Estimation
-   % ML forecast and impulse responses
-   % Hard or soft conditions for conditional forecasts
-   %(2)----------------------------------------------------------------------------
-   %
-   %* Arranged data information, WITHOUT dummy obs when 0 after mu is used.  See fn_rnrprior_covres_dobs.m for using the dummy
-   %    observations as part of an explicit prior.
-   [xtx,xty,yty,fss,phi,y,ncoef,xr,Bh] = fn_dataxy(nvar,options_.ms.nlags ,xdgel,mu,0,nexo);
-   if qmStart+options_.ms.nlags -options_.ms.dummy_obs >0
-      qmStartEsti = rem(qmStart+options_.ms.nlags -options_.ms.dummy_obs ,options_.ms.freq);   % dummy observations are included in the sample.
-      if (~qmStartEsti)
-         qmStartEsti = options_.ms.freq;
-      end
-      yrStartEsti = yrStart + floor((qmStart+options_.ms.nlags -options_.ms.dummy_obs )/(options_.ms.freq+0.01));
+    %(2)----------------------------------------------------------------------------
+    % Estimation
+    % ML forecast and impulse responses
+    % Hard or soft conditions for conditional forecasts
+    %(2)----------------------------------------------------------------------------
+    %
+    %* Arranged data information, WITHOUT dummy obs when 0 after mu is used.  See fn_rnrprior_covres_dobs.m for using the dummy
+    %    observations as part of an explicit prior.
+    [xtx,xty,yty,fss,phi,y,ncoef,xr,Bh] = fn_dataxy(nvar,options_.ms.nlags ,xdgel,mu,0,nexo);
+    if qmStart+options_.ms.nlags -options_.ms.dummy_obs >0
+        qmStartEsti = rem(qmStart+options_.ms.nlags -options_.ms.dummy_obs ,options_.ms.freq);   % dummy observations are included in the sample.
+        if (~qmStartEsti)
+            qmStartEsti = options_.ms.freq;
+        end
+        yrStartEsti = yrStart + floor((qmStart+options_.ms.nlags -options_.ms.dummy_obs )/(options_.ms.freq+0.01));
         % + 0.01 (or any number < 1)  is used so that qmStart+options_.ms.nlags -options_.ms.dummy_obs ==?*options_.ms.freq doesn't give us an extra year forward.
-   else
-      qmStartEsti = options_.ms.freq + rem(qmStart+options_.ms.nlags -options_.ms.dummy_obs ,options_.ms.freq);   % dummy observations are included in the sample.
-      if (qmStart+options_.ms.nlags -options_.ms.dummy_obs ==0)
-         yrStartEsti = yrStart - 1;   % one year back.
-      else
-         yrStartEsti = yrStart + floor((qmStart+options_.ms.nlags -options_.ms.dummy_obs )/(options_.ms.freq-0.01));
-        % - 0.01 (or any number < 1)  is used so that qmStart+options_.ms.nlags -options_.ms.dummy_obs ==-?*options_.ms.freq give us an extra year back.
-      end
-   end
-   dateswd = fn_dataext([yrStartEsti qmStartEsti],[yrEnd qmEnd],xdatae(:,[1:2]));  % dates with dummies
-   phie = [dateswd phi];
-   ye = [dateswd y];
-
-   %* Obtain linear restrictions
-   [Uiconst,Viconst,n0,np,ixmC0Pres] = feval(options_.ms.restriction_fname,nvar,nexo,options_.ms );
-   if min(n0)==0
-      skipline()
-      warning('A0: restrictions in dlrprior.m give no free parameter in one of equations')
-      disp('Press ctrl-c to abort')
-      pause
-   elseif min(np)==0
-      skipline()
-      warning('Ap: Restrictions in dlrprior.m give no free parameter in one of equations')
-      disp('Press ctrl-c to abort')
-      pause
-   end
-
-   if options_.ms.contemp_reduced_form 
-      Uiconst=cell(nvar,1); Viconst=cell(ncoef,1);
-      for kj=1:nvar
-         Uiconst{kj} = eye(nvar);  Viconst{kj} = eye(ncoef);
-      end
-   end
-
-   if options_.ms.bayesian_prior 
-      %*** Obtains asymmetric prior (with no linear restrictions) with dummy observations as part of an explicit prior (i.e,
-      %      reflected in Hpmulti and Hpinvmulti).  See Forecast II, pp.69a-69b for details.
-      if 1  % Liquidity effect prior on both MS and MD equations.
-         [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti] = fn_rnrprior_covres_dobs(nvar,options_.ms.freq,options_.ms.nlags ,xdgel,mu,indxDummy,hpmsmd,indxmsmdeqn);
-      else
-         [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti] = fn_rnrprior(nvar,options_.ms.freq,options_.ms.nlags ,xdgel,mu);
-      end
-
-      %*** Combines asymmetric prior with linear restrictions
-      [Ptld,H0invtld,Hpinvtld] = fn_rlrprior(Uiconst,Viconst,Pi,H0multi,Hpmulti,nvar);
-
-      %*** Obtains the posterior matrices for estimation and inference
-      [Pmat,H0inv,Hpinv] = fn_rlrpostr(xtx,xty,yty,Ptld,H0invtld,Hpinvtld,Uiconst,Viconst);
-
-      if options_.ms.contemp_reduced_form 
-         %*** Obtain the ML estimate
-         A0hatinv = chol(H0inv{1}/fss);   % upper triangular but lower triangular choleski
-         A0hat=inv(A0hatinv);
-         a0indx = find(A0hat);
-      else
-         %*** Obtain the ML estimate
-         %   load idenml
-         x = 10*rand(sum(n0),1);
-         H0 = eye(sum(n0));
-         crit = 1.0e-9;
-         nit = 10000;
-         %
-         [fhat,xhat,grad,Hhat,itct,fcount,retcodehat] = ...
-               csminwel('fn_a0freefun',x,H0,'fn_a0freegrad',crit,nit,Uiconst,nvar,n0,fss,H0inv);
-
-         A0hat = fn_tran_b2a(xhat,Uiconst,nvar,n0)
-         A0hatinv = inv(A0hat);
-         fhat
-         xhat
-         grad
-         itct
-         fcount
-         retcodehat
-         save outm.mat xhat A0hat A0hatinv grad fhat itct itct fcount retcodehat
-      end
-   else
-      %*** Obtain the posterior matrices for estimation and inference
-      [Pmat,H0inv,Hpinv] = fn_dlrpostr(xtx,xty,yty,Uiconst,Viconst);
-
-      if options_.ms.contemp_reduced_form 
-         %*** Obtain the ML estimate
-         A0hatinv = chol(H0inv{1}/fss);   % upper triangular but lower triangular choleski
-         A0hat=inv(A0hatinv);
-         a0indx = find(A0hat);
-      else
-         %*** Obtain the ML estimate
-         %   load idenml
-         x = 10*rand(sum(n0),1);
-         H0 = eye(sum(n0));
-         crit = 1.0e-9;
-         nit = 10000;
-         %
-         [fhat,xhat,grad,Hhat,itct,fcount,retcodehat] = ...
-               csminwel('fn_a0freefun',x,H0,'fn_a0freegrad',crit,nit,Uiconst,nvar,n0,fss,H0inv);
-
-         A0hat = fn_tran_b2a(xhat,Uiconst,nvar,n0)
-         A0hatinv = inv(A0hat);
-         fhat
-         xhat
-         grad
-         itct
-         fcount
-         retcodehat
-         save outm.mat xhat A0hat A0hatinv grad fhat itct itct fcount retcodehat
-      end
-   end
-
-   %**** impulse responses
-   swish = A0hatinv;       % each column corresponds to an equation
-   if options_.ms.contemp_reduced_form 
-      xhat = A0hat(a0indx);
-      Bhat=Pmat{1};
-      Fhat = Bhat*A0hat
-      ghat = NaN;
-   else
-      xhat = fn_tran_a2b(A0hat,Uiconst,nvar,n0);
-      [Fhat,ghat] = fn_gfmean(xhat,Pmat,Viconst,nvar,ncoef,n0,np);
-      if options_.ms.cross_restrictions 
-         Fhatur0P = Fhat;  % ur: unrestriced across A0 and A+
-         for ki = 1:size(ixmC0Pres,1)   % loop through the number of equations in which
-                     % cross-A0-A+ restrictions occur. See St. Louis Note p.5.
-            ixeq = ixmC0Pres{ki}(1,1);   % index for the jth equation in consideration.
-            Lit = Viconst{ixeq}(ixmC0Pres{ki}(:,2),:);  % transposed restriction matrix Li
-                     % V_j(i,:) in f_j(i) = V_j(i,:)*g_j
-            ci = ixmC0Pres{ki}(:,4) .* A0hat(ixmC0Pres{ki}(:,3),ixeq);
-                     % s * a_j(h) in the restriction f_j(i) = s * a_j(h).
-            LtH = Lit/Hpinv{ixeq};
-            HLV = LtH'/(LtH*Lit');
-            gihat = Viconst{ixeq}'*Fhatur0P(:,ixeq);
-            Fhat(:,ixeq) = Viconst{ixeq}*(gihat + HLV*(ci-Lit*gihat));
-         end
-      end
-      Fhat
-      Bhat = Fhat/A0hat;   % ncoef-by-nvar reduced form lagged parameters.
-   end
-   nn = [nvar options_.ms.nlags  imstp];
-   imfhat = fn_impulse(Bhat,swish,nn);    % in the form that is congenial to RATS
-   imf3hat=reshape(imfhat,size(imfhat,1),nvar,nvar);
-            % imf3: row--steps, column--nvar responses, 3rd dimension--nvar shocks
-   imf3shat=permute(imf3hat,[1 3 2]);
-            % imf3s: permuted so that row--steps, column--nvar shocks,
-            %                                3rd dimension--nvar responses
-            % Note: reshape(imf3s(1,:,:),nvar,nvar) = A0in  (columns -- equations)
-   if options_.ms.indxgimfhat
-      figure
-   end
-   scaleout = fn_imcgraph(imfhat,nvar,imstp,xlab,ylab,options_.ms.indxgimfhat);
-   imfstd = max(abs(scaleout)');   % row: nvar (largest number); used for standard deviations
-
-   %
-   %  %**** save stds. of both data and impulse responses in idfile1
-   %  temp = [std(yactqmyge(:,3:end)); std(yactyrge(:,3:end)); imfstd];  %<<>>
-   %  save idenyimstd.prn temp -ascii   % export forecast and impulse response to the file "idenyimstd.prn", 3-by-nvar
-   %  %
-   %  %**** save stds. of both data and impulse responses in idfile1
-   %  temp = [std(yactqmyge(:,3:end)); std(yactyrge(:,3:end)); imfstd];  %<<>>
-   %  save idenyimstd.prn temp -ascii   % export forecast and impulse response to the file "idenyimstd.prn", 3-by-nvar
-   %  if options_.ms.indxparr
-   %     idfile1='idenyimstd';
-   %  end
-
-   %=====================================
-   % Now, out-of-sample forecasts. Note: Hm1t does not change with A0.
-   %=====================================
-   %
-   % * updating the last row of X (phi) with the current (last row of) y.
-   tcwx = nvar*options_.ms.nlags ;  % total coefficeint without exogenous variables
-   phil = phi(size(phi,1),:);
-   phil(nvar+1:tcwx) = phil(1:tcwx-nvar);
-   phil(1:nvar) = y(end,:);
-   %*** exogenous variables excluding constant terms
-   if (nexo>1)
-      Xexoe = fn_dataext([yrEnd qmEnd],[yrEnd qmEnd],xdatae(:,[1:2 2+nvar+1:2+nvar+nexo-1]));
-      phil(1,tcwx+1:tcwx+nexo-1) = Xexoe(1,3:end);
-   end
-   %
-   %*** ML unconditional point forecast
-   nn = [nvar options_.ms.nlags  nfqm];
-   if nexo<2
-      yforehat = fn_forecast(Bhat,phil,nn);    % nfqm-by-nvar, in log
-   else
-      Xfexoe = fn_dataext(fdates(1,:),fdates(numel(fdates),:),xdatae(:,[1:2 2+nvar+1:2+nvar+nexo-1]));
-      %Xfexoe = fn_dataext(fdates(1,:),fdates(end,:),xdatae(:,[1:2 2+nvar+1:2+nvar+nexo-1]));
-      yforehat = fn_forecast(Bhat,phil,nn,nexo,Xfexoe(:,3:end));    % nfqm-by-nvar, in log
-   end
-   yforehate = [fdates yforehat];
-   %
-   yact1e = fn_dataext([yrEnd-nayr 1],[yrEnd qmEnd],xdatae(:,1:nvar+2));
-   if options_.ms.real_pseudo_forecast
-      %yact2e = fn_dataext([yrEnd-nayr 1],E2yrqm,xdatae);
-      yact2e = fn_dataext([yrEnd-nayr 1],[fdates(end,1) options_.ms.freq],xdatae(:,1:nvar+2));
-   else
-      yact2e=yact1e;
-   end
-   yafhate = [yact1e; yforehate];  % actual and forecast
-   %
-   %===== Converted to mg, qg, and calendar yg
-   %
-   [yafyrghate,yafyrhate,yafqmyghate] = fn_datana(yafhate,options_.ms.freq,options_.ms.log_var(1:nlogeno),options_.ms.percent_var(1:npereno));
-                  % actual and forecast growth rates
-   [yact2yrge,yact2yre,yact2qmyge] = fn_datana(yact2e,options_.ms.freq,options_.ms.log_var(1:nlogeno),options_.ms.percent_var(1:npereno));
-                  % only actual growth rates
-   yafyrghate
-   if options_.ms.indxgforhat
-      keyindx = [1:nvar];
-      conlab=['unconditional'];
-
-      figure
-      yafyrghate(:,3:end) = yafyrghate(:,3:end)/100;
-      yact2yrge(:,3:end) = yact2yrge(:,3:end)/100;
-      fn_foregraph(yafyrghate,yact2yrge,keyindx,rnum,cnum,options_.ms.freq,ylab,forelabel,conlab)
-   end
-
-   %-------------------------------------------------
-   % Setup for point conditional forecast
-   % ML Conditional Forecast
-   %-------------------------------------------------
-   %
-   %% See Zha's note "Forecast (1)" p. 5, RATS manual (some errors in RATS), etc.
-   %
-   %% Some notations:  y(t+1) = y(t)B1 + e(t+1)inv(A0). e(t+1) is 1-by-n.
-   %%    Let r(t+1)=e(t+1)inv(A0) + e(t+2)C + .... where inv(A0) is impulse
-   %%          response at t=1, C at t=2, etc. The row of inv(A0) or C is
-   %%          all responses to one shock.
-   %%    Let r be q-by-1 (such as r(1) = r(t+1)
-   %%                 = y(t+1) (constrained) - y(t+1) (forecast)).
-   %%    Use impulse responses to find out R (k-by-q) where k=nvar*nsteps
-   %%        where nsteps the largest constrained step.  The key of the program
-   %%        is to creat R using impulse responses
-   %%    Optimal solution for shock e where R'*e=r and e is k-by-1 is
-   %%                 e = R*inv(R'*R)*r.
-   %
-
-   if (nconstr > 0)
-      %*** initializing
-      stepcon=cell(nconstr,1);  % initializing, value y conditioned
-      valuecon=zeros(nconstr,1);  % initializing, value y conditioned
-      varcon=zeros(nconstr,1);  % initializing, endogous variables conditioned
-      varcon(:)=PorR;     % 1: Pcm; 3: FFR; 5: CPI
-
-      %
-      for i=1:nconstr
-         if i<=nconstr1
-            stepcon{i}=i;      % FFR
-         elseif i<=2*nconstr1
-            stepcon{i}=i-nconstr1;      % FFR
-         elseif i<=3*nconstr1
-            stepcon{i}=i-2*nconstr1;      % FFR
-         elseif i<=4*nconstr1
-            stepcon{i}=i-3*nconstr1;      % FFR
-         elseif i<=5*nconstr1
-            stepcon{i}=i-4*nconstr1;      % FFR
-         elseif i<=6*nconstr1
-            stepcon{i}=i-5*nconstr1;      % FFR
-         end
-      end
-
-%      for i=1:nconstr
-%         stepcon{i}=i;      % FFR
-%      end
-
-%      bend=12;
-%      stepcon{1}=[1:bend]'; % average over
-%      stepcon{nconstr1+1}=[1:options_.ms.freq-qmSub]';  % average over the remaing months in 1st forecast year
-%      stepcon{nconstr1+2}=[options_.ms.freq-qmSub+1:options_.ms.freq-qmSub+12]';    % average over 12 months next year
-%      stepcon{nconstr1+3}=[options_.ms.freq-qmSub+13:options_.ms.freq-qmSub+24]';    % average over 12 months. 3rd year
-%      stepcon{nconstr1+4}=[options_.ms.freq-qmSub+25:options_.ms.freq-qmSub+36]';    % average over 12 months. 4th year
-
-%      %**** avearage condition over, say, options_.ms.freq periods
-%      if qmEnd==options_.ms.freq
-%         stepcon{1}=[1:options_.ms.freq]';  % average over the remaing periods in 1st forecast year
-%      else
-%         stepcon{1}=[1:options_.ms.freq-qmEnd]';  % average over the remaing periods in 1st forecast year
-%      end
-%      for kj=2:nconstr
-%         stepcon{kj}=[length(stepcon{kj-1})+1:length(stepcon{kj-1})+options_.ms.freq]';    % average over 12 months next year
-%      end
-
-      if options_.ms.real_pseudo_forecast
-%         %*** conditions in every period
-%         for i=1:nconstr
-%            valuecon(i) = yact(actup+i,varcon(i));
-%            %valuecon(i) = mean( yact(actup+1:actup+bend,varcon(i)) );
-%            %valuecon(i) = 0.060;      % 95:01
-%            %valuecon(i) = (0.0475+0.055)/2;   % 94:10
-%         end
-
-%         %*** average condtions over,say, options_.ms.freq periods.
-%         for i=nconstr1+1:nconstr1+nconstr2
-%            i=1;
-%            valuecon(nconstr1+i) = ( ( mean(ylast12Cal(:,varcon(nconstr1+i)),1) + ...
-%                 log(1+yactCalyg(yAg-yFg+i,varcon(nconstr1+i))/100) )*options_.ms.freq - ...
-%                 yCal_1(:,varcon(nconstr1+i)) ) ./ length(stepcon{nconstr1+i});
-%                             % the same as unconditional "yactCalyg" 1st calendar year
-%            i=2;
-%            valuecon(nconstr1+i) = mean(ylast12Cal(:,varcon(nconstr1+i))) +  ...
-%                 log(1+yactCalyg(yAg-yFg+1,varcon(nconstr1+i))/100) ...
-%                                + log(1+yactCalyg(yAg-yFg+i,varcon(nconstr1+i))/100);
-%                                    % the same as actual "yactCalgy" 2nd calendar year
-%            i=3;
-%            valuecon(nconstr1+i) = valuecon(nconstr1+i-1) + ...
-%                                        log(1+yactCalyg(yAg-yFg+i,varcon(nconstr1+i))/100);
-%                                    % the same as actual "yactCalgy" 3rd calendar year
-%            %i=4;
-%            %valuecon(nconstr1+i) = valuecon(nconstr1+i-1) + ...
-%            %                            log(1+yactCalyg(yAg-yFg+i,varcon(nconstr1+i))/100);
-%                                    % the same as actual "yactCalgy" 4th calendar year
-%         end
-
-         %*** conditions in every period
-         vpntM = fn_dataext(E1yrqm, E2yrqm,xdatae); % point value matrix with dates
-         %     vaveM = fn_dataext([yrEnd+1 0],[yrEnd+options_.forecast  0],yact2yre); % average value matrix with dates
-         for i=1:nconstr
+    else
+        qmStartEsti = options_.ms.freq + rem(qmStart+options_.ms.nlags -options_.ms.dummy_obs ,options_.ms.freq);   % dummy observations are included in the sample.
+        if (qmStart+options_.ms.nlags -options_.ms.dummy_obs ==0)
+            yrStartEsti = yrStart - 1;   % one year back.
+        else
+            yrStartEsti = yrStart + floor((qmStart+options_.ms.nlags -options_.ms.dummy_obs )/(options_.ms.freq-0.01));
+            % - 0.01 (or any number < 1)  is used so that qmStart+options_.ms.nlags -options_.ms.dummy_obs ==-?*options_.ms.freq give us an extra year back.
+        end
+    end
+    dateswd = fn_dataext([yrStartEsti qmStartEsti],[yrEnd qmEnd],xdatae(:,[1:2]));  % dates with dummies
+    phie = [dateswd phi];
+    ye = [dateswd y];
+
+    %* Obtain linear restrictions
+    [Uiconst,Viconst,n0,np,ixmC0Pres] = feval(options_.ms.restriction_fname,nvar,nexo,options_.ms );
+    if min(n0)==0
+        skipline()
+        warning('A0: restrictions in dlrprior.m give no free parameter in one of equations')
+        disp('Press ctrl-c to abort')
+        pause
+    elseif min(np)==0
+        skipline()
+        warning('Ap: Restrictions in dlrprior.m give no free parameter in one of equations')
+        disp('Press ctrl-c to abort')
+        pause
+    end
+
+    if options_.ms.contemp_reduced_form
+        Uiconst=cell(nvar,1); Viconst=cell(ncoef,1);
+        for kj=1:nvar
+            Uiconst{kj} = eye(nvar);  Viconst{kj} = eye(ncoef);
+        end
+    end
+
+    if options_.ms.bayesian_prior
+        %*** Obtains asymmetric prior (with no linear restrictions) with dummy observations as part of an explicit prior (i.e,
+        %      reflected in Hpmulti and Hpinvmulti).  See Forecast II, pp.69a-69b for details.
+        if 1  % Liquidity effect prior on both MS and MD equations.
+            [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti] = fn_rnrprior_covres_dobs(nvar,options_.ms.freq,options_.ms.nlags ,xdgel,mu,indxDummy,hpmsmd,indxmsmdeqn);
+        else
+            [Pi,H0multi,Hpmulti,H0invmulti,Hpinvmulti] = fn_rnrprior(nvar,options_.ms.freq,options_.ms.nlags ,xdgel,mu);
+        end
+
+        %*** Combines asymmetric prior with linear restrictions
+        [Ptld,H0invtld,Hpinvtld] = fn_rlrprior(Uiconst,Viconst,Pi,H0multi,Hpmulti,nvar);
+
+        %*** Obtains the posterior matrices for estimation and inference
+        [Pmat,H0inv,Hpinv] = fn_rlrpostr(xtx,xty,yty,Ptld,H0invtld,Hpinvtld,Uiconst,Viconst);
+
+        if options_.ms.contemp_reduced_form
+            %*** Obtain the ML estimate
+            A0hatinv = chol(H0inv{1}/fss);   % upper triangular but lower triangular choleski
+            A0hat=inv(A0hatinv);
+            a0indx = find(A0hat);
+        else
+            %*** Obtain the ML estimate
+            %   load idenml
+            x = 10*rand(sum(n0),1);
+            H0 = eye(sum(n0));
+            crit = 1.0e-9;
+            nit = 10000;
+            %
+            [fhat,xhat,grad,Hhat,itct,fcount,retcodehat] = ...
+                csminwel('fn_a0freefun',x,H0,'fn_a0freegrad',crit,nit,Uiconst,nvar,n0,fss,H0inv);
+
+            A0hat = fn_tran_b2a(xhat,Uiconst,nvar,n0)
+            A0hatinv = inv(A0hat);
+            fhat
+            xhat
+            grad
+            itct
+            fcount
+            retcodehat
+            save outm.mat xhat A0hat A0hatinv grad fhat itct itct fcount retcodehat
+        end
+    else
+        %*** Obtain the posterior matrices for estimation and inference
+        [Pmat,H0inv,Hpinv] = fn_dlrpostr(xtx,xty,yty,Uiconst,Viconst);
+
+        if options_.ms.contemp_reduced_form
+            %*** Obtain the ML estimate
+            A0hatinv = chol(H0inv{1}/fss);   % upper triangular but lower triangular choleski
+            A0hat=inv(A0hatinv);
+            a0indx = find(A0hat);
+        else
+            %*** Obtain the ML estimate
+            %   load idenml
+            x = 10*rand(sum(n0),1);
+            H0 = eye(sum(n0));
+            crit = 1.0e-9;
+            nit = 10000;
+            %
+            [fhat,xhat,grad,Hhat,itct,fcount,retcodehat] = ...
+                csminwel('fn_a0freefun',x,H0,'fn_a0freegrad',crit,nit,Uiconst,nvar,n0,fss,H0inv);
+
+            A0hat = fn_tran_b2a(xhat,Uiconst,nvar,n0)
+            A0hatinv = inv(A0hat);
+            fhat
+            xhat
+            grad
+            itct
+            fcount
+            retcodehat
+            save outm.mat xhat A0hat A0hatinv grad fhat itct itct fcount retcodehat
+        end
+    end
+
+    %**** impulse responses
+    swish = A0hatinv;       % each column corresponds to an equation
+    if options_.ms.contemp_reduced_form
+        xhat = A0hat(a0indx);
+        Bhat=Pmat{1};
+        Fhat = Bhat*A0hat
+        ghat = NaN;
+    else
+        xhat = fn_tran_a2b(A0hat,Uiconst,nvar,n0);
+        [Fhat,ghat] = fn_gfmean(xhat,Pmat,Viconst,nvar,ncoef,n0,np);
+        if options_.ms.cross_restrictions
+            Fhatur0P = Fhat;  % ur: unrestriced across A0 and A+
+            for ki = 1:size(ixmC0Pres,1)   % loop through the number of equations in which
+                                           % cross-A0-A+ restrictions occur. See St. Louis Note p.5.
+                ixeq = ixmC0Pres{ki}(1,1);   % index for the jth equation in consideration.
+                Lit = Viconst{ixeq}(ixmC0Pres{ki}(:,2),:);  % transposed restriction matrix Li
+                                                            % V_j(i,:) in f_j(i) = V_j(i,:)*g_j
+                ci = ixmC0Pres{ki}(:,4) .* A0hat(ixmC0Pres{ki}(:,3),ixeq);
+                % s * a_j(h) in the restriction f_j(i) = s * a_j(h).
+                LtH = Lit/Hpinv{ixeq};
+                HLV = LtH'/(LtH*Lit');
+                gihat = Viconst{ixeq}'*Fhatur0P(:,ixeq);
+                Fhat(:,ixeq) = Viconst{ixeq}*(gihat + HLV*(ci-Lit*gihat));
+            end
+        end
+        Fhat
+        Bhat = Fhat/A0hat;   % ncoef-by-nvar reduced form lagged parameters.
+    end
+    nn = [nvar options_.ms.nlags  imstp];
+    imfhat = fn_impulse(Bhat,swish,nn);    % in the form that is congenial to RATS
+    imf3hat=reshape(imfhat,size(imfhat,1),nvar,nvar);
+    % imf3: row--steps, column--nvar responses, 3rd dimension--nvar shocks
+    imf3shat=permute(imf3hat,[1 3 2]);
+    % imf3s: permuted so that row--steps, column--nvar shocks,
+    %                                3rd dimension--nvar responses
+    % Note: reshape(imf3s(1,:,:),nvar,nvar) = A0in  (columns -- equations)
+    if options_.ms.indxgimfhat
+        figure
+    end
+    scaleout = fn_imcgraph(imfhat,nvar,imstp,xlab,ylab,options_.ms.indxgimfhat);
+    imfstd = max(abs(scaleout)');   % row: nvar (largest number); used for standard deviations
+
+    %
+    %  %**** save stds. of both data and impulse responses in idfile1
+    %  temp = [std(yactqmyge(:,3:end)); std(yactyrge(:,3:end)); imfstd];  %<<>>
+    %  save idenyimstd.prn temp -ascii   % export forecast and impulse response to the file "idenyimstd.prn", 3-by-nvar
+    %  %
+    %  %**** save stds. of both data and impulse responses in idfile1
+    %  temp = [std(yactqmyge(:,3:end)); std(yactyrge(:,3:end)); imfstd];  %<<>>
+    %  save idenyimstd.prn temp -ascii   % export forecast and impulse response to the file "idenyimstd.prn", 3-by-nvar
+    %  if options_.ms.indxparr
+    %     idfile1='idenyimstd';
+    %  end
+
+    %=====================================
+    % Now, out-of-sample forecasts. Note: Hm1t does not change with A0.
+    %=====================================
+    %
+    % * updating the last row of X (phi) with the current (last row of) y.
+    tcwx = nvar*options_.ms.nlags ;  % total coefficeint without exogenous variables
+    phil = phi(size(phi,1),:);
+    phil(nvar+1:tcwx) = phil(1:tcwx-nvar);
+    phil(1:nvar) = y(end,:);
+    %*** exogenous variables excluding constant terms
+    if (nexo>1)
+        Xexoe = fn_dataext([yrEnd qmEnd],[yrEnd qmEnd],xdatae(:,[1:2 2+nvar+1:2+nvar+nexo-1]));
+        phil(1,tcwx+1:tcwx+nexo-1) = Xexoe(1,3:end);
+    end
+    %
+    %*** ML unconditional point forecast
+    nn = [nvar options_.ms.nlags  nfqm];
+    if nexo<2
+        yforehat = fn_forecast(Bhat,phil,nn);    % nfqm-by-nvar, in log
+    else
+        Xfexoe = fn_dataext(fdates(1,:),fdates(numel(fdates),:),xdatae(:,[1:2 2+nvar+1:2+nvar+nexo-1]));
+        %Xfexoe = fn_dataext(fdates(1,:),fdates(end,:),xdatae(:,[1:2 2+nvar+1:2+nvar+nexo-1]));
+        yforehat = fn_forecast(Bhat,phil,nn,nexo,Xfexoe(:,3:end));    % nfqm-by-nvar, in log
+    end
+    yforehate = [fdates yforehat];
+    %
+    yact1e = fn_dataext([yrEnd-nayr 1],[yrEnd qmEnd],xdatae(:,1:nvar+2));
+    if options_.ms.real_pseudo_forecast
+        %yact2e = fn_dataext([yrEnd-nayr 1],E2yrqm,xdatae);
+        yact2e = fn_dataext([yrEnd-nayr 1],[fdates(end,1) options_.ms.freq],xdatae(:,1:nvar+2));
+    else
+        yact2e=yact1e;
+    end
+    yafhate = [yact1e; yforehate];  % actual and forecast
+                                    %
+                                    %===== Converted to mg, qg, and calendar yg
+                                    %
+    [yafyrghate,yafyrhate,yafqmyghate] = fn_datana(yafhate,options_.ms.freq,options_.ms.log_var(1:nlogeno),options_.ms.percent_var(1:npereno));
+    % actual and forecast growth rates
+    [yact2yrge,yact2yre,yact2qmyge] = fn_datana(yact2e,options_.ms.freq,options_.ms.log_var(1:nlogeno),options_.ms.percent_var(1:npereno));
+    % only actual growth rates
+    yafyrghate
+    if options_.ms.indxgforhat
+        keyindx = [1:nvar];
+        conlab=['unconditional'];
+
+        figure
+        yafyrghate(:,3:end) = yafyrghate(:,3:end)/100;
+        yact2yrge(:,3:end) = yact2yrge(:,3:end)/100;
+        fn_foregraph(yafyrghate,yact2yrge,keyindx,rnum,cnum,options_.ms.freq,ylab,forelabel,conlab)
+    end
+
+    %-------------------------------------------------
+    % Setup for point conditional forecast
+    % ML Conditional Forecast
+    %-------------------------------------------------
+    %
+    %% See Zha's note "Forecast (1)" p. 5, RATS manual (some errors in RATS), etc.
+    %
+    %% Some notations:  y(t+1) = y(t)B1 + e(t+1)inv(A0). e(t+1) is 1-by-n.
+    %%    Let r(t+1)=e(t+1)inv(A0) + e(t+2)C + .... where inv(A0) is impulse
+    %%          response at t=1, C at t=2, etc. The row of inv(A0) or C is
+    %%          all responses to one shock.
+    %%    Let r be q-by-1 (such as r(1) = r(t+1)
+    %%                 = y(t+1) (constrained) - y(t+1) (forecast)).
+    %%    Use impulse responses to find out R (k-by-q) where k=nvar*nsteps
+    %%        where nsteps the largest constrained step.  The key of the program
+    %%        is to creat R using impulse responses
+    %%    Optimal solution for shock e where R'*e=r and e is k-by-1 is
+    %%                 e = R*inv(R'*R)*r.
+    %
+
+    if (nconstr > 0)
+        %*** initializing
+        stepcon=cell(nconstr,1);  % initializing, value y conditioned
+        valuecon=zeros(nconstr,1);  % initializing, value y conditioned
+        varcon=zeros(nconstr,1);  % initializing, endogous variables conditioned
+        varcon(:)=PorR;     % 1: Pcm; 3: FFR; 5: CPI
+
+        %
+        for i=1:nconstr
             if i<=nconstr1
-               valuecon(i) = vpntM(i,2+varcon(i)); % 2: first 2 elements are dates
+                stepcon{i}=i;      % FFR
             elseif i<=2*nconstr1
-               valuecon(i) = vpntM(i-nconstr1,2+varcon(i));
+                stepcon{i}=i-nconstr1;      % FFR
             elseif i<=3*nconstr1
-               valuecon(i) = vpntM(i-2*nconstr1,2+varcon(i));
+                stepcon{i}=i-2*nconstr1;      % FFR
             elseif i<=4*nconstr1
-               valuecon(i) = vpntM(i-3*nconstr1,2+varcon(i));
+                stepcon{i}=i-3*nconstr1;      % FFR
             elseif i<=5*nconstr1
-               valuecon(i) = vpntM(i-4*nconstr1,2+varcon(i));
+                stepcon{i}=i-4*nconstr1;      % FFR
             elseif i<=6*nconstr1
-               valuecon(i) = vpntM(i-5*nconstr1,2+varcon(i));
+                stepcon{i}=i-5*nconstr1;      % FFR
             end
-         end
-
-%         %*** average condtions over,say, options_.ms.freq periods.
-%         if qmEnd==options_.ms.freq
-%            vaveM = fn_dataext([yrEnd+1 0],[yrEnd+options_.forecast  0],yact2yre); % average value matrix with dates
-%            valuecon(1) = vaveM(1,2+varcon(1));  % 2: first 2 elements are dates
-%         else
-%            vaveM = fn_dataext([yrEnd 0],[yrEnd+options_.forecast  0],yact2yre); % average value matrix with dates
-%            yactrem = fn_dataext([yrEnd qmEnd+1],[yrEnd options_.ms.freq],xdatae);
-%            valuecon(1) = sum(yactrem(:,2+varcon(1)),1)/length(stepcon{1});
-%                                    % 2: first 2 elements are dates
-%         end
-%         for kj=2:nconstr
-%            valuecon(kj) = vaveM(kj,2+varcon(kj));  % 2: first 2 elements are dates
-%         end
-      else
-         vpntM = dataext([yrEnd qmEnd+1],[yrEnd qmEnd+2],xdatae); % point value matrix with dates
-         for i=1:nconstr
-            if i<=nconstr1
-               valuecon(i) = vpntM(i,2+varcon(i)); % 2: first 2 elements are dates; Poil
-            elseif i<=2*nconstr1
-               valuecon(i) = vpntM(i-nconstr1,2+varcon(i)); % 2: first 2 elements are dates; M2
-            elseif i<=3*nconstr1
-               valuecon(i) = vpntM(i-2*nconstr1,2+varcon(i)); % 2: first 2 elements are dates; FFR
-            elseif i<=4*nconstr1
-               valuecon(i) = vpntM(i-3*nconstr1,2+varcon(i)); % 2: first 2 elements are dates; CPI
-            elseif i<=5*nconstr1
-               valuecon(i) = vpntM(i-4*nconstr1,2+varcon(i)); % 2: first 2 elements are dates; U
-            elseif i<=5*nconstr1+nconstr2
-               valuecon(i)=xdata(end,5)+(i-5*nconstr1)*log(1.001)/options_.ms.freq;  %CPI
-            elseif i<=5*nconstr1+2*nconstr2
-               valuecon(i)=0.0725;  %FFR
-            else
-               valuecon(i)=xdata(end,6)+(i-5*nconstr1-2*nconstr2)*0.01/nfqm;  %U
+        end
+
+        %      for i=1:nconstr
+        %         stepcon{i}=i;      % FFR
+        %      end
+
+        %      bend=12;
+        %      stepcon{1}=[1:bend]'; % average over
+        %      stepcon{nconstr1+1}=[1:options_.ms.freq-qmSub]';  % average over the remaing months in 1st forecast year
+        %      stepcon{nconstr1+2}=[options_.ms.freq-qmSub+1:options_.ms.freq-qmSub+12]';    % average over 12 months next year
+        %      stepcon{nconstr1+3}=[options_.ms.freq-qmSub+13:options_.ms.freq-qmSub+24]';    % average over 12 months. 3rd year
+        %      stepcon{nconstr1+4}=[options_.ms.freq-qmSub+25:options_.ms.freq-qmSub+36]';    % average over 12 months. 4th year
+
+        %      %**** avearage condition over, say, options_.ms.freq periods
+        %      if qmEnd==options_.ms.freq
+        %         stepcon{1}=[1:options_.ms.freq]';  % average over the remaing periods in 1st forecast year
+        %      else
+        %         stepcon{1}=[1:options_.ms.freq-qmEnd]';  % average over the remaing periods in 1st forecast year
+        %      end
+        %      for kj=2:nconstr
+        %         stepcon{kj}=[length(stepcon{kj-1})+1:length(stepcon{kj-1})+options_.ms.freq]';    % average over 12 months next year
+        %      end
+
+        if options_.ms.real_pseudo_forecast
+            %         %*** conditions in every period
+            %         for i=1:nconstr
+            %            valuecon(i) = yact(actup+i,varcon(i));
+            %            %valuecon(i) = mean( yact(actup+1:actup+bend,varcon(i)) );
+            %            %valuecon(i) = 0.060;      % 95:01
+            %            %valuecon(i) = (0.0475+0.055)/2;   % 94:10
+            %         end
+
+            %         %*** average condtions over,say, options_.ms.freq periods.
+            %         for i=nconstr1+1:nconstr1+nconstr2
+            %            i=1;
+            %            valuecon(nconstr1+i) = ( ( mean(ylast12Cal(:,varcon(nconstr1+i)),1) + ...
+            %                 log(1+yactCalyg(yAg-yFg+i,varcon(nconstr1+i))/100) )*options_.ms.freq - ...
+            %                 yCal_1(:,varcon(nconstr1+i)) ) ./ length(stepcon{nconstr1+i});
+            %                             % the same as unconditional "yactCalyg" 1st calendar year
+            %            i=2;
+            %            valuecon(nconstr1+i) = mean(ylast12Cal(:,varcon(nconstr1+i))) +  ...
+            %                 log(1+yactCalyg(yAg-yFg+1,varcon(nconstr1+i))/100) ...
+            %                                + log(1+yactCalyg(yAg-yFg+i,varcon(nconstr1+i))/100);
+            %                                    % the same as actual "yactCalgy" 2nd calendar year
+            %            i=3;
+            %            valuecon(nconstr1+i) = valuecon(nconstr1+i-1) + ...
+            %                                        log(1+yactCalyg(yAg-yFg+i,varcon(nconstr1+i))/100);
+            %                                    % the same as actual "yactCalgy" 3rd calendar year
+            %            %i=4;
+            %            %valuecon(nconstr1+i) = valuecon(nconstr1+i-1) + ...
+            %            %                            log(1+yactCalyg(yAg-yFg+i,varcon(nconstr1+i))/100);
+            %                                    % the same as actual "yactCalgy" 4th calendar year
+            %         end
+
+            %*** conditions in every period
+            vpntM = fn_dataext(E1yrqm, E2yrqm,xdatae); % point value matrix with dates
+                                                       %     vaveM = fn_dataext([yrEnd+1 0],[yrEnd+options_.forecast  0],yact2yre); % average value matrix with dates
+            for i=1:nconstr
+                if i<=nconstr1
+                    valuecon(i) = vpntM(i,2+varcon(i)); % 2: first 2 elements are dates
+                elseif i<=2*nconstr1
+                    valuecon(i) = vpntM(i-nconstr1,2+varcon(i));
+                elseif i<=3*nconstr1
+                    valuecon(i) = vpntM(i-2*nconstr1,2+varcon(i));
+                elseif i<=4*nconstr1
+                    valuecon(i) = vpntM(i-3*nconstr1,2+varcon(i));
+                elseif i<=5*nconstr1
+                    valuecon(i) = vpntM(i-4*nconstr1,2+varcon(i));
+                elseif i<=6*nconstr1
+                    valuecon(i) = vpntM(i-5*nconstr1,2+varcon(i));
+                end
+            end
+
+            %         %*** average condtions over,say, options_.ms.freq periods.
+            %         if qmEnd==options_.ms.freq
+            %            vaveM = fn_dataext([yrEnd+1 0],[yrEnd+options_.forecast  0],yact2yre); % average value matrix with dates
+            %            valuecon(1) = vaveM(1,2+varcon(1));  % 2: first 2 elements are dates
+            %         else
+            %            vaveM = fn_dataext([yrEnd 0],[yrEnd+options_.forecast  0],yact2yre); % average value matrix with dates
+            %            yactrem = fn_dataext([yrEnd qmEnd+1],[yrEnd options_.ms.freq],xdatae);
+            %            valuecon(1) = sum(yactrem(:,2+varcon(1)),1)/length(stepcon{1});
+            %                                    % 2: first 2 elements are dates
+            %         end
+            %         for kj=2:nconstr
+            %            valuecon(kj) = vaveM(kj,2+varcon(kj));  % 2: first 2 elements are dates
+            %         end
+        else
+            vpntM = dataext([yrEnd qmEnd+1],[yrEnd qmEnd+2],xdatae); % point value matrix with dates
+            for i=1:nconstr
+                if i<=nconstr1
+                    valuecon(i) = vpntM(i,2+varcon(i)); % 2: first 2 elements are dates; Poil
+                elseif i<=2*nconstr1
+                    valuecon(i) = vpntM(i-nconstr1,2+varcon(i)); % 2: first 2 elements are dates; M2
+                elseif i<=3*nconstr1
+                    valuecon(i) = vpntM(i-2*nconstr1,2+varcon(i)); % 2: first 2 elements are dates; FFR
+                elseif i<=4*nconstr1
+                    valuecon(i) = vpntM(i-3*nconstr1,2+varcon(i)); % 2: first 2 elements are dates; CPI
+                elseif i<=5*nconstr1
+                    valuecon(i) = vpntM(i-4*nconstr1,2+varcon(i)); % 2: first 2 elements are dates; U
+                elseif i<=5*nconstr1+nconstr2
+                    valuecon(i)=xdata(end,5)+(i-5*nconstr1)*log(1.001)/options_.ms.freq;  %CPI
+                elseif i<=5*nconstr1+2*nconstr2
+                    valuecon(i)=0.0725;  %FFR
+                else
+                    valuecon(i)=xdata(end,6)+(i-5*nconstr1-2*nconstr2)*0.01/nfqm;  %U
+                end
+            end
+            %valuecon(i) = 0.060;      % 95:01
+        end
+    else
+        valuecon = [];
+        stepcon = [];
+        varcon = [];
+    end
+
+    nstepsm = 0;   % initializing, the maximum step in all constraints
+    for i=1:nconstr
+        nstepsm = max([nstepsm max(stepcon{i})]);
+    end
+
+    if cnum
+        if options_.ms.real_pseudo_forecast && options_.ms.banact
+            for i=1:length(banstp{1})
+                banval{1}(1:length(banstp{1}),1) = ...
+                    yactCalyg(yAg-yFg+1:yAg-yFg+length(banstp{1}),banvar(1)) - 2;
+                banval{1}(1:length(banstp{1}),2) = ...
+                    yactCalyg(yAg-yFg+1:yAg-yFg+length(banstp{1}),banvar(1)) + 2;
             end
-         end
-         %valuecon(i) = 0.060;      % 95:01
-      end
-   else
-      valuecon = [];
-      stepcon = [];
-      varcon = [];
-   end
-
-   nstepsm = 0;   % initializing, the maximum step in all constraints
-   for i=1:nconstr
-      nstepsm = max([nstepsm max(stepcon{i})]);
-   end
-
-   if cnum
-      if options_.ms.real_pseudo_forecast && options_.ms.banact
-         for i=1:length(banstp{1})
-            banval{1}(1:length(banstp{1}),1) = ...
-                yactCalyg(yAg-yFg+1:yAg-yFg+length(banstp{1}),banvar(1)) - 2;
-            banval{1}(1:length(banstp{1}),2) = ...
-                yactCalyg(yAg-yFg+1:yAg-yFg+length(banstp{1}),banvar(1)) + 2;
-         end
-      end
-   end
-
-
-   %===================================================
-   % ML conditional forecast
-   %===================================================
-   %/*
-   [ychat,Estr,rcon] = fn_fcstidcnd(valuecon,stepcon,varcon,nstepsm,...
-            nconstr,options_.ms.eq_ms,nvar,options_.ms.nlags ,phil,0,0,yforehat,imf3shat,A0hat,Bhat,...
-            nfqm,options_.ms.tlindx,options_.ms.tlnumber,options_.ms.ncms,options_.ms.eq_cms);
-   ychate = [fdates ychat];
-   yachate = [yact1e; ychate];  % actual and condtional forecast
-   %===== Converted to mg, qg, and calendar yg
-   [yacyrghate,yacyrhate,yacqmyghate] = fn_datana(yachate,options_.ms.freq,options_.ms.log_var(1:nlogeno),options_.ms.percent_var(1:npereno));
-                         % actual and conditional forecast growth rates
-   if options_.ms.indxgdls && nconstr
-      keyindx = [1:nvar];
-      %  conlab=['conditional on' ylab{PorR(1)}];
-      conlab=['v-conditions'];
-
-      figure
-      fn_foregraph(yafyrghate,yact2yrge,keyindx,rnum,cnum,options_.ms.freq,ylab,forelabel,conlab)
-   end
-
-   if options_.ms.ncsk
-      Estr = zeros(nfqm,nvar);
-      Estr(1:2,:) = [
-         -2.1838      -1.5779      0.53064    -0.099425     -0.69269      -1.0391
-         1.9407       3.3138     -0.10563     -0.55457     -0.68772       1.3534
-                     ];
-      Estr(3:6,3) = [0.5*ones(1,4)]';     % MD shocks
-
-      Estr(3:10,2) = [1.5 1.5 1.5*ones(1,6)]';    % MS shocks
-
-      %Estr(3:6,6) = 1*ones(4,1);      % U shocks
-      %Estr(8:11,4) = 1*ones(4,1);      % y shocks
-
-      %Estr(3:10,2) = [2.5 2.5 1.5*ones(1,6)]';    % MS shocks alone
-
-      nn = [nvar options_.ms.noptions_.ms.nlags  nfqm];
-      ycEhat = forefixe(A0hat,Bhat,phil,nn,Estr);
-      ycEhate = [fdates ycEhat];
-      yacEhate = [yact1e; ycEhate];  % actual and condtional forecast
-      %===== Converted to mg, qg, and calendar yg
-      [yacEyrghate,yacEyrhate,yacEqmyghate] = datana(yacEhate,options_.ms.freq,options_.ms.log_var(1:nlogeno),options_.ms.percent_var(1:npereno));
-                           % actual and conditional forecast growth rates
-      disp([sprintf('%4.0f %2.0f %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f\n',yacEyrghate')])
-
-      if 1
-         keyindx = [1:nvar];
-         %  conlab=['conditional on' ylab{PorR(1)}];
-         conlab=['shock-conditions'];
-
-         figure
-         gyrfore(yacEyrghate,yact2yrge,keyindx,rnum,cnum,ylab,forelabel,conlab)
-      end
-   end
-
-   %-----------------------------------------------------------
-   % Compute structural shocks for the whole sample period excluding dummy observations.
-   %-----------------------------------------------------------
-   ywod = y(options_.ms.dummy_obs +1:end,:);     % without dummy observations
-   phiwod=phi(options_.ms.dummy_obs +1:end,:);    % without dummy observations
-   eplhat=ywod*A0hat-phiwod*Fhat;
-   qmStartWod = mod(qmStart+options_.ms.nlags ,options_.ms.freq);
-   if (~qmStartWod)
-      qmStartWod = options_.ms.freq;
-   end
-   yrStartWod = yrStart + floor((qmStart+options_.ms.nlags -1)/options_.ms.freq);
-   dateswod = fn_dataext([yrStartWod qmStartWod],[yrEnd qmEnd],xdatae(:,[1:2]));
-   eplhate = [dateswod eplhat];
-
-   Aphat = Fhat;
+        end
+    end
+
+
+    %===================================================
+    % ML conditional forecast
+    %===================================================
+    %/*
+    [ychat,Estr,rcon] = fn_fcstidcnd(valuecon,stepcon,varcon,nstepsm,...
+                                     nconstr,options_.ms.eq_ms,nvar,options_.ms.nlags ,phil,0,0,yforehat,imf3shat,A0hat,Bhat,...
+                                     nfqm,options_.ms.tlindx,options_.ms.tlnumber,options_.ms.ncms,options_.ms.eq_cms);
+    ychate = [fdates ychat];
+    yachate = [yact1e; ychate];  % actual and condtional forecast
+                                 %===== Converted to mg, qg, and calendar yg
+    [yacyrghate,yacyrhate,yacqmyghate] = fn_datana(yachate,options_.ms.freq,options_.ms.log_var(1:nlogeno),options_.ms.percent_var(1:npereno));
+    % actual and conditional forecast growth rates
+    if options_.ms.indxgdls && nconstr
+        keyindx = [1:nvar];
+        %  conlab=['conditional on' ylab{PorR(1)}];
+        conlab=['v-conditions'];
+
+        figure
+        fn_foregraph(yafyrghate,yact2yrge,keyindx,rnum,cnum,options_.ms.freq,ylab,forelabel,conlab)
+    end
+
+    if options_.ms.ncsk
+        Estr = zeros(nfqm,nvar);
+        Estr(1:2,:) = [
+            -2.1838      -1.5779      0.53064    -0.099425     -0.69269      -1.0391
+            1.9407       3.3138     -0.10563     -0.55457     -0.68772       1.3534
+                      ];
+        Estr(3:6,3) = [0.5*ones(1,4)]';     % MD shocks
+
+        Estr(3:10,2) = [1.5 1.5 1.5*ones(1,6)]';    % MS shocks
+
+        %Estr(3:6,6) = 1*ones(4,1);      % U shocks
+        %Estr(8:11,4) = 1*ones(4,1);      % y shocks
+
+        %Estr(3:10,2) = [2.5 2.5 1.5*ones(1,6)]';    % MS shocks alone
+
+        nn = [nvar options_.ms.noptions_.ms.nlags  nfqm];
+        ycEhat = forefixe(A0hat,Bhat,phil,nn,Estr);
+        ycEhate = [fdates ycEhat];
+        yacEhate = [yact1e; ycEhate];  % actual and condtional forecast
+                                       %===== Converted to mg, qg, and calendar yg
+        [yacEyrghate,yacEyrhate,yacEqmyghate] = datana(yacEhate,options_.ms.freq,options_.ms.log_var(1:nlogeno),options_.ms.percent_var(1:npereno));
+        % actual and conditional forecast growth rates
+        disp([sprintf('%4.0f %2.0f %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f\n',yacEyrghate')])
+
+        if 1
+            keyindx = [1:nvar];
+            %  conlab=['conditional on' ylab{PorR(1)}];
+            conlab=['shock-conditions'];
+
+            figure
+            gyrfore(yacEyrghate,yact2yrge,keyindx,rnum,cnum,ylab,forelabel,conlab)
+        end
+    end
+
+    %-----------------------------------------------------------
+    % Compute structural shocks for the whole sample period excluding dummy observations.
+    %-----------------------------------------------------------
+    ywod = y(options_.ms.dummy_obs +1:end,:);     % without dummy observations
+    phiwod=phi(options_.ms.dummy_obs +1:end,:);    % without dummy observations
+    eplhat=ywod*A0hat-phiwod*Fhat;
+    qmStartWod = mod(qmStart+options_.ms.nlags ,options_.ms.freq);
+    if (~qmStartWod)
+        qmStartWod = options_.ms.freq;
+    end
+    yrStartWod = yrStart + floor((qmStart+options_.ms.nlags -1)/options_.ms.freq);
+    dateswod = fn_dataext([yrStartWod qmStartWod],[yrEnd qmEnd],xdatae(:,[1:2]));
+    eplhate = [dateswod eplhat];
+
+    Aphat = Fhat;
 end
 
 %----------------------------------------
@@ -745,11 +745,11 @@ end
 %   from different idfile's.
 %----------------------------------------
 %
-%if ~options_.ms.contemp_reduced_form 
+%if ~options_.ms.contemp_reduced_form
 %   SpHR=A0in'*A0in;
 %end
 %%
-%if ~isnan(SpHR) && ~options_.ms.contemp_reduced_form 
+%if ~isnan(SpHR) && ~options_.ms.contemp_reduced_form
 %   warning(' ')
 %   disp('Make sure you run the program with options_.ms.contemp_reduced_form =1 first.')
 %   disp('Otherwise, the following test results such as Schwartz are incorrect.')
diff --git a/matlab/ms-sbvar/msstart_setup.m b/matlab/ms-sbvar/msstart_setup.m
index 37b6e27e9e05e5825264b3f40741adc40ffb73db..b32b92da41a074345282998f7e71e9688a912a9d 100644
--- a/matlab/ms-sbvar/msstart_setup.m
+++ b/matlab/ms-sbvar/msstart_setup.m
@@ -1,6 +1,6 @@
 %function []= msstart_setup(options_)
 
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -26,14 +26,14 @@
 % Exordium I
 %===========================================
 format short g     % format
-%
-%options_.ms.freq = 4;   % quarters or months
-%options_.ms.initial_year=1959;   % beginning of the year
-%options_.ms.initial_subperiod=1;    % begining of the quarter or month
-%options_.ms.final_year=2005;   % final year
-%options_.ms.final_subperiod=4;    % final month or quarter
+                   %
+                   %options_.ms.freq = 4;   % quarters or months
+                   %options_.ms.initial_year=1959;   % beginning of the year
+                   %options_.ms.initial_subperiod=1;    % begining of the quarter or month
+                   %options_.ms.final_year=2005;   % final year
+                   %options_.ms.final_subperiod=4;    % final month or quarter
 nData=(options_.ms.final_year-options_.ms.initial_year)*options_.ms.freq + (options_.ms.final_subperiod-options_.ms.initial_subperiod+1);
-       % total number of the available data -- this is all you have
+% total number of the available data -- this is all you have
 
 %*** Load data and series
 %load datainf_argen.prn      % the default name for the variable is "options_.ms.data".
@@ -61,19 +61,19 @@ nvar = length(options_.varobs);   % number of endogenous variables
 nlogeno = length(options_.ms.log_var);  % number of endogenous variables in options_.ms.log_var
 npereno = length(options_.ms.percent_var);  % number of endogenous variables in options_.ms.percent_var
 if (nvar~=(nlogeno+npereno))
-   skipline()
-   warning('Check xlab, nlogeno or npereno to make sure of endogenous variables in options_.ms.vlist')
-   disp('Press ctrl-c to abort')
-   return
+    skipline()
+    warning('Check xlab, nlogeno or npereno to make sure of endogenous variables in options_.ms.vlist')
+    disp('Press ctrl-c to abort')
+    return
 elseif (nvar==length(options_.ms.vlist))
-   nexo=1;    % only constants as an exogenous variable.  The default setting.
+    nexo=1;    % only constants as an exogenous variable.  The default setting.
 elseif (nvar<length(options_.ms.vlist))
-   nexo=length(options_.ms.vlist)-nvar+1;
+    nexo=length(options_.ms.vlist)-nvar+1;
 else
-   skipline()
-   warning('Make sure there are only nvar endogenous variables in options_.ms.vlist')
-   disp('Press ctrl-c to abort')
-   return
+    skipline()
+    warning('Make sure there are only nvar endogenous variables in options_.ms.vlist')
+    disp('Press ctrl-c to abort')
+    return
 end
 
 
@@ -84,24 +84,24 @@ yrEnd=options_.ms.final_year;
 qmEnd=options_.ms.final_subperiod;
 %options_.forecast = 4;   % number of years for forecasting
 if options_.forecast<1
-   error('To be safe, the number of forecast years should be at least 1')
+    error('To be safe, the number of forecast years should be at least 1')
 end
 forelabel = [num2str(yrEnd) ':' num2str(qmEnd) ' Forecast'];
 
 nSample=(yrEnd-yrStart)*options_.ms.freq + (qmEnd-qmStart+1);
 if qmEnd==options_.ms.freq
-   E1yrqm = [yrEnd+1 1];  % first year and quarter (month) after the sample
+    E1yrqm = [yrEnd+1 1];  % first year and quarter (month) after the sample
 else
-   E1yrqm = [yrEnd qmEnd+1];  % first year and quarter (month) after the sample
+    E1yrqm = [yrEnd qmEnd+1];  % first year and quarter (month) after the sample
 end
 E2yrqm = [yrEnd+options_.forecast qmEnd];   % end at the last month (quarter) of a calendar year after the sample
 [fdates,nfqm]=fn_calyrqm(options_.ms.freq,E1yrqm,E2yrqm);   % forecast dates and number of forecast dates
 [sdates,nsqm] = fn_calyrqm(options_.ms.freq,[yrStart qmStart],[yrEnd qmEnd]);
-   % sdates: dates for the whole sample (including options_.ms.nlags)
+% sdates: dates for the whole sample (including options_.ms.nlags)
 if nSample~=nsqm
-   warning('Make sure that nSample is consistent with the size of sdates')
-   disp('Hit any key to continue, or ctrl-c to abort')
-   pause
+    warning('Make sure that nSample is consistent with the size of sdates')
+    disp('Hit any key to continue, or ctrl-c to abort')
+    pause
 end
 imstp = 4*options_.ms.freq;    % <<>>  impulse responses (4 years)
 nayr = 4; %options_.forecast;  % number of years before forecasting for plotting.
@@ -110,18 +110,18 @@ nayr = 4; %options_.forecast;  % number of years before forecasting for plotting
 %------- Prior, etc. -------
 %options_.ms.nlags = 4;        % number of options_.ms.nlags
 %options_.ms.cross_restrictions = 0;   % 1: cross-A0-and-A+ restrictions; 0: options_.ms.restriction_fname is all we have
-            % Example for indxOres==1: restrictions of the form P(t) = P(t-1).
+% Example for indxOres==1: restrictions of the form P(t) = P(t-1).
 %options_.ms.contemp_reduced_form = 0;  % 1: contemporaneous recursive reduced form; 0: restricted (non-recursive) form
 %options_.ms.real_pseudo_forecast = 0;  % 1: options_.ms.real_pseudo_forecast forecasts; 0: real time forecasts
 %options_.ms.bayesian_prior = 1;  % 1: Bayesian prior; 0: no prior
 indxDummy = options_.ms.bayesian_prior;  % 1: add dummy observations to the data; 0: no dummy added.
-%options_.ms.dummy_obs = 0;  % No dummy observations for xtx, phi, fss, xdatae, etc.  Dummy observations are used as an explicit prior in fn_rnrprior_covres_dobs.m.
-%if indxDummy
-%   options_.ms.dummy_obs=nvar+1;         % number of dummy observations
-%else
-%   options_.ms.dummy_obs=0;    % no dummy observations
-%end
-%=== The following mu is effective only if options_.ms.bayesian_prior==1.
+                                         %options_.ms.dummy_obs = 0;  % No dummy observations for xtx, phi, fss, xdatae, etc.  Dummy observations are used as an explicit prior in fn_rnrprior_covres_dobs.m.
+                                         %if indxDummy
+                                         %   options_.ms.dummy_obs=nvar+1;         % number of dummy observations
+                                         %else
+                                         %   options_.ms.dummy_obs=0;    % no dummy observations
+                                         %end
+                                         %=== The following mu is effective only if options_.ms.bayesian_prior==1.
 
 mu = options_.ms.coefficients_prior_hyperparameters;
 
@@ -142,20 +142,15 @@ tdf = 3;          % degrees of freedom for t-dist for initial draw of the MC loo
 nbuffer = 1000;        % a block or buffer of draws (buffer) that is saved to the disk (not memory)
 ndraws1=1*nbuffer;         % 1st part of Monte Carlo draws
 ndraws2=10*ndraws1;        % 2nd part of Monte Carlo draws
-% seednumber = options_.DynareRandomStreams.seed; %7910;    %472534;   % if 0, random state at each clock time
-%            % good one 420 for [29 45], [29 54]
-% if seednumber
-%    randn('state',seednumber);
-%    rand('state',seednumber);
-% else
-%    randn('state',fix(100*sum(clock)));
-%    rand('state',fix(100*sum(clock)));
-% end
-%  nstarts=1         % number of starting points
-%  imndraws = nstarts*ndraws2;   % total draws for impulse responses or forecasts
-%<<<<<<<<<<<<<<<<<<<
-
-
-
-
-
+                           % seednumber = options_.DynareRandomStreams.seed; %7910;    %472534;   % if 0, random state at each clock time
+                           %            % good one 420 for [29 45], [29 54]
+                           % if seednumber
+                           %    randn('state',seednumber);
+                           %    rand('state',seednumber);
+                           % else
+                           %    randn('state',fix(100*sum(clock)));
+                           %    rand('state',fix(100*sum(clock)));
+                           % end
+                           %  nstarts=1         % number of starting points
+                           %  imndraws = nstarts*ndraws2;   % total draws for impulse responses or forecasts
+                           %<<<<<<<<<<<<<<<<<<<
diff --git a/matlab/ms-sbvar/plot_ms_forecast.m b/matlab/ms-sbvar/plot_ms_forecast.m
index c6f0661f3ca43062a02725298b4baf910cd14713..61f986e90a4454f6cf6908f62061b39753d10925 100644
--- a/matlab/ms-sbvar/plot_ms_forecast.m
+++ b/matlab/ms-sbvar/plot_ms_forecast.m
@@ -15,7 +15,7 @@ function plot_ms_forecast(M_, options_, forecast, figure_name)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -32,122 +32,122 @@ function plot_ms_forecast(M_, options_, forecast, figure_name)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-    nc = 2;
-    nr = 2;
-    nvars = M_.endo_nbr;
-    endo_names = M_.endo_names;
-    var_list = endo_names(1:M_.orig_endo_nbr,:);
-    names = {};
-    tex_names = {};
-    m = 1;
-    for i = 1:size(var_list)
-        tmp = strmatch(var_list(i,:),endo_names,'exact');
-        if isempty(tmp)
-            error([var_list(i,:) ' isn''t and endogenous variable'])
-        end
-        tex_name = deblank(M_.endo_names_tex(i,:));
-        if ~isempty(tex_name)
-            names{m} = deblank(var_list(i,:));
-            tex_names{m} = tex_name;
-            m = m + 1;
-        end
+nc = 2;
+nr = 2;
+nvars = M_.endo_nbr;
+endo_names = M_.endo_names;
+var_list = endo_names(1:M_.orig_endo_nbr,:);
+names = {};
+tex_names = {};
+m = 1;
+for i = 1:size(var_list)
+    tmp = strmatch(var_list(i,:),endo_names,'exact');
+    if isempty(tmp)
+        error([var_list(i,:) ' isn''t and endogenous variable'])
     end
-
-    dims = size(forecast);
-    if (length(dims) == 2)
-        % Point Forecast (horizon x nvars )
-        horizon = dims(1);
-        num_percentiles = 1;
-    elseif (length(dims) == 3)
-        % Banded Forecast
-        horizon = dims(2);
-        num_percentiles = dims(1);
-    else
-        error('The impulse response matrix passed to be plotted does not appear to be the correct size');
+    tex_name = deblank(M_.endo_names_tex(i,:));
+    if ~isempty(tex_name)
+        names{m} = deblank(var_list(i,:));
+        tex_names{m} = tex_name;
+        m = m + 1;
     end
+end
 
-    if num_percentiles == 1
-        plot_point_forecast(forecast, nvars, nr, nc, var_list, figure_name, ...
-            options_.graph_save_formats, options_.TeX, names, tex_names, ...
-            [options_.ms.output_file_tag filesep 'Output' filesep 'Forecast']);
-    else
-        plot_banded_forecast(forecast, nvars, nr, nc, var_list, num_percentiles, ...
-            figure_name, options_.graph_save_formats, options_.TeX, names, tex_names, ...
-            [options_.ms.output_file_tag filesep 'Output' filesep 'Forecast']);
-    end
+dims = size(forecast);
+if (length(dims) == 2)
+    % Point Forecast (horizon x nvars )
+    horizon = dims(1);
+    num_percentiles = 1;
+elseif (length(dims) == 3)
+    % Banded Forecast
+    horizon = dims(2);
+    num_percentiles = dims(1);
+else
+    error('The impulse response matrix passed to be plotted does not appear to be the correct size');
+end
+
+if num_percentiles == 1
+    plot_point_forecast(forecast, nvars, nr, nc, var_list, figure_name, ...
+                        options_.graph_save_formats, options_.TeX, names, tex_names, ...
+                        [options_.ms.output_file_tag filesep 'Output' filesep 'Forecast']);
+else
+    plot_banded_forecast(forecast, nvars, nr, nc, var_list, num_percentiles, ...
+                         figure_name, options_.graph_save_formats, options_.TeX, names, tex_names, ...
+                         [options_.ms.output_file_tag filesep 'Output' filesep 'Forecast']);
+end
 
 end
 
 function plot_point_forecast(forecast,nvars,nr,nc,endo_names,figure_name,save_graph_formats,TeX,names,tex_names,dirname)
-    if nvars > nr*nc
-        graph_name = ['MS (1) ' figure_name];
-        figure('Name', graph_name);
-    else
-        graph_name = figure_name;
-        figure('Name', graph_name);
-    end
-    m = 1;
-    n_fig = 1;
-    for j=1:nvars
-        if m > nr*nc
-            graph_name = ['MS (' int2str(n_fig) ') ' figure_name];
-            dyn_save_graph(dirname,['MS-forecast-' int2str(n_fig)],...
-                           save_graph_formats,TeX,names,tex_names,graph_name);
-            n_fig =n_fig+1;
-            figure('Name', graph_name);
-            m = 1;
-        end
-        subplot(nr,nc,m);
-        vn = deblank(endo_names(j,:));
-        plot(forecast(:,j))
-        title(vn,'Interpreter','none');
-        grid on;
-        m = m+1;
-    end
-    if m > 1
+if nvars > nr*nc
+    graph_name = ['MS (1) ' figure_name];
+    figure('Name', graph_name);
+else
+    graph_name = figure_name;
+    figure('Name', graph_name);
+end
+m = 1;
+n_fig = 1;
+for j=1:nvars
+    if m > nr*nc
+        graph_name = ['MS (' int2str(n_fig) ') ' figure_name];
         dyn_save_graph(dirname,['MS-forecast-' int2str(n_fig)],...
                        save_graph_formats,TeX,names,tex_names,graph_name);
+        n_fig =n_fig+1;
+        figure('Name', graph_name);
+        m = 1;
     end
+    subplot(nr,nc,m);
+    vn = deblank(endo_names(j,:));
+    plot(forecast(:,j))
+    title(vn,'Interpreter','none');
+    grid on;
+    m = m+1;
+end
+if m > 1
+    dyn_save_graph(dirname,['MS-forecast-' int2str(n_fig)],...
+                   save_graph_formats,TeX,names,tex_names,graph_name);
+end
 end
 
 function plot_banded_forecast(forecast,nvars,nr,nc,endo_names,num_percentiles,figure_name,save_graph_formats,TeX,names,tex_names,dirname)
-    if nvars > nr*nc
-        graph_name = ['MS (1) ' figure_name];
-        figure('Name', graph_name);
-    else
-        graph_name = figure_name;
-        figure('Name', graph_name);
+if nvars > nr*nc
+    graph_name = ['MS (1) ' figure_name];
+    figure('Name', graph_name);
+else
+    graph_name = figure_name;
+    figure('Name', graph_name);
+end
+m = 1;
+n_fig = 1;
+for j=1:nvars
+    if m > nr*nc
+        graph_name = ['MS (' int2str(n_fig) ') ' figure_name];
+        dyn_save_graph(dirname,['MS-forecast-' int2str(n_fig)],...
+                       save_graph_formats,TeX,names,tex_names,graph_name);
+        n_fig =n_fig+1;
+        figure('Name',graph_name);
+        m = 1;
     end
-    m = 1;
-    n_fig = 1;
-    for j=1:nvars
-        if m > nr*nc
-            graph_name = ['MS (' int2str(n_fig) ') ' figure_name];
-            dyn_save_graph(dirname,['MS-forecast-' int2str(n_fig)],...
-                           save_graph_formats,TeX,names,tex_names,graph_name);
-            n_fig =n_fig+1;
-            figure('Name',graph_name);
-            m = 1;
+    subplot(nr,nc,m);
+    vn = deblank(endo_names(j,:));
+    for k=1:num_percentiles
+        if ceil(num_percentiles/2) == k
+            plot(forecast(k,:,j),'LineWidth',1.5)
+        else
+            plot(forecast(k,:,j),'LineWidth',1.1)
         end
-        subplot(nr,nc,m);
-        vn = deblank(endo_names(j,:));
-        for k=1:num_percentiles
-            if ceil(num_percentiles/2) == k
-                plot(forecast(k,:,j),'LineWidth',1.5)
-            else
-                plot(forecast(k,:,j),'LineWidth',1.1)
-            end
-            if k==1
-                hold on;
-            end
+        if k==1
+            hold on;
         end
-        title(vn,'Interpreter','none');
-        hold off
-        grid on;
-        m = m+1;
-    end
-    if m > 1
-        dyn_save_graph(dirname,['MS-forecast-' int2str(n_fig)],...
-                       save_graph_formats,TeX,names,tex_names,graph_name);
     end
+    title(vn,'Interpreter','none');
+    hold off
+    grid on;
+    m = m+1;
+end
+if m > 1
+    dyn_save_graph(dirname,['MS-forecast-' int2str(n_fig)],...
+                   save_graph_formats,TeX,names,tex_names,graph_name);
+end
 end
diff --git a/matlab/ms-sbvar/plot_ms_irf.m b/matlab/ms-sbvar/plot_ms_irf.m
index 82c97274791d8a2a434806e5652c4d96a73a8de6..3bff3773b69d7c80fdb24d3b4cdd7dbde9ebc2b9 100644
--- a/matlab/ms-sbvar/plot_ms_irf.m
+++ b/matlab/ms-sbvar/plot_ms_irf.m
@@ -15,7 +15,7 @@ function plot_ms_irf(M_, options_, irf, figure_name, varlist)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -32,108 +32,108 @@ function plot_ms_irf(M_, options_, irf, figure_name, varlist)
 % 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
-        figure_name = '';
-    end
+if nargin < 4
+    figure_name = '';
+end
 
-    nvars = M_.endo_nbr;
-    endo_names = M_.endo_names;
+nvars = M_.endo_nbr;
+endo_names = M_.endo_names;
 
-    if isempty(varlist)
-        var_list = endo_names(1:M_.orig_endo_nbr,:);
-    end
+if isempty(varlist)
+    var_list = endo_names(1:M_.orig_endo_nbr,:);
+end
 
-    names = {};
-    tex_names = {};
-    m = 1;
-    for i = 1:size(var_list)
-        tmp = strmatch(var_list(i,:),endo_names,'exact');
-        if isempty(tmp)
-            error([var_list(i,:) ' isn''t and endogenous variable'])
-        end
-        tex_name = deblank(M_.endo_names_tex(tmp,:));
-        if ~isempty(tex_name)
-            names{m} = deblank(var_list(i,:));
-            tex_names{m} = tex_name;
-            m = m + 1;
-        end
+names = {};
+tex_names = {};
+m = 1;
+for i = 1:size(var_list)
+    tmp = strmatch(var_list(i,:),endo_names,'exact');
+    if isempty(tmp)
+        error([var_list(i,:) ' isn''t and endogenous variable'])
     end
-
-    for i=1:M_.exo_nbr
-        tex_name = deblank(M_.exo_names_tex(i,:));
-        if ~isempty(tex_name)
-            names{m} = deblank(M_.exo_names(i,:));
-            tex_names{m} = tex_name;
-            m = m + 1;
-        end
+    tex_name = deblank(M_.endo_names_tex(tmp,:));
+    if ~isempty(tex_name)
+        names{m} = deblank(var_list(i,:));
+        tex_names{m} = tex_name;
+        m = m + 1;
     end
+end
 
-    dims = size(irf);
-    if (length(dims) == 2)
-        % Point IRF (horizon x (nvarsxnvars) )
-        horizon = dims(1);
-        num_percentiles = 1;
-    elseif (length(dims) == 3)
-        % Banded IRF
-        horizon = dims(2);
-        num_percentiles = dims(1);
-    else
-        error('The impulse response matrix passed to be plotted does not appear to be the correct size');
+for i=1:M_.exo_nbr
+    tex_name = deblank(M_.exo_names_tex(i,:));
+    if ~isempty(tex_name)
+        names{m} = deblank(M_.exo_names(i,:));
+        tex_names{m} = tex_name;
+        m = m + 1;
     end
+end
 
-    if size(endo_names,1) ~= nvars
-        error('The names passed are not the same length as the number of variables');
-    end
+dims = size(irf);
+if (length(dims) == 2)
+    % Point IRF (horizon x (nvarsxnvars) )
+    horizon = dims(1);
+    num_percentiles = 1;
+elseif (length(dims) == 3)
+    % Banded IRF
+    horizon = dims(2);
+    num_percentiles = dims(1);
+else
+    error('The impulse response matrix passed to be plotted does not appear to be the correct size');
+end
 
-    if num_percentiles == 1
-        % loop through the shocks
-        for s=1:nvars
-            shock = zeros(horizon,nvars);
-            for i=1:nvars
-                shock(:,i) = irf(:,((i-1) + ((s-1)*nvars)+1));
-            end
-            plot_point_irf_for_shock(shock, nvars,endo_names, deblank(endo_names(s,:)), ...
-                figure_name, [options_.ms.output_file_tag filesep 'Output' filesep 'IRF'], options_, names, tex_names);
+if size(endo_names,1) ~= nvars
+    error('The names passed are not the same length as the number of variables');
+end
+
+if num_percentiles == 1
+    % loop through the shocks
+    for s=1:nvars
+        shock = zeros(horizon,nvars);
+        for i=1:nvars
+            shock(:,i) = irf(:,((i-1) + ((s-1)*nvars)+1));
         end
-    else
-        for s=1:nvars
-            shock = zeros(horizon,nvars,num_percentiles);
-            for n=1:num_percentiles
-                for i=1:nvars
-                    shock(:,i,n) = irf(n,:,((i-1) + ((s-1)*nvars)+1));
-                end
+        plot_point_irf_for_shock(shock, nvars,endo_names, deblank(endo_names(s,:)), ...
+                                 figure_name, [options_.ms.output_file_tag filesep 'Output' filesep 'IRF'], options_, names, tex_names);
+    end
+else
+    for s=1:nvars
+        shock = zeros(horizon,nvars,num_percentiles);
+        for n=1:num_percentiles
+            for i=1:nvars
+                shock(:,i,n) = irf(n,:,((i-1) + ((s-1)*nvars)+1));
             end
-            plot_banded_irf_for_shock(shock, nvars,endo_names, deblank(endo_names(s,:)), ...
-                figure_name, [options_.ms.output_file_tag filesep 'Output' filesep 'IRF'], options_, names, tex_names);
         end
+        plot_banded_irf_for_shock(shock, nvars,endo_names, deblank(endo_names(s,:)), ...
+                                  figure_name, [options_.ms.output_file_tag filesep 'Output' filesep 'IRF'], options_, names, tex_names);
     end
 end
+end
 
 function [fig] = plot_point_irf_for_shock(irf,nvars,endo_names,shock_name,figure_name,dirname,options_,names,tex_names)
-    fig = figure('Name',figure_name);
-    for k=1:nvars
-        subplot(ceil(sqrt(nvars)), ceil(sqrt(nvars)),k);
-        plot(irf(:,k))
-        disp([endo_names(k,:) ' shock from ' shock_name]);
-        title([endo_names(k,:) ' shock from ' shock_name]);
-    end
-    dyn_save_graph(dirname,[figure_name ' ' shock_name],options_.graph_save_formats, ...
-                   options_.TeX,names,tex_names,[figure_name ' ' shock_name]);
+fig = figure('Name',figure_name);
+for k=1:nvars
+    subplot(ceil(sqrt(nvars)), ceil(sqrt(nvars)),k);
+    plot(irf(:,k))
+    disp([endo_names(k,:) ' shock from ' shock_name]);
+    title([endo_names(k,:) ' shock from ' shock_name]);
+end
+dyn_save_graph(dirname,[figure_name ' ' shock_name],options_.graph_save_formats, ...
+               options_.TeX,names,tex_names,[figure_name ' ' shock_name]);
 end
 
 function [fig] = plot_banded_irf_for_shock(irf,nvars, endo_names, shock_name,figure_name,dirname,options_,names,tex_names)
-    fig = figure('Name',figure_name);
-    npercentiles = size(irf,3);
-    for k=1:nvars
-        subplot(ceil(sqrt(nvars)), ceil(sqrt(nvars)),k);
-        for nn=1:npercentiles
-            plot(irf(:,k,nn))
-            hold on
-        end
-        hold off
-        disp([endo_names(k,:) ' shock from ' shock_name]);
-        title([endo_names(k,:) ' shock from ' shock_name]);
+fig = figure('Name',figure_name);
+npercentiles = size(irf,3);
+for k=1:nvars
+    subplot(ceil(sqrt(nvars)), ceil(sqrt(nvars)),k);
+    for nn=1:npercentiles
+        plot(irf(:,k,nn))
+        hold on
     end
-    dyn_save_graph(dirname,[figure_name ' ' shock_name],options_.graph_save_formats, ...
-                   options_.TeX,names,tex_names,[figure_name ' ' shock_name]);
+    hold off
+    disp([endo_names(k,:) ' shock from ' shock_name]);
+    title([endo_names(k,:) ' shock from ' shock_name]);
+end
+dyn_save_graph(dirname,[figure_name ' ' shock_name],options_.graph_save_formats, ...
+               options_.TeX,names,tex_names,[figure_name ' ' shock_name]);
 end
diff --git a/matlab/ms-sbvar/plot_ms_probabilities.m b/matlab/ms-sbvar/plot_ms_probabilities.m
index 023ecfd4499ee346954a3ce63d42a739354d8aaa..b0e8ec7ca22867c12e2a3b7eecce8eb247eef929 100644
--- a/matlab/ms-sbvar/plot_ms_probabilities.m
+++ b/matlab/ms-sbvar/plot_ms_probabilities.m
@@ -3,7 +3,7 @@ function plot_ms_probabilities(computed_probabilities, options_)
 % Plots the regime probablities for each graph
 %
 % INPUTS
-%    computed_probabilities:      Txnstates 
+%    computed_probabilities:      Txnstates
 %
 % OUTPUTS
 %    none
@@ -11,7 +11,7 @@ function plot_ms_probabilities(computed_probabilities, options_)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -27,41 +27,41 @@ function plot_ms_probabilities(computed_probabilities, options_)
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
-  
-  [T,num_grand_regimes] = size(computed_probabilities);
-  num_chains = length(options_.ms.ms_chain);
-  for i=1:num_chains
+
+[T,num_grand_regimes] = size(computed_probabilities);
+num_chains = length(options_.ms.ms_chain);
+for i=1:num_chains
     chains(i).num_regimes = length(options_.ms.ms_chain(i).regime);
     chains(i).probabilities = zeros([T,chains(i).num_regimes]);
-  end
-  
-  for t=1:T
+end
+
+for t=1:T
     chains = iterate_chain(computed_probabilities(t,:), t, chains, 1, num_chains);
-  end
-  
-  for i=1:num_chains
+end
+
+for i=1:num_chains
     graph_name = ['MS-Probabilities, Chain ' int2str(i)];
     figure('Name',graph_name)
     plot(chains(i).probabilities,'LineWidth', 1.2);
     ltxt = {};
     for j=1:chains(i).num_regimes
-      ltxt{j} = ['Regime ' int2str(j)];
+        ltxt{j} = ['Regime ' int2str(j)];
     end
     legend(ltxt{:});
     title(['Chain ' int2str(i)]);
     ylim([0 1.0]);
     dyn_save_graph([options_.ms.output_file_tag filesep 'Output' filesep 'Probabilities'], ['MS-Probabilities-Chain-' int2str(i)], ...
-        options_.graph_save_formats,options_.TeX,[],[],graph_name);
-  end
+                   options_.graph_save_formats,options_.TeX,[],[],graph_name);
+end
 end
 
 function [chains] = iterate_chain(probs, t, chains, chain, num_chains)
-  offset_length = length(probs)/chains(chain).num_regimes;
-  for i=1:chains(chain).num_regimes
+offset_length = length(probs)/chains(chain).num_regimes;
+for i=1:chains(chain).num_regimes
     p = probs( (i-1)*offset_length+1 : i*offset_length );
     chains(chain).probabilities(t, i) = chains(chain).probabilities(t, i) + sum( p );
     if chain < num_chains
-      chains = iterate_chain(p, t, chains, chain+1, num_chains);
+        chains = iterate_chain(p, t, chains, chain+1, num_chains);
     end
-  end
+end
 end
diff --git a/matlab/ms-sbvar/plot_ms_variance_decomposition.m b/matlab/ms-sbvar/plot_ms_variance_decomposition.m
index 7cd30dca84cd97a42f0057343ff9bd7e1b42b955..d6b39ce635afb408fff2c6f9fe55f3dbb9a8a26e 100644
--- a/matlab/ms-sbvar/plot_ms_variance_decomposition.m
+++ b/matlab/ms-sbvar/plot_ms_variance_decomposition.m
@@ -9,12 +9,12 @@ function plot_ms_variance_decomposition(M_, options_, vd, figure_name, varargin)
 %    figure_name: (string)    graph name
 %
 % OPTIONAL INPUTS
-%		'data': the actual data, TxK with K=number of data series
-%		'steady': the steady state value, TxK
-%		'shock_names': to specify the names of the shocks
-%		'series_names': to specify the names of the different series
-%		'dates': pass a date vector to use, otherwise will just index on 1:T
-%		'colors': Jx3 list of the rgb colors to use for each shock
+%               'data': the actual data, TxK with K=number of data series
+%               'steady': the steady state value, TxK
+%               'shock_names': to specify the names of the shocks
+%               'series_names': to specify the names of the different series
+%               'dates': pass a date vector to use, otherwise will just index on 1:T
+%               'colors': Jx3 list of the rgb colors to use for each shock
 %
 % OUTPUTS
 %    none
@@ -22,7 +22,7 @@ function plot_ms_variance_decomposition(M_, options_, vd, figure_name, varargin)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -44,130 +44,130 @@ if length(size(vd)) == 3
     return;
 end
 
-    nvars = M_.endo_nbr;
-    endo_names = M_.endo_names;
+nvars = M_.endo_nbr;
+endo_names = M_.endo_names;
 
-    names = {};
-    tex_names = {};
-    m = 1;
-    for i=1:M_.orig_endo_nbr
-        tex_name = deblank(M_.endo_names_tex(i,:));
-        if ~isempty(tex_name)
-            names{m} = deblank(endo_names(i,:));
-            tex_names{m} = tex_name;
-            m = m + 1;
-        end
+names = {};
+tex_names = {};
+m = 1;
+for i=1:M_.orig_endo_nbr
+    tex_name = deblank(M_.endo_names_tex(i,:));
+    if ~isempty(tex_name)
+        names{m} = deblank(endo_names(i,:));
+        tex_names{m} = tex_name;
+        m = m + 1;
     end
+end
 
-    dims = size(vd);
-    if length(dims) == 3
-        T = dims(1);
-        K = dims(2);
-        J = dims(3);
-        shocks = vd;
-    else
-        T = dims(1);
-        K = nvars;
-        J = nvars;
-        temp_vd = zeros(T,K,J);
-        for i=1:nvars
-            for j=1:nvars
-                temp_vd(:,i,j) = vd(:,((j-1) + ((i-1)*nvars)+1));
-            end
+dims = size(vd);
+if length(dims) == 3
+    T = dims(1);
+    K = dims(2);
+    J = dims(3);
+    shocks = vd;
+else
+    T = dims(1);
+    K = nvars;
+    J = nvars;
+    temp_vd = zeros(T,K,J);
+    for i=1:nvars
+        for j=1:nvars
+            temp_vd(:,i,j) = vd(:,((j-1) + ((i-1)*nvars)+1));
         end
-        shocks = temp_vd;
     end
+    shocks = temp_vd;
+end
 
-    for i=1:nvars
-        shock_names{i} = endo_names(i,:);
-        series_names{i} = endo_names(i,:);
-    end
+for i=1:nvars
+    shock_names{i} = endo_names(i,:);
+    series_names{i} = endo_names(i,:);
+end
 
-    x = [1:T];
-    plot_dates = 0;
-    data = 0;
-    steady = 0;
-    colors = [ .1 .1 .75
-               .8 0 0
-               1 .7 .25
-               1 1 0
-               .5 1 .5
-               .7 .7 .1
-               .5 .6 .2
-               .1 .5 .1];
+x = [1:T];
+plot_dates = 0;
+data = 0;
+steady = 0;
+colors = [ .1 .1 .75
+           .8 0 0
+           1 .7 .25
+           1 1 0
+           .5 1 .5
+           .7 .7 .1
+           .5 .6 .2
+           .1 .5 .1];
 
-    % overide the defaults with optional inputs
-    for i=1:length(varargin)
-        if strcmpi(varargin{i},'data')
-            data = varargin{i+1};
-        elseif strcmpi(varargin{i},'steady')
-            steady = varargin{i+1};
-        elseif strcmpi(varargin{i},'shock_names')
-            shock_names = varargin{i+1};
-        elseif strcmpi(varargin{i},'series_names')
-            series_names = varargin{i+1};
-        elseif strcmpi(varargin{i}, 'dates')
-            x = varargin{i+1}; plot_dates = 1;
-        elseif strcmpi(varargin{i},'colors')
-            colors = varargin{i+1};
-        end
+% overide the defaults with optional inputs
+for i=1:length(varargin)
+    if strcmpi(varargin{i},'data')
+        data = varargin{i+1};
+    elseif strcmpi(varargin{i},'steady')
+        steady = varargin{i+1};
+    elseif strcmpi(varargin{i},'shock_names')
+        shock_names = varargin{i+1};
+    elseif strcmpi(varargin{i},'series_names')
+        series_names = varargin{i+1};
+    elseif strcmpi(varargin{i}, 'dates')
+        x = varargin{i+1}; plot_dates = 1;
+    elseif strcmpi(varargin{i},'colors')
+        colors = varargin{i+1};
     end
+end
 
-    % add an extra period to the time series
-    x(T+1) = x(T) + (x(T) - x(T-1));
+% add an extra period to the time series
+x(T+1) = x(T) + (x(T) - x(T-1));
 
-    figure('Name',figure_name)
-    for k=1:K
-        % Go through each series
-        subplot(K,1,k);
-        sshocks = shocks(:,k,:);
-        hold on
-        % plot the stacked shocks
-        for t=1:T
-            % step through each time period
-            pos_position = 0; neg_position = 0;
-            xt = [x(t) x(t) x(t+1) x(t+1)];
-            for j=1:J
-                % stack each shock
-                st = sshocks(t,1,j);
-                if st < 0
-                    yi = st+neg_position;
-                    y = [neg_position yi yi neg_position];
-                    neg_position = yi;
-                else
-                    yi = st+pos_position;
-                    y = [pos_position yi yi pos_position];
-                    pos_position = yi;
-                end
-                fill(xt,y,colors(j,:));
-                XY(t,j,:) = y;
-            end
-        end
-        if data
-            plot(x(2:end)',data(:,k),'k','LineWidth',2.5);
-        end
-        if steady
-            plot(x(2:end)',steady(:,k), '--k','LineWidth',2.25);
-        end
-        if k==K
-            if isoctave
-                legend(shock_names,'Location','SouthOutside');
+figure('Name',figure_name)
+for k=1:K
+    % Go through each series
+    subplot(K,1,k);
+    sshocks = shocks(:,k,:);
+    hold on
+    % plot the stacked shocks
+    for t=1:T
+        % step through each time period
+        pos_position = 0; neg_position = 0;
+        xt = [x(t) x(t) x(t+1) x(t+1)];
+        for j=1:J
+            % stack each shock
+            st = sshocks(t,1,j);
+            if st < 0
+                yi = st+neg_position;
+                y = [neg_position yi yi neg_position];
+                neg_position = yi;
             else
-                legend(shock_names,'Location','BestOutside','Orientation','horizontal');
+                yi = st+pos_position;
+                y = [pos_position yi yi pos_position];
+                pos_position = yi;
             end
+            fill(xt,y,colors(j,:));
+            XY(t,j,:) = y;
         end
-
-        hold off
-        if plot_dates
-            datetick 'x';
+    end
+    if data
+        plot(x(2:end)',data(:,k),'k','LineWidth',2.5);
+    end
+    if steady
+        plot(x(2:end)',steady(:,k), '--k','LineWidth',2.25);
+    end
+    if k==K
+        if isoctave
+            legend(shock_names,'Location','SouthOutside');
+        else
+            legend(shock_names,'Location','BestOutside','Orientation','horizontal');
         end
-        xlim([min(x),max(x)])
-        ylim([0 , 1])
-        grid on
-        title(series_names{k});
     end
-    dyn_save_graph([options_.ms.output_file_tag filesep 'Output' ...
-        filesep 'Variance_Decomposition'], 'MS-Variance-Decomposition', ...
-        options_.graph_save_formats, options_.TeX, names, tex_names, ...
-        'Variance decomposition');
+
+    hold off
+    if plot_dates
+        datetick 'x';
+    end
+    xlim([min(x),max(x)])
+    ylim([0 , 1])
+    grid on
+    title(series_names{k});
+end
+dyn_save_graph([options_.ms.output_file_tag filesep 'Output' ...
+                filesep 'Variance_Decomposition'], 'MS-Variance-Decomposition', ...
+               options_.graph_save_formats, options_.TeX, names, tex_names, ...
+               'Variance decomposition');
 end
diff --git a/matlab/ms-sbvar/plot_ms_variance_decomposition_error_bands.m b/matlab/ms-sbvar/plot_ms_variance_decomposition_error_bands.m
index cc03e87c7f31682b03734d78f4fde4803aa8265a..d88e757b5af3029d372ed888aa7c6c57cc7b7e9c 100644
--- a/matlab/ms-sbvar/plot_ms_variance_decomposition_error_bands.m
+++ b/matlab/ms-sbvar/plot_ms_variance_decomposition_error_bands.m
@@ -15,7 +15,7 @@ function plot_ms_variance_decomposition_error_bands(M_, options_, vddata, figure
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -79,14 +79,14 @@ for s=1:nvars
         end
     end
     plot_banded_vddata_for_shock(shock, nvars, endo_names, ...
-        deblank(endo_names(s,:)), figure_name, ...
-        [options_.ms.output_file_tag filesep 'Output' filesep 'Variance_Decomposition'], ...
-        options_, names, tex_names);
+                                 deblank(endo_names(s,:)), figure_name, ...
+                                 [options_.ms.output_file_tag filesep 'Output' filesep 'Variance_Decomposition'], ...
+                                 options_, names, tex_names);
 end
 end
 
 function [fig] = plot_banded_vddata_for_shock(vddata, nvars, endo_names, ...
-    shock_name, figure_name, dirname, options_, names, tex_names)
+                                              shock_name, figure_name, dirname, options_, names, tex_names)
 fig = figure('Name', figure_name);
 npercentiles = size(vddata,3);
 for k=1:nvars
@@ -100,6 +100,6 @@ for k=1:nvars
     title([endo_names(k,:) ' contribution to ' shock_name]);
 end
 dyn_save_graph(dirname, [figure_name ' ' shock_name], ...
-    options_.graph_save_formats, options_.TeX, names, tex_names, ...
-    [figure_name ' ' shock_name]);
+               options_.graph_save_formats, options_.TeX, names, tex_names, ...
+               [figure_name ' ' shock_name]);
 end
diff --git a/matlab/ms-sbvar/sbvar.m b/matlab/ms-sbvar/sbvar.m
index d92d7a6781c8449afd6e91594f7a6ff9ca03937b..874fd12babaf7dff330ed729583f12970cf43f9a 100644
--- a/matlab/ms-sbvar/sbvar.m
+++ b/matlab/ms-sbvar/sbvar.m
@@ -15,7 +15,7 @@ function sbvar(M, options)
 %   none.
 %
 
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2013 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/ms-sbvar/svar_global_identification_check.m b/matlab/ms-sbvar/svar_global_identification_check.m
index 549d5c7fd40150a46bd27d185de9662586c588cf..07397d18dca4d1a56e868d597c09c83b1859b627 100644
--- a/matlab/ms-sbvar/svar_global_identification_check.m
+++ b/matlab/ms-sbvar/svar_global_identification_check.m
@@ -16,7 +16,7 @@ function indent = svar_global_identification_check(options_)
 %   Autoregressions: Theory of Identification and Algorithms for
 %   Inference" in Review of Economic Studies, 77, 665-696.
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -47,7 +47,7 @@ if isequal(options_.ms.restriction_fname, 'upper_cholesky') || ...
 end
 nvar = length(options_.varobs);   % number of endogenous variables
 nexo = 1;
-   
+
 [Uiconst,Viconst,n0,np,ixmC0Pres,Qi,Ri] = exclusions(nvar,nexo,options_.ms );
 
 % order column constraints by rank
diff --git a/matlab/mult_elimination.m b/matlab/mult_elimination.m
index 3d63cfbfd604b1a17a334fe62e150d4c3b013775..91b441d35544315afaed3c5549697cd2e8b0174f 100644
--- a/matlab/mult_elimination.m
+++ b/matlab/mult_elimination.m
@@ -4,7 +4,7 @@ function dr=mult_elimination(varlist,M_, options_, oo_)
 % and shock variables
 %
 % INPUT
-%   none  
+%   none
 %
 % OUTPUT
 %   dr: a structure with the new decision rule
@@ -12,7 +12,7 @@ function dr=mult_elimination(varlist,M_, options_, oo_)
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2003-2012 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -107,13 +107,13 @@ if nvar > 0 && options_.noprint == 0
     for i=1:length(varlist)
         k = strmatch(varlist{i},M_.endo_names(dr.order_var,:),'exact');
         headers = char(headers,varlist{i});
-        
+
         res_table(1:nm_nbr,i) = M1(k,:)';
         res_table(nm_nbr+(1:nm_nbr),i) = M2(k,:)';
         res_table(2*nm_nbr+(1:M_.exo_nbr),i) = M3(k,:)';
         res_table(2*nm_nbr+M_.exo_nbr+(1:M_.exo_nbr),i) = M4(k,:)';
     end
-    
+
     my_title='ELIMINATION OF THE MULTIPLIERS';
     lab = nstates(nil,:);
     labels = strcat(deblank(lab(i,:)),'(-1)');
diff --git a/matlab/multivariate_sample_autocovariance.m b/matlab/multivariate_sample_autocovariance.m
index 6bc0ea32eae54f191fde28177e4990d1ced7fb47..40af070157d4b7e2c8708812d281350c6a39719a 100644
--- a/matlab/multivariate_sample_autocovariance.m
+++ b/matlab/multivariate_sample_autocovariance.m
@@ -1,17 +1,17 @@
 function autocov = multivariate_sample_autocovariance(data,q)
 % Computes the autocovariance function of multivariate time series.
-% 
 %
-% INPUTS 
+%
+% INPUTS
 %   data            [double]       T*m matrix of data.
-%   q               [integer]      Order of the autocovariance function. 
-%    
-% OUTPUTS 
+%   q               [integer]      Order of the autocovariance function.
+%
+% OUTPUTS
 %   autocov         [double]       m*m*(q+1) array, autocovariance function.
 %
 % SPECIAL REQUIREMENTS
 
-% Copyright (C) 2009 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/myboxplot.m b/matlab/myboxplot.m
index fc54607e2b09fc70fc8c834e9d498e11812fcbb3..b3490a4b39eb77da5c61a500f5850e6b8cf9c43f 100644
--- a/matlab/myboxplot.m
+++ b/matlab/myboxplot.m
@@ -4,7 +4,7 @@ function sout = myboxplot (data,notched,symbol,vertical,maxwhisker)
 %  sout = myboxplot (data,notched,symbol,vertical,maxwhisker)
 
 %
-% Copyright (C) 2010-2011 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -33,7 +33,7 @@ if notched==1, notched=0.25; end
 a=1-notched;
 
 % ## figure out how many data sets we have
-if iscell(data), 
+if iscell(data)
     nc = length(data);
 else
     %   if isvector(data), data = data(:); end
@@ -133,7 +133,7 @@ whisker_x(:,[chop,chop+nc]) = [];
 whisker_y(:,[chop,chop+nc]) = [];
 median_x(:,chop) = [];
 median_y(:,chop) = [];
-% % % % 
+% % % %
 % ## Add caps to the remaining whiskers
 cap_x = whisker_x;
 cap_x(1,:) =cap_x(1,:)- 0.05;
@@ -144,12 +144,12 @@ cap_y = whisker_y([1,1],:);
 % #whisker_x,whisker_y
 % #median_x,median_y
 % #cap_x,cap_y
-% 
+%
 % ## Do the plot
 
 mm=min(min(data));
 MM=max(max(data));
-if isnan(mm), mm=0; MM=0; end,
+if isnan(mm), mm=0; MM=0; end
 
 if vertical
     plot (quartile_x, quartile_y, 'b',  ...
@@ -171,7 +171,7 @@ else
     % % % % %     outliers2_y, outliers2_x, [symbol(2),"r;;"]);
 end
 
-if nargout,
+if nargout
     sout=s;
 end
 % % % endfunction
\ No newline at end of file
diff --git a/matlab/mydelete.m b/matlab/mydelete.m
index 13ef6ee9d61db9dd7171486f7e7423100e5ec067..c28d5ad94679cff69731559e3c865837c08f0814 100644
--- a/matlab/mydelete.m
+++ b/matlab/mydelete.m
@@ -1,7 +1,7 @@
 function mydelete(fname,pname)
 % Specialized version of delete() function
 
-% Copyright (C) 2009 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -18,16 +18,16 @@ function mydelete(fname,pname)
 % 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 ==0,
+if nargin ==0
     disp('mydelete(fname)')
     return
 end
 
-if nargin ==1,
+if nargin ==1
     pname='';
 end
 
 file_to_delete = dir([pname,fname]);
-for j=1:length(file_to_delete),
+for j=1:length(file_to_delete)
     delete([pname,file_to_delete(j).name]);
 end
diff --git a/matlab/name2index.m b/matlab/name2index.m
index b653e71c62a9feca12a5880ecab11b8e385185e0..22d116c792513ac145ef573ae6a1214940ec4bb1 100644
--- a/matlab/name2index.m
+++ b/matlab/name2index.m
@@ -2,21 +2,21 @@ function i = name2index(options_, M_, estim_params_, type, name1, name2 )
 % Returns the index associated to an estimated object (deep parameter,
 % variance of a structural shock or measurement error, covariance between
 % two structural shocks, covariance between two measurement errors).
-%  
+%
 % 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).
-%   name1           [string]       
-%   name2           [string]    
+%   name1           [string]
+%   name2           [string]
 % OUTPUTS
 %   i               [integer]      column index (in x2, an array of mh draws) associated to name1[,name2].
 %
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2008-2013 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -63,7 +63,7 @@ if strcmpi(type,'StructuralShock')
         end
     else% Covariance matrix off-diagonal term
         offset = nvx+nvn;
-        try 
+        try
             list_of_structural_shocks = { M_.exo_names(estim_params_.corrx(:,1),:) , M_.exo_names(estim_params_.corrx(:,2),:) };
             k1 = strmatch(name1,list_of_structural_shocks(:,1),'exact');
             k2 = strmatch(name2,list_of_structural_shocks(:,2),'exact');
diff --git a/matlab/non_linear_dsge_likelihood.m b/matlab/non_linear_dsge_likelihood.m
index 17d448927ad82bd7ee77def16b93904239b1624c..1f56c3be41e46866b1ff5bfb5023ea327c0ea2ca 100644
--- a/matlab/non_linear_dsge_likelihood.m
+++ b/matlab/non_linear_dsge_likelihood.m
@@ -150,7 +150,7 @@ end
 %------------------------------------------------------------------------------
 
 % Return, with endogenous penalty, if some parameters are smaller than the lower bound of the prior domain.
-if (DynareOptions.mode_compute~=1) && any(xparam1<BoundsInfo.lb)
+if isestimation(DynareOptions) && (DynareOptions.mode_compute~=1) && any(xparam1<BoundsInfo.lb)
     k = find(xparam1(:) < BoundsInfo.lb);
     fval = Inf;
     exit_flag = 0;
@@ -160,7 +160,7 @@ if (DynareOptions.mode_compute~=1) && any(xparam1<BoundsInfo.lb)
 end
 
 % Return, with endogenous penalty, if some parameters are greater than the upper bound of the prior domain.
-if (DynareOptions.mode_compute~=1) && any(xparam1>BoundsInfo.ub)
+if isestimation(DynareOptions) && (DynareOptions.mode_compute~=1) && any(xparam1>BoundsInfo.ub)
     k = find(xparam1(:)>BoundsInfo.ub);
     fval = Inf;
     exit_flag = 0;
@@ -229,8 +229,8 @@ end
 
 if info(1)
     if info(1) == 3 || info(1) == 4 || info(1) == 5 || info(1)==6 ||info(1) == 19 || ...
-            info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1) == 26 || ...
-            info(1) == 81 || info(1) == 84 ||  info(1) == 85
+                info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1) == 26 || ...
+                info(1) == 81 || info(1) == 84 ||  info(1) == 85
         %meaningful second entry of output that can be used
         fval = Inf;
         info(4) = info(2);
@@ -316,7 +316,8 @@ switch DynareOptions.particle.initialization
     StateVectorVariance = cov(y_');
     DynareOptions.periods = old_DynareOptionsperiods;
     clear('old_DynareOptionsperiods','y_');
-  case 3% Initial state vector covariance is a diagonal matrix.
+  case 3% Initial state vector covariance is a diagonal matrix (to be used
+        % if model has stochastic trends).
     StateVectorMean = ReducedForm.constant(mf0);
     StateVectorVariance = DynareOptions.particle.initial_state_prior_std*eye(number_of_state_variables);
   otherwise
@@ -375,4 +376,3 @@ if isinf(LIK)~=0
     exit_flag = 0;
     return
 end
-
diff --git a/matlab/occbin/call_solve_one_constraint.m b/matlab/occbin/call_solve_one_constraint.m
index b4ec1baed97f70f15033145e759e4d6a2c6e578f..65b98c4319590a11db0ff9b8a914df05d78a269e 100755
--- a/matlab/occbin/call_solve_one_constraint.m
+++ b/matlab/occbin/call_solve_one_constraint.m
@@ -1,21 +1,21 @@
-% Solve model, generate model IRFs
-[zdatalinear zdatapiecewise zdatass oobase_ Mbase_ ] = ...
-         solve_one_constraint(modnam,modnamstar,...
-                              constraint, constraint_relax,...
-                              shockssequence,irfshock,nperiods,maxiter);
-
-
-                          
-% unpack the IRFs                          
-for i=1:Mbase_.endo_nbr
-  eval([deblank(Mbase_.endo_names(i,:)),'_uncdifference=zdatalinear(:,i);']);
-  eval([deblank(Mbase_.endo_names(i,:)),'_difference=zdatapiecewise(:,i);']);
-  eval([deblank(Mbase_.endo_names(i,:)),'_ss=zdatass(i);']);
-end
-
-
-nparams = size(Mbase_.param_names,1);
-
-for i = 1:nparams
-  eval([Mbase_.param_names(i,:),'= Mbase_.params(i);']);
-end
+% Solve model, generate model IRFs
+[zdatalinear, zdatapiecewise, zdatass, oobase_, Mbase_ ] = ...
+    solve_one_constraint(modnam,modnamstar,...
+                         constraint, constraint_relax,...
+                         shockssequence,irfshock,nperiods,maxiter);
+
+
+
+% unpack the IRFs
+for i=1:Mbase_.endo_nbr
+    eval([deblank(Mbase_.endo_names(i,:)),'_uncdifference=zdatalinear(:,i);']);
+    eval([deblank(Mbase_.endo_names(i,:)),'_difference=zdatapiecewise(:,i);']);
+    eval([deblank(Mbase_.endo_names(i,:)),'_ss=zdatass(i);']);
+end
+
+
+nparams = size(Mbase_.param_names,1);
+
+for i = 1:nparams
+    eval([Mbase_.param_names(i,:),'= Mbase_.params(i);']);
+end
diff --git a/matlab/occbin/call_solve_two_constraints.m b/matlab/occbin/call_solve_two_constraints.m
index b782e6db76b9f6c1c1192f63cfcde9e5c0a4e766..5bbc1beb868e001b1126389e36e182249d0116a7 100755
--- a/matlab/occbin/call_solve_two_constraints.m
+++ b/matlab/occbin/call_solve_two_constraints.m
@@ -1,21 +1,21 @@
-[zdatalinear zdatapiecewise zdatass oobase_ Mbase_] = solve_two_constraints(...
-                 modnam_00,modnam_10,modnam_01,modnam_11,...
-                 constraint1, constraint2,...
-                 constraint_relax1, constraint_relax2,...
-                 scalefactormod,irfshock,nperiods,curb_retrench,maxiter);
-
-                           
-for i=1:Mbase_.endo_nbr
-  eval([deblank(Mbase_.endo_names(i,:)),'_uncdifference=zdatalinear(:,i);']);
-  eval([deblank(Mbase_.endo_names(i,:)),'_difference=zdatapiecewise(:,i);']);
-  eval([deblank(Mbase_.endo_names(i,:)),'_ss=zdatass(i);']);
-end
-
-constraint1_difference = process_constraint(constraint1,'_difference',Mbase_.endo_names,0);
-constraint2_difference = process_constraint(constraint2,'_difference',Mbase_.endo_names,0);
-
-nparams = size(Mbase_.param_names,1);
- 
-for i = 1:nparams
-   eval([Mbase_.param_names(i,:),'= Mbase_.params(i);']);
-end
+[zdatalinear, zdatapiecewise, zdatass, oobase_, Mbase_] = solve_two_constraints(...
+    modnam_00,modnam_10,modnam_01,modnam_11,...
+    constraint1, constraint2,...
+    constraint_relax1, constraint_relax2,...
+    scalefactormod,irfshock,nperiods,curb_retrench,maxiter);
+
+
+for i=1:Mbase_.endo_nbr
+    eval([deblank(Mbase_.endo_names(i,:)),'_uncdifference=zdatalinear(:,i);']);
+    eval([deblank(Mbase_.endo_names(i,:)),'_difference=zdatapiecewise(:,i);']);
+    eval([deblank(Mbase_.endo_names(i,:)),'_ss=zdatass(i);']);
+end
+
+constraint1_difference = process_constraint(constraint1,'_difference',Mbase_.endo_names,0);
+constraint2_difference = process_constraint(constraint2,'_difference',Mbase_.endo_names,0);
+
+nparams = size(Mbase_.param_names,1);
+
+for i = 1:nparams
+    eval([Mbase_.param_names(i,:),'= Mbase_.params(i);']);
+end
diff --git a/matlab/occbin/get_deriv.m b/matlab/occbin/get_deriv.m
index 24f1b42aeb8866593514fa040d0b6d56edd125d8..214b1cf42572ce693436e8f817cedca1f6510096 100755
--- a/matlab/occbin/get_deriv.m
+++ b/matlab/occbin/get_deriv.m
@@ -1,83 +1,82 @@
-function [hm1,h,hl1,j,resid] = get_deriv(M_,ys_)
-
-iy_ = M_.lead_lag_incidence;
-it_ = 1;
-
-x = zeros(1,M_.exo_nbr);
-
-% For most models, there are leads, lags and current values of variables
-if size(iy_,1)==3
-  % find non-zero columns of hm1
-  lag_cols = find(iy_(1,:)~=0);
-  % find non-zero columns of h
-  con_cols = find(iy_(2,:));
-  % find non-zero columns of hl1
-  lea_cols = find(iy_(3,:));
-  
-% If models either lacks leads or lags, iy_ will have two rows   
-% In this case, we guess that the row with more nonzeros is the row with current variables
-elseif size(iy_,1)==2
-  % if first row has more nonzero entries than the second, assume model lacks lagged variables 
-  if length(find(iy_(1,:)))>length(find(iy_(2,:)))
-  warning('Model does not have lagged endogenous variables')
-  con_cols = find(iy_(1,:));
-  lea_cols = find(iy_(2,:));
-  lag_cols = [];
-  else
-  warning('Model does not have expected future endogenous variables')
-  lag_cols = find(iy_(1,:));
-  con_cols = find(iy_(2,:));
-  lea_cols = [];
-  end
-  
-end
-    
-  
- 
-% find number of entries for y vector
-ny = length(find(iy_~=0));
-
-% build steady state y
-y = ys_(lag_cols);
-y = [y;ys_(con_cols)];
-y = [y;ys_(lea_cols)];
-
- 
-if ismac
-eval(['[resid,g1]=',M_.fname,'_dynamic(y,x, M_.params, ys_, it_);']);
-% Older versions of DYNARE for Mac did not include ys_ in the call structure    
-%eval(['[resid,g1]=',M_.fname,'_dynamic(y,x, M_.params, it_);']);
-else
-eval(['[resid,g1]=',M_.fname,'_dynamic(y,x, M_.params, ys_, it_);']);
-end
-
- 
-hm1=zeros(M_.endo_nbr);
-h = hm1;
-hl1 = hm1;
-j = zeros(M_.endo_nbr,M_.exo_nbr);
-
- 
-% build hm1
-nlag_cols = length(lag_cols);
-for i=1:nlag_cols
-    hm1(:,lag_cols(i)) = g1(:,i);
-end
-
-% build h
-ncon_cols = length(con_cols);
-for i=1:ncon_cols
-    h(:,con_cols(i)) = g1(:,i+nlag_cols);
-end
-
-% build hl1
-nlea_cols = length(lea_cols);
-for i=1:nlea_cols
-    hl1(:,lea_cols(i)) = g1(:,i+nlag_cols+ncon_cols);
-end
-
- 
-for i = 1:M_.exo_nbr;
-    j(:,i) =g1(:,i+ny);
-end
-
+function [hm1,h,hl1,j,resid] = get_deriv(M_,ys_)
+
+iy_ = M_.lead_lag_incidence;
+it_ = 1;
+
+x = zeros(1,M_.exo_nbr);
+
+% For most models, there are leads, lags and current values of variables
+if size(iy_,1)==3
+    % find non-zero columns of hm1
+    lag_cols = find(iy_(1,:)~=0);
+    % find non-zero columns of h
+    con_cols = find(iy_(2,:));
+    % find non-zero columns of hl1
+    lea_cols = find(iy_(3,:));
+
+    % If models either lacks leads or lags, iy_ will have two rows
+    % In this case, we guess that the row with more nonzeros is the row with current variables
+elseif size(iy_,1)==2
+    % if first row has more nonzero entries than the second, assume model lacks lagged variables
+    if length(find(iy_(1,:)))>length(find(iy_(2,:)))
+        warning('Model does not have lagged endogenous variables')
+        con_cols = find(iy_(1,:));
+        lea_cols = find(iy_(2,:));
+        lag_cols = [];
+    else
+        warning('Model does not have expected future endogenous variables')
+        lag_cols = find(iy_(1,:));
+        con_cols = find(iy_(2,:));
+        lea_cols = [];
+    end
+
+end
+
+
+
+% find number of entries for y vector
+ny = length(find(iy_~=0));
+
+% build steady state y
+y = ys_(lag_cols);
+y = [y;ys_(con_cols)];
+y = [y;ys_(lea_cols)];
+
+
+if ismac
+    eval(['[resid,g1]=',M_.fname,'_dynamic(y,x, M_.params, ys_, it_);']);
+    % Older versions of DYNARE for Mac did not include ys_ in the call structure
+    %eval(['[resid,g1]=',M_.fname,'_dynamic(y,x, M_.params, it_);']);
+else
+    eval(['[resid,g1]=',M_.fname,'_dynamic(y,x, M_.params, ys_, it_);']);
+end
+
+
+hm1=zeros(M_.endo_nbr);
+h = hm1;
+hl1 = hm1;
+j = zeros(M_.endo_nbr,M_.exo_nbr);
+
+
+% build hm1
+nlag_cols = length(lag_cols);
+for i=1:nlag_cols
+    hm1(:,lag_cols(i)) = g1(:,i);
+end
+
+% build h
+ncon_cols = length(con_cols);
+for i=1:ncon_cols
+    h(:,con_cols(i)) = g1(:,i+nlag_cols);
+end
+
+% build hl1
+nlea_cols = length(lea_cols);
+for i=1:nlea_cols
+    hl1(:,lea_cols(i)) = g1(:,i+nlag_cols+ncon_cols);
+end
+
+
+for i = 1:M_.exo_nbr
+    j(:,i) =g1(:,i+ny);
+end
diff --git a/matlab/occbin/get_pq.m b/matlab/occbin/get_pq.m
index 5caab79af26462708ce14753652f00432e913146..99888b8068b68e26d2ad22461463019e169fb4a7 100755
--- a/matlab/occbin/get_pq.m
+++ b/matlab/occbin/get_pq.m
@@ -1,28 +1,28 @@
-function [p,q]=get_pq(dr_,nstatic,nfwrd);
-
-nvars = size(dr_.ghx,1);
-nshocks = size(dr_.ghu,2);
-statevar_pos = (nstatic +1):(nvars-nfwrd);
-
-p = zeros(nvars);
-% interlace matrix
-nnotzero = length(statevar_pos);
-for i=1:nnotzero
-    p(:,statevar_pos(i)) = dr_.ghx(:,i);
-end
-
-% reorder p matrix according to order in lgy_
-inverse_order = zeros(nvars,1);
-for i=1:nvars
-    inverse_order(i) = find(i==dr_.order_var);
-end
-
-p_reordered = zeros(nvars);
-q = zeros(nvars,nshocks);
-for i=1:nvars
-    for j=1:nvars
-        p_reordered(i,j)=p(inverse_order(i),inverse_order(j)); 
-    end
-    q(i,:)=dr_.ghu(inverse_order(i),:); 
-end
+function [p,q]=get_pq(dr_,nstatic,nfwrd)
+
+nvars = size(dr_.ghx,1);
+nshocks = size(dr_.ghu,2);
+statevar_pos = (nstatic +1):(nvars-nfwrd);
+
+p = zeros(nvars);
+% interlace matrix
+nnotzero = length(statevar_pos);
+for i=1:nnotzero
+    p(:,statevar_pos(i)) = dr_.ghx(:,i);
+end
+
+% reorder p matrix according to order in lgy_
+inverse_order = zeros(nvars,1);
+for i=1:nvars
+    inverse_order(i) = find(i==dr_.order_var);
+end
+
+p_reordered = zeros(nvars);
+q = zeros(nvars,nshocks);
+for i=1:nvars
+    for j=1:nvars
+        p_reordered(i,j)=p(inverse_order(i),inverse_order(j));
+    end
+    q(i,:)=dr_.ghu(inverse_order(i),:);
+end
 p=p_reordered;
\ No newline at end of file
diff --git a/matlab/occbin/makechart.m b/matlab/occbin/makechart.m
index a3801e95667af5ae6ec03e4e66960e34b994aff5..934e8463bf1fb8620ba0ede35d5dc2e27600e329 100755
--- a/matlab/occbin/makechart.m
+++ b/matlab/occbin/makechart.m
@@ -1,81 +1,81 @@
-function makechart(titlelist,legendlist,figlabel,ylabels,zdata1,zdata2,zdata3)
-
-
-
-figure
-
-titlelist = char(strrep(cellstr(titlelist),'_','.'));
-
-ndsets=3;       % default, changed below as applicable
-if nargin==5
-    zdata2=nan*zdata1;
-    zdata3=nan*zdata1;
-    ndsets =1;
-elseif nargin == 6
-    zdata3 =nan*zdata1;
-    ndsets=2;
-elseif ((nargin>8) | (nargin <=4))
-    error ('makechart takes 5 to 6 arguments')
-end
-
-nobs = size(zdata1,1);
-xvalues = (1:nobs)';
-
-nvars = size(titlelist,1);
-if nvars==1 
-    nrows=1;
-    ncols = 1;
-elseif nvars==2
-    nrows =2;
-    ncols = 1;
-elseif (nvars == 3 | nvars ==4)
-    nrows = 2;
-    ncols =2;
-elseif (nvars==5 |nvars ==6)
-    nrows = 3;
-    ncols = 2;
-elseif (nvars==7 | nvars==8)
-    nrows = 4;
-    ncols = 2;
-elseif (nvars==9 | nvars==10)
-    nrows = 5;
-    ncols = 2;
-else 
-    error('too many variables (makechart)')
-end
-
-for i = 1:nvars
-    subplot(nrows,ncols,i)
-    h1=plot(xvalues,zdata1(:,i),'b-','linewidth',2); hold on
-    h1=plot(xvalues,zdata2(:,i),'r--','linewidth',2); hold on
-    h2=plot(xvalues,zdata3(:,i),'b-','LineWidth',3);
-    [x0 x1 y10 y11] = pickaxes(xvalues,zdata1(:,i));
-    [x0 x1 y20 y21] = pickaxes(xvalues,zdata2(:,i));
-    [x0 x1 y30 y31] = pickaxes(xvalues,zdata3(:,i));
-    y0 = min([y10,y20,y30]);
-    y1 = max([y11,y21,y31]);
-    if y0==y1
-        y1=y0+1;
-    end
-    
-    axis([x0 x1 y0 y1])
-    set(h1);
-
-    if i==1 && isempty(legendlist)==0
-        legend(legendlist)
-        text('String',figlabel,'Units','normalized','Position',[1.2 1.24],...
-       'FontSize',14,'FontWeight','bold','HorizontalAlignment','center');
-    end
- 
-    if i==nvars | i==nvars-1
-        xlabel('Time');
-    end
-%     set(gca,'XTick',xtick)
-%     set(gca,'XTickLabel',xticklabel)
-    
-    title([num2str(i),'. ',titlelist(i,:)]);
-    ylabel(ylabels(i,:))
-end
-
-% sets printing preferences
-%printpref
+function makechart(titlelist,legendlist,figlabel,ylabels,zdata1,zdata2,zdata3)
+
+
+
+figure
+
+titlelist = char(strrep(cellstr(titlelist),'_','.'));
+
+ndsets=3;       % default, changed below as applicable
+if nargin==5
+    zdata2=nan*zdata1;
+    zdata3=nan*zdata1;
+    ndsets =1;
+elseif nargin == 6
+    zdata3 =nan*zdata1;
+    ndsets=2;
+elseif ((nargin>8) | (nargin <=4))
+    error ('makechart takes 5 to 6 arguments')
+end
+
+nobs = size(zdata1,1);
+xvalues = (1:nobs)';
+
+nvars = size(titlelist,1);
+if nvars==1
+    nrows=1;
+    ncols = 1;
+elseif nvars==2
+    nrows =2;
+    ncols = 1;
+elseif (nvars == 3 | nvars ==4)
+    nrows = 2;
+    ncols =2;
+elseif (nvars==5 |nvars ==6)
+    nrows = 3;
+    ncols = 2;
+elseif (nvars==7 | nvars==8)
+    nrows = 4;
+    ncols = 2;
+elseif (nvars==9 | nvars==10)
+    nrows = 5;
+    ncols = 2;
+else
+    error('too many variables (makechart)')
+end
+
+for i = 1:nvars
+    subplot(nrows,ncols,i)
+    h1=plot(xvalues,zdata1(:,i),'b-','linewidth',2); hold on
+    h1=plot(xvalues,zdata2(:,i),'r--','linewidth',2); hold on
+    h2=plot(xvalues,zdata3(:,i),'b-','LineWidth',3);
+    [x0, x1, y10, y11] = pickaxes(xvalues,zdata1(:,i));
+    [x0, x1, y20, y21] = pickaxes(xvalues,zdata2(:,i));
+    [x0, x1, y30, y31] = pickaxes(xvalues,zdata3(:,i));
+    y0 = min([y10,y20,y30]);
+    y1 = max([y11,y21,y31]);
+    if y0==y1
+        y1=y0+1;
+    end
+
+    axis([x0 x1 y0 y1])
+    set(h1);
+
+    if i==1 && isempty(legendlist)==0
+        legend(legendlist)
+        text('String',figlabel,'Units','normalized','Position',[1.2 1.24],...
+             'FontSize',14,'FontWeight','bold','HorizontalAlignment','center');
+    end
+
+    if i==nvars | i==nvars-1
+        xlabel('Time');
+    end
+    %     set(gca,'XTick',xtick)
+    %     set(gca,'XTickLabel',xticklabel)
+
+    title([num2str(i),'. ',titlelist(i,:)]);
+    ylabel(ylabels(i,:))
+end
+
+% sets printing preferences
+%printpref
diff --git a/matlab/occbin/makechart9.m b/matlab/occbin/makechart9.m
index c6e65afcdf86785e1f4e5b106f11b20bbdc16279..264f9f58f73a0535c61adc47b6ff2954e617553b 100755
--- a/matlab/occbin/makechart9.m
+++ b/matlab/occbin/makechart9.m
@@ -1,136 +1,136 @@
-function makechart9(titlelist,legendlist,figlabel,yearshock,ylabels,...
-    zdata1,zdata2,zdata3,zdata4,zdata5,zdata6,zdata7)
-
-
-
-figure
-
-titlelist = char(strrep(cellstr(titlelist),'_','.'));
-
-ndsets=7;       % default, changed below as applicable
-if nargin==6
-    zdata2=nan*zdata1;
-    zdata3=nan*zdata1;
-    zdata4=nan*zdata1;
-    zdata5=nan*zdata1;
-    zdata6=nan*zdata1;
-    zdata7=nan*zdata1;
-    ndsets =1;
-elseif nargin==7
-    zdata3=nan*zdata1;
-    zdata4=nan*zdata1;
-    zdata5=nan*zdata1;
-    zdata6=nan*zdata1;
-    zdata7=nan*zdata1;
-    ndsets =2;
-elseif nargin == 8
-    zdata4 =nan*zdata1;
-    zdata5 =nan*zdata1;
-    zdata6=nan*zdata1;
-    zdata7=nan*zdata1;
-    ndsets=3;
-elseif nargin == 9
-    zdata5 =nan*zdata1;
-    zdata6=nan*zdata1;
-    zdata7=nan*zdata1;
-    ndsets=4;
-elseif nargin == 10
-    zdata6 =nan*zdata1;
-    zdata7=nan*zdata1;
-    ndsets=5;
-elseif nargin == 11
-    zdata7=nan*zdata1;
-    ndsets=6;
-elseif ((nargin>=13) | (nargin <=3))
-    error ('makechart takes 4 to 10 arguments')
-end
-
-nobs = size(zdata1,1);
-
-if yearshock>-100
-xvalues = yearshock+(0:nobs-1)'/4; % Matteo plot year on x axis
-else
-xvalues = (1:nobs)'; % Matteo plot year on x axis
-end
-
-nvars = size(titlelist,1);
-if nvars==1 
-    nrows=1;
-    ncols = 1;
-elseif nvars==2
-    nrows =2;
-    ncols = 1;
-elseif nvars == 3 
-    nrows = 3;
-    ncols = 1;
-elseif nvars==4 
-    nrows = 2;
-    ncols = 2;
-elseif (nvars==5 | nvars ==6)
-     nrows = 3;
-    ncols = 2; 
-elseif (nvars==7 | nvars==8)
-    nrows = 4;
-    ncols = 2;
-elseif nvars>8 & nvars<=12;
-    nrows = 3;
-    ncols = 4;
-elseif nvars>12 & nvars<=15;
-    nrows = 5;
-    ncols = 3;
-else 
-    error('too many variables (makechart)')
-end
-
-
-for i = 1:nvars
-    subplot(nrows,ncols,i)
-    h1=plot(xvalues,zdata1(:,i),'k',...
-        xvalues,zdata2(:,i),'r',...
-        xvalues,zdata3(:,i),'b',...
-        xvalues,zdata4(:,i),'g',...
-        xvalues,zdata5(:,i),'g',...
-        xvalues,zdata6(:,i),'c',...
-        xvalues,zdata7(:,i),'y');
-    [x0 x1 y10 y11] = pickaxes(xvalues,zdata1(:,i));
-    [x0 x1 y20 y21] = pickaxes(xvalues,zdata2(:,i));
-    [x0 x1 y30 y31] = pickaxes(xvalues,zdata3(:,i));
-    [x0 x1 y40 y41] = pickaxes(xvalues,zdata4(:,i));
-    [x0 x1 y50 y51] = pickaxes(xvalues,zdata5(:,i));
-    [x0 x1 y60 y61] = pickaxes(xvalues,zdata6(:,i));
-    [x0 x1 y70 y71] = pickaxes(xvalues,zdata7(:,i));
-     grid on
-    y0 = min([y10,y20,y30,y40,y50,y60,y70]);
-    y1 = max([y11,y21,y31,y41,y51,y61,y71]);
-    if y0==y1
-        y1=y0+1;
-    end
-    
-    axis([x0 x1 y0 y1])
-    set(h1,'linewidth',2);
-    if i==1
-      if numel(strvcat(legendlist(1,:)))
-        h=legend(legendlist,'Location','Northwest');
-        set(h,'Fontsize',8)
-      end
-    end
-    if i==1
-        if nvars>3
-        text('String',figlabel,'Units','normalized','Position',[1.2 1.21],...
-       'FontSize',13,'FontWeight','bold','HorizontalAlignment','center');
-        else
-        text('String',figlabel,'Units','normalized','Position',[0.4 1.24],...
-       'FontSize',13,'FontWeight','bold','HorizontalAlignment','center');
-        end
-    end
- 
-    %set(gca,'XTick',xtick)
-    %set(gca,'XTickLabel',xticklabel)
-    
-    title(titlelist(i,:),'Fontsize',11);
-    ylabel(ylabels(i,:))
-
-end
-
-% sets printing preferences
-%printpref
+function makechart9(titlelist,legendlist,figlabel,yearshock,ylabels,...
+                    zdata1,zdata2,zdata3,zdata4,zdata5,zdata6,zdata7)
+
+
+
+figure
+
+titlelist = char(strrep(cellstr(titlelist),'_','.'));
+
+ndsets=7;       % default, changed below as applicable
+if nargin==6
+    zdata2=nan*zdata1;
+    zdata3=nan*zdata1;
+    zdata4=nan*zdata1;
+    zdata5=nan*zdata1;
+    zdata6=nan*zdata1;
+    zdata7=nan*zdata1;
+    ndsets =1;
+elseif nargin==7
+    zdata3=nan*zdata1;
+    zdata4=nan*zdata1;
+    zdata5=nan*zdata1;
+    zdata6=nan*zdata1;
+    zdata7=nan*zdata1;
+    ndsets =2;
+elseif nargin == 8
+    zdata4 =nan*zdata1;
+    zdata5 =nan*zdata1;
+    zdata6=nan*zdata1;
+    zdata7=nan*zdata1;
+    ndsets=3;
+elseif nargin == 9
+    zdata5 =nan*zdata1;
+    zdata6=nan*zdata1;
+    zdata7=nan*zdata1;
+    ndsets=4;
+elseif nargin == 10
+    zdata6 =nan*zdata1;
+    zdata7=nan*zdata1;
+    ndsets=5;
+elseif nargin == 11
+    zdata7=nan*zdata1;
+    ndsets=6;
+elseif ((nargin>=13) | (nargin <=3))
+    error ('makechart takes 4 to 10 arguments')
+end
+
+nobs = size(zdata1,1);
+
+if yearshock>-100
+    xvalues = yearshock+(0:nobs-1)'/4; % Matteo plot year on x axis
+else
+    xvalues = (1:nobs)'; % Matteo plot year on x axis
+end
+
+nvars = size(titlelist,1);
+if nvars==1
+    nrows=1;
+    ncols = 1;
+elseif nvars==2
+    nrows =2;
+    ncols = 1;
+elseif nvars == 3
+    nrows = 3;
+    ncols = 1;
+elseif nvars==4
+    nrows = 2;
+    ncols = 2;
+elseif (nvars==5 | nvars ==6)
+    nrows = 3;
+    ncols = 2;
+elseif (nvars==7 | nvars==8)
+    nrows = 4;
+    ncols = 2;
+elseif nvars>8 & nvars<=12
+    nrows = 3;
+    ncols = 4;
+elseif nvars>12 & nvars<=15
+    nrows = 5;
+    ncols = 3;
+else
+    error('too many variables (makechart)')
+end
+
+
+for i = 1:nvars
+    subplot(nrows,ncols,i)
+    h1=plot(xvalues,zdata1(:,i),'k',...
+            xvalues,zdata2(:,i),'r',...
+            xvalues,zdata3(:,i),'b',...
+            xvalues,zdata4(:,i),'g',...
+            xvalues,zdata5(:,i),'g',...
+            xvalues,zdata6(:,i),'c',...
+            xvalues,zdata7(:,i),'y');
+    [x0, x1, y10, y11] = pickaxes(xvalues,zdata1(:,i));
+    [x0, x1, y20, y21] = pickaxes(xvalues,zdata2(:,i));
+    [x0, x1, y30, y31] = pickaxes(xvalues,zdata3(:,i));
+    [x0, x1, y40, y41] = pickaxes(xvalues,zdata4(:,i));
+    [x0, x1, y50, y51] = pickaxes(xvalues,zdata5(:,i));
+    [x0, x1, y60, y61] = pickaxes(xvalues,zdata6(:,i));
+    [x0, x1, y70, y71] = pickaxes(xvalues,zdata7(:,i));
+    grid on
+    y0 = min([y10,y20,y30,y40,y50,y60,y70]);
+    y1 = max([y11,y21,y31,y41,y51,y61,y71]);
+    if y0==y1
+        y1=y0+1;
+    end
+
+    axis([x0 x1 y0 y1])
+    set(h1,'linewidth',2);
+    if i==1
+        if numel(strvcat(legendlist(1,:)))
+            h=legend(legendlist,'Location','Northwest');
+            set(h,'Fontsize',8)
+        end
+    end
+    if i==1
+        if nvars>3
+            text('String',figlabel,'Units','normalized','Position',[1.2 1.21],...
+                 'FontSize',13,'FontWeight','bold','HorizontalAlignment','center');
+        else
+            text('String',figlabel,'Units','normalized','Position',[0.4 1.24],...
+                 'FontSize',13,'FontWeight','bold','HorizontalAlignment','center');
+        end
+    end
+
+    %set(gca,'XTick',xtick)
+    %set(gca,'XTickLabel',xticklabel)
+
+    title(titlelist(i,:),'Fontsize',11);
+    ylabel(ylabels(i,:))
+
+end
+
+% sets printing preferences
+%printpref
diff --git a/matlab/occbin/map_regime.m b/matlab/occbin/map_regime.m
index a3ed88b47870b3e0cffc33dedce292072d08306f..702b011f9fb516114539a7c6530ba44fec2bd378 100755
--- a/matlab/occbin/map_regime.m
+++ b/matlab/occbin/map_regime.m
@@ -1,25 +1,24 @@
-function [regime regimestart]=map_regimes(violvecbool)
-
-nperiods = length(violvecbool)-1;
-
-% analyse violvec and isolate contiguous periods in the other regime.
-            regime(1) = violvecbool(1);
-            regimeindx = 1;
-            regimestart(1) = 1;
-            for i=2:nperiods
-                if violvecbool(i)~=regime(regimeindx)
-                    regimeindx=regimeindx+1;
-                    regime(regimeindx) = violvecbool(i);
-                    regimestart(regimeindx)=i;
-                end
-            end
-            
-            
-            if (regime(1) == 1 & length(regimestart)==1)
-                warning('Increase nperiods');
-            end
-            
-            if (regime(end)==1)
-                warning('Increase nperiods');
-            end
-            
+function [regime, regimestart]=map_regime(violvecbool)
+
+nperiods = length(violvecbool)-1;
+
+% analyse violvec and isolate contiguous periods in the other regime.
+regime(1) = violvecbool(1);
+regimeindx = 1;
+regimestart(1) = 1;
+for i=2:nperiods
+    if violvecbool(i)~=regime(regimeindx)
+        regimeindx=regimeindx+1;
+        regime(regimeindx) = violvecbool(i);
+        regimestart(regimeindx)=i;
+    end
+end
+
+
+if (regime(1) == 1 & length(regimestart)==1)
+    warning('Increase nperiods');
+end
+
+if (regime(end)==1)
+    warning('Increase nperiods');
+end
diff --git a/matlab/occbin/mkdata.m b/matlab/occbin/mkdata.m
index a7f855743ddb228ecf8c75e65823849f054fd8b4..f22fb45f6574a12d6740ad53c6d8f5b0e6e6ce79 100755
--- a/matlab/occbin/mkdata.m
+++ b/matlab/occbin/mkdata.m
@@ -1,63 +1,63 @@
-function [zdata]=mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,scalefactormod,init)
-
-%[nsim, ksim, ysim, isim, csim] = mkdata(nperiods,cofb,endog_)
-
-% given decision rule 
-neqs = size(endog_,1);
-
-if  nargin<9
-   init = zeros(neqs,1);
-end
-
-if  nargin<8
-    scalefactormod=1;
-end
-
-if nargin<7
-    error('Not enough inputs')
-end
-
-history = zeros(neqs,nperiods+1);
-
-    nshocks = size(irfshock,1);
-    for i = 1:nshocks
-        shockpos = strmatch(irfshock(i,:),exog_,'exact');
-        if ~isempty(shockpos)
-            irfshockpos(i) = shockpos;
-        else
-            error(['Shock ',irfshock(i,:),' is not in the model']);
-        end
-    end
-
-
-% generate data
-% history will contain data, the state vector at each period in time will
-% be stored columnwise.
-history = zeros(neqs,nperiods);
-history(:,1)= init;
-
-lengthshock = size(scalefactormod,1);
-
-errvec = zeros(size(exog_,1),1);
-
-for i = 2:nperiods+1
-    if i<=(lengthshock+1)
-        for j = 1:nshocks
-            errvec(irfshockpos(j)) = scalefactormod(i-1,j);
-        end
-        history(:,i) = decrulea * history(:,i-1)+decruleb*errvec;
-    else
-    % update endogenous variables
-    history(:,i) = decrulea * history(:,i-1);
-    end
-end
-
-% extract desired variables
-nwish=size(wishlist,1);
-wishpos = zeros(nwish,1);
-
-history=history';
-for i=1:nwish
-    wishpos(i) = strmatch(wishlist(i,:),endog_,'exact');
-end
+function [zdata]=mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,scalefactormod,init)
+
+%[nsim, ksim, ysim, isim, csim] = mkdata(nperiods,cofb,endog_)
+
+% given decision rule
+neqs = size(endog_,1);
+
+if  nargin<9
+    init = zeros(neqs,1);
+end
+
+if  nargin<8
+    scalefactormod=1;
+end
+
+if nargin<7
+    error('Not enough inputs')
+end
+
+history = zeros(neqs,nperiods+1);
+
+nshocks = size(irfshock,1);
+for i = 1:nshocks
+    shockpos = strmatch(irfshock(i,:),exog_,'exact');
+    if ~isempty(shockpos)
+        irfshockpos(i) = shockpos;
+    else
+        error(['Shock ',irfshock(i,:),' is not in the model']);
+    end
+end
+
+
+% generate data
+% history will contain data, the state vector at each period in time will
+% be stored columnwise.
+history = zeros(neqs,nperiods);
+history(:,1)= init;
+
+lengthshock = size(scalefactormod,1);
+
+errvec = zeros(size(exog_,1),1);
+
+for i = 2:nperiods+1
+    if i<=(lengthshock+1)
+        for j = 1:nshocks
+            errvec(irfshockpos(j)) = scalefactormod(i-1,j);
+        end
+        history(:,i) = decrulea * history(:,i-1)+decruleb*errvec;
+    else
+        % update endogenous variables
+        history(:,i) = decrulea * history(:,i-1);
+    end
+end
+
+% extract desired variables
+nwish=size(wishlist,1);
+wishpos = zeros(nwish,1);
+
+history=history';
+for i=1:nwish
+    wishpos(i) = strmatch(wishlist(i,:),endog_,'exact');
+end
 zdata = history(2:end,wishpos);
\ No newline at end of file
diff --git a/matlab/occbin/mkdatap_anticipated.m b/matlab/occbin/mkdatap_anticipated.m
index 524d3dd5d78880eb42c8121ef702fa2acd3503ad..a9c9249663e52b5e80efb9d9937614dfdd361527 100755
--- a/matlab/occbin/mkdatap_anticipated.m
+++ b/matlab/occbin/mkdatap_anticipated.m
@@ -1,125 +1,125 @@
-function [zdata]=mkdatap_anticipated(nperiods,decrulea,decruleb,...
-    cof,Jbarmat,cofstar,Jstarbarmat,Dstarbarmat,...
-    regime,regimestart,violvecbool,...
-    endog_,exog_,irfshock,scalefactormod,init)
-
-
-
-nvars = size(endog_,1);
-
-
-if nargin<16
-    init=zeros(nvars,1);
-end
-
-if nargin<15;
-    scalefactormod=1;
-end
-
-
-nshocks = size(irfshock,1);
-for i = 1:nshocks
-    shockpos = strmatch(irfshock(i,:),exog_,'exact');
-    if ~isempty(shockpos)
-        irfshockpos(i) = shockpos;
-    else
-        error(['Shock ',irfshock(i,:),' is not in the model']);
-    end
-end
-
-
-nregimes = length(regime);
-
-Cbarmat = cof(:,1:nvars);
-Bbarmat = cof(:,nvars+1:2*nvars);
-Abarmat = cof(:,2*nvars+1:3*nvars);
-
-
-% cofstar contains the system for the model when the constraint binds
-Cstarbarmat = cofstar(:,1:nvars);
-Bstarbarmat = cofstar(:,nvars+1:2*nvars);
-Astarbarmat = cofstar(:,2*nvars+1:3*nvars);
-
-% get the time-dependent decision rules
-
-Tmax = regimestart(nregimes)-1;  % Tmax is the position of the last period
-% when the constraint binds
-
-if Tmax > 0
-    P = zeros(nvars,nvars,Tmax);
-    D = zeros(nvars,Tmax);
-    
-    
-    invmat = inv((Astarbarmat*decrulea+Bstarbarmat));
-    P(:,:,Tmax) = -invmat*Cstarbarmat;
-    D(:,Tmax) = -invmat*Dstarbarmat;
-    
-    
-    % equivalent to pre-multiplying by the inverse above if the target
-    % matrix is invertible. Otherwise it yields the minimum state solution
-    %P(:,:,Tmax) = -(Astarbarmat*decrulea+Bstarbarmat)\Cstarbarmat;
-    %D(:,Tmax) = -(Astarbarmat*decrulea+Bstarbarmat)\Dstarbarmat;
-    
- 
-    for i = Tmax-1:-1:1
-        
-        if violvecbool(i)
-            invmat = inv(Bstarbarmat+Astarbarmat*P(:,:,i+1));
-            P(:,:,i)=-invmat*Cstarbarmat;
-            D(:,i) = -invmat*(Astarbarmat*D(:,i+1)+Dstarbarmat);
-        else
-            invmat = inv(Bbarmat+Abarmat*P(:,:,i+1));
-            P(:,:,i)=-invmat*Cbarmat;
-            D(:,i) = -invmat*(Abarmat*D(:,i+1));
-        end
-    end
-
-if Tmax > 1    
-if violvecbool(1)
-    E = -invmat*Jstarbarmat;
-else
-    E = -invmat*Jbarmat;
-end
-else
-    invmat = inv(Astarbarmat*decrulea+Bstarbarmat);
-    E = -invmat*Jstarbarmat;
-
-end
-
-    
-end
-
-% generate data
-% history will contain data, the state vector at each period in time will
-% be stored columnwise.
-history = zeros(nvars,nperiods+1);
-history(:,1) = init;
-errvec = zeros(size(exog_,1),1);
-
-% deal with predetermined conditions
-for i = 1:nshocks
-    errvec(irfshockpos(i)) = scalefactormod(i);
-end
-
-% deal with shocks
-irfpos =1;
-if irfpos <=Tmax
-    history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+...
-        D(:,irfpos) + E*errvec;
-else
-    history(:,irfpos+1) = decrulea*history(:,irfpos)+decruleb*errvec;
-end
-
-% all other periods
-for irfpos=2:nperiods+1
-    if irfpos <=Tmax
-        history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+...
-            D(:,irfpos);
-    else
-        history(:,irfpos+1) = decrulea*history(:,irfpos);
-    end
-end
-
-
-history=history';
+function [zdata]=mkdatap_anticipated(nperiods,decrulea,decruleb,...
+                                     cof,Jbarmat,cofstar,Jstarbarmat,Dstarbarmat,...
+                                     regime,regimestart,violvecbool,...
+                                     endog_,exog_,irfshock,scalefactormod,init)
+
+
+
+nvars = size(endog_,1);
+
+
+if nargin<16
+    init=zeros(nvars,1);
+end
+
+if nargin<15
+    scalefactormod=1;
+end
+
+
+nshocks = size(irfshock,1);
+for i = 1:nshocks
+    shockpos = strmatch(irfshock(i,:),exog_,'exact');
+    if ~isempty(shockpos)
+        irfshockpos(i) = shockpos;
+    else
+        error(['Shock ',irfshock(i,:),' is not in the model']);
+    end
+end
+
+
+nregimes = length(regime);
+
+Cbarmat = cof(:,1:nvars);
+Bbarmat = cof(:,nvars+1:2*nvars);
+Abarmat = cof(:,2*nvars+1:3*nvars);
+
+
+% cofstar contains the system for the model when the constraint binds
+Cstarbarmat = cofstar(:,1:nvars);
+Bstarbarmat = cofstar(:,nvars+1:2*nvars);
+Astarbarmat = cofstar(:,2*nvars+1:3*nvars);
+
+% get the time-dependent decision rules
+
+Tmax = regimestart(nregimes)-1;  % Tmax is the position of the last period
+                                 % when the constraint binds
+
+if Tmax > 0
+    P = zeros(nvars,nvars,Tmax);
+    D = zeros(nvars,Tmax);
+
+
+    invmat = inv((Astarbarmat*decrulea+Bstarbarmat));
+    P(:,:,Tmax) = -invmat*Cstarbarmat;
+    D(:,Tmax) = -invmat*Dstarbarmat;
+
+
+    % equivalent to pre-multiplying by the inverse above if the target
+    % matrix is invertible. Otherwise it yields the minimum state solution
+    %P(:,:,Tmax) = -(Astarbarmat*decrulea+Bstarbarmat)\Cstarbarmat;
+    %D(:,Tmax) = -(Astarbarmat*decrulea+Bstarbarmat)\Dstarbarmat;
+
+
+    for i = Tmax-1:-1:1
+
+        if violvecbool(i)
+            invmat = inv(Bstarbarmat+Astarbarmat*P(:,:,i+1));
+            P(:,:,i)=-invmat*Cstarbarmat;
+            D(:,i) = -invmat*(Astarbarmat*D(:,i+1)+Dstarbarmat);
+        else
+            invmat = inv(Bbarmat+Abarmat*P(:,:,i+1));
+            P(:,:,i)=-invmat*Cbarmat;
+            D(:,i) = -invmat*(Abarmat*D(:,i+1));
+        end
+    end
+
+    if Tmax > 1
+        if violvecbool(1)
+            E = -invmat*Jstarbarmat;
+        else
+            E = -invmat*Jbarmat;
+        end
+    else
+        invmat = inv(Astarbarmat*decrulea+Bstarbarmat);
+        E = -invmat*Jstarbarmat;
+
+    end
+
+
+end
+
+% generate data
+% history will contain data, the state vector at each period in time will
+% be stored columnwise.
+history = zeros(nvars,nperiods+1);
+history(:,1) = init;
+errvec = zeros(size(exog_,1),1);
+
+% deal with predetermined conditions
+for i = 1:nshocks
+    errvec(irfshockpos(i)) = scalefactormod(i);
+end
+
+% deal with shocks
+irfpos =1;
+if irfpos <=Tmax
+    history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+...
+        D(:,irfpos) + E*errvec;
+else
+    history(:,irfpos+1) = decrulea*history(:,irfpos)+decruleb*errvec;
+end
+
+% all other periods
+for irfpos=2:nperiods+1
+    if irfpos <=Tmax
+        history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+...
+            D(:,irfpos);
+    else
+        history(:,irfpos+1) = decrulea*history(:,irfpos);
+    end
+end
+
+
+history=history';
 zdata = history(2:end,:);
\ No newline at end of file
diff --git a/matlab/occbin/mkdatap_anticipated_2constraints.m b/matlab/occbin/mkdatap_anticipated_2constraints.m
index b05c90d6dec49cd74b024b26fe1795acf9b02bdf..496f5a931c8777970f3e991e6012ab455e188aaa 100755
--- a/matlab/occbin/mkdatap_anticipated_2constraints.m
+++ b/matlab/occbin/mkdatap_anticipated_2constraints.m
@@ -1,180 +1,180 @@
-function [zdata]=mkdatap_anticipated_2constraints_alt(nperiods,decrulea,decruleb,...
-    cof,Jbarmat,...
-    cof10,Jbarmat10,Dbarmat10,...
-    cof01,Jbarmat01,Dbarmat01,...
-    cof11,Jbarmat11,Dbarmat11,...
-    regime1,regimestart1,...
-    regime2,regimestart2,...
-    violvecbool,endog_,exog_,...
-    irfshock,scalefactormod,init)
-
-
-nvars = size(endog_,1);
-
-
-if nargin<16
-    init=zeros(nvars,1);
-end
-
-if nargin<15;
-    scalefactormod=1;
-end
-
-
-nshocks = size(irfshock,1);
-for i = 1:nshocks
-    shockpos = strmatch(irfshock(i,:),exog_,'exact');
-    if ~isempty(shockpos)
-        irfshockpos(i) = shockpos;
-    else
-        error(['Shock ',irfshock(i,:),' is not in the model']);
-    end
-end
-
-
-
-Cbarmat = cof(:,1:nvars);
-Bbarmat = cof(:,nvars+1:2*nvars);
-Abarmat = cof(:,2*nvars+1:3*nvars);
-
-
-% cofstar contains the system for the model when the constraint binds
-
-
-Cbarmat10 = cof10(:,1:nvars);
-Bbarmat10 = cof10(:,nvars+1:2*nvars);
-Abarmat10 = cof10(:,2*nvars+1:3*nvars);
-
-Cbarmat01 = cof01(:,1:nvars);
-Bbarmat01 = cof01(:,nvars+1:2*nvars);
-Abarmat01 = cof01(:,2*nvars+1:3*nvars);
-
-Cbarmat11 = cof11(:,1:nvars);
-Bbarmat11 = cof11(:,nvars+1:2*nvars);
-Abarmat11 = cof11(:,2*nvars+1:3*nvars);
-
-% get the time-dependent decision rules
-nregimes1 = length(regime1);
-nregimes2 = length(regime2);
-
-Tmax = max([regimestart1(nregimes1) regimestart2(nregimes2)])-1;  % Tmax is the position of the last period
-% when the constraint binds
-
-if Tmax > 0
-    P = zeros(nvars,nvars,Tmax);
-    D = zeros(nvars,Tmax);
-    
-%     invmat = inv((Astarbarmat*decrulea+Bstarbarmat));
-%     P(:,:,Tmax) = -invmat*Cstarbarmat;
-%     D(:,Tmax) = -invmat*Dstarbarmat;
-    
-    
-    if (violvecbool(Tmax,1) & ~violvecbool(Tmax,2))
-    %XXX fix next three lines
-    invmat = inv((Abarmat10*decrulea+Bbarmat10));
-    P(:,:,Tmax) = -invmat*Cbarmat10;
-    D(:,Tmax) = -invmat*Dbarmat10;  
-    elseif (violvecbool(Tmax,1) & violvecbool(Tmax,2))
-    invmat = inv((Abarmat11*decrulea+Bbarmat11));
-    P(:,:,Tmax) = -invmat*Cbarmat11;
-    D(:,Tmax) = -invmat*Dbarmat11;
-    else
-    invmat = inv((Abarmat01*decrulea+Bbarmat01));
-    P(:,:,Tmax) = -invmat*Cbarmat01;
-    D(:,Tmax) = -invmat*Dbarmat01;  
-    end
-    
-    
-    
-    
-    for i = Tmax-1:-1:1        
-        
-        if (violvecbool(i,1) & ~violvecbool(i,2))
-            invmat = inv(Bbarmat10+Abarmat10*P(:,:,i+1));
-            P(:,:,i)=-invmat*Cbarmat10;
-            D(:,i) = -invmat*(Abarmat10*D(:,i+1)+Dbarmat10);
-        elseif (~violvecbool(i,1) & violvecbool(i,2))
-            invmat = inv(Bbarmat01+Abarmat01*P(:,:,i+1));
-            P(:,:,i)=-invmat*Cbarmat01;
-            D(:,i) = -invmat*(Abarmat01*D(:,i+1)+Dbarmat01);
-        elseif (violvecbool(i,1) & violvecbool(i,2))
-            invmat = inv(Bbarmat11+Abarmat11*P(:,:,i+1));
-            P(:,:,i)=-invmat*Cbarmat11;
-            D(:,i) = -invmat*(Abarmat11*D(:,i+1)+Dbarmat11);
-        else
-            invmat = inv(Bbarmat+Abarmat*P(:,:,i+1));
-            P(:,:,i)=-invmat*Cbarmat;
-            D(:,i) = -invmat*(Abarmat*D(:,i+1));
-        end
-        
-    end
-
-    
-% Double check the appropriate invmat in each case
-% right now -- inherited from previous loop
-if Tmax > 1
-    
-    if ( ~violvecbool(1,1) & violvecbool(1,2) )
-        E = -invmat*Jbarmat01;
-    elseif ( violvecbool(1,1) & ~violvecbool(1,2) )
-        E = -invmat*Jbarmat10;
-    elseif ( violvecbool(1,1) & violvecbool(1,2) )
-        E = -invmat*Jbarmat11;
-    else
-        E = -invmat*Jbarmat;
-    end
-    
-else  % Tmax is equal to 1    
-%     invmat = inv((Astarbarmat*decrulea+Bstarbarmat));
-%     E = -invmat*Jstarbarmat;
-    
-    if ( ~violvecbool(1,1) & violvecbool(1,2) )
-       invmat = inv((Abarmat01*decrulea+Bbarmat01));
-       E = -invmat*Jbarmat01;  
-    elseif ( violvecbool(1,1) & violvecbool(1,2) )
-        invmat = inv((Abarmat11*decrulea+Bbarmat11));
-        E = -invmat*Jbarmat11;     
-    else
-        invmat = inv((Abarmat10*decrulea+Bbarmat10));
-        E = -invmat*Jbarmat10;
-            
-    end
-    
-end
-
-    
-end
-
-% generate data
-% history will contain data, the state vector at each period in time will
-% be stored columnwise.
-history = zeros(nvars,nperiods+1);
-history(:,1) = init;
-errvec = zeros(size(exog_,1),1);
-
-for i = 1:nshocks
-    errvec(irfshockpos(i)) = scalefactormod(i);
-end
-
-% deal with shocks
-irfpos =1;
-if irfpos <=Tmax
-    history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+...
-        D(:,irfpos) + E*errvec;
-else
-    history(:,irfpos+1) = decrulea*history(:,irfpos)+decruleb*errvec;
-end
-
-% all other periods
-for irfpos=2:nperiods+1
-    if irfpos <=Tmax
-        history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+...
-            D(:,irfpos);
-    else
-        history(:,irfpos+1) = decrulea*history(:,irfpos);
-    end
-end
-
-
-history=history';
+function [zdata]=mkdatap_anticipated_2constraints(nperiods,decrulea,decruleb,...
+                                                  cof,Jbarmat,...
+                                                  cof10,Jbarmat10,Dbarmat10,...
+                                                  cof01,Jbarmat01,Dbarmat01,...
+                                                  cof11,Jbarmat11,Dbarmat11,...
+                                                  regime1,regimestart1,...
+                                                  regime2,regimestart2,...
+                                                  violvecbool,endog_,exog_,...
+                                                  irfshock,scalefactormod,init)
+
+
+nvars = size(endog_,1);
+
+
+if nargin<16
+    init=zeros(nvars,1);
+end
+
+if nargin<15
+    scalefactormod=1;
+end
+
+
+nshocks = size(irfshock,1);
+for i = 1:nshocks
+    shockpos = strmatch(irfshock(i,:),exog_,'exact');
+    if ~isempty(shockpos)
+        irfshockpos(i) = shockpos;
+    else
+        error(['Shock ',irfshock(i,:),' is not in the model']);
+    end
+end
+
+
+
+Cbarmat = cof(:,1:nvars);
+Bbarmat = cof(:,nvars+1:2*nvars);
+Abarmat = cof(:,2*nvars+1:3*nvars);
+
+
+% cofstar contains the system for the model when the constraint binds
+
+
+Cbarmat10 = cof10(:,1:nvars);
+Bbarmat10 = cof10(:,nvars+1:2*nvars);
+Abarmat10 = cof10(:,2*nvars+1:3*nvars);
+
+Cbarmat01 = cof01(:,1:nvars);
+Bbarmat01 = cof01(:,nvars+1:2*nvars);
+Abarmat01 = cof01(:,2*nvars+1:3*nvars);
+
+Cbarmat11 = cof11(:,1:nvars);
+Bbarmat11 = cof11(:,nvars+1:2*nvars);
+Abarmat11 = cof11(:,2*nvars+1:3*nvars);
+
+% get the time-dependent decision rules
+nregimes1 = length(regime1);
+nregimes2 = length(regime2);
+
+Tmax = max([regimestart1(nregimes1) regimestart2(nregimes2)])-1;  % Tmax is the position of the last period
+                                                                  % when the constraint binds
+
+if Tmax > 0
+    P = zeros(nvars,nvars,Tmax);
+    D = zeros(nvars,Tmax);
+
+    %     invmat = inv((Astarbarmat*decrulea+Bstarbarmat));
+    %     P(:,:,Tmax) = -invmat*Cstarbarmat;
+    %     D(:,Tmax) = -invmat*Dstarbarmat;
+
+
+    if (violvecbool(Tmax,1) & ~violvecbool(Tmax,2))
+        %XXX fix next three lines
+        invmat = inv((Abarmat10*decrulea+Bbarmat10));
+        P(:,:,Tmax) = -invmat*Cbarmat10;
+        D(:,Tmax) = -invmat*Dbarmat10;
+    elseif (violvecbool(Tmax,1) & violvecbool(Tmax,2))
+        invmat = inv((Abarmat11*decrulea+Bbarmat11));
+        P(:,:,Tmax) = -invmat*Cbarmat11;
+        D(:,Tmax) = -invmat*Dbarmat11;
+    else
+        invmat = inv((Abarmat01*decrulea+Bbarmat01));
+        P(:,:,Tmax) = -invmat*Cbarmat01;
+        D(:,Tmax) = -invmat*Dbarmat01;
+    end
+
+
+
+
+    for i = Tmax-1:-1:1
+
+        if (violvecbool(i,1) & ~violvecbool(i,2))
+            invmat = inv(Bbarmat10+Abarmat10*P(:,:,i+1));
+            P(:,:,i)=-invmat*Cbarmat10;
+            D(:,i) = -invmat*(Abarmat10*D(:,i+1)+Dbarmat10);
+        elseif (~violvecbool(i,1) & violvecbool(i,2))
+            invmat = inv(Bbarmat01+Abarmat01*P(:,:,i+1));
+            P(:,:,i)=-invmat*Cbarmat01;
+            D(:,i) = -invmat*(Abarmat01*D(:,i+1)+Dbarmat01);
+        elseif (violvecbool(i,1) & violvecbool(i,2))
+            invmat = inv(Bbarmat11+Abarmat11*P(:,:,i+1));
+            P(:,:,i)=-invmat*Cbarmat11;
+            D(:,i) = -invmat*(Abarmat11*D(:,i+1)+Dbarmat11);
+        else
+            invmat = inv(Bbarmat+Abarmat*P(:,:,i+1));
+            P(:,:,i)=-invmat*Cbarmat;
+            D(:,i) = -invmat*(Abarmat*D(:,i+1));
+        end
+
+    end
+
+
+    % Double check the appropriate invmat in each case
+    % right now -- inherited from previous loop
+    if Tmax > 1
+
+        if ( ~violvecbool(1,1) & violvecbool(1,2) )
+            E = -invmat*Jbarmat01;
+        elseif ( violvecbool(1,1) & ~violvecbool(1,2) )
+            E = -invmat*Jbarmat10;
+        elseif ( violvecbool(1,1) & violvecbool(1,2) )
+            E = -invmat*Jbarmat11;
+        else
+            E = -invmat*Jbarmat;
+        end
+
+    else  % Tmax is equal to 1
+          %     invmat = inv((Astarbarmat*decrulea+Bstarbarmat));
+          %     E = -invmat*Jstarbarmat;
+
+        if ( ~violvecbool(1,1) & violvecbool(1,2) )
+            invmat = inv((Abarmat01*decrulea+Bbarmat01));
+            E = -invmat*Jbarmat01;
+        elseif ( violvecbool(1,1) & violvecbool(1,2) )
+            invmat = inv((Abarmat11*decrulea+Bbarmat11));
+            E = -invmat*Jbarmat11;
+        else
+            invmat = inv((Abarmat10*decrulea+Bbarmat10));
+            E = -invmat*Jbarmat10;
+
+        end
+
+    end
+
+
+end
+
+% generate data
+% history will contain data, the state vector at each period in time will
+% be stored columnwise.
+history = zeros(nvars,nperiods+1);
+history(:,1) = init;
+errvec = zeros(size(exog_,1),1);
+
+for i = 1:nshocks
+    errvec(irfshockpos(i)) = scalefactormod(i);
+end
+
+% deal with shocks
+irfpos =1;
+if irfpos <=Tmax
+    history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+...
+        D(:,irfpos) + E*errvec;
+else
+    history(:,irfpos+1) = decrulea*history(:,irfpos)+decruleb*errvec;
+end
+
+% all other periods
+for irfpos=2:nperiods+1
+    if irfpos <=Tmax
+        history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+...
+            D(:,irfpos);
+    else
+        history(:,irfpos+1) = decrulea*history(:,irfpos);
+    end
+end
+
+
+history=history';
 zdata = history(2:end,:);
\ No newline at end of file
diff --git a/matlab/occbin/pickaxes.m b/matlab/occbin/pickaxes.m
index 46c4b79c6db0176bb5a076573d4a95fdc7869378..26c9b6b1a397d0eb019f20b4670e8c0317e54a8a 100755
--- a/matlab/occbin/pickaxes.m
+++ b/matlab/occbin/pickaxes.m
@@ -1,16 +1,16 @@
-function [x0,x1,y0,y1] = pickaxes(xvalues,yvalues)
-
-x0=xvalues(1);
-nobs = length(xvalues);
-x1=xvalues(nobs);
-
-maxy = max(yvalues);
-miny = min(yvalues);
-
-
-y0 = miny - .05*abs(miny);
-if (miny>0 & y0<0) 
-    y0 = 0;
-end
-
-y1 = maxy + .05*abs(maxy);
+function [x0,x1,y0,y1] = pickaxes(xvalues,yvalues)
+
+x0=xvalues(1);
+nobs = length(xvalues);
+x1=xvalues(nobs);
+
+maxy = max(yvalues);
+miny = min(yvalues);
+
+
+y0 = miny - .05*abs(miny);
+if (miny>0 & y0<0)
+    y0 = 0;
+end
+
+y1 = maxy + .05*abs(maxy);
diff --git a/matlab/occbin/process_constraint.m b/matlab/occbin/process_constraint.m
index d209111755fde2bd1e9e192397fae953fd092624..2d2b35f364299ed84cc072d35311eedeef3675c8 100755
--- a/matlab/occbin/process_constraint.m
+++ b/matlab/occbin/process_constraint.m
@@ -1,38 +1,38 @@
-% this function looks for occurrences of the endogenous variables in
-% endo_names in the input string constraint
-% all occurrences of the endogenous variables are appended a suffix
-% if the invert_switch is true, the direction of the inequality in the
-% constraint is inverted
-
-function constraint1 = process_constraint(constraint,suffix,endo_names,invert_switch)
-
-% create a list of delimiters that can separate parameters and endogenoous
-% variables in the string that expresses the constraint
-delimiters = char(',',';','(',')','+','-','^','*','/',' ','>','<','=');
-
-% split the string that holds the constraint into tokens
-tokens = tokenize(constraint,delimiters);
-
-ntokens = length(tokens);
-
-% search for tokens that match the list of endogenous variables
-for i=1:ntokens
-    if ~isempty(find(strcmp(tokens(i),endo_names)))
-        % when there is a match with an endogenous variable append the
-        % suffix
-        tokens(i) = cellstr([char(tokens(i)),suffix]);
-    end
-    
-    % if the invert_switch is true
-    % reverse the direction of the inequality
-    if invert_switch
-        if  strcmp(tokens(i),cellstr('>'))
-            tokens(i) = cellstr('<');
-        elseif strcmp(tokens(i),cellstr('<'))
-            tokens(i) = cellstr('>');
-        end
-    end
-end
-
-% reassemble the tokens to create a string that expresses the constraint
+% this function looks for occurrences of the endogenous variables in
+% endo_names in the input string constraint
+% all occurrences of the endogenous variables are appended a suffix
+% if the invert_switch is true, the direction of the inequality in the
+% constraint is inverted
+
+function constraint1 = process_constraint(constraint,suffix,endo_names,invert_switch)
+
+% create a list of delimiters that can separate parameters and endogenoous
+% variables in the string that expresses the constraint
+delimiters = char(',',';','(',')','+','-','^','*','/',' ','>','<','=');
+
+% split the string that holds the constraint into tokens
+tokens = tokenize(constraint,delimiters);
+
+ntokens = length(tokens);
+
+% search for tokens that match the list of endogenous variables
+for i=1:ntokens
+    if ~isempty(find(strcmp(tokens(i),endo_names)))
+        % when there is a match with an endogenous variable append the
+        % suffix
+        tokens(i) = cellstr([char(tokens(i)),suffix]);
+    end
+
+    % if the invert_switch is true
+    % reverse the direction of the inequality
+    if invert_switch
+        if  strcmp(tokens(i),cellstr('>'))
+            tokens(i) = cellstr('<');
+        elseif strcmp(tokens(i),cellstr('<'))
+            tokens(i) = cellstr('>');
+        end
+    end
+end
+
+% reassemble the tokens to create a string that expresses the constraint
 constraint1 = strmerge(tokens);
\ No newline at end of file
diff --git a/matlab/occbin/setss.m b/matlab/occbin/setss.m
index d1c0e440ac6b23f14a6726bad535274a3dfc8eaa..7fc52f6c0ec32e373251e1db2a80dbdf5707cda4 100755
--- a/matlab/occbin/setss.m
+++ b/matlab/occbin/setss.m
@@ -1,14 +1,13 @@
-% Script that retrieves parameter values once model is solved
-
-nendog = size(Mbase_.endo_names,1);
-
-for i=1:nendog
-  eval([deblank(Mbase_.endo_names(i,:)) '_ss = oo_.dr.ys(i); ']);
-end
-
-nparams = size(Mbase_.param_names);
-
-for i = 1:nparams
-  eval([Mbase_.param_names(i,:),'= M_.params(i);']);
-end
-
+% Script that retrieves parameter values once model is solved
+
+nendog = size(Mbase_.endo_names,1);
+
+for i=1:nendog
+    eval([deblank(Mbase_.endo_names(i,:)) '_ss = oo_.dr.ys(i); ']);
+end
+
+nparams = size(Mbase_.param_names);
+
+for i = 1:nparams
+    eval([Mbase_.param_names(i,:),'= M_.params(i);']);
+end
diff --git a/matlab/occbin/solve_no_constraint.m b/matlab/occbin/solve_no_constraint.m
index d9671409d26bc41ef12b7fda8e6ca6f8d2ea930b..27af64f1ce1fa0ed5554911fab109e347bc4f0bb 100755
--- a/matlab/occbin/solve_no_constraint.m
+++ b/matlab/occbin/solve_no_constraint.m
@@ -1,50 +1,49 @@
-function [zdata_, zdatass_, oobase_, Mbase_ ] = ...
-    solve_no_constraint(modnam,...
-    shockssequence,irfshock,nperiods)
-
-global M_ oo_
-
-errlist = [];
-
-% solve model
-eval(['dynare ',modnam,' noclearall'])
-oobase_ = oo_;
-Mbase_ = M_;
-
-ys_ = oobase_.dr.ys;
-nvars = numel(ys_);
-zdatass_ = ys_ ;
-
-for i=1:Mbase_.endo_nbr
-  eval([deblank(Mbase_.endo_names(i,:)) '_ss = oo_.dr.ys(i); ']);
-end
-
-for i = 1:size(Mbase_.param_names)
-  eval([Mbase_.param_names(i,:),'= M_.params(i);']);
-end
-
-
-
-
-
-
-
-[hm1,h,hl1,Jbarmat] = get_deriv(Mbase_,ys_);
-cof = [hm1,h,hl1];
-
-[decrulea,decruleb]=get_pq(oobase_.dr);
-endog_ = M_.endo_names;
-exog_ =  M_.exo_names;
-
-nvars = numel(Mbase_.endo_nbr);
-
-
-nshocks = size(shockssequence,1);
-init = zeros(nvars,1);
-
-wishlist = endog_;
-nwishes = size(wishlist,1);
-
-
-zdata_ = mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,shockssequence);
-
+function [zdata_, zdatass_, oobase_, Mbase_ ] = ...
+    solve_no_constraint(modnam,...
+                        shockssequence,irfshock,nperiods)
+
+global M_ oo_
+
+errlist = [];
+
+% solve model
+eval(['dynare ',modnam,' noclearall'])
+oobase_ = oo_;
+Mbase_ = M_;
+
+ys_ = oobase_.dr.ys;
+nvars = numel(ys_);
+zdatass_ = ys_ ;
+
+for i=1:Mbase_.endo_nbr
+    eval([deblank(Mbase_.endo_names(i,:)) '_ss = oo_.dr.ys(i); ']);
+end
+
+for i = 1:size(Mbase_.param_names)
+    eval([Mbase_.param_names(i,:),'= M_.params(i);']);
+end
+
+
+
+
+
+
+
+[hm1,h,hl1,Jbarmat] = get_deriv(Mbase_,ys_);
+cof = [hm1,h,hl1];
+
+[decrulea,decruleb]=get_pq(oobase_.dr);
+endog_ = M_.endo_names;
+exog_ =  M_.exo_names;
+
+nvars = numel(Mbase_.endo_nbr);
+
+
+nshocks = size(shockssequence,1);
+init = zeros(nvars,1);
+
+wishlist = endog_;
+nwishes = size(wishlist,1);
+
+
+zdata_ = mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,shockssequence);
diff --git a/matlab/occbin/solve_no_constraint_noclear.m b/matlab/occbin/solve_no_constraint_noclear.m
index 309c5c546e13db96b4516146302f3fc72aaded6c..8012f9126cc0c85d7cf61b43d8c9b471f00b2790 100755
--- a/matlab/occbin/solve_no_constraint_noclear.m
+++ b/matlab/occbin/solve_no_constraint_noclear.m
@@ -1,48 +1,47 @@
-function [zdata oobase_ Mbase_ ] = ...
-    solve_no_constraint_noclear(modnam,...
-    shockssequence,irfshock,nperiods);
-
-global M_ oo_
-
-errlist = [];
-
-% solve model
-eval(['dynare ',modnam,'  nolog']);
-oobase_ = oo_;
-Mbase_ = M_;
-
-ys_ = oobase_.dr.ys;
-
-for i=1:Mbase_.endo_nbr
-  eval([deblank(Mbase_.endo_names(i,:)) '_ss = oo_.dr.ys(i); ']);
-end
-
-for i = 1:size(Mbase_.param_names)
-  eval([Mbase_.param_names(i,:),'= M_.params(i);']);
-end
-
-setss
-
-
-
-
-
-[hm1,h,hl1,Jbarmat] = get_deriv(Mbase_,ys_);
-cof = [hm1,h,hl1];
-
-[decrulea,decruleb]=get_pq(oobase_.dr);
-endog_ = M_.endo_names;
-exog_ =  M_.exo_names;
-
-
-nvars = numel(Mbase_.endo_nbr);
-
-nshocks = size(shockssequence,1);
-init = zeros(nvars,1);
-
-wishlist = endog_;
-nwishes = size(wishlist,1);
-
-
-zdata = mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,shockssequence);
-
+function [zdata, oobase_, Mbase_ ] = ...
+    solve_no_constraint_noclear(modnam,...
+                                shockssequence,irfshock,nperiods)
+
+global M_ oo_
+
+errlist = [];
+
+% solve model
+eval(['dynare ',modnam,'  nolog']);
+oobase_ = oo_;
+Mbase_ = M_;
+
+ys_ = oobase_.dr.ys;
+
+for i=1:Mbase_.endo_nbr
+    eval([deblank(Mbase_.endo_names(i,:)) '_ss = oo_.dr.ys(i); ']);
+end
+
+for i = 1:size(Mbase_.param_names)
+    eval([Mbase_.param_names(i,:),'= M_.params(i);']);
+end
+
+setss
+
+
+
+
+
+[hm1,h,hl1,Jbarmat] = get_deriv(Mbase_,ys_);
+cof = [hm1,h,hl1];
+
+[decrulea,decruleb]=get_pq(oobase_.dr);
+endog_ = M_.endo_names;
+exog_ =  M_.exo_names;
+
+
+nvars = numel(Mbase_.endo_nbr);
+
+nshocks = size(shockssequence,1);
+init = zeros(nvars,1);
+
+wishlist = endog_;
+nwishes = size(wishlist,1);
+
+
+zdata = mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,shockssequence);
diff --git a/matlab/occbin/solve_one_constraint.1.m b/matlab/occbin/solve_one_constraint.1.m
index 34e296496b4c535a01cb2eb05b16536fded1cf42..aa155c234fb4033230b0cc06522c7922e14ce6bf 100755
--- a/matlab/occbin/solve_one_constraint.1.m
+++ b/matlab/occbin/solve_one_constraint.1.m
@@ -1,192 +1,192 @@
-% solve_one_constraint [zdatalinear zdatapiecewise zdatass oo base M base] = solve one constraint(modnam, modnamstar, constraint, constraint relax, shockssequence, irfshock, nperiods, maxiter, init);
-% 
-% Inputs: 
-% modnam: name of .mod file for the reference regime (excludes the .mod extension).
-% modnamstar: name of .mod file for the alternative regime (excludes the .mod exten- sion).
-% constraint: the constraint (see notes 1 and 2 below). When the condition in constraint evaluates to true, the solution switches from the reference to the alternative regime.
-% constraint relax: when the condition in constraint relax evaluates to true, the solution returns to the reference regime.
-% shockssequence: a sequence of unforeseen shocks under which one wants to solve the model (size T�nshocks).
-% irfshock: label for innovation for IRFs, from Dynare .mod file (one or more of the ?varexo?).
-% nperiods: simulation horizon (can be longer than the sequence of shocks defined in shockssequence; must be long enough to ensure convergence back to the reference model at the end of the simulation horizon and may need to be varied depending on the sequence of shocks).
-% maxiter: maximum number of iterations allowed for the solution algorithm (20 if not specified).
-% init:	the initial position for the vector of state variables, in deviation from steady state (if not specified, the default is steady state). The ordering follows the definition order in the .mod files.
-%
-% Outputs:
-% zdatalinear: an array containing paths for all endogenous variables ignoring the occasionally binding constraint (the linear solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
-% zdatapiecewise: an array containing paths for all endogenous variables satisfying the occasionally binding constraint (the occbin/piecewise solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
-% zdatass: theinitialpositionforthevectorofstatevariables,indeviationfromsteady state (if not specified, the default is a vectors of zero implying that the initial conditions coincide with the steady state). The ordering follows the definition order in the .mod files.
-% oobase,Mbase: structures produced by Dynare for the reference model ? see Dynare User Guide.
-
-% Log of changes:
-% 6/17/2013 -- Luca added a trailing underscore to local variables in an
-% attempt to avoid conflicts with parameter names defined in the .mod files
-% to be processed.
-% 6/17/2013 -- Luca replaced external .m file setss.m
-
-
-function [zdatalinear_ zdatapiecewise_ zdatass_ oobase_ Mbase_  ] = ...
-    solve_one_constraint(modnam_,modnamstar_,...
-    constraint_, constraint_relax_,...
-    shockssequence_,irfshock_,nperiods_,maxiter_,init_)
-
-global M_ oo_
-
-errlist_ = [];
-
-% solve the reference model linearly
-eval(['dynare ',modnam_,' noclearall nolog '])
-oobase_ = oo_;
-Mbase_ = M_;
-
-% import locally the values of parameters assigned in the reference .mod
-% file
-for i_indx_ = 1:Mbase_.param_nbr
-  eval([Mbase_.param_names(i_indx_,:),'= M_.params(i_indx_);']);
-end
-
-% Create steady state values of the variables if needed for processing the constraint
-for i=1:Mbase_.endo_nbr
-   eval([deblank(Mbase_.endo_names(i,:)) '_ss = oobase_.dr.ys(i); ']);
-end
-
-
-% parse the .mod file for the alternative regime
-eval(['dynare ',modnamstar_,' noclearall nolog '])
-oostar_ = oo_;
-Mstar_ = M_;
-
-
-% check inputs
-if ~strcmp(Mbase_.endo_names,Mstar_.endo_names)
-    error('The two .mod files need to have exactly the same endogenous variables declared in the same order')
-end
-
-if ~strcmp(Mbase_.exo_names,Mstar_.exo_names)
-    error('The two .mod files need to have exactly the same exogenous variables declared in the same order')
-end
-
-if ~strcmp(Mbase_.param_names,Mstar_.param_names)
-    warning('The parameter list does not match across .mod files')
-end
-
-% ensure that the two models have the same parameters
-% use the parameters for the base model.
-Mstar_.params = Mbase_.params;
-
-nvars_ = Mbase_.endo_nbr;
-zdatass_ = oobase_.dr.ys;
-
-
-% get the matrices holding the first derivatives for the model
-% each regime is treated separately
-[hm1_,h_,hl1_,Jbarmat_] = get_deriv(Mbase_,zdatass_);
-cof_ = [hm1_,h_,hl1_];
-
-[hm1_,h_,hl1_,Jstarbarmat_,resid_] = get_deriv(Mstar_,zdatass_);
-cofstar_ = [hm1_,h_,hl1_];
-Dstartbarmat_ = resid_;
-
-[decrulea_,decruleb_]=get_pq(oobase_.dr);
-endog_ = M_.endo_names;
-exog_ =  M_.exo_names;
-
-
-% processes the constraints specified in the call to this function
-% uppend a suffix to each endogenous variable
-constraint_difference_ = process_constraint(constraint_,'_difference',Mbase_.endo_names,0);
-
-constraint_relax_difference_ = process_constraint(constraint_relax_,'_difference',Mbase_.endo_names,0);
-
-
-
-nshocks_ = size(shockssequence_,1);
-
-% if necessary, set default values for optional arguments
-if ~exist('init_')
-    init_ = zeros(nvars_,1);
-end
-
-if ~exist('maxiter_')
-    maxiter_ = 20;
-end
-
-if ~exist('nperiods_')
-    nperiods_ = 100;
-end
-
-
-% set some initial conditions and loop through the shocks 
-% period by period
-init_orig_ = init_;
-zdatapiecewise_ = zeros(nperiods_,nvars_);
-wishlist_ = endog_;
-nwishes_ = size(wishlist_,1);
-violvecbool_ = zeros(nperiods_+1,1);
-
-
-for ishock_ = 1:nshocks_
-    
-    changes_=1;
-    iter_ = 0;
-    
-    
-    while (changes_ & iter_<maxiter_)
-        iter_ = iter_ +1;
-        
-        % analyze when each regime starts based on current guess
-        [regime regimestart]=map_regime(violvecbool_);
-        
-        
-        % get the hypothesized piece wise linear solution
-        [zdatalinear_]=mkdatap_anticipated(nperiods_,decrulea_,decruleb_,...
-            cof_,Jbarmat_,cofstar_,Jstarbarmat_,Dstartbarmat_,...
-            regime,regimestart,violvecbool_,...
-            endog_,exog_,irfshock_,shockssequence_(ishock_,:),init_);
-        
-        for i_indx_=1:nwishes_
-            eval([deblank(wishlist_(i_indx_,:)),'_difference=zdatalinear_(:,i_indx_);']);
-        end
-        
-        
-        
-        newviolvecbool_ = eval(constraint_difference_);
-        relaxconstraint_ = eval(constraint_relax_difference_);
-        
-        
-        
-        % check if changes to the hypothesis of the duration for each
-        % regime
-        if (max(newviolvecbool_-violvecbool_>0)) | sum(relaxconstraint_(find(violvecbool_==1))>0)
-            changes_ = 1;
-        else
-            changes_ = 0;
-        end
-        
-        
-        violvecbool_ = (violvecbool_|newviolvecbool_)-(relaxconstraint_ & violvecbool_);
-        
-        
-    end
-    
-    init_ = zdatalinear_(1,:);
-    zdatapiecewise_(ishock_,:)=init_;
-    init_= init_';
-    
-    % reset violvecbool_ for next period's shock -- this resetting is 
-    % consistent with expecting no additional shocks
-    violvecbool_=[violvecbool_(2:end);0];
-    
-end
-
-% if necessary, fill in the rest of the path with the remainder of the 
-% last IRF computed.
-zdatapiecewise_(ishock_+1:end,:)=zdatalinear_(2:nperiods_-ishock_+1,:);
-
-% get the linear responses
-zdatalinear_ = mkdata(max(nperiods_,size(shockssequence_,1)),...
-                  decrulea_,decruleb_,endog_,exog_,...
-                  wishlist_,irfshock_,shockssequence_,init_orig_);
-
-if changes_ ==1
-    display('Did not converge -- increase maxiter_')
-end
+% solve_one_constraint [zdatalinear zdatapiecewise zdatass oo base M base] = solve one constraint(modnam, modnamstar, constraint, constraint relax, shockssequence, irfshock, nperiods, maxiter, init);
+%
+% Inputs:
+% modnam: name of .mod file for the reference regime (excludes the .mod extension).
+% modnamstar: name of .mod file for the alternative regime (excludes the .mod exten- sion).
+% constraint: the constraint (see notes 1 and 2 below). When the condition in constraint evaluates to true, the solution switches from the reference to the alternative regime.
+% constraint relax: when the condition in constraint relax evaluates to true, the solution returns to the reference regime.
+% shockssequence: a sequence of unforeseen shocks under which one wants to solve the model (size T×nshocks).
+% irfshock: label for innovation for IRFs, from Dynare .mod file (one or more of the ?varexo?).
+% nperiods: simulation horizon (can be longer than the sequence of shocks defined in shockssequence; must be long enough to ensure convergence back to the reference model at the end of the simulation horizon and may need to be varied depending on the sequence of shocks).
+% maxiter: maximum number of iterations allowed for the solution algorithm (20 if not specified).
+% init: the initial position for the vector of state variables, in deviation from steady state (if not specified, the default is steady state). The ordering follows the definition order in the .mod files.
+%
+% Outputs:
+% zdatalinear: an array containing paths for all endogenous variables ignoring the occasionally binding constraint (the linear solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
+% zdatapiecewise: an array containing paths for all endogenous variables satisfying the occasionally binding constraint (the occbin/piecewise solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
+% zdatass: theinitialpositionforthevectorofstatevariables,indeviationfromsteady state (if not specified, the default is a vectors of zero implying that the initial conditions coincide with the steady state). The ordering follows the definition order in the .mod files.
+% oobase,Mbase: structures produced by Dynare for the reference model ? see Dynare User Guide.
+
+% Log of changes:
+% 6/17/2013 -- Luca added a trailing underscore to local variables in an
+% attempt to avoid conflicts with parameter names defined in the .mod files
+% to be processed.
+% 6/17/2013 -- Luca replaced external .m file setss.m
+
+
+function [zdatalinear_ zdatapiecewise_ zdatass_ oobase_ Mbase_  ] = ...
+    solve_one_constraint.1(modnam_,modnamstar_,...
+                         constraint_, constraint_relax_,...
+                         shockssequence_,irfshock_,nperiods_,maxiter_,init_)
+
+global M_ oo_
+
+errlist_ = [];
+
+% solve the reference model linearly
+eval(['dynare ',modnam_,' noclearall nolog '])
+oobase_ = oo_;
+Mbase_ = M_;
+
+% import locally the values of parameters assigned in the reference .mod
+% file
+for i_indx_ = 1:Mbase_.param_nbr
+    eval([Mbase_.param_names(i_indx_,:),'= M_.params(i_indx_);']);
+end
+
+% Create steady state values of the variables if needed for processing the constraint
+for i=1:Mbase_.endo_nbr
+    eval([deblank(Mbase_.endo_names(i,:)) '_ss = oobase_.dr.ys(i); ']);
+end
+
+
+% parse the .mod file for the alternative regime
+eval(['dynare ',modnamstar_,' noclearall nolog '])
+oostar_ = oo_;
+Mstar_ = M_;
+
+
+% check inputs
+if ~strcmp(Mbase_.endo_names,Mstar_.endo_names)
+    error('The two .mod files need to have exactly the same endogenous variables declared in the same order')
+end
+
+if ~strcmp(Mbase_.exo_names,Mstar_.exo_names)
+    error('The two .mod files need to have exactly the same exogenous variables declared in the same order')
+end
+
+if ~strcmp(Mbase_.param_names,Mstar_.param_names)
+    warning('The parameter list does not match across .mod files')
+end
+
+% ensure that the two models have the same parameters
+% use the parameters for the base model.
+Mstar_.params = Mbase_.params;
+
+nvars_ = Mbase_.endo_nbr;
+zdatass_ = oobase_.dr.ys;
+
+
+% get the matrices holding the first derivatives for the model
+% each regime is treated separately
+[hm1_,h_,hl1_,Jbarmat_] = get_deriv(Mbase_,zdatass_);
+cof_ = [hm1_,h_,hl1_];
+
+[hm1_,h_,hl1_,Jstarbarmat_,resid_] = get_deriv(Mstar_,zdatass_);
+cofstar_ = [hm1_,h_,hl1_];
+Dstartbarmat_ = resid_;
+
+[decrulea_,decruleb_]=get_pq(oobase_.dr);
+endog_ = M_.endo_names;
+exog_ =  M_.exo_names;
+
+
+% processes the constraints specified in the call to this function
+% uppend a suffix to each endogenous variable
+constraint_difference_ = process_constraint(constraint_,'_difference',Mbase_.endo_names,0);
+
+constraint_relax_difference_ = process_constraint(constraint_relax_,'_difference',Mbase_.endo_names,0);
+
+
+
+nshocks_ = size(shockssequence_,1);
+
+% if necessary, set default values for optional arguments
+if ~exist('init_')
+    init_ = zeros(nvars_,1);
+end
+
+if ~exist('maxiter_')
+    maxiter_ = 20;
+end
+
+if ~exist('nperiods_')
+    nperiods_ = 100;
+end
+
+
+% set some initial conditions and loop through the shocks
+% period by period
+init_orig_ = init_;
+zdatapiecewise_ = zeros(nperiods_,nvars_);
+wishlist_ = endog_;
+nwishes_ = size(wishlist_,1);
+violvecbool_ = zeros(nperiods_+1,1);
+
+
+for ishock_ = 1:nshocks_
+
+    changes_=1;
+    iter_ = 0;
+
+
+    while (changes_ & iter_<maxiter_)
+        iter_ = iter_ +1;
+
+        % analyze when each regime starts based on current guess
+        [regime regimestart]=map_regime(violvecbool_);
+
+
+        % get the hypothesized piece wise linear solution
+        [zdatalinear_]=mkdatap_anticipated(nperiods_,decrulea_,decruleb_,...
+                                           cof_,Jbarmat_,cofstar_,Jstarbarmat_,Dstartbarmat_,...
+                                           regime,regimestart,violvecbool_,...
+                                           endog_,exog_,irfshock_,shockssequence_(ishock_,:),init_);
+
+        for i_indx_=1:nwishes_
+            eval([deblank(wishlist_(i_indx_,:)),'_difference=zdatalinear_(:,i_indx_);']);
+        end
+
+
+
+        newviolvecbool_ = eval(constraint_difference_);
+        relaxconstraint_ = eval(constraint_relax_difference_);
+
+
+
+        % check if changes to the hypothesis of the duration for each
+        % regime
+        if (max(newviolvecbool_-violvecbool_>0)) | sum(relaxconstraint_(find(violvecbool_==1))>0)
+            changes_ = 1;
+        else
+            changes_ = 0;
+        end
+
+
+        violvecbool_ = (violvecbool_|newviolvecbool_)-(relaxconstraint_ & violvecbool_);
+
+
+    end
+
+    init_ = zdatalinear_(1,:);
+    zdatapiecewise_(ishock_,:)=init_;
+    init_= init_';
+
+    % reset violvecbool_ for next period's shock -- this resetting is
+    % consistent with expecting no additional shocks
+    violvecbool_=[violvecbool_(2:end);0];
+
+end
+
+% if necessary, fill in the rest of the path with the remainder of the
+% last IRF computed.
+zdatapiecewise_(ishock_+1:end,:)=zdatalinear_(2:nperiods_-ishock_+1,:);
+
+% get the linear responses
+zdatalinear_ = mkdata(max(nperiods_,size(shockssequence_,1)),...
+                      decrulea_,decruleb_,endog_,exog_,...
+                      wishlist_,irfshock_,shockssequence_,init_orig_);
+
+if changes_ ==1
+    display('Did not converge -- increase maxiter_')
+end
diff --git a/matlab/occbin/solve_one_constraint.m b/matlab/occbin/solve_one_constraint.m
index c446f4c40dc164fadbf362d70cc79ceed4260a04..5959636bf76c40936ac5947262895dee217bcef6 100755
--- a/matlab/occbin/solve_one_constraint.m
+++ b/matlab/occbin/solve_one_constraint.m
@@ -1,200 +1,200 @@
-% solve_one_constraint [zdatalinear zdatapiecewise zdatass oo base M base] = solve one constraint(modnam, modnamstar, constraint, constraint relax, shockssequence, irfshock, nperiods, maxiter, init);
-% 
-% Inputs: 
-% modnam: name of .mod file for the reference regime (excludes the .mod extension).
-% modnamstar: name of .mod file for the alternative regime (excludes the .mod exten- sion).
-% constraint: the constraint (see notes 1 and 2 below). When the condition in constraint evaluates to true, the solution switches from the reference to the alternative regime.
-% constraint relax: when the condition in constraint relax evaluates to true, the solution returns to the reference regime.
-% shockssequence: a sequence of unforeseen shocks under which one wants to solve the model (size T�nshocks).
-% irfshock: label for innovation for IRFs, from Dynare .mod file (one or more of the ?varexo?).
-% nperiods: simulation horizon (can be longer than the sequence of shocks defined in shockssequence; must be long enough to ensure convergence back to the reference model at the end of the simulation horizon and may need to be varied depending on the sequence of shocks).
-% maxiter: maximum number of iterations allowed for the solution algorithm (20 if not specified).
-% init:	the initial position for the vector of state variables, in deviation from steady state (if not specified, the default is steady state). The ordering follows the definition order in the .mod files.
-%
-% Outputs:
-% zdatalinear: an array containing paths for all endogenous variables ignoring the occasionally binding constraint (the linear solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
-% zdatapiecewise: an array containing paths for all endogenous variables satisfying the occasionally binding constraint (the occbin/piecewise solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
-% zdatass: theinitialpositionforthevectorofstatevariables,indeviationfromsteady state (if not specified, the default is a vectors of zero implying that the initial conditions coincide with the steady state). The ordering follows the definition order in the .mod files.
-% oobase,Mbase: structures produced by Dynare for the reference model ? see Dynare User Guide.
-
-% Log of changes:
-% 6/17/2013 -- Luca added a trailing underscore to local variables in an
-% attempt to avoid conflicts with parameter names defined in the .mod files
-% to be processed.
-% 6/17/2013 -- Luca replaced external .m file setss.m
-
-
-function [zdatalinear_ zdatapiecewise_ zdatass_ oobase_ Mbase_  ] = ...
-    solve_one_constraint(modnam_,modnamstar_,...
-    constraint_, constraint_relax_,...
-    shockssequence_,irfshock_,nperiods_,maxiter_,init_)
-
-global M_ oo_
-
-errlist_ = [];
-
-% solve the reference model linearly
-eval(['dynare ',modnam_,' noclearall nolog '])
-oobase_ = oo_;
-Mbase_ = M_;
-
-% import locally the values of parameters assigned in the reference .mod
-% file
-for i_indx_ = 1:Mbase_.param_nbr
-  eval([Mbase_.param_names(i_indx_,:),'= M_.params(i_indx_);']);
-end
-
-% Create steady state values of the variables if needed for processing the constraint
-for i=1:Mbase_.endo_nbr
-   eval([deblank(Mbase_.endo_names(i,:)) '_ss = oobase_.dr.ys(i); ']);
-end
-
-
-% parse the .mod file for the alternative regime
-eval(['dynare ',modnamstar_,' noclearall nolog '])
-oostar_ = oo_;
-Mstar_ = M_;
-
-
-% check inputs
-if ~strcmp(Mbase_.endo_names,Mstar_.endo_names)
-    error('The two .mod files need to have exactly the same endogenous variables declared in the same order')
-end
-
-if ~strcmp(Mbase_.exo_names,Mstar_.exo_names)
-    error('The two .mod files need to have exactly the same exogenous variables declared in the same order')
-end
-
-if ~strcmp(Mbase_.param_names,Mstar_.param_names)
-    warning('The parameter list does not match across .mod files')
-end
-
-% ensure that the two models have the same parameters
-% use the parameters for the base model.
-Mstar_.params = Mbase_.params;
-
-nvars_ = Mbase_.endo_nbr;
-zdatass_ = oobase_.dr.ys;
-
-
-% get the matrices holding the first derivatives for the model
-% each regime is treated separately
-[hm1_,h_,hl1_,Jbarmat_] = get_deriv(Mbase_,zdatass_);
-cof_ = [hm1_,h_,hl1_];
-
-[hm1_,h_,hl1_,Jstarbarmat_,resid_] = get_deriv(Mstar_,zdatass_);
-cofstar_ = [hm1_,h_,hl1_];
-Dstartbarmat_ = resid_;
-
-if isfield(Mbase_,'nfwrd')
-    % the latest Dynare distributions have moved nstatic and nfwrd
-    [decrulea_,decruleb_]=get_pq(oobase_.dr,Mbase_.nstatic,Mbase_.nfwrd);
-else
-    [decrulea_,decruleb_]=get_pq(oobase_.dr,oobase_.dr.nstatic,oobase_.dr.nfwrd);
-end
-
-endog_ = M_.endo_names;
-exog_ =  M_.exo_names;
-
-
-% processes the constraints specified in the call to this function
-% uppend a suffix to each endogenous variable
-constraint_difference_ = process_constraint(constraint_,'_difference',Mbase_.endo_names,0);
-
-constraint_relax_difference_ = process_constraint(constraint_relax_,'_difference',Mbase_.endo_names,0);
-
-
-
-nshocks_ = size(shockssequence_,1);
-
-% if necessary, set default values for optional arguments
-if ~exist('init_')
-    init_ = zeros(nvars_,1);
-end
-
-if ~exist('maxiter_')
-    maxiter_ = 20;
-end
-
-if ~exist('nperiods_')
-    nperiods_ = 100;
-end
-
-
-% set some initial conditions and loop through the shocks 
-% period by period
-init_orig_ = init_;
-zdatapiecewise_ = zeros(nperiods_,nvars_);
-wishlist_ = endog_;
-nwishes_ = size(wishlist_,1);
-violvecbool_ = zeros(nperiods_+1,1);
-
-
-for ishock_ = 1:nshocks_
-    
-    changes_=1;
-    iter_ = 0;
-    
-    
-    while (changes_ & iter_<maxiter_)
-        iter_ = iter_ +1;
-        
-        % analyze when each regime starts based on current guess
-        [regime regimestart]=map_regime(violvecbool_);
-        
-        
-        
-        % get the hypothesized piece wise linear solution
-        [zdatalinear_]=mkdatap_anticipated(nperiods_,decrulea_,decruleb_,...
-            cof_,Jbarmat_,cofstar_,Jstarbarmat_,Dstartbarmat_,...
-            regime,regimestart,violvecbool_,...
-            endog_,exog_,irfshock_,shockssequence_(ishock_,:),init_);
-        
-        for i_indx_=1:nwishes_
-            eval([deblank(wishlist_(i_indx_,:)),'_difference=zdatalinear_(:,i_indx_);']);
-        end
-        
-        
-        
-        newviolvecbool_ = eval(constraint_difference_);
-        relaxconstraint_ = eval(constraint_relax_difference_);
-        
-        
-        
-        % check if changes to the hypothesis of the duration for each
-        % regime
-        if (max(newviolvecbool_-violvecbool_>0)) | sum(relaxconstraint_(find(violvecbool_==1))>0)
-            changes_ = 1;
-        else
-            changes_ = 0;
-        end
-        
-        
-        
-        violvecbool_ = (violvecbool_|newviolvecbool_)-(relaxconstraint_ & violvecbool_);
-                
-        
-    end
-    
-    init_ = zdatalinear_(1,:);
-    zdatapiecewise_(ishock_,:)=init_;
-    init_= init_';
-    
-    % reset violvecbool_ for next period's shock -- this resetting is 
-    % consistent with expecting no additional shocks
-    violvecbool_=[violvecbool_(2:end);0];
-    
-end
-
-% if necessary, fill in the rest of the path with the remainder of the 
-% last IRF computed.
-zdatapiecewise_(ishock_+1:end,:)=zdatalinear_(2:nperiods_-ishock_+1,:);
-
-% get the linear responses
-zdatalinear_ = mkdata(max(nperiods_,size(shockssequence_,1)),...
-                  decrulea_,decruleb_,endog_,exog_,...
-                  wishlist_,irfshock_,shockssequence_,init_orig_);
-
-if changes_ ==1
-    display('Did not converge -- increase maxiter_')
-end
+% solve_one_constraint [zdatalinear zdatapiecewise zdatass oo base M base] = solve one constraint(modnam, modnamstar, constraint, constraint relax, shockssequence, irfshock, nperiods, maxiter, init);
+%
+% Inputs:
+% modnam: name of .mod file for the reference regime (excludes the .mod extension).
+% modnamstar: name of .mod file for the alternative regime (excludes the .mod exten- sion).
+% constraint: the constraint (see notes 1 and 2 below). When the condition in constraint evaluates to true, the solution switches from the reference to the alternative regime.
+% constraint relax: when the condition in constraint relax evaluates to true, the solution returns to the reference regime.
+% shockssequence: a sequence of unforeseen shocks under which one wants to solve the model (size T×nshocks).
+% irfshock: label for innovation for IRFs, from Dynare .mod file (one or more of the ?varexo?).
+% nperiods: simulation horizon (can be longer than the sequence of shocks defined in shockssequence; must be long enough to ensure convergence back to the reference model at the end of the simulation horizon and may need to be varied depending on the sequence of shocks).
+% maxiter: maximum number of iterations allowed for the solution algorithm (20 if not specified).
+% init: the initial position for the vector of state variables, in deviation from steady state (if not specified, the default is steady state). The ordering follows the definition order in the .mod files.
+%
+% Outputs:
+% zdatalinear: an array containing paths for all endogenous variables ignoring the occasionally binding constraint (the linear solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
+% zdatapiecewise: an array containing paths for all endogenous variables satisfying the occasionally binding constraint (the occbin/piecewise solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
+% zdatass: theinitialpositionforthevectorofstatevariables,indeviationfromsteady state (if not specified, the default is a vectors of zero implying that the initial conditions coincide with the steady state). The ordering follows the definition order in the .mod files.
+% oobase,Mbase: structures produced by Dynare for the reference model ? see Dynare User Guide.
+
+% Log of changes:
+% 6/17/2013 -- Luca added a trailing underscore to local variables in an
+% attempt to avoid conflicts with parameter names defined in the .mod files
+% to be processed.
+% 6/17/2013 -- Luca replaced external .m file setss.m
+
+
+function [zdatalinear_, zdatapiecewise_, zdatass_, oobase_, Mbase_  ] = ...
+    solve_one_constraint(modnam_,modnamstar_,...
+                         constraint_, constraint_relax_,...
+                         shockssequence_,irfshock_,nperiods_,maxiter_,init_)
+
+global M_ oo_
+
+errlist_ = [];
+
+% solve the reference model linearly
+eval(['dynare ',modnam_,' noclearall nolog '])
+oobase_ = oo_;
+Mbase_ = M_;
+
+% import locally the values of parameters assigned in the reference .mod
+% file
+for i_indx_ = 1:Mbase_.param_nbr
+    eval([Mbase_.param_names(i_indx_,:),'= M_.params(i_indx_);']);
+end
+
+% Create steady state values of the variables if needed for processing the constraint
+for i=1:Mbase_.endo_nbr
+    eval([deblank(Mbase_.endo_names(i,:)) '_ss = oobase_.dr.ys(i); ']);
+end
+
+
+% parse the .mod file for the alternative regime
+eval(['dynare ',modnamstar_,' noclearall nolog '])
+oostar_ = oo_;
+Mstar_ = M_;
+
+
+% check inputs
+if ~strcmp(Mbase_.endo_names,Mstar_.endo_names)
+    error('The two .mod files need to have exactly the same endogenous variables declared in the same order')
+end
+
+if ~strcmp(Mbase_.exo_names,Mstar_.exo_names)
+    error('The two .mod files need to have exactly the same exogenous variables declared in the same order')
+end
+
+if ~strcmp(Mbase_.param_names,Mstar_.param_names)
+    warning('The parameter list does not match across .mod files')
+end
+
+% ensure that the two models have the same parameters
+% use the parameters for the base model.
+Mstar_.params = Mbase_.params;
+
+nvars_ = Mbase_.endo_nbr;
+zdatass_ = oobase_.dr.ys;
+
+
+% get the matrices holding the first derivatives for the model
+% each regime is treated separately
+[hm1_,h_,hl1_,Jbarmat_] = get_deriv(Mbase_,zdatass_);
+cof_ = [hm1_,h_,hl1_];
+
+[hm1_,h_,hl1_,Jstarbarmat_,resid_] = get_deriv(Mstar_,zdatass_);
+cofstar_ = [hm1_,h_,hl1_];
+Dstartbarmat_ = resid_;
+
+if isfield(Mbase_,'nfwrd')
+    % the latest Dynare distributions have moved nstatic and nfwrd
+    [decrulea_,decruleb_]=get_pq(oobase_.dr,Mbase_.nstatic,Mbase_.nfwrd);
+else
+    [decrulea_,decruleb_]=get_pq(oobase_.dr,oobase_.dr.nstatic,oobase_.dr.nfwrd);
+end
+
+endog_ = M_.endo_names;
+exog_ =  M_.exo_names;
+
+
+% processes the constraints specified in the call to this function
+% uppend a suffix to each endogenous variable
+constraint_difference_ = process_constraint(constraint_,'_difference',Mbase_.endo_names,0);
+
+constraint_relax_difference_ = process_constraint(constraint_relax_,'_difference',Mbase_.endo_names,0);
+
+
+
+nshocks_ = size(shockssequence_,1);
+
+% if necessary, set default values for optional arguments
+if ~exist('init_')
+    init_ = zeros(nvars_,1);
+end
+
+if ~exist('maxiter_')
+    maxiter_ = 20;
+end
+
+if ~exist('nperiods_')
+    nperiods_ = 100;
+end
+
+
+% set some initial conditions and loop through the shocks
+% period by period
+init_orig_ = init_;
+zdatapiecewise_ = zeros(nperiods_,nvars_);
+wishlist_ = endog_;
+nwishes_ = size(wishlist_,1);
+violvecbool_ = zeros(nperiods_+1,1);
+
+
+for ishock_ = 1:nshocks_
+
+    changes_=1;
+    iter_ = 0;
+
+
+    while (changes_ & iter_<maxiter_)
+        iter_ = iter_ +1;
+
+        % analyze when each regime starts based on current guess
+        [regime, regimestart]=map_regime(violvecbool_);
+
+
+
+        % get the hypothesized piece wise linear solution
+        [zdatalinear_]=mkdatap_anticipated(nperiods_,decrulea_,decruleb_,...
+                                           cof_,Jbarmat_,cofstar_,Jstarbarmat_,Dstartbarmat_,...
+                                           regime,regimestart,violvecbool_,...
+                                           endog_,exog_,irfshock_,shockssequence_(ishock_,:),init_);
+
+        for i_indx_=1:nwishes_
+            eval([deblank(wishlist_(i_indx_,:)),'_difference=zdatalinear_(:,i_indx_);']);
+        end
+
+
+
+        newviolvecbool_ = eval(constraint_difference_);
+        relaxconstraint_ = eval(constraint_relax_difference_);
+
+
+
+        % check if changes to the hypothesis of the duration for each
+        % regime
+        if (max(newviolvecbool_-violvecbool_>0)) | sum(relaxconstraint_(find(violvecbool_==1))>0)
+            changes_ = 1;
+        else
+            changes_ = 0;
+        end
+
+
+
+        violvecbool_ = (violvecbool_|newviolvecbool_)-(relaxconstraint_ & violvecbool_);
+
+
+    end
+
+    init_ = zdatalinear_(1,:);
+    zdatapiecewise_(ishock_,:)=init_;
+    init_= init_';
+
+    % reset violvecbool_ for next period's shock -- this resetting is
+    % consistent with expecting no additional shocks
+    violvecbool_=[violvecbool_(2:end);0];
+
+end
+
+% if necessary, fill in the rest of the path with the remainder of the
+% last IRF computed.
+zdatapiecewise_(ishock_+1:end,:)=zdatalinear_(2:nperiods_-ishock_+1,:);
+
+% get the linear responses
+zdatalinear_ = mkdata(max(nperiods_,size(shockssequence_,1)),...
+                      decrulea_,decruleb_,endog_,exog_,...
+                      wishlist_,irfshock_,shockssequence_,init_orig_);
+
+if changes_ ==1
+    display('Did not converge -- increase maxiter_')
+end
diff --git a/matlab/occbin/solve_two_constraints.m b/matlab/occbin/solve_two_constraints.m
index dfca403a2233aade5bb8a9ecf44f093f9d65c3e0..1b436ad00fb38b909bec99442a48716841270d60 100755
--- a/matlab/occbin/solve_two_constraints.m
+++ b/matlab/occbin/solve_two_constraints.m
@@ -1,305 +1,304 @@
-% [zdatalinear zdatapiecewise zdatass oo 00 M 00] = solve two constraints(modnam 00,modnam 10,modnam 01,modnam 11,... constraint1, constraint2,... constraint relax1, constraint relax2,... shockssequence,irfshock,nperiods,curb retrench,maxiter,init);
-% 
-% Inputs:
-% modnam 00: name of the .mod file for reference regime (excludes the .mod extension). modnam10: name of the .mod file for the alternative regime governed by the first
-% constraint.
-% modnam01: name of the .mod file for the alternative regime governed by the second constraint.
-% modnam 11: name of the .mod file for the case in which both constraints force a switch to their alternative regimes.
-% constraint1: the first constraint (see notes 1 and 2 below). If constraint1 evaluates to true, then the solution switches to the alternative regime for condition 1. In thatcase, if constraint2 (described below) evaluates to false, then the model solution switches to enforcing the conditions for an equilibrium in modnam 10. Otherwise, if constraint2 also evaluates to true, then the model solution switches to enforcing the conditions for an equilibrium in modnam 11.
-% constraint relax1: when the condition in constraint relax1 evaluates to true, the solution returns to the reference regime for constraint1.
-% constraint2: the second constraint (see notes 1 and 2 below). constraint relax2: when the condition in constraint relax2 evaluates to true, the
-% solution returns to the reference regime for constraint2. shockssequence: a sequence of unforeseen shocks under which one wants to solve the
-% model
-% irfshock: label for innovation for IRFs, from Dynare .mod file (one or more of the ?varexo?)
-% nperiods: simulation horizon (can be longer than the sequence of shocks defined in shockssequence; must be long enough to ensure convergence back to the reference model at the end of the simulation horizon and may need to be varied depending on the sequence of shocks).
-% curb retrench:	a scalar equal to 0 or 1. Default is 0. When set to 0, it updates the guess based of regimes based on the previous iteration. When set to 1, it updates in a manner similar to a Gauss-Jacobi scheme, slowing the iterations down by updating the guess of regimes only one period at a time.
-% maxiter: maximum number of iterations allowed for the solution algorithm (20 if not specified).
-% init:	the initial position for the vector of state variables, in deviation from steady state (if not specified, the default is a vector of zero implying that the initial conditions coincide with the steady state). The ordering follows the definition order in the .mod files.
-%
-% Outputs:
-% zdatalinear: an array containing paths for all endogenous variables ignoring the occasionally binding constraint (the linear solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
-% zdatapiecewise: an array containing paths for all endogenous variables satisfying the occasionally binding constraint (the occbin/piecewise solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
-% zdatass: a vector that holds the steady state values of the endogenous variables ( following the definition order in the .mod file).
-% oo00 , M00 :	structures produced by Dynare for the reference model ? see Dynare User Guide.
-
-
-% Log of changes
-% 6/17/2013 -- Luca added a trailing underscore to local variables in an
-% attempt to avoid conflicts with parameter names defined in the .mod files
-% to be processed.
-% 6/17/2013 -- Luca replaced external .m file setss.m
-
-function [ zdatalinear_ zdatapiecewise_ zdatass_ oo00_  M00_ ] = ...
-  solve_two_constraints(modnam_00_,modnam_10_,modnam_01_,modnam_11_,...
-    constrain1_, constrain2_,...
-    constraint_relax1_, constraint_relax2_,...
-    shockssequence_,irfshock_,nperiods_,curb_retrench_,maxiter_,init_)
-
-global M_ oo_
-
-
-
-% solve model
-eval(['dynare ',modnam_00_,' noclearall nolog'])
-oo00_ = oo_;
-M00_ = M_;
-
-
-for i=1:M00_.endo_nbr
-   eval([deblank(M00_.endo_names(i,:)) '_ss = oo00_.dr.ys(i); ']);
-end
-
-for i_indx_ = 1:M00_.param_nbr
-  eval([M00_.param_names(i_indx_,:),'= M00_.params(i_indx_);']);
-end
-
-
-
-eval(['dynare ',modnam_10_,' noclearall'])
-oo10_ = oo_;
-M10_ = M_;
-
-eval(['dynare ',modnam_01_,' noclearall'])
-oo01_ = oo_;
-M01_ = M_;
-
-eval(['dynare ',modnam_11_,' noclearall'])
-oo11_ = oo_;
-M11_ = M_;
-
-
-% do some error checking
-
-% check inputs
-if ~strcmp(M00_.endo_names,M10_.endo_names)
-    error([modnam_00_,' and ',modnam_10_,' need to have exactly the same endogenous variables and they need to be declared in the same order'])
-end
-
-if ~strcmp(M00_.exo_names,M10_.exo_names)
-    error([modnam_00_,' and ',modnam_10_,' need to have exactly the same exogenous variables and they need to be declared in the same order'])
-end
-
-if ~strcmp(M00_.param_names,M10_.param_names)
-    warning(['The parameter list does not match across the files ',modnam_00_,' and ',modnam_10_])
-end
-
-
-if ~strcmp(M00_.endo_names,M01_.endo_names)
-    error([modnam_00,' and ',modnam_01_,' need to have exactly the same endogenous variables and they need to be declared in the same order'])
-end
-
-if ~strcmp(M00_.exo_names,M01_.exo_names)
-    error([modnam_00_,' and ',modnam_01_,' need to have exactly the same exogenous variables and they need to be declared in the same order'])
-end
-
-if ~strcmp(M00_.param_names,M01_.param_names)
-    warning(['The parameter list does not match across the files ',modnam_00_,' and ',modnam_01_])
-end
-
-
-if ~strcmp(M00_.endo_names,M11_.endo_names)
-    error([modnam_00_,' and ',modnam_11_,' need to have exactly the same endogenous variables and they need to be declared in the same order'])
-end
-
-if ~strcmp(M00_.exo_names,M11_.exo_names)
-    error([modnam_00_,' and ',modnam_11_,' need to have exactly the same exogenous variables and they need to be declared in the same order'])
-end
-
-if ~strcmp(M00_.param_names,M11_.param_names)
-    warning(['The parameter list does not match across the files ',modnam_00_,' and ',modnam_11_])
-end
-
-
-
-
-
-nvars_ = M00_.endo_nbr;
-zdatass_ = oo00_.dr.ys;
-
-
-[hm1_,h_,hl1_,Jbarmat_] = get_deriv(M00_,zdatass_);
-cof_ = [hm1_,h_,hl1_];
-
-
-M10_.params = M00_.params;
-[hm1_,h_,hl1_,Jbarmat10_,resid_] = get_deriv(M10_,zdatass_);
-cof10_ = [hm1_,h_,hl1_];
-Dbarmat10_ = resid_;
-
-M01_.params = M00_.params;
-[hm1_,h_,hl1_,Jbarmat01_,resid_] = get_deriv(M01_,zdatass_);
-cof01_ = [hm1_,h_,hl1_];
-Dbarmat01_ = resid_;
-
-M11_.params = M00_.params;
-[hm1_,h_,hl1_,Jbarmat11_,resid_] = get_deriv(M11_,zdatass_);
-cof11_ = [hm1_,h_,hl1_];
-Dbarmat11_ = resid_;
-
-
-if isfield(M00_,'nfwrd')  % needed for bakward compatibility with older Dynare releases
-[decrulea,decruleb]=get_pq(oo00_.dr,M00_.nstatic,M00_.nfwrd);
-else
-[decrulea,decruleb]=get_pq(oo00_.dr,oo00_.dr.nstatic,oo00_.dr.nfwrd);    
-end
-endog_ = M00_.endo_names;
-exog_ =  M00_.exo_names;
-
-
-% processes the constrain so as to uppend a suffix to each
-% endogenous variables
-constraint1_difference_ = process_constraint(constrain1_,'_difference',M00_.endo_names,0);
-
-% when the last argument in process_constraint is set to 1, the
-% direction of the inequality in the constraint is inverted
-constraint_relax1_difference_ = process_constraint(constraint_relax1_,'_difference',M00_.endo_names,0);
-
-
-% processes the constrain so as to uppend a suffix to each
-% endogenous variables
-constraint2_difference_ = process_constraint(constrain2_,'_difference',M00_.endo_names,0);
-
-% when the last argument in process_constraint is set to 1, the
-% direction of the inequality in the constraint is inverted
-constraint_relax2_difference_ = process_constraint(constraint_relax2_,'_difference',M00_.endo_names,0);
-
-
-
-nshocks = size(shockssequence_,1);
-
-
-
-
-if ~exist('init_')
-    init_ = zeros(nvars_,1);
-end
-
-if ~exist('maxiter_')
-    maxiter_ = 20;
-end
-
-if ~exist('curb_retrench_')
-    curb_retrench_ = 0;
-end
-
-init_orig_ = init_;
-
-
-
-
-
-
-zdatapiecewise_ = zeros(nperiods_,nvars_);
-
-
-violvecbool_ = zeros(nperiods_+1,2);  % This sets the first guess for when
-% the constraints are going to hold.
-% The variable is a boolean with two
-% columns. The first column refers to
-% constrain1_; the second to
-% constrain2_.
-% Each row is a period in time.
-% If the boolean is true it indicates
-% the relevant constraint is expected
-% to evaluate to true.
-% The default initial guess is
-% consistent with the base model always
-% holding -- equivalent to the linear
-% solution.
-
-wishlist_ = endog_;
-nwishes_ = size(wishlist_,1);
-for ishock_ = 1:nshocks
-    
-    
-    changes_=1;
-    iter_ = 0;
-    
-    while (changes_ & iter_<maxiter_)
-        iter_ = iter_ +1;
-        
-        % analyse violvec and isolate contiguous periods in the other
-        % regime.
-        [regime1 regimestart1]=map_regime(violvecbool_(:,1));
-        [regime2 regimestart2]=map_regime(violvecbool_(:,2));
-        
-        
-        [zdatalinear_]=mkdatap_anticipated_2constraints(nperiods_,decrulea,decruleb,...
-            cof_,Jbarmat_,...
-            cof10_,Jbarmat10_,Dbarmat10_,...
-            cof01_,Jbarmat01_,Dbarmat01_,...
-            cof11_,Jbarmat11_,Dbarmat11_,...
-            regime1,regimestart1,...
-            regime2,regimestart2,...
-            violvecbool_,endog_,exog_,...
-            irfshock_,shockssequence_(ishock_,:),init_);
-        
-        for i_indx_=1:nwishes_
-            eval([deblank(wishlist_(i_indx_,:)),'_difference=zdatalinear_(:,i_indx_);']);
-        end
-        
-        
-        
-        
-        newviolvecbool1_ = eval(constraint1_difference_);
-        relaxconstraint1_ = eval(constraint_relax1_difference_);
-        
-        newviolvecbool2_ = eval(constraint2_difference_);
-        relaxconstraint2_ = eval(constraint_relax2_difference_);
-        
-        
-        
-        newviolvecbool_ = [newviolvecbool1_;newviolvecbool2_];
-        relaxconstraint_ = [relaxconstraint1_;relaxconstraint2_];
-        
-        
-        
-        % check if changes_
-        if (max(newviolvecbool_(:)-violvecbool_(:)>0)) | sum(relaxconstraint_(find(violvecbool_==1))>0)
-            changes_ = 1;
-        else
-            changes_ = 0;
-        end
-        
-        if curb_retrench_   % apply Gauss-Sidel idea of slowing down the change in the guess
-            % for the constraint -- only relax one
-            % period at a time starting from the last
-            % one when each of the constraints is true.
-            retrench = 0*violvecbool_(:);
-            if ~isempty(find(relaxconstraint1_ & violvecbool_(:,1)))
-                retrenchpos = max(find(relaxconstraint1_ & violvecbool_(:,1)));
-                retrench(retrenchpos) = 1;
-            end
-            if ~isempty(find(relaxconstraint2_ & violvecbool_(:,2)))
-                retrenchpos = max(find(relaxconstraint2_ & violvecbool_(:,2)));
-                retrench(retrenchpos+nperiods_+1) = 1;
-            end
-            violvecbool_ = (violvecbool_(:) | newviolvecbool_(:))-retrench(:);
-        else
-            violvecbool_ = (violvecbool_(:) | newviolvecbool_(:))-(relaxconstraint_(:) & violvecbool_(:));
-        end
-        
-        violvecbool_ = reshape(violvecbool_,nperiods_+1,2);
-        
-        
-        
-    end
-    if changes_ ==1
-        display('Did not converge -- increase maxiter')
-    end
-    
-    init_ = zdatalinear_(1,:);
-    zdatapiecewise_(ishock_,:)=init_;
-    init_= init_';
-    
-    % update the guess for constraint violations for next period
-    % update is consistent with expecting no additional shocks next period
-    violvecbool_=[violvecbool_(2:end,:);zeros(1,2)];
-    
-end
-
-
-zdatapiecewise_(ishock_+1:end,:)=zdatalinear_(2:nperiods_-ishock_+1,:);
-
-zdatalinear_ = mkdata(nperiods_,decrulea,decruleb,endog_,exog_,wishlist_,irfshock_,shockssequence_,init_orig_);
-
+% [zdatalinear zdatapiecewise zdatass oo 00 M 00] = solve two constraints(modnam 00,modnam 10,modnam 01,modnam 11,... constraint1, constraint2,... constraint relax1, constraint relax2,... shockssequence,irfshock,nperiods,curb retrench,maxiter,init);
+%
+% Inputs:
+% modnam 00: name of the .mod file for reference regime (excludes the .mod extension). modnam10: name of the .mod file for the alternative regime governed by the first
+% constraint.
+% modnam01: name of the .mod file for the alternative regime governed by the second constraint.
+% modnam 11: name of the .mod file for the case in which both constraints force a switch to their alternative regimes.
+% constraint1: the first constraint (see notes 1 and 2 below). If constraint1 evaluates to true, then the solution switches to the alternative regime for condition 1. In thatcase, if constraint2 (described below) evaluates to false, then the model solution switches to enforcing the conditions for an equilibrium in modnam 10. Otherwise, if constraint2 also evaluates to true, then the model solution switches to enforcing the conditions for an equilibrium in modnam 11.
+% constraint relax1: when the condition in constraint relax1 evaluates to true, the solution returns to the reference regime for constraint1.
+% constraint2: the second constraint (see notes 1 and 2 below). constraint relax2: when the condition in constraint relax2 evaluates to true, the
+% solution returns to the reference regime for constraint2. shockssequence: a sequence of unforeseen shocks under which one wants to solve the
+% model
+% irfshock: label for innovation for IRFs, from Dynare .mod file (one or more of the ?varexo?)
+% nperiods: simulation horizon (can be longer than the sequence of shocks defined in shockssequence; must be long enough to ensure convergence back to the reference model at the end of the simulation horizon and may need to be varied depending on the sequence of shocks).
+% curb retrench:        a scalar equal to 0 or 1. Default is 0. When set to 0, it updates the guess based of regimes based on the previous iteration. When set to 1, it updates in a manner similar to a Gauss-Jacobi scheme, slowing the iterations down by updating the guess of regimes only one period at a time.
+% maxiter: maximum number of iterations allowed for the solution algorithm (20 if not specified).
+% init: the initial position for the vector of state variables, in deviation from steady state (if not specified, the default is a vector of zero implying that the initial conditions coincide with the steady state). The ordering follows the definition order in the .mod files.
+%
+% Outputs:
+% zdatalinear: an array containing paths for all endogenous variables ignoring the occasionally binding constraint (the linear solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
+% zdatapiecewise: an array containing paths for all endogenous variables satisfying the occasionally binding constraint (the occbin/piecewise solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
+% zdatass: a vector that holds the steady state values of the endogenous variables ( following the definition order in the .mod file).
+% oo00 , M00 :  structures produced by Dynare for the reference model ? see Dynare User Guide.
+
+
+% Log of changes
+% 6/17/2013 -- Luca added a trailing underscore to local variables in an
+% attempt to avoid conflicts with parameter names defined in the .mod files
+% to be processed.
+% 6/17/2013 -- Luca replaced external .m file setss.m
+
+function [ zdatalinear_, zdatapiecewise_, zdatass_, oo00_ , M00_ ] = ...
+    solve_two_constraints(modnam_00_,modnam_10_,modnam_01_,modnam_11_,...
+                          constrain1_, constrain2_,...
+                          constraint_relax1_, constraint_relax2_,...
+                          shockssequence_,irfshock_,nperiods_,curb_retrench_,maxiter_,init_)
+
+global M_ oo_
+
+
+
+% solve model
+eval(['dynare ',modnam_00_,' noclearall nolog'])
+oo00_ = oo_;
+M00_ = M_;
+
+
+for i=1:M00_.endo_nbr
+    eval([deblank(M00_.endo_names(i,:)) '_ss = oo00_.dr.ys(i); ']);
+end
+
+for i_indx_ = 1:M00_.param_nbr
+    eval([M00_.param_names(i_indx_,:),'= M00_.params(i_indx_);']);
+end
+
+
+
+eval(['dynare ',modnam_10_,' noclearall'])
+oo10_ = oo_;
+M10_ = M_;
+
+eval(['dynare ',modnam_01_,' noclearall'])
+oo01_ = oo_;
+M01_ = M_;
+
+eval(['dynare ',modnam_11_,' noclearall'])
+oo11_ = oo_;
+M11_ = M_;
+
+
+% do some error checking
+
+% check inputs
+if ~strcmp(M00_.endo_names,M10_.endo_names)
+    error([modnam_00_,' and ',modnam_10_,' need to have exactly the same endogenous variables and they need to be declared in the same order'])
+end
+
+if ~strcmp(M00_.exo_names,M10_.exo_names)
+    error([modnam_00_,' and ',modnam_10_,' need to have exactly the same exogenous variables and they need to be declared in the same order'])
+end
+
+if ~strcmp(M00_.param_names,M10_.param_names)
+    warning(['The parameter list does not match across the files ',modnam_00_,' and ',modnam_10_])
+end
+
+
+if ~strcmp(M00_.endo_names,M01_.endo_names)
+    error([modnam_00,' and ',modnam_01_,' need to have exactly the same endogenous variables and they need to be declared in the same order'])
+end
+
+if ~strcmp(M00_.exo_names,M01_.exo_names)
+    error([modnam_00_,' and ',modnam_01_,' need to have exactly the same exogenous variables and they need to be declared in the same order'])
+end
+
+if ~strcmp(M00_.param_names,M01_.param_names)
+    warning(['The parameter list does not match across the files ',modnam_00_,' and ',modnam_01_])
+end
+
+
+if ~strcmp(M00_.endo_names,M11_.endo_names)
+    error([modnam_00_,' and ',modnam_11_,' need to have exactly the same endogenous variables and they need to be declared in the same order'])
+end
+
+if ~strcmp(M00_.exo_names,M11_.exo_names)
+    error([modnam_00_,' and ',modnam_11_,' need to have exactly the same exogenous variables and they need to be declared in the same order'])
+end
+
+if ~strcmp(M00_.param_names,M11_.param_names)
+    warning(['The parameter list does not match across the files ',modnam_00_,' and ',modnam_11_])
+end
+
+
+
+
+
+nvars_ = M00_.endo_nbr;
+zdatass_ = oo00_.dr.ys;
+
+
+[hm1_,h_,hl1_,Jbarmat_] = get_deriv(M00_,zdatass_);
+cof_ = [hm1_,h_,hl1_];
+
+
+M10_.params = M00_.params;
+[hm1_,h_,hl1_,Jbarmat10_,resid_] = get_deriv(M10_,zdatass_);
+cof10_ = [hm1_,h_,hl1_];
+Dbarmat10_ = resid_;
+
+M01_.params = M00_.params;
+[hm1_,h_,hl1_,Jbarmat01_,resid_] = get_deriv(M01_,zdatass_);
+cof01_ = [hm1_,h_,hl1_];
+Dbarmat01_ = resid_;
+
+M11_.params = M00_.params;
+[hm1_,h_,hl1_,Jbarmat11_,resid_] = get_deriv(M11_,zdatass_);
+cof11_ = [hm1_,h_,hl1_];
+Dbarmat11_ = resid_;
+
+
+if isfield(M00_,'nfwrd')  % needed for bakward compatibility with older Dynare releases
+    [decrulea,decruleb]=get_pq(oo00_.dr,M00_.nstatic,M00_.nfwrd);
+else
+    [decrulea,decruleb]=get_pq(oo00_.dr,oo00_.dr.nstatic,oo00_.dr.nfwrd);
+end
+endog_ = M00_.endo_names;
+exog_ =  M00_.exo_names;
+
+
+% processes the constrain so as to uppend a suffix to each
+% endogenous variables
+constraint1_difference_ = process_constraint(constrain1_,'_difference',M00_.endo_names,0);
+
+% when the last argument in process_constraint is set to 1, the
+% direction of the inequality in the constraint is inverted
+constraint_relax1_difference_ = process_constraint(constraint_relax1_,'_difference',M00_.endo_names,0);
+
+
+% processes the constrain so as to uppend a suffix to each
+% endogenous variables
+constraint2_difference_ = process_constraint(constrain2_,'_difference',M00_.endo_names,0);
+
+% when the last argument in process_constraint is set to 1, the
+% direction of the inequality in the constraint is inverted
+constraint_relax2_difference_ = process_constraint(constraint_relax2_,'_difference',M00_.endo_names,0);
+
+
+
+nshocks = size(shockssequence_,1);
+
+
+
+
+if ~exist('init_')
+    init_ = zeros(nvars_,1);
+end
+
+if ~exist('maxiter_')
+    maxiter_ = 20;
+end
+
+if ~exist('curb_retrench_')
+    curb_retrench_ = 0;
+end
+
+init_orig_ = init_;
+
+
+
+
+
+
+zdatapiecewise_ = zeros(nperiods_,nvars_);
+
+
+violvecbool_ = zeros(nperiods_+1,2);  % This sets the first guess for when
+                                      % the constraints are going to hold.
+                                      % The variable is a boolean with two
+                                      % columns. The first column refers to
+                                      % constrain1_; the second to
+                                      % constrain2_.
+                                      % Each row is a period in time.
+                                      % If the boolean is true it indicates
+                                      % the relevant constraint is expected
+                                      % to evaluate to true.
+                                      % The default initial guess is
+                                      % consistent with the base model always
+                                      % holding -- equivalent to the linear
+                                      % solution.
+
+wishlist_ = endog_;
+nwishes_ = size(wishlist_,1);
+for ishock_ = 1:nshocks
+
+
+    changes_=1;
+    iter_ = 0;
+
+    while (changes_ & iter_<maxiter_)
+        iter_ = iter_ +1;
+
+        % analyse violvec and isolate contiguous periods in the other
+        % regime.
+        [regime1, regimestart1]=map_regime(violvecbool_(:,1));
+        [regime2, regimestart2]=map_regime(violvecbool_(:,2));
+
+
+        [zdatalinear_]=mkdatap_anticipated_2constraints(nperiods_,decrulea,decruleb,...
+                                                        cof_,Jbarmat_,...
+                                                        cof10_,Jbarmat10_,Dbarmat10_,...
+                                                        cof01_,Jbarmat01_,Dbarmat01_,...
+                                                        cof11_,Jbarmat11_,Dbarmat11_,...
+                                                        regime1,regimestart1,...
+                                                        regime2,regimestart2,...
+                                                        violvecbool_,endog_,exog_,...
+                                                        irfshock_,shockssequence_(ishock_,:),init_);
+
+        for i_indx_=1:nwishes_
+            eval([deblank(wishlist_(i_indx_,:)),'_difference=zdatalinear_(:,i_indx_);']);
+        end
+
+
+
+
+        newviolvecbool1_ = eval(constraint1_difference_);
+        relaxconstraint1_ = eval(constraint_relax1_difference_);
+
+        newviolvecbool2_ = eval(constraint2_difference_);
+        relaxconstraint2_ = eval(constraint_relax2_difference_);
+
+
+
+        newviolvecbool_ = [newviolvecbool1_;newviolvecbool2_];
+        relaxconstraint_ = [relaxconstraint1_;relaxconstraint2_];
+
+
+
+        % check if changes_
+        if (max(newviolvecbool_(:)-violvecbool_(:)>0)) | sum(relaxconstraint_(find(violvecbool_==1))>0)
+            changes_ = 1;
+        else
+            changes_ = 0;
+        end
+
+        if curb_retrench_   % apply Gauss-Sidel idea of slowing down the change in the guess
+                            % for the constraint -- only relax one
+                            % period at a time starting from the last
+                            % one when each of the constraints is true.
+            retrench = 0*violvecbool_(:);
+            if ~isempty(find(relaxconstraint1_ & violvecbool_(:,1)))
+                retrenchpos = max(find(relaxconstraint1_ & violvecbool_(:,1)));
+                retrench(retrenchpos) = 1;
+            end
+            if ~isempty(find(relaxconstraint2_ & violvecbool_(:,2)))
+                retrenchpos = max(find(relaxconstraint2_ & violvecbool_(:,2)));
+                retrench(retrenchpos+nperiods_+1) = 1;
+            end
+            violvecbool_ = (violvecbool_(:) | newviolvecbool_(:))-retrench(:);
+        else
+            violvecbool_ = (violvecbool_(:) | newviolvecbool_(:))-(relaxconstraint_(:) & violvecbool_(:));
+        end
+
+        violvecbool_ = reshape(violvecbool_,nperiods_+1,2);
+
+
+
+    end
+    if changes_ ==1
+        display('Did not converge -- increase maxiter')
+    end
+
+    init_ = zdatalinear_(1,:);
+    zdatapiecewise_(ishock_,:)=init_;
+    init_= init_';
+
+    % update the guess for constraint violations for next period
+    % update is consistent with expecting no additional shocks next period
+    violvecbool_=[violvecbool_(2:end,:);zeros(1,2)];
+
+end
+
+
+zdatapiecewise_(ishock_+1:end,:)=zdatalinear_(2:nperiods_-ishock_+1,:);
+
+zdatalinear_ = mkdata(nperiods_,decrulea,decruleb,endog_,exog_,wishlist_,irfshock_,shockssequence_,init_orig_);
diff --git a/matlab/occbin/strmerge.m b/matlab/occbin/strmerge.m
index b8585df04d40537b79f5762d5a6f7c7a346ad104..8aebb009956fb505bf4aedf678b07f1e0cf08945 100755
--- a/matlab/occbin/strmerge.m
+++ b/matlab/occbin/strmerge.m
@@ -1,9 +1,9 @@
-function string = strmerge(tokens)
-
-ntokens = length(tokens);
-
-string = char(tokens(1));
-
-for i=2:ntokens
-    string = [string,char(tokens(i))];
+function string = strmerge(tokens)
+
+ntokens = length(tokens);
+
+string = char(tokens(1));
+
+for i=2:ntokens
+    string = [string,char(tokens(i))];
 end
\ No newline at end of file
diff --git a/matlab/occbin/tokenize.m b/matlab/occbin/tokenize.m
index f6e9f330c90bd4bd371532fe4fb5dbd79229b4db..2cd8fb41031491d0a9d812a6d42e55fb2f02c07f 100755
--- a/matlab/occbin/tokenize.m
+++ b/matlab/occbin/tokenize.m
@@ -1,55 +1,54 @@
-function tokens = tokenize(source,delimiter)
-% syntax
-% tokens = tokenize(source,delimiters)
-%
-% source is a string to be broken into tokens
-% delimiters is a character array of single character delimiters
-% tokens is a cell string array containing the tokens
-
-
-posdelims = [];
-
-% assumes that delimiter cannot be in the first position or the last
-% position
-ndelimiters = size(delimiter,1);
-for i=1:ndelimiters
-    newpositions = strfind(source,delimiter(i,:));
-    if ~isempty(newpositions)
-        posdelims =[posdelims, newpositions];
-    end
-end
-
-% reorder posdelims in ascending order
-posdelims = sort(posdelims);
-
-if isempty(posdelims)
-    tokens = cellstr(source);
-else
-    ndelims = length(posdelims);
-    % build positions for substrings
-    delims = zeros(ndelims+1,2);
-    for i=1:ndelims+1;
-        if i==1
-                if posdelims(1) == 1
-                   tokens = cellstr(source(1));
-                else
-                   delims(i,:) = [1,posdelims(i)-1];
-                   tokens = cellstr(source([delims(i,1):delims(i,2)]));
-                   tokens = [tokens, source(posdelims(i))];
-                end
-        elseif  i==ndelims+1
-                if (posdelims(i-1) < length(source))
-                    delims(i,:) = [posdelims(i-1)+1,length(source)];
-                    tokens = [tokens, cellstr(source([delims(i,1):delims(i,2)]))];
-                end
-        else
-                if posdelims(i)>posdelims(i-1)+1
-                    delims(i,:) = [posdelims(i-1)+1,posdelims(i)-1];
-                    tokens = [tokens, cellstr(source([delims(i,1):delims(i,2)]))];
-                end
-                tokens = [tokens, source(posdelims(i))];
-        end
-    end
-
-end
-
+function tokens = tokenize(source,delimiter)
+% syntax
+% tokens = tokenize(source,delimiters)
+%
+% source is a string to be broken into tokens
+% delimiters is a character array of single character delimiters
+% tokens is a cell string array containing the tokens
+
+
+posdelims = [];
+
+% assumes that delimiter cannot be in the first position or the last
+% position
+ndelimiters = size(delimiter,1);
+for i=1:ndelimiters
+    newpositions = strfind(source,delimiter(i,:));
+    if ~isempty(newpositions)
+        posdelims =[posdelims, newpositions];
+    end
+end
+
+% reorder posdelims in ascending order
+posdelims = sort(posdelims);
+
+if isempty(posdelims)
+    tokens = cellstr(source);
+else
+    ndelims = length(posdelims);
+    % build positions for substrings
+    delims = zeros(ndelims+1,2);
+    for i=1:ndelims+1
+        if i==1
+            if posdelims(1) == 1
+                tokens = cellstr(source(1));
+            else
+                delims(i,:) = [1,posdelims(i)-1];
+                tokens = cellstr(source([delims(i,1):delims(i,2)]));
+                tokens = [tokens, source(posdelims(i))];
+            end
+        elseif  i==ndelims+1
+            if (posdelims(i-1) < length(source))
+                delims(i,:) = [posdelims(i-1)+1,length(source)];
+                tokens = [tokens, cellstr(source([delims(i,1):delims(i,2)]))];
+            end
+        else
+            if posdelims(i)>posdelims(i-1)+1
+                delims(i,:) = [posdelims(i-1)+1,posdelims(i)-1];
+                tokens = [tokens, cellstr(source([delims(i,1):delims(i,2)]))];
+            end
+            tokens = [tokens, source(posdelims(i))];
+        end
+    end
+
+end
diff --git a/matlab/octave_ver_less_than.m b/matlab/octave_ver_less_than.m
index 9d702d5972e4c22fbc57c53b84745bb210f3111b..3c1a6a6a0e5c4186b9819d277f2de77e4010b8fd 100644
--- a/matlab/octave_ver_less_than.m
+++ b/matlab/octave_ver_less_than.m
@@ -8,14 +8,14 @@ function r = octave_ver_less_than(verstr)
 %
 % INPUTS
 %    verstr: a string of the format 'x.y' or 'x.y.z'
-%    
+%
 % OUTPUTS
 %    r: 0 or 1
 %
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2008-2011 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/one_sided_hp_filter.m b/matlab/one_sided_hp_filter.m
index 38af32ea28cb8265c9003836ce8851bb48853738..9715a33510658fedb956163eed9f066d62e6ca9b 100644
--- a/matlab/one_sided_hp_filter.m
+++ b/matlab/one_sided_hp_filter.m
@@ -32,13 +32,13 @@ function [ytrend,ycycle]=one_sided_hp_filter(y,lambda,x_user,P_user,discard)
 %
 %       y_t=tau_t+epsilon_t
 %       (1-L)^2 tau_t=eta_t"
-% 
-%  The Kalman filter notation follows Chapter 13 of Hamilton, J.D. (1994). 
+%
+%  The Kalman filter notation follows Chapter 13 of Hamilton, J.D. (1994).
 %   Time Series Analysis, with the exception of H, which is equivalent to his H'.
 
 
 % Copyright (C) 200?-2015 Alexander Meyer-Gohde
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -63,26 +63,26 @@ end
 %Set up state space
 q=1/lambda;     % the signal-to-noise ration: i.e. var eta_t / var epsilon_t
 F=[2,-1;
-    1,0];       % state transition matrix
+   1,0];       % state transition matrix
 H=[1,0];        % observation matrix
 Q=[q,0;
-   0,0];        % covariance matrix state equation errors 
+   0,0];        % covariance matrix state equation errors
 R=1;            % variance observation equation error
 
 for k=1:n %Run the Kalman filter for each variable
     if nargin < 4 || isempty(x_user) %no intial value for state, extrapolate back two periods from the observations
-        x=[2*y(1,k)-y(2,k); 
-           3*y(1,k)-2*y(2,k)]; 
+        x=[2*y(1,k)-y(2,k);
+           3*y(1,k)-2*y(2,k)];
     else
         x=x_user(:,k);
-    end 
+    end
     if nargin < 4 || isempty(P_user) %no initial value for the MSE, set a rather high one
         P= [1e5 0;
-            0 1e5]; 
+            0 1e5];
     else
         P=P_user{k};
-    end 
-    
+    end
+
     for j=1:T %Get the estimates for each period
         [x,P]=kalman_update(F,H,Q,R,y(j,k),x,P); %get new state estimate and update recursion
         ytrend(j,k)=x(2);%second state is trend estimate
@@ -103,9 +103,9 @@ end
 
 function   [x,P]=kalman_update(F,H,Q,R,obs,x,P)
 % Updates the Kalman filter estimation of the state and MSE
-S=H*P*H'+R; 
-K=F*P*H';     
-K=K/S; 
+S=H*P*H'+R;
+K=F*P*H';
+K=K/S;
 x=F*x+K*(obs -H*x); %State estimate
 Temp=F-K*H;
 P=Temp*P*Temp';
diff --git a/matlab/optimization/apprgrdn.m b/matlab/optimization/apprgrdn.m
index 9f16e44667b2c415968c541884bc1031642a04ff..2d79f0489f831cd49a0fb436e864f416e2260fce 100644
--- a/matlab/optimization/apprgrdn.m
+++ b/matlab/optimization/apprgrdn.m
@@ -2,7 +2,7 @@ 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;
@@ -14,10 +14,10 @@ function g = apprgrdn(x,f,fun,deltax,obj,varargin)
 % Modified by Giovanni Lombardo and Johannes Pfeifer to accomodate Dynare
 % structure
 %
-% 
-% Copyright (C) 1997-2008, Alexei Kuntsevich and Franz Kappel 
+%
+% Copyright (C) 1997-2008, Alexei Kuntsevich and Franz Kappel
 % Copyright (C) 2008-2015 Giovanni Lombardo
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -38,10 +38,10 @@ 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); 
+    idx=find(abs(di)<2e-10);
     di(idx)=2e-10*sign(di(idx));
 else
-    idx=find(abs(di)<5e-15); 
+    idx=find(abs(di)<5e-15);
     di(idx)=5e-15*sign(di(idx));
 end
 y=x;
@@ -51,7 +51,7 @@ for i=1:n
     y(i)=x(i)+di(i);
     fi=feval(fun,y,varargin{:});
     if obj
-        if fi==f,
+        if fi==f
             for j=1:3
                 di(i)=di(i)*10;  y(i)=x(i)+di(i);
                 fi=feval(fun,y,varargin{:});
diff --git a/matlab/optimization/bfgsi1.m b/matlab/optimization/bfgsi1.m
index 696ee410b1ae82930b51c58ff3221e9c02d3bae0..7a76a89b230e8bfaee48e249e057772bee339b84 100644
--- a/matlab/optimization/bfgsi1.m
+++ b/matlab/optimization/bfgsi1.m
@@ -1,22 +1,22 @@
 function H = bfgsi1(H0,dg,dx,Verbose,Save_files)
 % H = bfgsi1(H0,dg,dx,Verbose,Save_files)
 % 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;
 %   Verbose [scalar]    Indicator for silent mode
-%   Save_files [scalar] Indicator whether to save files  
-% 
+%   Save_files [scalar] Indicator whether to save files
+%
 % 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
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/optimization/cmaes.m b/matlab/optimization/cmaes.m
index 833dbe9b2f9ce82dbf8a4cfdcb7650e7e25db3a9..2ead9b50eba2c6aa1ea68228ca346b8aa2ca3340 100644
--- a/matlab/optimization/cmaes.m
+++ b/matlab/optimization/cmaes.m
@@ -1,164 +1,164 @@
 function [xmin, ...      % minimum search point of last iteration
-	  fmin, ...      % function value of xmin
-	  counteval, ... % number of function evaluations done
-	  stopflag, ...  % stop criterion reached
-	  out, ...     % struct with various histories and solutions
-	  bestever ... % struct containing overall best solution (for convenience)
-	 ] = cmaes( ...
-    fitfun, ...    % name of objective/fitness function
-    xstart, ...    % objective variables initial point, determines N
-    insigma, ...   % initial coordinate wise standard deviation(s)
-    inopts, ...    % options struct, see defopts below
-    varargin )     % arguments passed to objective function 
-% cmaes.m, Version 3.56.beta, last change: February, 2012 
-% CMAES implements an Evolution Strategy with Covariance Matrix
-% Adaptation (CMA-ES) for nonlinear function minimization.  For
-% introductory comments and copyright (GPL) see end of file (type 
-% 'type cmaes'). cmaes.m runs with MATLAB (Windows, Linux) and, 
-% without data logging and plotting, it should run under Octave 
-% (Linux, package octave-forge is needed).
-%
-% OPTS = CMAES returns default options. 
-% OPTS = CMAES('defaults') returns default options quietly.
-% OPTS = CMAES('displayoptions') displays options. 
-% OPTS = CMAES('defaults', OPTS) supplements options OPTS with default 
-% options. 
-%
-% XMIN = CMAES(FUN, X0, SIGMA[, OPTS]) locates the minimum XMIN of
-% function FUN starting from column vector X0 with the initial
-% coordinate wise search standard deviation SIGMA.
-%
-% Input arguments: 
-%
-%  FUN is a string function name like 'myfun'. FUN takes as argument a
-%     column vector of size of X0 and returns a scalar. An easy way to
-%     implement a hard non-linear constraint is to return NaN. Then,
-%     this function evaluation is not counted and a newly sampled
-%     point is tried immediately.
-%
-%   X0 is a column vector, or a matrix, or a string. If X0 is a matrix,
-%     mean(X0, 2) is taken as initial point. If X0 is a string like
-%     '2*rand(10,1)-1', the string is evaluated first.
-%
-%   SIGMA is a scalar, or a column vector of size(X0,1), or a string
-%     that can be evaluated into one of these. SIGMA determines the
-%     initial coordinate wise standard deviations for the search.
-%     Setting SIGMA one third of the initial search region is
-%     appropriate, e.g., the initial point in [0, 6]^10 and SIGMA=2
-%     means cmaes('myfun', 3*rand(10,1), 2).  If SIGMA is missing and
-%     size(X0,2) > 1, SIGMA is set to sqrt(var(X0')'). That is, X0 is
-%     used as a sample for estimating initial mean and variance of the
-%     search distribution.
-%
-%   OPTS (an optional argument) is a struct holding additional input
-%     options. Valid field names and a short documentation can be
-%     discovered by looking at the default options (type 'cmaes'
-%     without arguments, see above). Empty or missing fields in OPTS
-%     invoke the default value, i.e. OPTS needs not to have all valid
-%     field names.  Capitalization does not matter and unambiguous
-%     abbreviations can be used for the field names. If a string is
-%     given where a numerical value is needed, the string is evaluated
-%     by eval, where 'N' expands to the problem dimension
-%     (==size(X0,1)) and 'popsize' to the population size. 
-%
-% [XMIN, FMIN, COUNTEVAL, STOPFLAG, OUT, BESTEVER] = ...
-%    CMAES(FITFUN, X0, SIGMA)
-% returns the best (minimal) point XMIN (found in the last
-% generation); function value FMIN of XMIN; the number of needed
-% function evaluations COUNTEVAL; a STOPFLAG value as cell array,
-% where possible entries are 'fitness', 'tolx', 'tolupx', 'tolfun',
-% 'maxfunevals', 'maxiter', 'stoptoresume', 'manual',
-% 'warnconditioncov', 'warnnoeffectcoord', 'warnnoeffectaxis',
-% 'warnequalfunvals', 'warnequalfunvalhist', 'bug' (use
-% e.g. any(strcmp(STOPFLAG, 'tolx')) or findstr(strcat(STOPFLAG,
-% 'tolx')) for further processing); a record struct OUT with some
-% more output, where the struct SOLUTIONS.BESTEVER contains the overall
-% best evaluated point X with function value F evaluated at evaluation
-% count EVALS. The last output argument BESTEVER equals 
-% OUT.SOLUTIONS.BESTEVER. Moreover a history of solutions and 
-% parameters is written to files according to the Log-options. 
-%
-% A regular manual stop can be achieved via the file signals.par. The
-% program is terminated if the first two non-white sequences in any
-% line of this file are 'stop' and the value of the LogFilenamePrefix
-% option (by default 'outcmaes'). Also a run can be skipped.
-% Given, for example, 'skip outcmaes run 2', skips the second run
-% if option Restarts is at least 2, and another run will be started.
-% 
-% To run the code completely silently set Disp, Save, and Log options
-% to 0.  With OPTS.LogModulo > 0 (1 by default) the most important
-% data are written to ASCII files permitting to investigate the
-% results (e.g. plot with function plotcmaesdat) even while CMAES is
-% still running (which can be quite useful on expensive objective
-% functions). When OPTS.SaveVariables==1 (default) everything is saved
-% in file OPTS.SaveFilename (default 'variablescmaes.mat') allowing to
-% resume the search afterwards by using the resume option.
-%
-% To find the best ever evaluated point load the variables typing
-% "es=load('variablescmaes')" and investigate the variable
-% es.out.solutions.bestever. 
-%
-% In case of a noisy objective function (uncertainties) set
-% OPTS.Noise.on = 1. This option interferes presumably with some 
-% termination criteria, because the step-size sigma will presumably
-% not converge to zero anymore. If CMAES was provided with a 
-% fifth argument (P1 in the below example, which is passed to the 
-% objective function FUN), this argument is multiplied with the 
-% factor given in option Noise.alphaevals, each time the detected 
-% noise exceeds a threshold. This argument can be used within 
-% FUN, for example, as averaging number to reduce the noise level.  
-%
-% OPTS.DiagonalOnly > 1 defines the number of initial iterations,
-% where the covariance matrix remains diagonal and the algorithm has
-% internally linear time complexity. OPTS.DiagonalOnly = 1 means
-% keeping the covariance matrix always diagonal and this setting
-% also exhibits linear space complexity. This can be particularly
-% useful for dimension > 100. The default is OPTS.DiagonalOnly = 0. 
-% 
-% OPTS.CMA.active = 1 turns on "active CMA" with a negative update 
-% of the covariance matrix and checks for positive definiteness. 
-% OPTS.CMA.active = 2 does not check for pos. def. and is numerically
-% faster. Active CMA usually speeds up the adaptation and might 
-% become a default in near future. 
-%
-% The primary strategy parameter to play with is OPTS.PopSize, which
-% can be increased from its default value.  Increasing the population
-% size (by default linked to increasing parent number OPTS.ParentNumber)
-% improves global search properties in exchange to speed. Speed
-% decreases, as a rule, at most linearely with increasing population
-% size. It is advisable to begin with the default small population
-% size. The options Restarts and IncPopSize can be used for an
-% automated multistart where the population size is increased by the
-% factor IncPopSize (two by default) before each restart. X0 (given as
-% string) is reevaluated for each restart. Stopping options
-% StopFunEvals, StopIter, MaxFunEvals, and Fitness terminate the
-% program, all others including MaxIter invoke another restart, where
-% the iteration counter is reset to zero.
-%
-% Examples: 
-%
-%   XMIN = cmaes('myfun', 5*ones(10,1), 1.5); starts the search at
-%   10D-point 5 and initially searches mainly between 5-3 and 5+3
-%   (+- two standard deviations), but this is not a strict bound.
-%   'myfun' is a name of a function that returns a scalar from a 10D
-%   column vector.
-%
-%   opts.LBounds = 0; opts.UBounds = 10; 
-%   X=cmaes('myfun', 10*rand(10,1), 5, opts);
-%   search within lower bound of 0 and upper bound of 10. Bounds can
-%   also be given as column vectors. If the optimum is not located
-%   on the boundary, use rather a penalty approach to handle bounds. 
-%
-%   opts=cmaes; opts.StopFitness=1e-10;
-%   X=cmaes('myfun', rand(5,1), 0.5, opts); stops the search, if
-%   the function value is smaller than 1e-10.
-%   
-%   [X, F, E, STOP, OUT] = cmaes('myfun2', 'rand(5,1)', 1, [], P1, P2); 
-%   passes two additional parameters to the function MYFUN2.
-%
-
-% Copyright (C) 2001-2012 Nikolaus Hansen, 
-% Copyright (C) 2012 Dynare Team
+          fmin, ...      % function value of xmin
+          counteval, ... % number of function evaluations done
+          stopflag, ...  % stop criterion reached
+          out, ...     % struct with various histories and solutions
+          bestever ... % struct containing overall best solution (for convenience)
+         ] = cmaes( ...
+             fitfun, ...    % name of objective/fitness function
+             xstart, ...    % objective variables initial point, determines N
+             insigma, ...   % initial coordinate wise standard deviation(s)
+             inopts, ...    % options struct, see defopts below
+             varargin )     % arguments passed to objective function
+                            % cmaes.m, Version 3.56.beta, last change: February, 2012
+                            % CMAES implements an Evolution Strategy with Covariance Matrix
+                            % Adaptation (CMA-ES) for nonlinear function minimization.  For
+                            % introductory comments and copyright (GPL) see end of file (type
+                            % 'type cmaes'). cmaes.m runs with MATLAB (Windows, Linux) and,
+                            % without data logging and plotting, it should run under Octave
+                            % (Linux, package octave-forge is needed).
+                            %
+                            % OPTS = CMAES returns default options.
+                            % OPTS = CMAES('defaults') returns default options quietly.
+                            % OPTS = CMAES('displayoptions') displays options.
+                            % OPTS = CMAES('defaults', OPTS) supplements options OPTS with default
+                            % options.
+                            %
+                            % XMIN = CMAES(FUN, X0, SIGMA[, OPTS]) locates the minimum XMIN of
+                            % function FUN starting from column vector X0 with the initial
+                            % coordinate wise search standard deviation SIGMA.
+                            %
+                            % Input arguments:
+                            %
+                            %  FUN is a string function name like 'myfun'. FUN takes as argument a
+                            %     column vector of size of X0 and returns a scalar. An easy way to
+                            %     implement a hard non-linear constraint is to return NaN. Then,
+                            %     this function evaluation is not counted and a newly sampled
+                            %     point is tried immediately.
+                            %
+                            %   X0 is a column vector, or a matrix, or a string. If X0 is a matrix,
+                            %     mean(X0, 2) is taken as initial point. If X0 is a string like
+                            %     '2*rand(10,1)-1', the string is evaluated first.
+                            %
+                            %   SIGMA is a scalar, or a column vector of size(X0,1), or a string
+                            %     that can be evaluated into one of these. SIGMA determines the
+                            %     initial coordinate wise standard deviations for the search.
+                            %     Setting SIGMA one third of the initial search region is
+                            %     appropriate, e.g., the initial point in [0, 6]^10 and SIGMA=2
+                            %     means cmaes('myfun', 3*rand(10,1), 2).  If SIGMA is missing and
+                            %     size(X0,2) > 1, SIGMA is set to sqrt(var(X0')'). That is, X0 is
+                            %     used as a sample for estimating initial mean and variance of the
+                            %     search distribution.
+                            %
+                            %   OPTS (an optional argument) is a struct holding additional input
+                            %     options. Valid field names and a short documentation can be
+                            %     discovered by looking at the default options (type 'cmaes'
+                            %     without arguments, see above). Empty or missing fields in OPTS
+                            %     invoke the default value, i.e. OPTS needs not to have all valid
+                            %     field names.  Capitalization does not matter and unambiguous
+                            %     abbreviations can be used for the field names. If a string is
+                            %     given where a numerical value is needed, the string is evaluated
+                            %     by eval, where 'N' expands to the problem dimension
+                            %     (==size(X0,1)) and 'popsize' to the population size.
+                            %
+                            % [XMIN, FMIN, COUNTEVAL, STOPFLAG, OUT, BESTEVER] = ...
+                            %    CMAES(FITFUN, X0, SIGMA)
+                            % returns the best (minimal) point XMIN (found in the last
+                            % generation); function value FMIN of XMIN; the number of needed
+                            % function evaluations COUNTEVAL; a STOPFLAG value as cell array,
+                            % where possible entries are 'fitness', 'tolx', 'tolupx', 'tolfun',
+                            % 'maxfunevals', 'maxiter', 'stoptoresume', 'manual',
+                            % 'warnconditioncov', 'warnnoeffectcoord', 'warnnoeffectaxis',
+                            % 'warnequalfunvals', 'warnequalfunvalhist', 'bug' (use
+                            % e.g. any(strcmp(STOPFLAG, 'tolx')) or findstr(strcat(STOPFLAG,
+                            % 'tolx')) for further processing); a record struct OUT with some
+                            % more output, where the struct SOLUTIONS.BESTEVER contains the overall
+                            % best evaluated point X with function value F evaluated at evaluation
+                            % count EVALS. The last output argument BESTEVER equals
+                            % OUT.SOLUTIONS.BESTEVER. Moreover a history of solutions and
+                            % parameters is written to files according to the Log-options.
+                            %
+                            % A regular manual stop can be achieved via the file signals.par. The
+                            % program is terminated if the first two non-white sequences in any
+                            % line of this file are 'stop' and the value of the LogFilenamePrefix
+                            % option (by default 'outcmaes'). Also a run can be skipped.
+                            % Given, for example, 'skip outcmaes run 2', skips the second run
+                            % if option Restarts is at least 2, and another run will be started.
+                            %
+                            % To run the code completely silently set Disp, Save, and Log options
+                            % to 0.  With OPTS.LogModulo > 0 (1 by default) the most important
+                            % data are written to ASCII files permitting to investigate the
+                            % results (e.g. plot with function plotcmaesdat) even while CMAES is
+                            % still running (which can be quite useful on expensive objective
+                            % functions). When OPTS.SaveVariables==1 (default) everything is saved
+                            % in file OPTS.SaveFilename (default 'variablescmaes.mat') allowing to
+                            % resume the search afterwards by using the resume option.
+                            %
+                            % To find the best ever evaluated point load the variables typing
+                            % "es=load('variablescmaes')" and investigate the variable
+                            % es.out.solutions.bestever.
+                            %
+                            % In case of a noisy objective function (uncertainties) set
+                            % OPTS.Noise.on = 1. This option interferes presumably with some
+                            % termination criteria, because the step-size sigma will presumably
+                            % not converge to zero anymore. If CMAES was provided with a
+                            % fifth argument (P1 in the below example, which is passed to the
+                            % objective function FUN), this argument is multiplied with the
+                            % factor given in option Noise.alphaevals, each time the detected
+                            % noise exceeds a threshold. This argument can be used within
+                            % FUN, for example, as averaging number to reduce the noise level.
+                            %
+                            % OPTS.DiagonalOnly > 1 defines the number of initial iterations,
+                            % where the covariance matrix remains diagonal and the algorithm has
+                            % internally linear time complexity. OPTS.DiagonalOnly = 1 means
+                            % keeping the covariance matrix always diagonal and this setting
+                            % also exhibits linear space complexity. This can be particularly
+                            % useful for dimension > 100. The default is OPTS.DiagonalOnly = 0.
+                            %
+                            % OPTS.CMA.active = 1 turns on "active CMA" with a negative update
+                            % of the covariance matrix and checks for positive definiteness.
+                            % OPTS.CMA.active = 2 does not check for pos. def. and is numerically
+                            % faster. Active CMA usually speeds up the adaptation and might
+                            % become a default in near future.
+                            %
+                            % The primary strategy parameter to play with is OPTS.PopSize, which
+                            % can be increased from its default value.  Increasing the population
+                            % size (by default linked to increasing parent number OPTS.ParentNumber)
+                            % improves global search properties in exchange to speed. Speed
+                            % decreases, as a rule, at most linearely with increasing population
+                            % size. It is advisable to begin with the default small population
+                            % size. The options Restarts and IncPopSize can be used for an
+                            % automated multistart where the population size is increased by the
+                            % factor IncPopSize (two by default) before each restart. X0 (given as
+                            % string) is reevaluated for each restart. Stopping options
+                            % StopFunEvals, StopIter, MaxFunEvals, and Fitness terminate the
+                            % program, all others including MaxIter invoke another restart, where
+                            % the iteration counter is reset to zero.
+                            %
+                            % Examples:
+                            %
+                            %   XMIN = cmaes('myfun', 5*ones(10,1), 1.5); starts the search at
+                            %   10D-point 5 and initially searches mainly between 5-3 and 5+3
+                            %   (+- two standard deviations), but this is not a strict bound.
+                            %   'myfun' is a name of a function that returns a scalar from a 10D
+                            %   column vector.
+                            %
+                            %   opts.LBounds = 0; opts.UBounds = 10;
+                            %   X=cmaes('myfun', 10*rand(10,1), 5, opts);
+                            %   search within lower bound of 0 and upper bound of 10. Bounds can
+                            %   also be given as column vectors. If the optimum is not located
+                            %   on the boundary, use rather a penalty approach to handle bounds.
+                            %
+                            %   opts=cmaes; opts.StopFitness=1e-10;
+                            %   X=cmaes('myfun', rand(5,1), 0.5, opts); stops the search, if
+                            %   the function value is smaller than 1e-10.
+                            %
+                            %   [X, F, E, STOP, OUT] = cmaes('myfun2', 'rand(5,1)', 1, [], P1, P2);
+                            %   passes two additional parameters to the function MYFUN2.
+                            %
+
+% Copyright (C) 2001-2012 Nikolaus Hansen,
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -176,7 +176,7 @@ function [xmin, ...      % minimum search point of last iteration
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 
-cmaVersion = '3.60.beta'; 
+cmaVersion = '3.60.beta';
 
 % ----------- Set Defaults for Input Parameters and Options -------------
 % These defaults may be edited for convenience
@@ -197,1596 +197,1596 @@ defopts.TolFun       = '1e-10 % stop if fun-changes smaller TolFun';
 defopts.TolHistFun   = '1e-11 % stop if back fun-changes smaller TolHistFun';
 defopts.StopOnStagnation = 'on  % stop when fitness stagnates for a long time';
 defopts.StopOnWarnings = 'yes  % ''no''==''off''==0, ''on''==''yes''==1 ';
-defopts.StopOnEqualFunctionValues = '2 + N/3  % number of iterations';  
+defopts.StopOnEqualFunctionValues = '2 + N/3  % number of iterations';
 
 % Options defaults: Other
 defopts.DiffMaxChange = 'Inf  % maximal variable change(s), can be Nx1-vector';
 defopts.DiffMinChange = '0    % minimal variable change(s), can be Nx1-vector';
 defopts.WarnOnEqualFunctionValues = ...
     'yes  % ''no''==''off''==0, ''on''==''yes''==1 ';
-defopts.LBounds = '-Inf % lower bounds, scalar or Nx1-vector'; 
-defopts.UBounds = 'Inf  % upper bounds, scalar or Nx1-vector'; 
+defopts.LBounds = '-Inf % lower bounds, scalar or Nx1-vector';
+defopts.UBounds = 'Inf  % upper bounds, scalar or Nx1-vector';
 defopts.EvalParallel = 'no   % objective function FUN accepts NxM matrix, with M>1?';
 defopts.EvalInitialX = 'yes  % evaluation of initial solution';
 defopts.Restarts     = '0    % number of restarts ';
 defopts.IncPopSize   = '2    % multiplier for population size before each restart';
 
-defopts.PopSize      = '(4 + floor(3*log(N)))  % population size, lambda'; 
+defopts.PopSize      = '(4 + floor(3*log(N)))  % population size, lambda';
 defopts.ParentNumber = 'floor(popsize/2)       % AKA mu, popsize equals lambda';
 defopts.RecombinationWeights = 'superlinear decrease % or linear, or equal';
-defopts.DiagonalOnly = '0*(1+100*N/sqrt(popsize))+(N>=1000)  % C is diagonal for given iterations, 1==always'; 
-defopts.Noise.on = '0  % uncertainty handling is off by default'; 
+defopts.DiagonalOnly = '0*(1+100*N/sqrt(popsize))+(N>=1000)  % C is diagonal for given iterations, 1==always';
+defopts.Noise.on = '0  % uncertainty handling is off by default';
 defopts.Noise.reevals  = '1*ceil(0.05*lambda)  % nb. of re-evaluated for uncertainty measurement';
 defopts.Noise.theta = '0.5  % threshold to invoke uncertainty treatment'; % smaller: more likely to diverge
-defopts.Noise.cum = '0.3  % cumulation constant for uncertainty'; 
+defopts.Noise.cum = '0.3  % cumulation constant for uncertainty';
 defopts.Noise.cutoff = '2*lambda/3  % rank change cutoff for summation';
 defopts.Noise.alphasigma  = '1+2/(N+10)  % factor for increasing sigma'; % smaller: slower adaptation
 defopts.Noise.epsilon  = '1e-7  % additional relative perturbation before reevaluation';
-defopts.Noise.minmaxevals = '[1 inf]  % min and max value of 2nd arg to fitfun, start value is 5th arg to cmaes'; 
-defopts.Noise.alphaevals  = '1+2/(N+10)  % factor for increasing 2nd arg to fitfun'; 
+defopts.Noise.minmaxevals = '[1 inf]  % min and max value of 2nd arg to fitfun, start value is 5th arg to cmaes';
+defopts.Noise.alphaevals  = '1+2/(N+10)  % factor for increasing 2nd arg to fitfun';
 defopts.Noise.callback = '[]  % callback function when uncertainty threshold is exceeded';
-% defopts.TPA = 0; 
-defopts.CMA.cs = '(mueff+2)/(N+mueff+3)  % cumulation constant for step-size'; 
-   %qqq cs = (mueff^0.5)/(N^0.5+mueff^0.5) % the short time horizon version
+% defopts.TPA = 0;
+defopts.CMA.cs = '(mueff+2)/(N+mueff+3)  % cumulation constant for step-size';
+%qqq cs = (mueff^0.5)/(N^0.5+mueff^0.5) % the short time horizon version
 defopts.CMA.damps = '1 + 2*max(0,sqrt((mueff-1)/(N+1))-1) + cs  % damping for step-size';
-% defopts.CMA.ccum = '4/(N+4)  % cumulation constant for covariance matrix'; 
+% defopts.CMA.ccum = '4/(N+4)  % cumulation constant for covariance matrix';
 defopts.CMA.ccum = '(4 + mueff/N) / (N+4 + 2*mueff/N)  % cumulation constant for pc';
-defopts.CMA.ccov1 = '2 / ((N+1.3)^2+mueff)  % learning rate for rank-one update'; 
-defopts.CMA.ccovmu = '2 * (mueff-2+1/mueff) / ((N+2)^2+mueff) % learning rate for rank-mu update'; 
-defopts.CMA.on     = 'yes'; 
-defopts.CMA.active = '0  % active CMA 1: neg. updates with pos. def. check, 2: neg. updates'; 
+defopts.CMA.ccov1 = '2 / ((N+1.3)^2+mueff)  % learning rate for rank-one update';
+defopts.CMA.ccovmu = '2 * (mueff-2+1/mueff) / ((N+2)^2+mueff) % learning rate for rank-mu update';
+defopts.CMA.on     = 'yes';
+defopts.CMA.active = '0  % active CMA 1: neg. updates with pos. def. check, 2: neg. updates';
 
 flg_future_setting = 0;  % testing for possible future variant(s)
-if flg_future_setting    
-  disp('in the future')
+if flg_future_setting
+    disp('in the future')
 
-  % damps setting from Brockhoff et al 2010
-  %   this damps diverges with popsize 400:
-  %   cmaeshtml('benchmarkszero', ones(20,1)*2, 5, o, 15);
-  defopts.CMA.damps = '2*mueff/lambda + 0.3 + cs  % damping for step-size';  % cs: for large mueff
-  % how about:
-  % defopts.CMA.damps = '2*mueff/lambda + 0.3 + 2*max(0,sqrt((mueff-1)/(N+1))-1) + cs  % damping for step-size';
+    % damps setting from Brockhoff et al 2010
+    %   this damps diverges with popsize 400:
+    %   cmaeshtml('benchmarkszero', ones(20,1)*2, 5, o, 15);
+    defopts.CMA.damps = '2*mueff/lambda + 0.3 + cs  % damping for step-size';  % cs: for large mueff
+                                                                               % how about:
+                                                                               % defopts.CMA.damps = '2*mueff/lambda + 0.3 + 2*max(0,sqrt((mueff-1)/(N+1))-1) + cs  % damping for step-size';
 
-  % ccum adjusted for large mueff, better on schefelmult? 
-  % TODO: this should also depend on diagonal option!?  
-  defopts.CMA.ccum = '(4 + mueff/N) / (N+4 + 2*mueff/N)  % cumulation constant for pc';
+    % ccum adjusted for large mueff, better on schefelmult?
+    % TODO: this should also depend on diagonal option!?
+    defopts.CMA.ccum = '(4 + mueff/N) / (N+4 + 2*mueff/N)  % cumulation constant for pc';
 
-  defopts.CMA.active = '1  % active CMA 1: neg. updates with pos. def. check, 2: neg. updates'; 
+    defopts.CMA.active = '1  % active CMA 1: neg. updates with pos. def. check, 2: neg. updates';
 end
-  
-defopts.Resume   = 'no   % resume former run from SaveFile'; 
-defopts.Science  = 'on  % off==do some additional (minor) problem capturing, NOT IN USE'; 
+
+defopts.Resume   = 'no   % resume former run from SaveFile';
+defopts.Science  = 'on  % off==do some additional (minor) problem capturing, NOT IN USE';
 defopts.ReadSignals = 'on  % from file signals.par for termination, yet a stumb';
 defopts.Seed = 'sum(100*clock)  % evaluated if it is a string';
 defopts.DispFinal  = 'on   % display messages like initial and final message';
 defopts.DispModulo = '100  % [0:Inf], disp messages after every i-th iteration';
 defopts.SaveVariables = 'on   % [on|final|off][-v6] save variables to .mat file';
-defopts.SaveFilename = 'variablescmaes.mat  % save all variables, see SaveVariables'; 
+defopts.SaveFilename = 'variablescmaes.mat  % save all variables, see SaveVariables';
 defopts.LogModulo = '1    % [0:Inf] if >1 record data less frequently after gen=100';
 defopts.LogTime   = '25   % [0:100] max. percentage of time for recording data';
-defopts.LogFilenamePrefix = 'outcmaes  % files for output data'; 
+defopts.LogFilenamePrefix = 'outcmaes  % files for output data';
 defopts.LogPlot = 'off    % plot while running using output data files';
 
-%qqqkkk 
-%defopts.varopt1 = ''; % 'for temporary and hacking purposes'; 
-%defopts.varopt2 = ''; % 'for temporary and hacking purposes'; 
+%qqqkkk
+%defopts.varopt1 = ''; % 'for temporary and hacking purposes';
+%defopts.varopt2 = ''; % 'for temporary and hacking purposes';
 defopts.UserData = 'for saving data/comments associated with the run';
 defopts.UserDat2 = ''; 'for saving data/comments associated with the run';
 
 % ---------------------- Handling Input Parameters ----------------------
 
 if nargin < 1 || isequal(fitfun, 'defaults') % pass default options
-  if nargin < 1
-    disp('Default options returned (type "help cmaes" for help).');
-  end
-  xmin = defopts;
-  if nargin > 1 % supplement second argument with default options
-    xmin = getoptions(xstart, defopts);
-  end
-  return;
+    if nargin < 1
+        disp('Default options returned (type "help cmaes" for help).');
+    end
+    xmin = defopts;
+    if nargin > 1 % supplement second argument with default options
+        xmin = getoptions(xstart, defopts);
+    end
+    return
 end
 
 if isequal(fitfun, 'displayoptions')
- names = fieldnames(defopts); 
- for name = names'
-   disp([name{:} repmat(' ', 1, 20-length(name{:})) ': ''' defopts.(name{:}) '''']); 
- end
- return; 
+    names = fieldnames(defopts);
+    for name = names'
+        disp([name{:} repmat(' ', 1, 20-length(name{:})) ': ''' defopts.(name{:}) '''']);
+    end
+    return
 end
 
 input.fitfun = fitfun; % record used input
 if isempty(fitfun)
-  % fitfun = definput.fitfun; 
-  % warning(['Objective function not determined, ''' fitfun ''' used']);
-  error(['Objective function not determined']);
+    % fitfun = definput.fitfun;
+    % warning(['Objective function not determined, ''' fitfun ''' used']);
+    error(['Objective function not determined']);
 end
 if ~ischar(fitfun)
-  error('first argument FUN must be a string');
+    error('first argument FUN must be a string');
 end
 
 
-if nargin < 2 
-  xstart = [];
+if nargin < 2
+    xstart = [];
 end
 
 input.xstart = xstart;
 if isempty(xstart)
-  % xstart = definput.xstart;  % objective variables initial point
-  % warning('Initial search point, and problem dimension, not determined');
-  error('Initial search point, and problem dimension, not determined');
+    % xstart = definput.xstart;  % objective variables initial point
+    % warning('Initial search point, and problem dimension, not determined');
+    error('Initial search point, and problem dimension, not determined');
 end
 
-if nargin < 3 
-  insigma = [];
+if nargin < 3
+    insigma = [];
 end
 if isa(insigma, 'struct')
-  error(['Third argument SIGMA must be (or eval to) a scalar '...
-	   'or a column vector of size(X0,1)']);
+    error(['Third argument SIGMA must be (or eval to) a scalar '...
+           'or a column vector of size(X0,1)']);
 end
 input.sigma = insigma;
 if isempty(insigma)
-  if all(size(myeval(xstart)) > 1)
-    insigma = std(xstart, 0, 2); 
-    if any(insigma == 0)
-      error(['Initial search volume is zero, choose SIGMA or X0 appropriate']);
+    if all(size(myeval(xstart)) > 1)
+        insigma = std(xstart, 0, 2);
+        if any(insigma == 0)
+            error(['Initial search volume is zero, choose SIGMA or X0 appropriate']);
+        end
+    else
+        % will be captured later
+        % error(['Initial step sizes (SIGMA) not determined']);
     end
-  else
-    % will be captured later
-    % error(['Initial step sizes (SIGMA) not determined']);
-  end
 end
 
 % Compose options opts
 if nargin < 4 || isempty(inopts) % no input options available
-  inopts = []; 
-  opts = defopts;
+    inopts = [];
+    opts = defopts;
 else
-  opts = getoptions(inopts, defopts);
+    opts = getoptions(inopts, defopts);
 end
 i = strfind(opts.SaveFilename, ' '); % remove everything after white space
 if ~isempty(i)
-  opts.SaveFilename = opts.SaveFilename(1:i(1)-1);
+    opts.SaveFilename = opts.SaveFilename(1:i(1)-1);
 end
 
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
-counteval = 0; countevalNaN = 0; 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+counteval = 0; countevalNaN = 0;
 irun = 0;
 while irun <= myeval(opts.Restarts) % for-loop does not work with resume
-  irun = irun + 1; 
-
-% ------------------------ Initialization -------------------------------
-
-% Handle resuming of old run
-flgresume = myevalbool(opts.Resume);
-xmean = myeval(xstart); 
-if all(size(xmean) > 1)
-   xmean = mean(xmean, 2); % in case if xstart is a population
-elseif size(xmean, 2) > 1
-  xmean = xmean';
-end 
-if ~flgresume % not resuming a former run
-  % Assign settings from input parameters and options for myeval...
-  N = size(xmean, 1); numberofvariables = N; 
-  lambda0 = floor(myeval(opts.PopSize) * myeval(opts.IncPopSize)^(irun-1)); 
-  % lambda0 = floor(myeval(opts.PopSize) * 3^floor((irun-1)/2)); 
-  popsize = lambda0;
-  lambda = lambda0;
-  insigma = myeval(insigma);
-  if all(size(insigma) == [N 2]) 
-    insigma = 0.5 * (insigma(:,2) - insigma(:,1));
-  end
-else % flgresume is true, do resume former run
-  tmp = whos('-file', opts.SaveFilename);
-  for i = 1:length(tmp)
-    if strcmp(tmp(i).name, 'localopts');
-      error('Saved variables include variable "localopts", please remove');
-    end
-  end
-  local.opts = opts; % keep stopping and display options
-  local.varargin = varargin;
-  load(opts.SaveFilename); 
-  varargin = local.varargin;
-  flgresume = 1;
-
-  % Overwrite old stopping and display options
-  opts.StopFitness = local.opts.StopFitness; 
-  %%opts.MaxFunEvals = local.opts.MaxFunEvals;
-  %%opts.MaxIter = local.opts.MaxIter; 
-  opts.StopFunEvals = local.opts.StopFunEvals; 
-  opts.StopIter = local.opts.StopIter;  
-  opts.TolX = local.opts.TolX;
-  opts.TolUpX = local.opts.TolUpX;
-  opts.TolFun = local.opts.TolFun;
-  opts.TolHistFun = local.opts.TolHistFun;
-  opts.StopOnStagnation = local.opts.StopOnStagnation; 
-  opts.StopOnWarnings = local.opts.StopOnWarnings; 
-  opts.ReadSignals = local.opts.ReadSignals; 
-  opts.DispFinal = local.opts.DispFinal;
-  opts.LogPlot = local.opts.LogPlot;
-  opts.DispModulo = local.opts.DispModulo;
-  opts.SaveVariables = local.opts.SaveVariables;
-  opts.LogModulo = local.opts.LogModulo;
-  opts.LogTime = local.opts.LogTime;
-  clear local; % otherwise local would be overwritten during load
-end
-  
-%--------------------------------------------------------------
-% Evaluate options
-stopFitness = myeval(opts.StopFitness); 
-stopMaxFunEvals = myeval(opts.MaxFunEvals);  
-stopMaxIter = myeval(opts.MaxIter);  
-stopFunEvals = myeval(opts.StopFunEvals);  
-stopIter = myeval(opts.StopIter);  
-stopTolX = myeval(opts.TolX);
-stopTolUpX = myeval(opts.TolUpX);
-stopTolFun = myeval(opts.TolFun);
-stopTolHistFun = myeval(opts.TolHistFun);
-stopOnStagnation = myevalbool(opts.StopOnStagnation); 
-stopOnWarnings = myevalbool(opts.StopOnWarnings); 
-flgreadsignals = myevalbool(opts.ReadSignals);
-flgWarnOnEqualFunctionValues = myevalbool(opts.WarnOnEqualFunctionValues);
-flgEvalParallel = myevalbool(opts.EvalParallel);
-stopOnEqualFunctionValues = myeval(opts.StopOnEqualFunctionValues);
-arrEqualFunvals = zeros(1,10+N);
-flgDiagonalOnly = myeval(opts.DiagonalOnly); 
-flgActiveCMA = myeval(opts.CMA.active); 
-noiseHandling = myevalbool(opts.Noise.on);
-noiseMinMaxEvals = myeval(opts.Noise.minmaxevals);
-noiseAlphaEvals = myeval(opts.Noise.alphaevals);
-noiseCallback = myeval(opts.Noise.callback); 
-flgdisplay = myevalbool(opts.DispFinal);
-flgplotting = myevalbool(opts.LogPlot);
-verbosemodulo = myeval(opts.DispModulo);
-flgscience = myevalbool(opts.Science);
-flgsaving = [];
-strsaving = [];
-if strfind(opts.SaveVariables, '-v6') 
-  i = strfind(opts.SaveVariables, '%');
-  if isempty(i) || i == 0 || strfind(opts.SaveVariables, '-v6') < i
-    strsaving = '-v6';
-    flgsaving = 1;
-    flgsavingfinal = 1;
-  end
-end
-if strncmp('final', opts.SaveVariables, 5)
-  flgsaving = 0;
-  flgsavingfinal = 1;
-end
-if isempty(flgsaving)
-  flgsaving = myevalbool(opts.SaveVariables);
-  flgsavingfinal = flgsaving;
-end
-savemodulo = myeval(opts.LogModulo);
-savetime = myeval(opts.LogTime);
-
-i = strfind(opts.LogFilenamePrefix, ' '); % remove everything after white space
-if ~isempty(i)
-  opts.LogFilenamePrefix = opts.LogFilenamePrefix(1:i(1)-1);
-end
-
-% TODO here silent option? set disp, save and log options to 0 
-
-%--------------------------------------------------------------
-
-if (isfinite(stopFunEvals) || isfinite(stopIter)) && ~flgsaving
-  warning('To resume later the saving option needs to be set');
-end
-
-
-% Do more checking and initialization 
-if flgresume % resume is on
-  time.t0 = clock;
-  if flgdisplay
-    disp(['  resumed from ' opts.SaveFilename ]); 
-  end
-  if counteval >= stopMaxFunEvals 
-    error(['MaxFunEvals exceeded, use StopFunEvals as stopping ' ...
-	  'criterion before resume']);
-  end
-  if countiter >= stopMaxIter 
-    error(['MaxIter exceeded, use StopIter as stopping criterion ' ...
-	  'before resume']);
-  end
-  
-else % flgresume
-  % xmean = mean(myeval(xstart), 2); % evaluate xstart again, because of irun
-  maxdx = myeval(opts.DiffMaxChange); % maximal sensible variable change
-  mindx = myeval(opts.DiffMinChange); % minimal sensible variable change 
-				      % can both also be defined as Nx1 vectors
-  lbounds = myeval(opts.LBounds);		     
-  ubounds = myeval(opts.UBounds);
-  if length(lbounds) == 1
-    lbounds = repmat(lbounds, N, 1);
-  end
-  if length(ubounds) == 1
-    ubounds = repmat(ubounds, N, 1);
-  end
-  if isempty(insigma) % last chance to set insigma
-    if all(lbounds > -Inf) && all(ubounds < Inf)
-      if any(lbounds>=ubounds)
-	error('upper bound must be greater than lower bound');
-      end
-      insigma = 0.3*(ubounds-lbounds);
-      stopTolX = myeval(opts.TolX);  % reevaluate these
-      stopTolUpX = myeval(opts.TolUpX);
-    else
-      error(['Initial step sizes (SIGMA) not determined']);
-    end
-  end
-
-  % Check all vector sizes
-  if size(xmean, 2) > 1 || size(xmean,1) ~= N
-    error(['intial search point should be a column vector of size ' ...
-	   num2str(N)]);
-  elseif ~(all(size(insigma) == [1 1]) || all(size(insigma) == [N 1]))
-    error(['input parameter SIGMA should be (or eval to) a scalar '...
-	   'or a column vector of size ' num2str(N)] );
-  elseif size(stopTolX, 2) > 1 || ~ismember(size(stopTolX, 1), [1 N])
-    error(['option TolX should be (or eval to) a scalar '...
-	   'or a column vector of size ' num2str(N)] );
-  elseif size(stopTolUpX, 2) > 1 || ~ismember(size(stopTolUpX, 1), [1 N])
-    error(['option TolUpX should be (or eval to) a scalar '...
-	   'or a column vector of size ' num2str(N)] );
-  elseif size(maxdx, 2) > 1 || ~ismember(size(maxdx, 1), [1 N])
-    error(['option DiffMaxChange should be (or eval to) a scalar '...
-	   'or a column vector of size ' num2str(N)] );
-  elseif size(mindx, 2) > 1 || ~ismember(size(mindx, 1), [1 N])
-    error(['option DiffMinChange should be (or eval to) a scalar '...
-	   'or a column vector of size ' num2str(N)] );
-  elseif size(lbounds, 2) > 1 || ~ismember(size(lbounds, 1), [1 N])
-    error(['option lbounds should be (or eval to) a scalar '...
-	   'or a column vector of size ' num2str(N)] );
-  elseif size(ubounds, 2) > 1 || ~ismember(size(ubounds, 1), [1 N])
-    error(['option ubounds should be (or eval to) a scalar '...
-	   'or a column vector of size ' num2str(N)] );
-  end
-  
-  % Initialize dynamic internal state parameters
-  if any(insigma <= 0) 
-    error(['Initial search volume (SIGMA) must be greater than zero']);
-  end
-  if max(insigma)/min(insigma) > 1e6
-    error(['Initial search volume (SIGMA) badly conditioned']);
-  end
-  sigma = max(insigma);              % overall standard deviation
-  pc = zeros(N,1); ps = zeros(N,1);  % evolution paths for C and sigma
-
-  if length(insigma) == 1
-    insigma = insigma * ones(N,1) ;
-  end
-  diagD = insigma/max(insigma);      % diagonal matrix D defines the scaling
-  diagC = diagD.^2; 
-  if flgDiagonalOnly ~= 1            % use at some point full covariance matrix
-    B = eye(N,N);                      % B defines the coordinate system
-    BD = B.*repmat(diagD',N,1);        % B*D for speed up only
-    C = diag(diagC);                   % covariance matrix == BD*(BD)'
-  end
-  if flgDiagonalOnly
-    B = 1; 
-  end
-
-  fitness.hist=NaN*ones(1,10+ceil(3*10*N/lambda)); % history of fitness values
-  fitness.histsel=NaN*ones(1,10+ceil(3*10*N/lambda)); % history of fitness values
-  fitness.histbest=[]; % history of fitness values
-  fitness.histmedian=[]; % history of fitness values
-
-  % Initialize boundary handling
-  bnd.isactive = any(lbounds > -Inf) || any(ubounds < Inf); 
-  if bnd.isactive
-    if any(lbounds>ubounds)
-      error('lower bound found to be greater than upper bound');
+    irun = irun + 1;
+
+    % ------------------------ Initialization -------------------------------
+
+    % Handle resuming of old run
+    flgresume = myevalbool(opts.Resume);
+    xmean = myeval(xstart);
+    if all(size(xmean) > 1)
+        xmean = mean(xmean, 2); % in case if xstart is a population
+    elseif size(xmean, 2) > 1
+        xmean = xmean';
     end
-    [xmean ti] = xintobounds(xmean, lbounds, ubounds); % just in case
-    if any(ti)
-      warning('Initial point was out of bounds, corrected');
+    if ~flgresume % not resuming a former run
+                  % Assign settings from input parameters and options for myeval...
+        N = size(xmean, 1); numberofvariables = N;
+        lambda0 = floor(myeval(opts.PopSize) * myeval(opts.IncPopSize)^(irun-1));
+        % lambda0 = floor(myeval(opts.PopSize) * 3^floor((irun-1)/2));
+        popsize = lambda0;
+        lambda = lambda0;
+        insigma = myeval(insigma);
+        if all(size(insigma) == [N 2])
+            insigma = 0.5 * (insigma(:,2) - insigma(:,1));
+        end
+    else % flgresume is true, do resume former run
+        tmp = whos('-file', opts.SaveFilename);
+        for i = 1:length(tmp)
+            if strcmp(tmp(i).name, 'localopts')
+                error('Saved variables include variable "localopts", please remove');
+            end
+        end
+        local.opts = opts; % keep stopping and display options
+        local.varargin = varargin;
+        load(opts.SaveFilename);
+        varargin = local.varargin;
+        flgresume = 1;
+
+        % Overwrite old stopping and display options
+        opts.StopFitness = local.opts.StopFitness;
+        %%opts.MaxFunEvals = local.opts.MaxFunEvals;
+        %%opts.MaxIter = local.opts.MaxIter;
+        opts.StopFunEvals = local.opts.StopFunEvals;
+        opts.StopIter = local.opts.StopIter;
+        opts.TolX = local.opts.TolX;
+        opts.TolUpX = local.opts.TolUpX;
+        opts.TolFun = local.opts.TolFun;
+        opts.TolHistFun = local.opts.TolHistFun;
+        opts.StopOnStagnation = local.opts.StopOnStagnation;
+        opts.StopOnWarnings = local.opts.StopOnWarnings;
+        opts.ReadSignals = local.opts.ReadSignals;
+        opts.DispFinal = local.opts.DispFinal;
+        opts.LogPlot = local.opts.LogPlot;
+        opts.DispModulo = local.opts.DispModulo;
+        opts.SaveVariables = local.opts.SaveVariables;
+        opts.LogModulo = local.opts.LogModulo;
+        opts.LogTime = local.opts.LogTime;
+        clear local; % otherwise local would be overwritten during load
     end
-    bnd.weights = zeros(N,1);         % weights for bound penalty
-    % scaling is better in axis-parallel case, worse in rotated
-    bnd.flgscale = 0; % scaling will be omitted if zero 
-    if bnd.flgscale ~= 0 
-      bnd.scale = diagC/mean(diagC);
-    else
-      bnd.scale = ones(N,1);
+
+    %--------------------------------------------------------------
+    % Evaluate options
+    stopFitness = myeval(opts.StopFitness);
+    stopMaxFunEvals = myeval(opts.MaxFunEvals);
+    stopMaxIter = myeval(opts.MaxIter);
+    stopFunEvals = myeval(opts.StopFunEvals);
+    stopIter = myeval(opts.StopIter);
+    stopTolX = myeval(opts.TolX);
+    stopTolUpX = myeval(opts.TolUpX);
+    stopTolFun = myeval(opts.TolFun);
+    stopTolHistFun = myeval(opts.TolHistFun);
+    stopOnStagnation = myevalbool(opts.StopOnStagnation);
+    stopOnWarnings = myevalbool(opts.StopOnWarnings);
+    flgreadsignals = myevalbool(opts.ReadSignals);
+    flgWarnOnEqualFunctionValues = myevalbool(opts.WarnOnEqualFunctionValues);
+    flgEvalParallel = myevalbool(opts.EvalParallel);
+    stopOnEqualFunctionValues = myeval(opts.StopOnEqualFunctionValues);
+    arrEqualFunvals = zeros(1,10+N);
+    flgDiagonalOnly = myeval(opts.DiagonalOnly);
+    flgActiveCMA = myeval(opts.CMA.active);
+    noiseHandling = myevalbool(opts.Noise.on);
+    noiseMinMaxEvals = myeval(opts.Noise.minmaxevals);
+    noiseAlphaEvals = myeval(opts.Noise.alphaevals);
+    noiseCallback = myeval(opts.Noise.callback);
+    flgdisplay = myevalbool(opts.DispFinal);
+    flgplotting = myevalbool(opts.LogPlot);
+    verbosemodulo = myeval(opts.DispModulo);
+    flgscience = myevalbool(opts.Science);
+    flgsaving = [];
+    strsaving = [];
+    if strfind(opts.SaveVariables, '-v6')
+        i = strfind(opts.SaveVariables, '%');
+        if isempty(i) || i == 0 || strfind(opts.SaveVariables, '-v6') < i
+            strsaving = '-v6';
+            flgsaving = 1;
+            flgsavingfinal = 1;
+        end
     end
-    
-    idx = (lbounds > -Inf) | (ubounds < Inf);
-    if length(idx) == 1
-      idx = idx * ones(N,1);
+    if strncmp('final', opts.SaveVariables, 5)
+        flgsaving = 0;
+        flgsavingfinal = 1;
     end
-    bnd.isbounded = zeros(N,1);
-    bnd.isbounded(find(idx)) = 1; 
-    maxdx = min(maxdx, (ubounds - lbounds)/2);
-    if any(sigma*sqrt(diagC) > maxdx)
-      fac = min(maxdx ./ sqrt(diagC))/sigma;
-      sigma = min(maxdx ./ sqrt(diagC));
-      warning(['Initial SIGMA multiplied by the factor ' num2str(fac) ...
-	       ', because it was larger than half' ...
-	       ' of one of the boundary intervals']);
+    if isempty(flgsaving)
+        flgsaving = myevalbool(opts.SaveVariables);
+        flgsavingfinal = flgsaving;
     end
-    idx = (lbounds > -Inf) & (ubounds < Inf);
-    dd = diagC;
-    if any(5*sigma*sqrt(dd(idx)) < ubounds(idx) - lbounds(idx))
-      warning(['Initial SIGMA is, in at least one coordinate, ' ...
-	       'much smaller than the '...
-	       'given boundary intervals. For reasonable ' ...
-	       'global search performance SIGMA should be ' ...
-	       'between 0.2 and 0.5 of the bounded interval in ' ...
-	       'each coordinate. If all coordinates have ' ... 
-	       'lower and upper bounds SIGMA can be empty']);
+    savemodulo = myeval(opts.LogModulo);
+    savetime = myeval(opts.LogTime);
+
+    i = strfind(opts.LogFilenamePrefix, ' '); % remove everything after white space
+    if ~isempty(i)
+        opts.LogFilenamePrefix = opts.LogFilenamePrefix(1:i(1)-1);
     end
-    bnd.dfithist = 1;              % delta fit for setting weights
-    bnd.aridxpoints = [];          % remember complete outside points
-    bnd.arfitness = [];            % and their fitness
-    bnd.validfitval = 0;
-    bnd.iniphase = 1;
-  end
-
-  % ooo initial feval, for output only
-  if irun == 1 
-    out.solutions.bestever.x = xmean;
-    out.solutions.bestever.f = Inf;  % for simpler comparison below
-    out.solutions.bestever.evals = counteval;
-    bestever = out.solutions.bestever;
-  end
-  if myevalbool(opts.EvalInitialX)
-    fitness.hist(1)=feval(fitfun, xmean, varargin{:}); 
-    fitness.histsel(1)=fitness.hist(1);
-    counteval = counteval + 1;
-    if fitness.hist(1) < out.solutions.bestever.f 
-	out.solutions.bestever.x = xmean;
-	out.solutions.bestever.f = fitness.hist(1);
-	out.solutions.bestever.evals = counteval;
-	bestever = out.solutions.bestever;
+
+    % TODO here silent option? set disp, save and log options to 0
+
+    %--------------------------------------------------------------
+
+    if (isfinite(stopFunEvals) || isfinite(stopIter)) && ~flgsaving
+        warning('To resume later the saving option needs to be set');
     end
-  else
-    fitness.hist(1)=NaN; 
-    fitness.histsel(1)=NaN; 
-  end
-    
-  % initialize random number generator
+
+
+    % Do more checking and initialization
+    if flgresume % resume is on
+        time.t0 = clock;
+        if flgdisplay
+            disp(['  resumed from ' opts.SaveFilename ]);
+        end
+        if counteval >= stopMaxFunEvals
+            error(['MaxFunEvals exceeded, use StopFunEvals as stopping ' ...
+                   'criterion before resume']);
+        end
+        if countiter >= stopMaxIter
+            error(['MaxIter exceeded, use StopIter as stopping criterion ' ...
+                   'before resume']);
+        end
+
+    else % flgresume
+         % xmean = mean(myeval(xstart), 2); % evaluate xstart again, because of irun
+        maxdx = myeval(opts.DiffMaxChange); % maximal sensible variable change
+        mindx = myeval(opts.DiffMinChange); % minimal sensible variable change
+                                            % can both also be defined as Nx1 vectors
+        lbounds = myeval(opts.LBounds);
+        ubounds = myeval(opts.UBounds);
+        if length(lbounds) == 1
+            lbounds = repmat(lbounds, N, 1);
+        end
+        if length(ubounds) == 1
+            ubounds = repmat(ubounds, N, 1);
+        end
+        if isempty(insigma) % last chance to set insigma
+            if all(lbounds > -Inf) && all(ubounds < Inf)
+                if any(lbounds>=ubounds)
+                    error('upper bound must be greater than lower bound');
+                end
+                insigma = 0.3*(ubounds-lbounds);
+                stopTolX = myeval(opts.TolX);  % reevaluate these
+                stopTolUpX = myeval(opts.TolUpX);
+            else
+                error(['Initial step sizes (SIGMA) not determined']);
+            end
+        end
+
+        % Check all vector sizes
+        if size(xmean, 2) > 1 || size(xmean,1) ~= N
+            error(['intial search point should be a column vector of size ' ...
+                   num2str(N)]);
+        elseif ~(all(size(insigma) == [1 1]) || all(size(insigma) == [N 1]))
+            error(['input parameter SIGMA should be (or eval to) a scalar '...
+                   'or a column vector of size ' num2str(N)] );
+        elseif size(stopTolX, 2) > 1 || ~ismember(size(stopTolX, 1), [1 N])
+            error(['option TolX should be (or eval to) a scalar '...
+                   'or a column vector of size ' num2str(N)] );
+        elseif size(stopTolUpX, 2) > 1 || ~ismember(size(stopTolUpX, 1), [1 N])
+            error(['option TolUpX should be (or eval to) a scalar '...
+                   'or a column vector of size ' num2str(N)] );
+        elseif size(maxdx, 2) > 1 || ~ismember(size(maxdx, 1), [1 N])
+            error(['option DiffMaxChange should be (or eval to) a scalar '...
+                   'or a column vector of size ' num2str(N)] );
+        elseif size(mindx, 2) > 1 || ~ismember(size(mindx, 1), [1 N])
+            error(['option DiffMinChange should be (or eval to) a scalar '...
+                   'or a column vector of size ' num2str(N)] );
+        elseif size(lbounds, 2) > 1 || ~ismember(size(lbounds, 1), [1 N])
+            error(['option lbounds should be (or eval to) a scalar '...
+                   'or a column vector of size ' num2str(N)] );
+        elseif size(ubounds, 2) > 1 || ~ismember(size(ubounds, 1), [1 N])
+            error(['option ubounds should be (or eval to) a scalar '...
+                   'or a column vector of size ' num2str(N)] );
+        end
+
+        % Initialize dynamic internal state parameters
+        if any(insigma <= 0)
+            error(['Initial search volume (SIGMA) must be greater than zero']);
+        end
+        if max(insigma)/min(insigma) > 1e6
+            error(['Initial search volume (SIGMA) badly conditioned']);
+        end
+        sigma = max(insigma);              % overall standard deviation
+        pc = zeros(N,1); ps = zeros(N,1);  % evolution paths for C and sigma
+
+        if length(insigma) == 1
+            insigma = insigma * ones(N,1) ;
+        end
+        diagD = insigma/max(insigma);      % diagonal matrix D defines the scaling
+        diagC = diagD.^2;
+        if flgDiagonalOnly ~= 1            % use at some point full covariance matrix
+            B = eye(N,N);                      % B defines the coordinate system
+            BD = B.*repmat(diagD',N,1);        % B*D for speed up only
+            C = diag(diagC);                   % covariance matrix == BD*(BD)'
+        end
+        if flgDiagonalOnly
+            B = 1;
+        end
+
+        fitness.hist=NaN*ones(1,10+ceil(3*10*N/lambda)); % history of fitness values
+        fitness.histsel=NaN*ones(1,10+ceil(3*10*N/lambda)); % history of fitness values
+        fitness.histbest=[]; % history of fitness values
+        fitness.histmedian=[]; % history of fitness values
+
+        % Initialize boundary handling
+        bnd.isactive = any(lbounds > -Inf) || any(ubounds < Inf);
+        if bnd.isactive
+            if any(lbounds>ubounds)
+                error('lower bound found to be greater than upper bound');
+            end
+            [xmean, ti] = xintobounds(xmean, lbounds, ubounds); % just in case
+            if any(ti)
+                warning('Initial point was out of bounds, corrected');
+            end
+            bnd.weights = zeros(N,1);         % weights for bound penalty
+                                              % scaling is better in axis-parallel case, worse in rotated
+            bnd.flgscale = 0; % scaling will be omitted if zero
+            if bnd.flgscale ~= 0
+                bnd.scale = diagC/mean(diagC);
+            else
+                bnd.scale = ones(N,1);
+            end
+
+            idx = (lbounds > -Inf) | (ubounds < Inf);
+            if length(idx) == 1
+                idx = idx * ones(N,1);
+            end
+            bnd.isbounded = zeros(N,1);
+            bnd.isbounded(find(idx)) = 1;
+            maxdx = min(maxdx, (ubounds - lbounds)/2);
+            if any(sigma*sqrt(diagC) > maxdx)
+                fac = min(maxdx ./ sqrt(diagC))/sigma;
+                sigma = min(maxdx ./ sqrt(diagC));
+                warning(['Initial SIGMA multiplied by the factor ' num2str(fac) ...
+                         ', because it was larger than half' ...
+                         ' of one of the boundary intervals']);
+            end
+            idx = (lbounds > -Inf) & (ubounds < Inf);
+            dd = diagC;
+            if any(5*sigma*sqrt(dd(idx)) < ubounds(idx) - lbounds(idx))
+                warning(['Initial SIGMA is, in at least one coordinate, ' ...
+                         'much smaller than the '...
+                         'given boundary intervals. For reasonable ' ...
+                         'global search performance SIGMA should be ' ...
+                         'between 0.2 and 0.5 of the bounded interval in ' ...
+                         'each coordinate. If all coordinates have ' ...
+                         'lower and upper bounds SIGMA can be empty']);
+            end
+            bnd.dfithist = 1;              % delta fit for setting weights
+            bnd.aridxpoints = [];          % remember complete outside points
+            bnd.arfitness = [];            % and their fitness
+            bnd.validfitval = 0;
+            bnd.iniphase = 1;
+        end
+
+        % ooo initial feval, for output only
+        if irun == 1
+            out.solutions.bestever.x = xmean;
+            out.solutions.bestever.f = Inf;  % for simpler comparison below
+            out.solutions.bestever.evals = counteval;
+            bestever = out.solutions.bestever;
+        end
+        if myevalbool(opts.EvalInitialX)
+            fitness.hist(1)=feval(fitfun, xmean, varargin{:});
+            fitness.histsel(1)=fitness.hist(1);
+            counteval = counteval + 1;
+            if fitness.hist(1) < out.solutions.bestever.f
+                out.solutions.bestever.x = xmean;
+                out.solutions.bestever.f = fitness.hist(1);
+                out.solutions.bestever.evals = counteval;
+                bestever = out.solutions.bestever;
+            end
+        else
+            fitness.hist(1)=NaN;
+            fitness.histsel(1)=NaN;
+        end
+
+        % initialize random number generator
 % $$$   if ischar(opts.Seed)
 % $$$     randn('state', eval(opts.Seed));     % random number generator state
 % $$$   else
 % $$$     randn('state', opts.Seed);
 % $$$   end
-  %qqq
+%qqq
 %  load(opts.SaveFilename, 'startseed');
 %  randn('state', startseed);
 %  disp(['SEED RELOADED FROM ' opts.SaveFilename]);
 %  startseed = randn('state');         % for retrieving in saved variables
 
-  % Initialize further constants
-  chiN=N^0.5*(1-1/(4*N)+1/(21*N^2));  % expectation of 
-				      %   ||N(0,I)|| == norm(randn(N,1))
-  
-  countiter = 0;
-  % Initialize records and output
-  if irun == 1
-    time.t0 = clock;
-    
-    % TODO: keep also median solution? 
-    out.evals = counteval;  % should be first entry
-    out.stopflag = {};
-
-    outiter = 0;
-
-    % Write headers to output data files 
-    filenameprefix = opts.LogFilenamePrefix; 
-    if savemodulo && savetime
-      filenames = {};
-      filenames(end+1) = {'axlen'};
-      filenames(end+1) = {'fit'};
-      filenames(end+1) = {'stddev'};
-      filenames(end+1) = {'xmean'};
-      filenames(end+1) = {'xrecentbest'};
-      str = [' (startseed=' num2str(startseed(2)) ...
-             ', ' num2str(clock, '%d/%02d/%d %d:%d:%2.2f') ')'];
-      for namecell = filenames(:)'
-        name = namecell{:};
-
-	[fid, err] = fopen(['./' filenameprefix name '.dat'], 'w');
-	if fid < 1 % err ~= 0 
-	  warning(['could not open ' filenameprefix name '.dat']);
-	  filenames(find(strcmp(filenames,name))) = [];
-	else
-%	  fprintf(fid, '%s\n', ...
-%	      ['<CMAES-OUTPUT version="' cmaVersion '">']);
-%	  fprintf(fid, ['  <NAME>' name '</NAME>\n']);
-%	  fprintf(fid, ['  <DATE>' date() '</DATE>\n']);
-%	  fprintf(fid, '  <PARAMETERS>\n');
-%	  fprintf(fid, ['    dimension=' num2str(N) '\n']);
-%	  fprintf(fid, '  </PARAMETERS>\n');
-	  % different cases for DATA columns annotations here
-%	  fprintf(fid, '  <DATA');
-	  if strcmp(name, 'axlen')
-	     fprintf(fid, ['%%  columns="iteration, evaluation, sigma, ' ...
-		 'max axis length, min axis length, ' ...
-		 'all principal axes lengths (sorted square roots ' ...
-                  'of eigenvalues of C)"' str]);
-	  elseif strcmp(name, 'fit')
-	    fprintf(fid, ['%%  columns="iteration, evaluation, sigma, axis ratio, bestever,' ...
-		' best, median, worst fitness function value,' ...
-		' further objective values of best"' str]);
-	  elseif strcmp(name, 'stddev')
-	    fprintf(fid, ['%%  columns=["iteration, evaluation, sigma, void, void, ' ...
-		'stds==sigma*sqrt(diag(C))"' str]);
-	  elseif strcmp(name, 'xmean')
-	    fprintf(fid, ['%%  columns="iteration, evaluation, void, ' ...
-                          'void, void, xmean"' str]);
-	  elseif strcmp(name, 'xrecentbest')
-	    fprintf(fid, ['%%  columns="iteration, evaluation, fitness, ' ...
-                          'void, void, xrecentbest"' str]);
-	  end
-	  fprintf(fid, '\n'); % DATA
-	  if strcmp(name, 'xmean')
-	    fprintf(fid, '%ld %ld 0 0 0 ', 0, counteval); 
-	    % fprintf(fid, '%ld %ld 0 0 %e ', countiter, counteval, fmean); 
-%qqq	    fprintf(fid, msprintf('%e ', genophenotransform(out.genopheno, xmean)) + '\n'); 
-	    fprintf(fid, '%e ', xmean);
-            fprintf(fid, '\n'); 
-	  end
-	  fclose(fid); 
-          clear fid; % preventing 
-	end
-      end % for files
-    end % savemodulo
-  end % irun == 1
-  
-end % else flgresume 
-
-% -------------------- Generation Loop --------------------------------
-stopflag = {};
-while isempty(stopflag)
-  % set internal parameters
-  if countiter == 0 || lambda ~= lambda_last
-    if countiter > 0 && floor(log10(lambda)) ~= floor(log10(lambda_last)) ...
-          && flgdisplay
-      disp(['  lambda = ' num2str(lambda)]);
-      lambda_hist(:,end+1) = [countiter+1; lambda];
-    else
-      lambda_hist = [countiter+1; lambda]; 
-    end
-    lambda_last = lambda;
-    % Strategy internal parameter setting: Selection  
-    mu = myeval(opts.ParentNumber); % number of parents/points for recombination
-    if strncmp(lower(opts.RecombinationWeights), 'equal', 3)
-      weights = ones(mu,1); % (mu_I,lambda)-CMA-ES
-    elseif strncmp(lower(opts.RecombinationWeights), 'linear', 3)
-      weights = mu+0.5-(1:mu)'; 
-    elseif strncmp(lower(opts.RecombinationWeights), 'superlinear', 3)
-      weights = log(mu+0.5)-log(1:mu)'; % muXone array for weighted recombination
-                                        % qqq mu can be non-integer and
-                                        % should become ceil(mu-0.5) (minor correction)
-    else
-      error(['Recombination weights to be "' opts.RecombinationWeights ...
-             '" is not implemented']);
-    end
-    mueff=sum(weights)^2/sum(weights.^2); % variance-effective size of mu
-    weights = weights/sum(weights);     % normalize recombination weights array
-    if mueff == lambda
-      error(['Combination of values for PopSize, ParentNumber and ' ...
-             ' and RecombinationWeights is not reasonable']);
-    end
-    
-    % Strategy internal parameter setting: Adaptation
-    cc = myeval(opts.CMA.ccum); % time constant for cumulation for covariance matrix
-    cs = myeval(opts.CMA.cs); 
-
-    % old way TODO: remove this at some point
-    % mucov = mueff;   % size of mu used for calculating learning rate ccov
-    % ccov = (1/mucov) * 2/(N+1.41)^2 ... % learning rate for covariance matrix
-    %        + (1-1/mucov) * min(1,(2*mucov-1)/((N+2)^2+mucov)); 
-
-    % new way
-    if myevalbool(opts.CMA.on) 
-      ccov1 = myeval(opts.CMA.ccov1); 
-      ccovmu = min(1-ccov1, myeval(opts.CMA.ccovmu));
-    else
-      ccov1 = 0;
-      ccovmu = 0;
-    end
-    
-    % flgDiagonalOnly = -lambda*4*1/ccov; % for ccov==1 it is not needed
-    % 0 : C will never be diagonal anymore
-    % 1 : C will always be diagonal
-    % >1: C is diagonal for first iterations, set to 0 afterwards
-    if flgDiagonalOnly < 1
-      flgDiagonalOnly = 0; 
-    end
-    if flgDiagonalOnly
-      ccov1_sep = min(1, ccov1 * (N+1.5) / 3); 
-      ccovmu_sep = min(1-ccov1_sep, ccovmu * (N+1.5) / 3); 
-    elseif N > 98 && flgdisplay && countiter == 0
-      disp('consider option DiagonalOnly for high-dimensional problems');
-    end
-
-    % ||ps|| is close to sqrt(mueff/N) for mueff large on linear fitness
-    %damps = ... % damping for step size control, usually close to one 
-    %    (1 + 2*max(0,sqrt((mueff-1)/(N+1))-1)) ... % limit sigma increase
-    %    * max(0.3, ... % reduce damps, if max. iteration number is small
-    %          1 - N/min(stopMaxIter,stopMaxFunEvals/lambda)) + cs; 
-    damps = myeval(opts.CMA.damps); 
-    if noiseHandling
-      noiseReevals = min(myeval(opts.Noise.reevals), lambda); 
-      noiseAlpha = myeval(opts.Noise.alphasigma); 
-      noiseEpsilon = myeval(opts.Noise.epsilon); 
-      noiseTheta = myeval(opts.Noise.theta); 
-      noisecum = myeval(opts.Noise.cum);
-      noiseCutOff = myeval(opts.Noise.cutoff);  % arguably of minor relevance
-    else
-      noiseReevals = 0; % more convenient in later coding
-    end
+        % Initialize further constants
+        chiN=N^0.5*(1-1/(4*N)+1/(21*N^2));  % expectation of
+                                            %   ||N(0,I)|| == norm(randn(N,1))
+
+        countiter = 0;
+        % Initialize records and output
+        if irun == 1
+            time.t0 = clock;
+
+            % TODO: keep also median solution?
+            out.evals = counteval;  % should be first entry
+            out.stopflag = {};
+
+            outiter = 0;
+
+            % Write headers to output data files
+            filenameprefix = opts.LogFilenamePrefix;
+            if savemodulo && savetime
+                filenames = {};
+                filenames(end+1) = {'axlen'};
+                filenames(end+1) = {'fit'};
+                filenames(end+1) = {'stddev'};
+                filenames(end+1) = {'xmean'};
+                filenames(end+1) = {'xrecentbest'};
+                str = [' (startseed=' num2str(startseed(2)) ...
+                       ', ' num2str(clock, '%d/%02d/%d %d:%d:%2.2f') ')'];
+                for namecell = filenames(:)'
+                    name = namecell{:};
+
+                    [fid, err] = fopen(['./' filenameprefix name '.dat'], 'w');
+                    if fid < 1 % err ~= 0
+                        warning(['could not open ' filenameprefix name '.dat']);
+                        filenames(find(strcmp(filenames,name))) = [];
+                    else
+                        %         fprintf(fid, '%s\n', ...
+                        %             ['<CMAES-OUTPUT version="' cmaVersion '">']);
+                        %         fprintf(fid, ['  <NAME>' name '</NAME>\n']);
+                        %         fprintf(fid, ['  <DATE>' date() '</DATE>\n']);
+                        %         fprintf(fid, '  <PARAMETERS>\n');
+                        %         fprintf(fid, ['    dimension=' num2str(N) '\n']);
+                        %         fprintf(fid, '  </PARAMETERS>\n');
+                        % different cases for DATA columns annotations here
+                        %         fprintf(fid, '  <DATA');
+                        if strcmp(name, 'axlen')
+                            fprintf(fid, ['%%  columns="iteration, evaluation, sigma, ' ...
+                                          'max axis length, min axis length, ' ...
+                                          'all principal axes lengths (sorted square roots ' ...
+                                          'of eigenvalues of C)"' str]);
+                        elseif strcmp(name, 'fit')
+                            fprintf(fid, ['%%  columns="iteration, evaluation, sigma, axis ratio, bestever,' ...
+                                          ' best, median, worst fitness function value,' ...
+                                          ' further objective values of best"' str]);
+                        elseif strcmp(name, 'stddev')
+                            fprintf(fid, ['%%  columns=["iteration, evaluation, sigma, void, void, ' ...
+                                          'stds==sigma*sqrt(diag(C))"' str]);
+                        elseif strcmp(name, 'xmean')
+                            fprintf(fid, ['%%  columns="iteration, evaluation, void, ' ...
+                                          'void, void, xmean"' str]);
+                        elseif strcmp(name, 'xrecentbest')
+                            fprintf(fid, ['%%  columns="iteration, evaluation, fitness, ' ...
+                                          'void, void, xrecentbest"' str]);
+                        end
+                        fprintf(fid, '\n'); % DATA
+                        if strcmp(name, 'xmean')
+                            fprintf(fid, '%ld %ld 0 0 0 ', 0, counteval);
+                            % fprintf(fid, '%ld %ld 0 0 %e ', countiter, counteval, fmean);
+                            %qqq        fprintf(fid, msprintf('%e ', genophenotransform(out.genopheno, xmean)) + '\n');
+                            fprintf(fid, '%e ', xmean);
+                            fprintf(fid, '\n');
+                        end
+                        fclose(fid);
+                        clear fid; % preventing
+                    end
+                end % for files
+            end % savemodulo
+        end % irun == 1
+
+    end % else flgresume
+
+    % -------------------- Generation Loop --------------------------------
+    stopflag = {};
+    while isempty(stopflag)
+        % set internal parameters
+        if countiter == 0 || lambda ~= lambda_last
+            if countiter > 0 && floor(log10(lambda)) ~= floor(log10(lambda_last)) ...
+                    && flgdisplay
+                disp(['  lambda = ' num2str(lambda)]);
+                lambda_hist(:,end+1) = [countiter+1; lambda];
+            else
+                lambda_hist = [countiter+1; lambda];
+            end
+            lambda_last = lambda;
+            % Strategy internal parameter setting: Selection
+            mu = myeval(opts.ParentNumber); % number of parents/points for recombination
+            if strncmp(lower(opts.RecombinationWeights), 'equal', 3)
+                weights = ones(mu,1); % (mu_I,lambda)-CMA-ES
+            elseif strncmp(lower(opts.RecombinationWeights), 'linear', 3)
+                weights = mu+0.5-(1:mu)';
+            elseif strncmp(lower(opts.RecombinationWeights), 'superlinear', 3)
+                weights = log(mu+0.5)-log(1:mu)'; % muXone array for weighted recombination
+                                                  % qqq mu can be non-integer and
+                                                  % should become ceil(mu-0.5) (minor correction)
+            else
+                error(['Recombination weights to be "' opts.RecombinationWeights ...
+                       '" is not implemented']);
+            end
+            mueff=sum(weights)^2/sum(weights.^2); % variance-effective size of mu
+            weights = weights/sum(weights);     % normalize recombination weights array
+            if mueff == lambda
+                error(['Combination of values for PopSize, ParentNumber and ' ...
+                       ' and RecombinationWeights is not reasonable']);
+            end
+
+            % Strategy internal parameter setting: Adaptation
+            cc = myeval(opts.CMA.ccum); % time constant for cumulation for covariance matrix
+            cs = myeval(opts.CMA.cs);
+
+            % old way TODO: remove this at some point
+            % mucov = mueff;   % size of mu used for calculating learning rate ccov
+            % ccov = (1/mucov) * 2/(N+1.41)^2 ... % learning rate for covariance matrix
+            %        + (1-1/mucov) * min(1,(2*mucov-1)/((N+2)^2+mucov));
+
+            % new way
+            if myevalbool(opts.CMA.on)
+                ccov1 = myeval(opts.CMA.ccov1);
+                ccovmu = min(1-ccov1, myeval(opts.CMA.ccovmu));
+            else
+                ccov1 = 0;
+                ccovmu = 0;
+            end
+
+            % flgDiagonalOnly = -lambda*4*1/ccov; % for ccov==1 it is not needed
+            % 0 : C will never be diagonal anymore
+            % 1 : C will always be diagonal
+            % >1: C is diagonal for first iterations, set to 0 afterwards
+            if flgDiagonalOnly < 1
+                flgDiagonalOnly = 0;
+            end
+            if flgDiagonalOnly
+                ccov1_sep = min(1, ccov1 * (N+1.5) / 3);
+                ccovmu_sep = min(1-ccov1_sep, ccovmu * (N+1.5) / 3);
+            elseif N > 98 && flgdisplay && countiter == 0
+                disp('consider option DiagonalOnly for high-dimensional problems');
+            end
+
+            % ||ps|| is close to sqrt(mueff/N) for mueff large on linear fitness
+            %damps = ... % damping for step size control, usually close to one
+            %    (1 + 2*max(0,sqrt((mueff-1)/(N+1))-1)) ... % limit sigma increase
+            %    * max(0.3, ... % reduce damps, if max. iteration number is small
+            %          1 - N/min(stopMaxIter,stopMaxFunEvals/lambda)) + cs;
+            damps = myeval(opts.CMA.damps);
+            if noiseHandling
+                noiseReevals = min(myeval(opts.Noise.reevals), lambda);
+                noiseAlpha = myeval(opts.Noise.alphasigma);
+                noiseEpsilon = myeval(opts.Noise.epsilon);
+                noiseTheta = myeval(opts.Noise.theta);
+                noisecum = myeval(opts.Noise.cum);
+                noiseCutOff = myeval(opts.Noise.cutoff);  % arguably of minor relevance
+            else
+                noiseReevals = 0; % more convenient in later coding
+            end
+
+            %qqq hacking of a different parameter setting, e.g. for ccov or damps,
+            %  can be done here, but is not necessary anymore, see opts.CMA.
+            % ccov1 = 0.0*ccov1; disp(['CAVE: ccov1=' num2str(ccov1)]);
+            % ccovmu = 0.0*ccovmu; disp(['CAVE: ccovmu=' num2str(ccovmu)]);
+            % damps = inf*damps; disp(['CAVE: damps=' num2str(damps)]);
+            % cc = 1; disp(['CAVE: cc=' num2str(cc)]);
 
-    %qqq hacking of a different parameter setting, e.g. for ccov or damps,
-    %  can be done here, but is not necessary anymore, see opts.CMA. 
-    % ccov1 = 0.0*ccov1; disp(['CAVE: ccov1=' num2str(ccov1)]);
-    % ccovmu = 0.0*ccovmu; disp(['CAVE: ccovmu=' num2str(ccovmu)]);
-    % damps = inf*damps; disp(['CAVE: damps=' num2str(damps)]);
-    % cc = 1; disp(['CAVE: cc=' num2str(cc)]);
-
-  end    
-
-  % Display initial message
-  if countiter == 0 && flgdisplay 
-    if mu == 1
-      strw = '100';
-    elseif mu < 8
-      strw = [sprintf('%.0f', 100*weights(1)) ... 
-              sprintf(' %.0f', 100*weights(2:end)')];
-    else
-      strw = [sprintf('%.2g ', 100*weights(1:2)') ...
-              sprintf('%.2g', 100*weights(3)') '...' ...
-              sprintf(' %.2g', 100*weights(end-1:end)') ']%, '];      
-    end
-    if irun > 1
-      strrun = [', run ' num2str(irun)];
-    else
-      strrun = '';
-    end
-    disp(['  n=' num2str(N) ': (' num2str(mu) ',' ...
-          num2str(lambda) ')-CMA-ES(w=[' ...
-          strw ']%, ' ...
-          'mu_eff=' num2str(mueff,'%.1f') ...
-          ') on function ' ...
-          (fitfun) strrun]);
-    if flgDiagonalOnly == 1
-      disp('    C is diagonal');
-    elseif flgDiagonalOnly
-      disp(['    C is diagonal for ' num2str(floor(flgDiagonalOnly)) ' iterations']);
-    end
-  end
-
-  flush;
-
-  countiter = countiter + 1; 
-
-  % Generate and evaluate lambda offspring
- 
-  fitness.raw = repmat(NaN, 1, lambda + noiseReevals);
-
-  % parallel evaluation
-  if flgEvalParallel
-      arz = randn(N,lambda);
-
-      if ~flgDiagonalOnly
-        arx = repmat(xmean, 1, lambda) + sigma * (BD * arz); % Eq. (1)
-      else
-        arx = repmat(xmean, 1, lambda) + repmat(sigma * diagD, 1, lambda) .* arz; 
-      end
-
-      if noiseHandling 
-        if noiseEpsilon == 0
-          arx = [arx arx(:,1:noiseReevals)]; 
-        elseif flgDiagonalOnly
-          arx = [arx arx(:,1:noiseReevals) + ...
-                 repmat(noiseEpsilon * sigma * diagD, 1, noiseReevals) ...
-                 .* randn(N,noiseReevals)]; 
-        else 
-          arx = [arx arx(:,1:noiseReevals) + ...
-                 noiseEpsilon * sigma * ...
-                 (BD * randn(N,noiseReevals))]; 
-        end
-      end
-
-      % You may handle constraints here. You may either resample
-      % arz(:,k) and/or multiply it with a factor between -1 and 1
-      % (the latter will decrease the overall step size) and
-      % recalculate arx accordingly. Do not change arx or arz in any
-      % other way.
- 
-      if ~bnd.isactive
-        arxvalid = arx;
-      else
-        arxvalid = xintobounds(arx, lbounds, ubounds);
-      end
-      % You may handle constraints here.  You may copy and alter
-      % (columns of) arxvalid(:,k) only for the evaluation of the
-      % fitness function. arx and arxvalid should not be changed.
-      fitness.raw = feval(fitfun, arxvalid, varargin{:}); 
-      countevalNaN = countevalNaN + sum(isnan(fitness.raw));
-      counteval = counteval + sum(~isnan(fitness.raw)); 
-  end
-
-  % non-parallel evaluation and remaining NaN-values
-  % set also the reevaluated solution to NaN
-  fitness.raw(lambda + find(isnan(fitness.raw(1:noiseReevals)))) = NaN;  
-  for k=find(isnan(fitness.raw)), 
-    % fitness.raw(k) = NaN; 
-    tries = 0;
-    % Resample, until fitness is not NaN
-    while isnan(fitness.raw(k))
-      if k <= lambda  % regular samples (not the re-evaluation-samples)
-        arz(:,k) = randn(N,1); % (re)sample
-
-        if flgDiagonalOnly  
-          arx(:,k) = xmean + sigma * diagD .* arz(:,k);              % Eq. (1)
-        else
-          arx(:,k) = xmean + sigma * (BD * arz(:,k));                % Eq. (1)
         end
-      else % re-evaluation solution with index > lambda
-        if flgDiagonalOnly  
-          arx(:,k) = arx(:,k-lambda) + (noiseEpsilon * sigma) * diagD .* randn(N,1);
-        else
-          arx(:,k) = arx(:,k-lambda) + (noiseEpsilon * sigma) * (BD * randn(N,1));
-        end
-      end
-      
-      % You may handle constraints here. You may either resample
-      % arz(:,k) and/or multiply it with a factor between -1 and 1
-      % (the latter will decrease the overall step size) and
-      % recalculate arx accordingly. Do not change arx or arz in any
-      % other way.
- 
-      if ~bnd.isactive
-        arxvalid(:,k) = arx(:,k);
-      else
-        arxvalid(:,k) = xintobounds(arx(:,k), lbounds, ubounds);
-      end
-      % You may handle constraints here.  You may copy and alter
-      % (columns of) arxvalid(:,k) only for the evaluation of the
-      % fitness function. arx should not be changed.
-      fitness.raw(k) = feval(fitfun, arxvalid(:,k), varargin{:}); 
-      tries = tries + 1;
-      if isnan(fitness.raw(k))
-	countevalNaN = countevalNaN + 1;
-      end
-      if mod(tries, 100) == 0
-	warning([num2str(tries) ...
-                 ' NaN objective function values at evaluation ' ...
-                 num2str(counteval)]);
-      end
-    end
-    counteval = counteval + 1; % retries due to NaN are not counted
-  end
-
-  fitness.sel = fitness.raw; 
-
-  % ----- handle boundaries -----
-  if 1 < 3 && bnd.isactive
-    % Get delta fitness values
-    val = myprctile(fitness.raw, [25 75]);
-    % more precise would be exp(mean(log(diagC)))
-    val = (val(2) - val(1)) / N / mean(diagC) / sigma^2;
-    %val = (myprctile(fitness.raw, 75) - myprctile(fitness.raw, 25)) ...
-    %    / N / mean(diagC) / sigma^2;
-    % Catch non-sensible values 
-    if ~isfinite(val)
-      warning('Non-finite fitness range');
-      val = max(bnd.dfithist);  
-    elseif val == 0 % happens if all points are out of bounds
-      val = min(bnd.dfithist(bnd.dfithist>0));  % seems not to make sense, given all solutions are out of bounds
-    elseif bnd.validfitval == 0 % flag that first sensible val was found
-      bnd.dfithist = [];
-      bnd.validfitval = 1;
-    end
 
-    % Store delta fitness values
-    if length(bnd.dfithist) < 20+(3*N)/lambda
-      bnd.dfithist = [bnd.dfithist val];
-    else
-      bnd.dfithist = [bnd.dfithist(2:end) val];
-    end
-
-    [tx ti]  = xintobounds(xmean, lbounds, ubounds);
-
-    % Set initial weights
-    if bnd.iniphase 
-      if any(ti) 
-        bnd.weights(find(bnd.isbounded)) = 2.0002 * median(bnd.dfithist);
-	if bnd.flgscale == 0 % scale only initial weights then
-	  dd = diagC; 
-	  idx = find(bnd.isbounded); 
-	  dd = dd(idx) / mean(dd); %  remove mean scaling
-	  bnd.weights(idx) = bnd.weights(idx) ./ dd; 
-	end
-	if bnd.validfitval && countiter > 2
-          bnd.iniphase = 0;
-	end
-      end
-    end
-
-    % Increase weights
-    if  1 < 3 && any(ti) % any coordinate of xmean out of bounds
-      % judge distance of xmean to boundary
-      tx = xmean - tx;
-      idx = (ti ~= 0 & abs(tx) > 3*max(1,sqrt(N)/mueff) ... 
-	     * sigma*sqrt(diagC)) ;
-      % only increase if xmean is moving away
-      idx = idx & (sign(tx) == sign(xmean - xold));
-      if ~isempty(idx) % increase
-        % the factor became 1.2 instead of 1.1, because
-        % changed from max to min in version 3.52
-        bnd.weights(idx) = 1.2^(min(1, mueff/10/N)) * bnd.weights(idx); 
-      end
-    end
-
-    % Calculate scaling biased to unity, product is one
-    if bnd.flgscale ~= 0 
-      bnd.scale = exp(0.9*(log(diagC)-mean(log(diagC)))); 
-    end
+        % Display initial message
+        if countiter == 0 && flgdisplay
+            if mu == 1
+                strw = '100';
+            elseif mu < 8
+                strw = [sprintf('%.0f', 100*weights(1)) ...
+                        sprintf(' %.0f', 100*weights(2:end)')];
+            else
+                strw = [sprintf('%.2g ', 100*weights(1:2)') ...
+                        sprintf('%.2g', 100*weights(3)') '...' ...
+                        sprintf(' %.2g', 100*weights(end-1:end)') ']%, '];
+            end
+            if irun > 1
+                strrun = [', run ' num2str(irun)];
+            else
+                strrun = '';
+            end
+            disp(['  n=' num2str(N) ': (' num2str(mu) ',' ...
+                  num2str(lambda) ')-CMA-ES(w=[' ...
+                  strw ']%, ' ...
+                  'mu_eff=' num2str(mueff,'%.1f') ...
+                  ') on function ' ...
+                  (fitfun) strrun]);
+            if flgDiagonalOnly == 1
+                disp('    C is diagonal');
+            elseif flgDiagonalOnly
+                disp(['    C is diagonal for ' num2str(floor(flgDiagonalOnly)) ' iterations']);
+            end
+        end
 
-    % Assigned penalized fitness
-    bnd.arpenalty = (bnd.weights ./ bnd.scale)' * (arxvalid - arx).^2; 
-
-    fitness.sel = fitness.raw + bnd.arpenalty;
-
-  end % handle boundaries
-  % ----- end handle boundaries -----
-  
-  % compute noise measurement and reduce fitness arrays to size lambda
-  if noiseHandling 
-    [noiseS] = local_noisemeasurement(fitness.sel(1:lambda), ...
-                                      fitness.sel(lambda+(1:noiseReevals)), ...
-                                      noiseReevals, noiseTheta, noiseCutOff); 
-    if countiter == 1 % TODO: improve this very rude way of initialization
-      noiseSS = 0;
-      noiseN = 0;  % counter for mean
-    end
-    noiseSS = noiseSS + noisecum * (noiseS - noiseSS); 
-
-    % noise-handling could be done here, but the original sigma is still needed
-    % disp([noiseS noiseSS noisecum])
-
-    fitness.rawar12 = fitness.raw; % just documentary
-    fitness.selar12 = fitness.sel; % just documentary
-    % qqq refine fitness based on both values
-    if 11 < 3  % TODO: in case of outliers this mean is counterproductive 
-               % median out of three would be ok 
-      fitness.raw(1:noiseReevals) = ... % not so raw anymore
-          (fitness.raw(1:noiseReevals) + fitness.raw(lambda+(1:noiseReevals))) / 2; 
-      fitness.sel(1:noiseReevals) = ... 
-          (fitness.sel(1:noiseReevals) + fitness.sel(lambda+(1:noiseReevals))) / 2; 
-    end      
-    fitness.raw = fitness.raw(1:lambda); 
-    fitness.sel = fitness.sel(1:lambda); 
-  end
-  
-  % Sort by fitness 
-  [fitness.raw, fitness.idx] = sort(fitness.raw); 
-  [fitness.sel, fitness.idxsel] = sort(fitness.sel);  % minimization
-  fitness.hist(2:end) = fitness.hist(1:end-1);    % record short history of
-  fitness.hist(1) = fitness.raw(1);               % best fitness values
-  if length(fitness.histbest) < 120+ceil(30*N/lambda) || ...
-       (mod(countiter, 5) == 0  && length(fitness.histbest) < 2e4)  % 20 percent of 1e5 gen.
-    fitness.histbest = [fitness.raw(1) fitness.histbest];          % best fitness values
-    fitness.histmedian = [median(fitness.raw) fitness.histmedian]; % median fitness values
-  else
-    fitness.histbest(2:end) = fitness.histbest(1:end-1); 
-    fitness.histmedian(2:end) = fitness.histmedian(1:end-1); 
-    fitness.histbest(1) = fitness.raw(1);           % best fitness values
-    fitness.histmedian(1) = median(fitness.raw);    % median fitness values
-  end
-  fitness.histsel(2:end) = fitness.histsel(1:end-1); % record short history of
-  fitness.histsel(1) = fitness.sel(1);               % best sel fitness values
-
-  % Calculate new xmean, this is selection and recombination 
-  xold = xmean; % for speed up of Eq. (2) and (3)
-  xmean = arx(:,fitness.idxsel(1:mu))*weights; 
-  zmean = arz(:,fitness.idxsel(1:mu))*weights;%==D^-1*B'*(xmean-xold)/sigma
-  if mu == 1
-    fmean = fitness.sel(1);
-  else
-    fmean = NaN; % [] does not work in the latter assignment
-    % fmean = feval(fitfun, xintobounds(xmean, lbounds, ubounds), varargin{:});
-    % counteval = counteval + 1;
-  end
-  
-  % Cumulation: update evolution paths
-  ps = (1-cs)*ps + sqrt(cs*(2-cs)*mueff) * (B*zmean);          % Eq. (4)
-  hsig = norm(ps)/sqrt(1-(1-cs)^(2*countiter))/chiN < 1.4 + 2/(N+1);
-  if flg_future_setting
-    hsig = sum(ps.^2) / (1-(1-cs)^(2*countiter)) / N < 2 + 4/(N+1); % just simplified
-  end
-%  hsig = norm(ps)/sqrt(1-(1-cs)^(2*countiter))/chiN < 1.4 + 2/(N+1);
-%  hsig = norm(ps)/sqrt(1-(1-cs)^(2*countiter))/chiN < 1.5 + 1/(N-0.5);
-%  hsig = norm(ps) < 1.5 * sqrt(N);
-%  hsig = 1;
-
-  pc = (1-cc)*pc ...
-        + hsig*(sqrt(cc*(2-cc)*mueff)/sigma) * (xmean-xold);     % Eq. (2)
-  if hsig == 0
-    % disp([num2str(countiter) ' ' num2str(counteval) ' pc update stalled']);
-  end
-
-  % Adapt covariance matrix
-  neg.ccov = 0;  % TODO: move parameter setting upwards at some point
-  if ccov1 + ccovmu > 0                                                    % Eq. (3)
-    if flgDiagonalOnly % internal linear(?) complexity
-      diagC = (1-ccov1_sep-ccovmu_sep+(1-hsig)*ccov1_sep*cc*(2-cc)) * diagC ... % regard old matrix 
-          + ccov1_sep * pc.^2 ...               % plus rank one update
-          + ccovmu_sep ...                      % plus rank mu update
-            * (diagC .* (arz(:,fitness.idxsel(1:mu)).^2 * weights));
-%             * (repmat(diagC,1,mu) .* arz(:,fitness.idxsel(1:mu)).^2 * weights);
-      diagD = sqrt(diagC); % replaces eig(C)
-    else
-      arpos = (arx(:,fitness.idxsel(1:mu))-repmat(xold,1,mu)) / sigma;
-      % "active" CMA update: negative update, in case controlling pos. definiteness 
-      if flgActiveCMA > 0
-        % set parameters
-        neg.mu = mu;  
-        neg.mueff = mueff;
-        if flgActiveCMA > 10  % flat weights with mu=lambda/2
-          neg.mu = floor(lambda/2);  
-          neg.mueff = neg.mu;
+        flush;
+
+        countiter = countiter + 1;
+
+        % Generate and evaluate lambda offspring
+
+        fitness.raw = repmat(NaN, 1, lambda + noiseReevals);
+
+        % parallel evaluation
+        if flgEvalParallel
+            arz = randn(N,lambda);
+
+            if ~flgDiagonalOnly
+                arx = repmat(xmean, 1, lambda) + sigma * (BD * arz); % Eq. (1)
+            else
+                arx = repmat(xmean, 1, lambda) + repmat(sigma * diagD, 1, lambda) .* arz;
+            end
+
+            if noiseHandling
+                if noiseEpsilon == 0
+                    arx = [arx arx(:,1:noiseReevals)];
+                elseif flgDiagonalOnly
+                    arx = [arx arx(:,1:noiseReevals) + ...
+                           repmat(noiseEpsilon * sigma * diagD, 1, noiseReevals) ...
+                           .* randn(N,noiseReevals)];
+                else
+                    arx = [arx arx(:,1:noiseReevals) + ...
+                           noiseEpsilon * sigma * ...
+                           (BD * randn(N,noiseReevals))];
+                end
+            end
+
+            % You may handle constraints here. You may either resample
+            % arz(:,k) and/or multiply it with a factor between -1 and 1
+            % (the latter will decrease the overall step size) and
+            % recalculate arx accordingly. Do not change arx or arz in any
+            % other way.
+
+            if ~bnd.isactive
+                arxvalid = arx;
+            else
+                arxvalid = xintobounds(arx, lbounds, ubounds);
+            end
+            % You may handle constraints here.  You may copy and alter
+            % (columns of) arxvalid(:,k) only for the evaluation of the
+            % fitness function. arx and arxvalid should not be changed.
+            fitness.raw = feval(fitfun, arxvalid, varargin{:});
+            countevalNaN = countevalNaN + sum(isnan(fitness.raw));
+            counteval = counteval + sum(~isnan(fitness.raw));
         end
-        % neg.mu = ceil(min([N, lambda/4, mueff]));  neg.mueff = mu; % i.e. neg.mu <= N 
-        % Parameter study: in 3-D lambda=50,100, 10-D lambda=200,400, 30-D lambda=1000,2000 a 
-        % three times larger neg.ccov does not work. 
-        %   increasing all ccov rates three times does work (probably because of the factor (1-ccovmu))
-        %   in 30-D to looks fine
-
-        neg.ccov = (1 - ccovmu) * 0.25 * neg.mueff / ((N+2)^1.5 + 2*neg.mueff);
-        neg.minresidualvariance = 0.66;  % keep at least 0.66 in all directions, small popsize are most critical
-        neg.alphaold = 0.5;  % where to make up for the variance loss, 0.5 means no idea what to do
-                             % 1 is slightly more robust and gives a better "guaranty" for pos. def., 
-                             % but does it make sense from the learning perspective for large ccovmu? 
-
-        neg.ccovfinal = neg.ccov;
-
-        % prepare vectors, compute negative updating matrix Cneg and checking matrix Ccheck
-        arzneg = arz(:,fitness.idxsel(lambda:-1:lambda - neg.mu + 1));
-        % i-th longest becomes i-th shortest
-        % TODO: this is not in compliance with the paper Hansen&Ros2010, 
-        %       where simply arnorms = arnorms(end:-1:1) ? 
-        [arnorms idxnorms] = sort(sqrt(sum(arzneg.^2, 1))); 
-        [ignore idxnorms] = sort(idxnorms);  % inverse index 
-        arnormfacs = arnorms(end:-1:1) ./ arnorms; 
-        % arnormfacs = arnorms(randperm(neg.mu)) ./ arnorms;
-        arnorms = arnorms(end:-1:1); % for the record
-        if flgActiveCMA < 20
-          arzneg = arzneg .* repmat(arnormfacs(idxnorms), N, 1);  % E x*x' is N
-          % arzneg = sqrt(N) * arzneg ./ repmat(sqrt(sum(arzneg.^2, 1)), N, 1);  % E x*x' is N
+
+        % non-parallel evaluation and remaining NaN-values
+        % set also the reevaluated solution to NaN
+        fitness.raw(lambda + find(isnan(fitness.raw(1:noiseReevals)))) = NaN;
+        for k=find(isnan(fitness.raw))
+            % fitness.raw(k) = NaN;
+            tries = 0;
+            % Resample, until fitness is not NaN
+            while isnan(fitness.raw(k))
+                if k <= lambda  % regular samples (not the re-evaluation-samples)
+                    arz(:,k) = randn(N,1); % (re)sample
+
+                    if flgDiagonalOnly
+                        arx(:,k) = xmean + sigma * diagD .* arz(:,k);              % Eq. (1)
+                    else
+                        arx(:,k) = xmean + sigma * (BD * arz(:,k));                % Eq. (1)
+                    end
+                else % re-evaluation solution with index > lambda
+                    if flgDiagonalOnly
+                        arx(:,k) = arx(:,k-lambda) + (noiseEpsilon * sigma) * diagD .* randn(N,1);
+                    else
+                        arx(:,k) = arx(:,k-lambda) + (noiseEpsilon * sigma) * (BD * randn(N,1));
+                    end
+                end
+
+                % You may handle constraints here. You may either resample
+                % arz(:,k) and/or multiply it with a factor between -1 and 1
+                % (the latter will decrease the overall step size) and
+                % recalculate arx accordingly. Do not change arx or arz in any
+                % other way.
+
+                if ~bnd.isactive
+                    arxvalid(:,k) = arx(:,k);
+                else
+                    arxvalid(:,k) = xintobounds(arx(:,k), lbounds, ubounds);
+                end
+                % You may handle constraints here.  You may copy and alter
+                % (columns of) arxvalid(:,k) only for the evaluation of the
+                % fitness function. arx should not be changed.
+                fitness.raw(k) = feval(fitfun, arxvalid(:,k), varargin{:});
+                tries = tries + 1;
+                if isnan(fitness.raw(k))
+                    countevalNaN = countevalNaN + 1;
+                end
+                if mod(tries, 100) == 0
+                    warning([num2str(tries) ...
+                             ' NaN objective function values at evaluation ' ...
+                             num2str(counteval)]);
+                end
+            end
+            counteval = counteval + 1; % retries due to NaN are not counted
         end
-        if flgActiveCMA < 10 && neg.mu == mu  % weighted sum
-          if mod(flgActiveCMA, 10) == 1 % TODO: prevent this with a less tight but more efficient check (see below) 
-            Ccheck = arzneg * diag(weights) * arzneg';  % in order to check the largest EV
-          end
-          artmp = BD * arzneg;
-          Cneg = artmp * diag(weights) * artmp';
-        else  % simple sum
-          if mod(flgActiveCMA, 10) == 1
-            Ccheck = (1/neg.mu) * arzneg*arzneg';  % in order to check largest EV
-          end
-          artmp = BD * arzneg;
-          Cneg = (1/neg.mu) * artmp*artmp';
 
+        fitness.sel = fitness.raw;
+
+        % ----- handle boundaries -----
+        if 1 < 3 && bnd.isactive
+            % Get delta fitness values
+            val = myprctile(fitness.raw, [25 75]);
+            % more precise would be exp(mean(log(diagC)))
+            val = (val(2) - val(1)) / N / mean(diagC) / sigma^2;
+            %val = (myprctile(fitness.raw, 75) - myprctile(fitness.raw, 25)) ...
+            %    / N / mean(diagC) / sigma^2;
+            % Catch non-sensible values
+            if ~isfinite(val)
+                warning('Non-finite fitness range');
+                val = max(bnd.dfithist);
+            elseif val == 0 % happens if all points are out of bounds
+                val = min(bnd.dfithist(bnd.dfithist>0));  % seems not to make sense, given all solutions are out of bounds
+            elseif bnd.validfitval == 0 % flag that first sensible val was found
+                bnd.dfithist = [];
+                bnd.validfitval = 1;
+            end
+
+            % Store delta fitness values
+            if length(bnd.dfithist) < 20+(3*N)/lambda
+                bnd.dfithist = [bnd.dfithist val];
+            else
+                bnd.dfithist = [bnd.dfithist(2:end) val];
+            end
+
+            [tx, ti]  = xintobounds(xmean, lbounds, ubounds);
+
+            % Set initial weights
+            if bnd.iniphase
+                if any(ti)
+                    bnd.weights(find(bnd.isbounded)) = 2.0002 * median(bnd.dfithist);
+                    if bnd.flgscale == 0 % scale only initial weights then
+                        dd = diagC;
+                        idx = find(bnd.isbounded);
+                        dd = dd(idx) / mean(dd); %  remove mean scaling
+                        bnd.weights(idx) = bnd.weights(idx) ./ dd;
+                    end
+                    if bnd.validfitval && countiter > 2
+                        bnd.iniphase = 0;
+                    end
+                end
+            end
+
+            % Increase weights
+            if  1 < 3 && any(ti) % any coordinate of xmean out of bounds
+                                 % judge distance of xmean to boundary
+                tx = xmean - tx;
+                idx = (ti ~= 0 & abs(tx) > 3*max(1,sqrt(N)/mueff) ...
+                       * sigma*sqrt(diagC)) ;
+                % only increase if xmean is moving away
+                idx = idx & (sign(tx) == sign(xmean - xold));
+                if ~isempty(idx) % increase
+                                 % the factor became 1.2 instead of 1.1, because
+                                 % changed from max to min in version 3.52
+                    bnd.weights(idx) = 1.2^(min(1, mueff/10/N)) * bnd.weights(idx);
+                end
+            end
+
+            % Calculate scaling biased to unity, product is one
+            if bnd.flgscale ~= 0
+                bnd.scale = exp(0.9*(log(diagC)-mean(log(diagC))));
+            end
+
+            % Assigned penalized fitness
+            bnd.arpenalty = (bnd.weights ./ bnd.scale)' * (arxvalid - arx).^2;
+
+            fitness.sel = fitness.raw + bnd.arpenalty;
+
+        end % handle boundaries
+            % ----- end handle boundaries -----
+
+            % compute noise measurement and reduce fitness arrays to size lambda
+            if noiseHandling
+                [noiseS] = local_noisemeasurement(fitness.sel(1:lambda), ...
+                                                  fitness.sel(lambda+(1:noiseReevals)), ...
+                                                  noiseReevals, noiseTheta, noiseCutOff);
+                if countiter == 1 % TODO: improve this very rude way of initialization
+                    noiseSS = 0;
+                    noiseN = 0;  % counter for mean
+                end
+                noiseSS = noiseSS + noisecum * (noiseS - noiseSS);
+
+                % noise-handling could be done here, but the original sigma is still needed
+                % disp([noiseS noiseSS noisecum])
+
+                fitness.rawar12 = fitness.raw; % just documentary
+                fitness.selar12 = fitness.sel; % just documentary
+                                               % qqq refine fitness based on both values
+                if 11 < 3  % TODO: in case of outliers this mean is counterproductive
+                           % median out of three would be ok
+                    fitness.raw(1:noiseReevals) = ... % not so raw anymore
+                        (fitness.raw(1:noiseReevals) + fitness.raw(lambda+(1:noiseReevals))) / 2;
+                    fitness.sel(1:noiseReevals) = ...
+                        (fitness.sel(1:noiseReevals) + fitness.sel(lambda+(1:noiseReevals))) / 2;
+                end
+                fitness.raw = fitness.raw(1:lambda);
+                fitness.sel = fitness.sel(1:lambda);
+            end
+
+            % Sort by fitness
+            [fitness.raw, fitness.idx] = sort(fitness.raw);
+            [fitness.sel, fitness.idxsel] = sort(fitness.sel);  % minimization
+            fitness.hist(2:end) = fitness.hist(1:end-1);    % record short history of
+            fitness.hist(1) = fitness.raw(1);               % best fitness values
+            if length(fitness.histbest) < 120+ceil(30*N/lambda) || ...
+                    (mod(countiter, 5) == 0  && length(fitness.histbest) < 2e4)  % 20 percent of 1e5 gen.
+                fitness.histbest = [fitness.raw(1) fitness.histbest];          % best fitness values
+                fitness.histmedian = [median(fitness.raw) fitness.histmedian]; % median fitness values
+            else
+                fitness.histbest(2:end) = fitness.histbest(1:end-1);
+                fitness.histmedian(2:end) = fitness.histmedian(1:end-1);
+                fitness.histbest(1) = fitness.raw(1);           % best fitness values
+                fitness.histmedian(1) = median(fitness.raw);    % median fitness values
+            end
+            fitness.histsel(2:end) = fitness.histsel(1:end-1); % record short history of
+            fitness.histsel(1) = fitness.sel(1);               % best sel fitness values
+
+            % Calculate new xmean, this is selection and recombination
+            xold = xmean; % for speed up of Eq. (2) and (3)
+            xmean = arx(:,fitness.idxsel(1:mu))*weights;
+            zmean = arz(:,fitness.idxsel(1:mu))*weights;%==D^-1*B'*(xmean-xold)/sigma
+            if mu == 1
+                fmean = fitness.sel(1);
+            else
+                fmean = NaN; % [] does not work in the latter assignment
+                             % fmean = feval(fitfun, xintobounds(xmean, lbounds, ubounds), varargin{:});
+                             % counteval = counteval + 1;
+            end
+
+            % Cumulation: update evolution paths
+            ps = (1-cs)*ps + sqrt(cs*(2-cs)*mueff) * (B*zmean);          % Eq. (4)
+            hsig = norm(ps)/sqrt(1-(1-cs)^(2*countiter))/chiN < 1.4 + 2/(N+1);
+            if flg_future_setting
+                hsig = sum(ps.^2) / (1-(1-cs)^(2*countiter)) / N < 2 + 4/(N+1); % just simplified
+            end
+            %  hsig = norm(ps)/sqrt(1-(1-cs)^(2*countiter))/chiN < 1.4 + 2/(N+1);
+            %  hsig = norm(ps)/sqrt(1-(1-cs)^(2*countiter))/chiN < 1.5 + 1/(N-0.5);
+            %  hsig = norm(ps) < 1.5 * sqrt(N);
+            %  hsig = 1;
+
+            pc = (1-cc)*pc ...
+                 + hsig*(sqrt(cc*(2-cc)*mueff)/sigma) * (xmean-xold);     % Eq. (2)
+            if hsig == 0
+                % disp([num2str(countiter) ' ' num2str(counteval) ' pc update stalled']);
+            end
+
+            % Adapt covariance matrix
+            neg.ccov = 0;  % TODO: move parameter setting upwards at some point
+            if ccov1 + ccovmu > 0                                                    % Eq. (3)
+                if flgDiagonalOnly % internal linear(?) complexity
+                    diagC = (1-ccov1_sep-ccovmu_sep+(1-hsig)*ccov1_sep*cc*(2-cc)) * diagC ... % regard old matrix
+                            + ccov1_sep * pc.^2 ...               % plus rank one update
+                            + ccovmu_sep ...                      % plus rank mu update
+                            * (diagC .* (arz(:,fitness.idxsel(1:mu)).^2 * weights));
+                    %             * (repmat(diagC,1,mu) .* arz(:,fitness.idxsel(1:mu)).^2 * weights);
+                    diagD = sqrt(diagC); % replaces eig(C)
+                else
+                    arpos = (arx(:,fitness.idxsel(1:mu))-repmat(xold,1,mu)) / sigma;
+                    % "active" CMA update: negative update, in case controlling pos. definiteness
+                    if flgActiveCMA > 0
+                        % set parameters
+                        neg.mu = mu;
+                        neg.mueff = mueff;
+                        if flgActiveCMA > 10  % flat weights with mu=lambda/2
+                            neg.mu = floor(lambda/2);
+                            neg.mueff = neg.mu;
+                        end
+                        % neg.mu = ceil(min([N, lambda/4, mueff]));  neg.mueff = mu; % i.e. neg.mu <= N
+                        % Parameter study: in 3-D lambda=50,100, 10-D lambda=200,400, 30-D lambda=1000,2000 a
+                        % three times larger neg.ccov does not work.
+                        %   increasing all ccov rates three times does work (probably because of the factor (1-ccovmu))
+                        %   in 30-D to looks fine
+
+                        neg.ccov = (1 - ccovmu) * 0.25 * neg.mueff / ((N+2)^1.5 + 2*neg.mueff);
+                        neg.minresidualvariance = 0.66;  % keep at least 0.66 in all directions, small popsize are most critical
+                        neg.alphaold = 0.5;  % where to make up for the variance loss, 0.5 means no idea what to do
+                                             % 1 is slightly more robust and gives a better "guaranty" for pos. def.,
+                                             % but does it make sense from the learning perspective for large ccovmu?
+
+                        neg.ccovfinal = neg.ccov;
+
+                        % prepare vectors, compute negative updating matrix Cneg and checking matrix Ccheck
+                        arzneg = arz(:,fitness.idxsel(lambda:-1:lambda - neg.mu + 1));
+                        % i-th longest becomes i-th shortest
+                        % TODO: this is not in compliance with the paper Hansen&Ros2010,
+                        %       where simply arnorms = arnorms(end:-1:1) ?
+                        [arnorms, idxnorms] = sort(sqrt(sum(arzneg.^2, 1)));
+                        [ignore, idxnorms] = sort(idxnorms);  % inverse index
+                        arnormfacs = arnorms(end:-1:1) ./ arnorms;
+                        % arnormfacs = arnorms(randperm(neg.mu)) ./ arnorms;
+                        arnorms = arnorms(end:-1:1); % for the record
+                        if flgActiveCMA < 20
+                            arzneg = arzneg .* repmat(arnormfacs(idxnorms), N, 1);  % E x*x' is N
+                                                                                    % arzneg = sqrt(N) * arzneg ./ repmat(sqrt(sum(arzneg.^2, 1)), N, 1);  % E x*x' is N
+                        end
+                        if flgActiveCMA < 10 && neg.mu == mu  % weighted sum
+                            if mod(flgActiveCMA, 10) == 1 % TODO: prevent this with a less tight but more efficient check (see below)
+                                Ccheck = arzneg * diag(weights) * arzneg';  % in order to check the largest EV
+                            end
+                            artmp = BD * arzneg;
+                            Cneg = artmp * diag(weights) * artmp';
+                        else  % simple sum
+                            if mod(flgActiveCMA, 10) == 1
+                                Ccheck = (1/neg.mu) * arzneg*arzneg';  % in order to check largest EV
+                            end
+                            artmp = BD * arzneg;
+                            Cneg = (1/neg.mu) * artmp*artmp';
+
+                        end
+
+                        % check pos.def. and set learning rate neg.ccov accordingly,
+                        % this check makes the original choice of neg.ccov extremly failsafe
+                        % still assuming C == BD*BD', which is only approxim. correct
+                        if mod(flgActiveCMA, 10) == 1 && 1 - neg.ccov * arnorms(idxnorms).^2 * weights < neg.minresidualvariance
+                            % TODO: the simple and cheap way would be to set
+                            %    fac = 1 - ccovmu - ccov1 OR 1 - mueff/lambda and
+                            %    neg.ccov = fac*(1 - neg.minresidualvariance) / (arnorms(idxnorms).^2 * weights)
+                            % this is the more sophisticated way:
+                            % maxeigenval = eigs(arzneg * arzneg', 1, 'lm', eigsopts);  % not faster
+                            maxeigenval = max(eig(Ccheck));  % norm is much slower, because (norm()==max(svd())
+                                                             %disp([countiter log10([neg.ccov, maxeigenval, arnorms(idxnorms).^2 * weights, max(arnorms)^2]), ...
+                                                             %          neg.ccov * arnorms(idxnorms).^2 * weights])
+                                                             % pause
+                                                             % remove less than ??34*(1-cmu)%?? of variance in any direction
+                                                             %     1-ccovmu is the variance left from the old C
+                            neg.ccovfinal = min(neg.ccov, (1-ccovmu)*(1-neg.minresidualvariance)/maxeigenval);
+                            % -ccov1 removed to avoid error message??
+                            if neg.ccovfinal < neg.ccov
+                                disp(['active CMA at iteration ' num2str(countiter) ...
+                                      ': max EV ==', num2str([maxeigenval, neg.ccov, neg.ccovfinal])]);
+                            end
+                        end
+                        % xmean = xold;  % the distribution does not degenerate!?
+                        % update C
+                        C = (1-ccov1-ccovmu+neg.alphaold*neg.ccovfinal+(1-hsig)*ccov1*cc*(2-cc)) * C ... % regard old matrix
+                            + ccov1 * pc*pc' ...     % plus rank one update
+                            + (ccovmu + (1-neg.alphaold)*neg.ccovfinal) ...  % plus rank mu update
+                            * arpos * (repmat(weights,1,N) .* arpos') ...
+                            - neg.ccovfinal * Cneg;                        % minus rank mu update
+                    else  % no active (negative) update
+                        C = (1-ccov1-ccovmu+(1-hsig)*ccov1*cc*(2-cc)) * C ... % regard old matrix
+                            + ccov1 * pc*pc' ...     % plus rank one update
+                            + ccovmu ...             % plus rank mu update
+                            * arpos * (repmat(weights,1,N) .* arpos');
+                        % is now O(mu*N^2 + mu*N), was O(mu*N^2 + mu^2*N) when using diag(weights)
+                        %   for mu=30*N it is now 10 times faster, overall 3 times faster
+                    end
+                    diagC = diag(C);
+                end
+            end
+
+            % the following is de-preciated and will be removed in future
+            % better setting for cc makes this hack obsolete
+            if 11 < 2 && ~flgscience
+                % remove momentum in ps, if ps is large and fitness is getting worse.
+                % this should rarely happen.
+                % this might very well be counterproductive in dynamic environments
+                if sum(ps.^2)/N > 1.5 + 10*(2/N)^.5 && ...
+                        fitness.histsel(1) > max(fitness.histsel(2:3))
+                    ps = ps * sqrt(N*(1+max(0,log(sum(ps.^2)/N))) / sum(ps.^2));
+                    if flgdisplay
+                        disp(['Momentum in ps removed at [niter neval]=' ...
+                              num2str([countiter counteval]) ']']);
+                    end
+                end
+            end
+
+            % Adapt sigma
+            if flg_future_setting  % according to a suggestion from Dirk Arnold (2000)
+                                   % exp(1) is still not reasonably small enough
+                sigma = sigma * exp(min(1, (sum(ps.^2)/N - 1)/2 * cs/damps));            % Eq. (5)
+            else
+                % exp(1) is still not reasonably small enough
+                sigma = sigma * exp(min(1, (sqrt(sum(ps.^2))/chiN - 1) * cs/damps));             % Eq. (5)
+            end
+            % disp([countiter norm(ps)/chiN]);
+
+            if 11 < 3   % testing with optimal step-size
+                if countiter == 1
+                    disp('*********** sigma set to const * ||x|| ******************');
+                end
+                sigma = 0.04 * mueff * sqrt(sum(xmean.^2)) / N; % 20D,lam=1000:25e3
+                sigma = 0.3 * mueff * sqrt(sum(xmean.^2)) / N; % 20D,lam=(40,1000):17e3
+                                                               %      75e3 with def (1.5)
+                                                               %      35e3 with damps=0.25
+            end
+            if 11 < 3
+                if countiter == 1
+                    disp('*********** xmean set to const ******************');
+                end
+                xmean = ones(N,1);
+            end
+
+            % Update B and D from C
+
+            if ~flgDiagonalOnly && (ccov1+ccovmu+neg.ccov) > 0 && mod(countiter, 1/(ccov1+ccovmu+neg.ccov)/N/10) < 1
+                C=triu(C)+triu(C,1)'; % enforce symmetry to prevent complex numbers
+                [B,tmp] = eig(C);     % eigen decomposition, B==normalized eigenvectors
+                                      % effort: approx. 15*N matrix-vector multiplications
+                diagD = diag(tmp);
+
+                if any(~isfinite(diagD))
+                    clear idx; % prevents error under octave
+                    save(['tmp' opts.SaveFilename]);
+                    error(['function eig returned non-finited eigenvalues, cond(C)=' ...
+                           num2str(cond(C)) ]);
+                end
+                if any(any(~isfinite(B)))
+                    clear idx; % prevents error under octave
+                    save(['tmp' opts.SaveFilename]);
+                    error(['function eig returned non-finited eigenvectors, cond(C)=' ...
+                           num2str(cond(C)) ]);
+                end
+
+                % limit condition of C to 1e14 + 1
+                if min(diagD) <= 0
+                    if stopOnWarnings
+                        stopflag(end+1) = {'warnconditioncov'};
+                    else
+                        warning(['Iteration ' num2str(countiter) ...
+                                 ': Eigenvalue (smaller) zero']);
+                        diagD(diagD<0) = 0;
+                        tmp = max(diagD)/1e14;
+                        C = C + tmp*eye(N,N); diagD = diagD + tmp*ones(N,1);
+                    end
+                end
+                if max(diagD) > 1e14*min(diagD)
+                    if stopOnWarnings
+                        stopflag(end+1) = {'warnconditioncov'};
+                    else
+                        warning(['Iteration ' num2str(countiter) ': condition of C ' ...
+                                 'at upper limit' ]);
+                        tmp = max(diagD)/1e14 - min(diagD);
+                        C = C + tmp*eye(N,N); diagD = diagD + tmp*ones(N,1);
+                    end
+                end
+
+                diagC = diag(C);
+                diagD = sqrt(diagD); % D contains standard deviations now
+                                     % diagD = diagD / prod(diagD)^(1/N);  C = C / prod(diagD)^(2/N);
+                BD = B.*repmat(diagD',N,1); % O(n^2)
+            end % if mod
+
+            % Align/rescale order of magnitude of scales of sigma and C for nicer output
+            % not a very usual case
+            if 1 < 2 && sigma > 1e10*max(diagD)
+                fac = sigma / max(diagD);
+                sigma = sigma/fac;
+                pc = fac * pc;
+                diagD = fac * diagD;
+                if ~flgDiagonalOnly
+                    C = fac^2 * C; % disp(fac);
+                    BD = B.*repmat(diagD',N,1); % O(n^2), but repmat might be inefficient todo?
+                end
+                diagC = fac^2 * diagC;
+            end
+
+            if flgDiagonalOnly > 1 && countiter > flgDiagonalOnly
+                % full covariance matrix from now on
+                flgDiagonalOnly = 0;
+                B = eye(N,N);
+                BD = diag(diagD);
+                C = diag(diagC); % is better, because correlations are spurious anyway
+            end
+
+            if noiseHandling
+                if countiter == 1  % assign firstvarargin for noise treatment e.g. as #reevaluations
+                    if ~isempty(varargin) && length(varargin{1}) == 1 && isnumeric(varargin{1})
+                        if irun == 1
+                            firstvarargin = varargin{1};
+                        else
+                            varargin{1} =  firstvarargin;  % reset varargin{1}
+                        end
+                    else
+                        firstvarargin = 0;
+                    end
+                end
+                if noiseSS < 0 && noiseMinMaxEvals(2) > noiseMinMaxEvals(1) && firstvarargin
+                    varargin{1} = max(noiseMinMaxEvals(1), varargin{1} / noiseAlphaEvals^(1/4));  % still experimental
+                elseif noiseSS > 0
+                    if ~isempty(noiseCallback)  % to be removed?
+                        res = feval(noiseCallback); % should also work without output argument!?
+                        if ~isempty(res) && res > 1 % TODO: decide for interface of callback
+                                                    %       also a dynamic popsize could be done here
+                            sigma = sigma * noiseAlpha;
+                        end
+                    else
+                        if noiseMinMaxEvals(2) > noiseMinMaxEvals(1) && firstvarargin
+                            varargin{1} = min(noiseMinMaxEvals(2), varargin{1} * noiseAlphaEvals);
+                        end
+
+                        sigma = sigma * noiseAlpha;
+                        % lambda = ceil(0.1 * sqrt(lambda) + lambda);
+                        % TODO: find smallest increase of lambda with log-linear
+                        %       convergence in iterations
+                    end
+                    % qqq experimental: take a mean to estimate the true optimum
+                    noiseN = noiseN + 1;
+                    if noiseN == 1
+                        noiseX = xmean;
+                    else
+                        noiseX = noiseX + (3/noiseN) * (xmean - noiseX);
+                    end
+                end
+            end
+
+            % ----- numerical error management -----
+            % Adjust maximal coordinate axis deviations
+            if any(sigma*sqrt(diagC) > maxdx)
+                sigma = min(maxdx ./ sqrt(diagC));
+                %warning(['Iteration ' num2str(countiter) ': coordinate axis std ' ...
+                %         'deviation at upper limit of ' num2str(maxdx)]);
+                % stopflag(end+1) = {'maxcoorddev'};
+            end
+            % Adjust minimal coordinate axis deviations
+            if any(sigma*sqrt(diagC) < mindx)
+                sigma = max(mindx ./ sqrt(diagC)) * exp(0.05+cs/damps);
+                %warning(['Iteration ' num2str(countiter) ': coordinate axis std ' ...
+                %         'deviation at lower limit of ' num2str(mindx)]);
+                % stopflag(end+1) = {'mincoorddev'};;
+            end
+            % Adjust too low coordinate axis deviations
+            if any(xmean == xmean + 0.2*sigma*sqrt(diagC))
+                if stopOnWarnings
+                    stopflag(end+1) = {'warnnoeffectcoord'};
+                else
+                    warning(['Iteration ' num2str(countiter) ': coordinate axis std ' ...
+                             'deviation too low' ]);
+                    if flgDiagonalOnly
+                        diagC = diagC + (ccov1_sep+ccovmu_sep) * (diagC .* ...
+                                                                  (xmean == xmean + 0.2*sigma*sqrt(diagC)));
+                    else
+                        C = C + (ccov1+ccovmu) * diag(diagC .* ...
+                                                      (xmean == xmean + 0.2*sigma*sqrt(diagC)));
+                    end
+                    sigma = sigma * exp(0.05+cs/damps);
+                end
+            end
+            % Adjust step size in case of (numerical) precision problem
+            if flgDiagonalOnly
+                tmp = 0.1*sigma*diagD;
+            else
+                tmp = 0.1*sigma*BD(:,1+floor(mod(countiter,N)));
+            end
+            if all(xmean == xmean + tmp)
+                i = 1+floor(mod(countiter,N));
+                if stopOnWarnings
+                    stopflag(end+1) = {'warnnoeffectaxis'};
+                else
+                    warning(['Iteration ' num2str(countiter) ...
+                             ': main axis standard deviation ' ...
+                             num2str(sigma*diagD(i)) ' has no effect' ]);
+                    sigma = sigma * exp(0.2+cs/damps);
+                end
+            end
+            % Adjust step size in case of equal function values (flat fitness)
+            % isequalfuncvalues = 0;
+            if fitness.sel(1) == fitness.sel(1+ceil(0.1+lambda/4))
+                % isequalfuncvalues = 1;
+                if stopOnEqualFunctionValues
+                    arrEqualFunvals = [countiter arrEqualFunvals(1:end-1)];
+                    % stop if this happens in more than 33%
+                    if arrEqualFunvals(end) > countiter - 3 * length(arrEqualFunvals)
+                        stopflag(end+1) = {'equalfunvals'};
+                    end
+                else
+                    if flgWarnOnEqualFunctionValues
+                        warning(['Iteration ' num2str(countiter) ...
+                                 ': equal function values f=' num2str(fitness.sel(1)) ...
+                                 ' at maximal main axis sigma ' ...
+                                 num2str(sigma*max(diagD))]);
+                    end
+                    sigma = sigma * exp(0.2+cs/damps);
+                end
+            end
+            % Adjust step size in case of equal function values
+            if countiter > 2 && myrange([fitness.hist fitness.sel(1)]) == 0
+                if stopOnWarnings
+                    stopflag(end+1) = {'warnequalfunvalhist'};
+                else
+                    warning(['Iteration ' num2str(countiter) ...
+                             ': equal function values in history at maximal main ' ...
+                             'axis sigma ' num2str(sigma*max(diagD))]);
+                    sigma = sigma * exp(0.2+cs/damps);
+                end
+            end
+
+            % ----- end numerical error management -----
+
+            % Keep overall best solution
+            out.evals = counteval;
+            out.solutions.evals = counteval;
+            out.solutions.mean.x = xmean;
+            out.solutions.mean.f = fmean;
+            out.solutions.mean.evals = counteval;
+            out.solutions.recentbest.x = arxvalid(:, fitness.idx(1));
+            out.solutions.recentbest.f = fitness.raw(1);
+            out.solutions.recentbest.evals = counteval + fitness.idx(1) - lambda;
+            out.solutions.recentworst.x = arxvalid(:, fitness.idx(end));
+            out.solutions.recentworst.f = fitness.raw(end);
+            out.solutions.recentworst.evals = counteval + fitness.idx(end) - lambda;
+            if fitness.hist(1) < out.solutions.bestever.f
+                out.solutions.bestever.x = arxvalid(:, fitness.idx(1));
+                out.solutions.bestever.f = fitness.hist(1);
+                out.solutions.bestever.evals = counteval + fitness.idx(1) - lambda;
+                bestever = out.solutions.bestever;
+            end
+
+            % Set stop flag
+            if fitness.raw(1) <= stopFitness, stopflag(end+1) = {'fitness'}; end
+            if counteval >= stopMaxFunEvals, stopflag(end+1) = {'maxfunevals'}; end
+            if countiter >= stopMaxIter, stopflag(end+1) = {'maxiter'}; end
+            if all(sigma*(max(abs(pc), sqrt(diagC))) < stopTolX)
+                stopflag(end+1) = {'tolx'};
+            end
+            if any(sigma*sqrt(diagC) > stopTolUpX)
+                stopflag(end+1) = {'tolupx'};
+            end
+            if sigma*max(diagD) == 0  % should never happen
+                stopflag(end+1) = {'bug'};
+            end
+            if countiter > 2 && myrange([fitness.sel fitness.hist]) <= stopTolFun
+                stopflag(end+1) = {'tolfun'};
+            end
+            if countiter >= length(fitness.hist) && myrange(fitness.hist) <= stopTolHistFun
+                stopflag(end+1) = {'tolhistfun'};
+            end
+            l = floor(length(fitness.histbest)/3);
+            if 1 < 2 && stopOnStagnation && ...  % leads sometimes early stop on ftablet, fcigtab
+                    countiter > N * (5+100/lambda) && ...
+                    length(fitness.histbest) > 100 && ...
+                    median(fitness.histmedian(1:l)) >= median(fitness.histmedian(end-l:end)) && ...
+                    median(fitness.histbest(1:l)) >= median(fitness.histbest(end-l:end))
+                stopflag(end+1) = {'stagnation'};
+            end
+
+            if counteval >= stopFunEvals || countiter >= stopIter
+                stopflag(end+1) = {'stoptoresume'};
+                if length(stopflag) == 1 && flgsaving == 0
+                    error('To resume later the saving option needs to be set');
+                end
+            end
+            % read stopping message from file signals.par
+            if flgreadsignals
+                fid = fopen('./signals.par', 'rt');  % can be performance critical
+                while fid > 0
+                    strline = fgetl(fid); %fgets(fid, 300);
+                    if strline < 0 % fgets and fgetl returns -1 at end of file
+                        break
+                    end
+                    % 'stop filename' sets stopflag to manual
+                    str = sscanf(strline, ' %s %s', 2);
+                    if strcmp(str, ['stop' opts.LogFilenamePrefix])
+                        stopflag(end+1) = {'manual'};
+                        break
+                    end
+                    % 'skip filename run 3' skips a run, but not the last
+                    str = sscanf(strline, ' %s %s %s', 3);
+                    if strcmp(str, ['skip' opts.LogFilenamePrefix 'run'])
+                        i = strfind(strline, 'run');
+                        if irun == sscanf(strline(i+3:end), ' %d ', 1) && irun <= myeval(opts.Restarts)
+                            stopflag(end+1) = {'skipped'};
+                        end
+                    end
+                end % while, break
+                if fid > 0
+                    fclose(fid);
+                    clear fid; % prevents strange error under octave
+                end
+            end
+
+            out.stopflag = stopflag;
+
+            % ----- output generation -----
+            if verbosemodulo > 0 && isfinite(verbosemodulo)
+                if countiter == 1 || mod(countiter, 10*verbosemodulo) < 1
+                    disp(['Iterat, #Fevals:   Function Value    (median,worst) ' ...
+                          '|Axis Ratio|' ...
+                          'idx:Min SD idx:Max SD']);
+                end
+                if mod(countiter, verbosemodulo) < 1 ...
+                        || (verbosemodulo > 0 && isfinite(verbosemodulo) && ...
+                            (countiter < 3 || ~isempty(stopflag)))
+                    [minstd, minstdidx] = min(sigma*sqrt(diagC));
+                    [maxstd, maxstdidx] = max(sigma*sqrt(diagC));
+                    % format display nicely
+                    disp([repmat(' ',1,4-floor(log10(countiter))) ...
+                          num2str(countiter) ' , ' ...
+                          repmat(' ',1,5-floor(log10(counteval))) ...
+                          num2str(counteval) ' : ' ...
+                          num2str(fitness.hist(1), '%.13e') ...
+                          ' +(' num2str(median(fitness.raw)-fitness.hist(1), '%.0e ') ...
+                          ',' num2str(max(fitness.raw)-fitness.hist(1), '%.0e ') ...
+                          ') | ' ...
+                          num2str(max(diagD)/min(diagD), '%4.2e') ' | ' ...
+                          repmat(' ',1,1-floor(log10(minstdidx))) num2str(minstdidx) ':' ...
+                          num2str(minstd, ' %.1e') ' ' ...
+                          repmat(' ',1,1-floor(log10(maxstdidx))) num2str(maxstdidx) ':' ...
+                          num2str(maxstd, ' %.1e')]);
+                end
+            end
+
+            % measure time for recording data
+            if countiter < 3
+                time.c = 0.05;
+                time.nonoutput = 0;
+                time.recording = 0;
+                time.saving  = 0.15; % first saving after 3 seconds of 100 iterations
+                time.plotting = 0;
+            elseif countiter > 300
+                % set backward horizon, must be long enough to cover infrequent plotting etc
+                % time.c = min(1, time.nonoutput/3 + 1e-9);
+                time.c = max(1e-5, 0.1/sqrt(countiter)); % mean over all or 1e-5
+            end
+            % get average time per iteration
+            time.t1 = clock;
+            time.act = max(0,etime(time.t1, time.t0));
+            time.nonoutput = (1-time.c) * time.nonoutput ...
+                + time.c * time.act;
+
+            time.recording = (1-time.c) * time.recording;  % per iteration
+            time.saving  = (1-time.c) * time.saving;
+            time.plotting = (1-time.c) * time.plotting;
+
+            % record output data, concerning time issues
+            if savemodulo && savetime && (countiter < 1e2 || ~isempty(stopflag) || ...
+                                          countiter >= outiter + savemodulo)
+                outiter = countiter;
+                % Save output data to files
+                for namecell = filenames(:)'
+                    name = namecell{:};
+
+                    [fid, err] = fopen(['./' filenameprefix name '.dat'], 'a');
+                    if fid < 1 % err ~= 0
+                        warning(['could not open ' filenameprefix name '.dat']);
+                    else
+                        if strcmp(name, 'axlen')
+                            fprintf(fid, '%d %d %e %e %e ', countiter, counteval, sigma, ...
+                                    max(diagD), min(diagD));
+                            fprintf(fid, '%e ', sort(diagD));
+                            fprintf(fid, '\n');
+                        elseif strcmp(name, 'disp') % TODO
+                        elseif strcmp(name, 'fit')
+                            fprintf(fid, '%ld %ld %e %e %25.18e %25.18e %25.18e %25.18e', ...
+                                    countiter, counteval, sigma, max(diagD)/min(diagD), ...
+                                    out.solutions.bestever.f, ...
+                                    fitness.raw(1), median(fitness.raw), fitness.raw(end));
+                            if ~isempty(varargin) && length(varargin{1}) == 1 && isnumeric(varargin{1}) && varargin{1} ~= 0
+                                fprintf(fid, ' %f', varargin{1});
+                            end
+                            fprintf(fid, '\n');
+                        elseif strcmp(name, 'stddev')
+                            fprintf(fid, '%ld %ld %e 0 0 ', countiter, counteval, sigma);
+                            fprintf(fid, '%e ', sigma*sqrt(diagC));
+                            fprintf(fid, '\n');
+                        elseif strcmp(name, 'xmean')
+                            if isnan(fmean)
+                                fprintf(fid, '%ld %ld 0 0 0 ', countiter, counteval);
+                            else
+                                fprintf(fid, '%ld %ld 0 0 %e ', countiter, counteval, fmean);
+                            end
+                            fprintf(fid, '%e ', xmean);
+                            fprintf(fid, '\n');
+                        elseif strcmp(name, 'xrecentbest')
+                            % TODO: fitness is inconsistent with x-value
+                            fprintf(fid, '%ld %ld %25.18e 0 0 ', countiter, counteval, fitness.raw(1));
+                            fprintf(fid, '%e ', arx(:,fitness.idx(1)));
+                            fprintf(fid, '\n');
+                        end
+                        fclose(fid);
+                    end
+                end
+
+                % get average time for recording data
+                time.t2 = clock;
+                time.recording = time.recording + time.c * max(0,etime(time.t2, time.t1));
+
+                % plot
+                if flgplotting && countiter > 1
+                    if countiter == 2
+                        iterplotted = 0;
+                    end
+                    if ~isempty(stopflag) || ...
+                            ((time.nonoutput+time.recording) * (countiter - iterplotted) > 1 && ...
+                             time.plotting < 0.05 * (time.nonoutput+time.recording))
+                        local_plotcmaesdat(324, filenameprefix);
+                        iterplotted = countiter;
+                        %  outplot(out); % outplot defined below
+                        if time.plotting == 0  % disregard opening of the window
+                            time.plotting = time.nonoutput+time.recording;
+                        else
+                            time.plotting = time.plotting + time.c * max(0,etime(clock, time.t2));
+                        end
+                    end
+                end
+                if countiter > 100 + 20 && savemodulo && ...
+                        time.recording * countiter > 0.1 && ...  % absolute time larger 0.1 second
+                        time.recording > savetime * (time.nonoutput+time.recording) / 100
+                    savemodulo = floor(1.1 * savemodulo) + 1;
+                    % disp('++savemodulo'); %qqq
+                end
+            end % if output
+
+            % save everything
+            time.t3 = clock;
+            if ~isempty(stopflag) || time.saving < 0.05 * time.nonoutput || countiter == 100
+                xmin = arxvalid(:, fitness.idx(1));
+                fmin = fitness.raw(1);
+                if flgsaving && countiter > 2
+                    clear idx; % prevents error under octave
+                               % -v6 : non-compressed non-unicode for version 6 and earlier
+                    if ~isempty(strsaving) && ~isoctave
+                        save('-mat', strsaving, opts.SaveFilename); % for inspection and possible restart
+                    else
+                        save('-mat', opts.SaveFilename); % for inspection and possible restart
+                    end
+                    time.saving = time.saving + time.c * max(0,etime(clock, time.t3));
+                end
+            end
+            time.t0 = clock;
+
+            % ----- end output generation -----
+
+    end % while, end generation loop
+
+        % -------------------- Final Procedures -------------------------------
+
+        % Evaluate xmean and return best recent point in xmin
+        fmin = fitness.raw(1);
+        xmin = arxvalid(:, fitness.idx(1)); % Return best point of last generation.
+        if length(stopflag) > sum(strcmp(stopflag, 'stoptoresume')) % final stopping
+            out.solutions.mean.f = ...
+                feval(fitfun, xintobounds(xmean, lbounds, ubounds), varargin{:});
+            counteval = counteval + 1;
+            out.solutions.mean.evals = counteval;
+            if out.solutions.mean.f < fitness.raw(1)
+                fmin = out.solutions.mean.f;
+                xmin = xintobounds(xmean, lbounds, ubounds); % Return xmean as best point
+            end
+            if out.solutions.mean.f < out.solutions.bestever.f
+                out.solutions.bestever = out.solutions.mean; % Return xmean as bestever point
+                out.solutions.bestever.x = xintobounds(xmean, lbounds, ubounds);
+                bestever = out.solutions.bestever;
+            end
         end
 
-        % check pos.def. and set learning rate neg.ccov accordingly, 
-        % this check makes the original choice of neg.ccov extremly failsafe 
-        % still assuming C == BD*BD', which is only approxim. correct 
-        if mod(flgActiveCMA, 10) == 1 && 1 - neg.ccov * arnorms(idxnorms).^2 * weights < neg.minresidualvariance
-          % TODO: the simple and cheap way would be to set
-          %    fac = 1 - ccovmu - ccov1 OR 1 - mueff/lambda and
-          %    neg.ccov = fac*(1 - neg.minresidualvariance) / (arnorms(idxnorms).^2 * weights)
-          % this is the more sophisticated way: 
-          % maxeigenval = eigs(arzneg * arzneg', 1, 'lm', eigsopts);  % not faster
-          maxeigenval = max(eig(Ccheck));  % norm is much slower, because (norm()==max(svd())
-          %disp([countiter log10([neg.ccov, maxeigenval, arnorms(idxnorms).^2 * weights, max(arnorms)^2]), ...
-           %          neg.ccov * arnorms(idxnorms).^2 * weights])
-          % pause
-          % remove less than ??34*(1-cmu)%?? of variance in any direction
-          %     1-ccovmu is the variance left from the old C
-          neg.ccovfinal = min(neg.ccov, (1-ccovmu)*(1-neg.minresidualvariance)/maxeigenval); 
-                                        % -ccov1 removed to avoid error message??
-          if neg.ccovfinal < neg.ccov
-            disp(['active CMA at iteration ' num2str(countiter) ...
-                 ': max EV ==', num2str([maxeigenval, neg.ccov, neg.ccovfinal])]);
-          end
+        % Save everything and display final message
+        if flgsavingfinal
+            clear idx; % prevents error under octave
+            if ~isempty(strsaving) && ~isoctave
+                save('-mat', strsaving, opts.SaveFilename); % for inspection and possible restart
+            else
+                save('-mat', opts.SaveFilename);    % for inspection and possible restart
+            end
+            message = [' (saved to ' opts.SaveFilename ')'];
+        else
+            message = [];
         end
-        % xmean = xold;  % the distribution does not degenerate!? 
-        % update C
-        C = (1-ccov1-ccovmu+neg.alphaold*neg.ccovfinal+(1-hsig)*ccov1*cc*(2-cc)) * C ... % regard old matrix 
-            + ccov1 * pc*pc' ...     % plus rank one update
-            + (ccovmu + (1-neg.alphaold)*neg.ccovfinal) ...  % plus rank mu update
-              * arpos * (repmat(weights,1,N) .* arpos') ...
-              - neg.ccovfinal * Cneg;                        % minus rank mu update
-      else  % no active (negative) update
-        C = (1-ccov1-ccovmu+(1-hsig)*ccov1*cc*(2-cc)) * C ... % regard old matrix 
-            + ccov1 * pc*pc' ...     % plus rank one update
-            + ccovmu ...             % plus rank mu update
-              * arpos * (repmat(weights,1,N) .* arpos');
-        % is now O(mu*N^2 + mu*N), was O(mu*N^2 + mu^2*N) when using diag(weights)
-        %   for mu=30*N it is now 10 times faster, overall 3 times faster
-      end
-      diagC = diag(C);
-    end
-  end
-  
-  % the following is de-preciated and will be removed in future
-  % better setting for cc makes this hack obsolete
-  if 11 < 2 && ~flgscience  
-    % remove momentum in ps, if ps is large and fitness is getting worse.
-    % this should rarely happen. 
-    % this might very well be counterproductive in dynamic environments
-    if sum(ps.^2)/N > 1.5 + 10*(2/N)^.5 && ...
-        fitness.histsel(1) > max(fitness.histsel(2:3))
-      ps = ps * sqrt(N*(1+max(0,log(sum(ps.^2)/N))) / sum(ps.^2));
-      if flgdisplay
-        disp(['Momentum in ps removed at [niter neval]=' ...
-              num2str([countiter counteval]) ']']);
-      end
-    end
-  end
-
-  % Adapt sigma
-  if flg_future_setting  % according to a suggestion from Dirk Arnold (2000)
-    % exp(1) is still not reasonably small enough
-    sigma = sigma * exp(min(1, (sum(ps.^2)/N - 1)/2 * cs/damps));            % Eq. (5)
-  else
-    % exp(1) is still not reasonably small enough
-    sigma = sigma * exp(min(1, (sqrt(sum(ps.^2))/chiN - 1) * cs/damps));             % Eq. (5)
-  end
-  % disp([countiter norm(ps)/chiN]);
-  
-  if 11 < 3   % testing with optimal step-size
-      if countiter == 1
-          disp('*********** sigma set to const * ||x|| ******************');
-      end
-      sigma = 0.04 * mueff * sqrt(sum(xmean.^2)) / N; % 20D,lam=1000:25e3
-      sigma = 0.3 * mueff * sqrt(sum(xmean.^2)) / N; % 20D,lam=(40,1000):17e3
-                                                     %      75e3 with def (1.5)
-                                                     %      35e3 with damps=0.25
-  end
-  if 11 < 3 
-          if countiter == 1
-              disp('*********** xmean set to const ******************');
-          end
-      xmean = ones(N,1);
-  end
-  
-  % Update B and D from C
-
-  if ~flgDiagonalOnly && (ccov1+ccovmu+neg.ccov) > 0 && mod(countiter, 1/(ccov1+ccovmu+neg.ccov)/N/10) < 1
-    C=triu(C)+triu(C,1)'; % enforce symmetry to prevent complex numbers
-    [B,tmp] = eig(C);     % eigen decomposition, B==normalized eigenvectors
-                          % effort: approx. 15*N matrix-vector multiplications
-    diagD = diag(tmp); 
-
-    if any(~isfinite(diagD))
-      clear idx; % prevents error under octave 
-      save(['tmp' opts.SaveFilename]);
-      error(['function eig returned non-finited eigenvalues, cond(C)=' ...
-	     num2str(cond(C)) ]);
-    end
-    if any(any(~isfinite(B)))
-      clear idx; % prevents error under octave
-      save(['tmp' opts.SaveFilename]);
-      error(['function eig returned non-finited eigenvectors, cond(C)=' ...
-	     num2str(cond(C)) ]);
-    end
 
-    % limit condition of C to 1e14 + 1
-    if min(diagD) <= 0
-	if stopOnWarnings
-	  stopflag(end+1) = {'warnconditioncov'};
-	else
-	  warning(['Iteration ' num2str(countiter) ...
-		   ': Eigenvalue (smaller) zero']);
-	  diagD(diagD<0) = 0;
-	  tmp = max(diagD)/1e14;
-	  C = C + tmp*eye(N,N); diagD = diagD + tmp*ones(N,1); 
-	end
-    end
-    if max(diagD) > 1e14*min(diagD) 
-	if stopOnWarnings
-	  stopflag(end+1) = {'warnconditioncov'};
-	else
-	  warning(['Iteration ' num2str(countiter) ': condition of C ' ...
-		   'at upper limit' ]);
-	  tmp = max(diagD)/1e14 - min(diagD);
-	  C = C + tmp*eye(N,N); diagD = diagD + tmp*ones(N,1); 
-	end
-    end
+        if flgdisplay
+            disp(['#Fevals:   f(returned x)   |    bestever.f     | stopflag' ...
+                  message]);
+            if isoctave
+                strstop = stopflag(:);
+            else
+                strcat(stopflag(:), '.');
+            end
+            strstop = stopflag(:); %strcat(stopflag(:), '.');
+            disp([repmat(' ',1,6-floor(log10(counteval))) ...
+                  num2str(counteval, '%6.0f') ': ' num2str(fmin, '%.11e') ' | ' ...
+                  num2str(out.solutions.bestever.f, '%.11e') ' | ' ...
+                  strstop{1:end}]);
+            if N < 102
+                disp(['mean solution:' sprintf(' %+.1e', xmean)]);
+                disp(['std deviation:' sprintf('  %.1e', sigma*sqrt(diagC))]);
+                disp(sprintf('use plotcmaesdat.m for plotting the output at any time (option LogModulo must not be zero)'));
+            end
+            if exist('sfile', 'var')
+                disp(['Results saved in ' sfile]);
+            end
+        end
 
-    diagC = diag(C); 
-    diagD = sqrt(diagD); % D contains standard deviations now
-    % diagD = diagD / prod(diagD)^(1/N);  C = C / prod(diagD)^(2/N);
-    BD = B.*repmat(diagD',N,1); % O(n^2)
-  end % if mod
-
-  % Align/rescale order of magnitude of scales of sigma and C for nicer output
-  % not a very usual case
-  if 1 < 2 && sigma > 1e10*max(diagD)
-    fac = sigma / max(diagD);
-    sigma = sigma/fac;
-    pc = fac * pc;
-    diagD = fac * diagD; 
-    if ~flgDiagonalOnly
-      C = fac^2 * C; % disp(fac);
-      BD = B.*repmat(diagD',N,1); % O(n^2), but repmat might be inefficient todo?
-    end
-    diagC = fac^2 * diagC; 
-  end
-
-  if flgDiagonalOnly > 1 && countiter > flgDiagonalOnly 
-    % full covariance matrix from now on 
-    flgDiagonalOnly = 0; 
-    B = eye(N,N);
-    BD = diag(diagD);
-    C = diag(diagC); % is better, because correlations are spurious anyway
-  end
-
-  if noiseHandling 
-   if countiter == 1  % assign firstvarargin for noise treatment e.g. as #reevaluations
-     if ~isempty(varargin) && length(varargin{1}) == 1 && isnumeric(varargin{1})
-       if irun == 1
-         firstvarargin = varargin{1};
-       else
-         varargin{1} =  firstvarargin;  % reset varargin{1}
-       end
-     else
-       firstvarargin = 0;
-     end
-   end
-   if noiseSS < 0 && noiseMinMaxEvals(2) > noiseMinMaxEvals(1) && firstvarargin
-     varargin{1} = max(noiseMinMaxEvals(1), varargin{1} / noiseAlphaEvals^(1/4));  % still experimental
-   elseif noiseSS > 0
-    if ~isempty(noiseCallback)  % to be removed? 
-      res = feval(noiseCallback); % should also work without output argument!?
-      if ~isempty(res) && res > 1 % TODO: decide for interface of callback
-                                  %       also a dynamic popsize could be done here 
-        sigma = sigma * noiseAlpha;
-      end
-    else
-      if noiseMinMaxEvals(2) > noiseMinMaxEvals(1) && firstvarargin
-        varargin{1} = min(noiseMinMaxEvals(2), varargin{1} * noiseAlphaEvals);
-      end
-    
-      sigma = sigma * noiseAlpha; 
-      % lambda = ceil(0.1 * sqrt(lambda) + lambda);
-      % TODO: find smallest increase of lambda with log-linear
-      %       convergence in iterations
-    end
-    % qqq experimental: take a mean to estimate the true optimum
-    noiseN = noiseN + 1;
-    if noiseN == 1
-      noiseX = xmean; 
-    else
-      noiseX = noiseX + (3/noiseN) * (xmean - noiseX); 
-    end
-   end
-  end
-
-  % ----- numerical error management -----
-  % Adjust maximal coordinate axis deviations
-  if any(sigma*sqrt(diagC) > maxdx)
-    sigma = min(maxdx ./ sqrt(diagC));
-    %warning(['Iteration ' num2str(countiter) ': coordinate axis std ' ...
-    %         'deviation at upper limit of ' num2str(maxdx)]);
-    % stopflag(end+1) = {'maxcoorddev'};
-  end
-  % Adjust minimal coordinate axis deviations
-  if any(sigma*sqrt(diagC) < mindx)
-    sigma = max(mindx ./ sqrt(diagC)) * exp(0.05+cs/damps); 
-    %warning(['Iteration ' num2str(countiter) ': coordinate axis std ' ...
-    %         'deviation at lower limit of ' num2str(mindx)]);
-    % stopflag(end+1) = {'mincoorddev'};;
-  end
-  % Adjust too low coordinate axis deviations
-  if any(xmean == xmean + 0.2*sigma*sqrt(diagC)) 
-    if stopOnWarnings
-      stopflag(end+1) = {'warnnoeffectcoord'};
-    else
-      warning(['Iteration ' num2str(countiter) ': coordinate axis std ' ...
-                'deviation too low' ]);
-      if flgDiagonalOnly
-        diagC = diagC + (ccov1_sep+ccovmu_sep) * (diagC .* ...
-                                                  (xmean == xmean + 0.2*sigma*sqrt(diagC)));
-      else
-        C = C + (ccov1+ccovmu) * diag(diagC .* ...
-                                      (xmean == xmean + 0.2*sigma*sqrt(diagC)));
-      end
-      sigma = sigma * exp(0.05+cs/damps); 
-    end
-  end
-  % Adjust step size in case of (numerical) precision problem 
-  if flgDiagonalOnly
-    tmp = 0.1*sigma*diagD; 
-  else
-    tmp = 0.1*sigma*BD(:,1+floor(mod(countiter,N)));
-  end
-  if all(xmean == xmean + tmp)
-    i = 1+floor(mod(countiter,N));
-    if stopOnWarnings
-	stopflag(end+1) = {'warnnoeffectaxis'};
-    else
-      warning(['Iteration ' num2str(countiter) ...
-	       ': main axis standard deviation ' ...
-	       num2str(sigma*diagD(i)) ' has no effect' ]);
-	sigma = sigma * exp(0.2+cs/damps); 
-    end
-  end
-  % Adjust step size in case of equal function values (flat fitness)
-  % isequalfuncvalues = 0; 
-  if fitness.sel(1) == fitness.sel(1+ceil(0.1+lambda/4))
-    % isequalfuncvalues = 1; 
-    if stopOnEqualFunctionValues
-      arrEqualFunvals = [countiter arrEqualFunvals(1:end-1)];
-      % stop if this happens in more than 33%
-      if arrEqualFunvals(end) > countiter - 3 * length(arrEqualFunvals)
-        stopflag(end+1) = {'equalfunvals'}; 
-      end
-    else
-      if flgWarnOnEqualFunctionValues
-        warning(['Iteration ' num2str(countiter) ...
-		 ': equal function values f=' num2str(fitness.sel(1)) ...
-		 ' at maximal main axis sigma ' ...
-        num2str(sigma*max(diagD))]);
-      end
-      sigma = sigma * exp(0.2+cs/damps); 
-    end
-  end
-  % Adjust step size in case of equal function values
-  if countiter > 2 && myrange([fitness.hist fitness.sel(1)]) == 0  
-    if stopOnWarnings
-	stopflag(end+1) = {'warnequalfunvalhist'};
-    else
-      warning(['Iteration ' num2str(countiter) ...
-	       ': equal function values in history at maximal main ' ...
-	       'axis sigma ' num2str(sigma*max(diagD))]);
-	sigma = sigma * exp(0.2+cs/damps); 
-    end
-  end
-    
-  % ----- end numerical error management -----
-  
-  % Keep overall best solution
-  out.evals = counteval;
-  out.solutions.evals = counteval;
-  out.solutions.mean.x = xmean;
-  out.solutions.mean.f = fmean;
-  out.solutions.mean.evals = counteval;
-  out.solutions.recentbest.x = arxvalid(:, fitness.idx(1));
-  out.solutions.recentbest.f = fitness.raw(1);
-  out.solutions.recentbest.evals = counteval + fitness.idx(1) - lambda;
-  out.solutions.recentworst.x = arxvalid(:, fitness.idx(end));
-  out.solutions.recentworst.f = fitness.raw(end);
-  out.solutions.recentworst.evals = counteval + fitness.idx(end) - lambda;
-  if fitness.hist(1) < out.solutions.bestever.f
-    out.solutions.bestever.x = arxvalid(:, fitness.idx(1));
-    out.solutions.bestever.f = fitness.hist(1);
-    out.solutions.bestever.evals = counteval + fitness.idx(1) - lambda;
-    bestever = out.solutions.bestever;
-  end
-
-  % Set stop flag
-  if fitness.raw(1) <= stopFitness, stopflag(end+1) = {'fitness'}; end
-  if counteval >= stopMaxFunEvals, stopflag(end+1) = {'maxfunevals'}; end
-  if countiter >= stopMaxIter, stopflag(end+1) = {'maxiter'}; end
-  if all(sigma*(max(abs(pc), sqrt(diagC))) < stopTolX) 
-    stopflag(end+1) = {'tolx'};
-  end
-  if any(sigma*sqrt(diagC) > stopTolUpX) 
-    stopflag(end+1) = {'tolupx'};
-  end
-  if sigma*max(diagD) == 0  % should never happen
-    stopflag(end+1) = {'bug'};
-  end
-  if countiter > 2 && myrange([fitness.sel fitness.hist]) <= stopTolFun 
-    stopflag(end+1) = {'tolfun'};
-  end
-  if countiter >= length(fitness.hist) && myrange(fitness.hist) <= stopTolHistFun 
-    stopflag(end+1) = {'tolhistfun'};
-  end
-  l = floor(length(fitness.histbest)/3);
-  if 1 < 2 && stopOnStagnation && ...  % leads sometimes early stop on ftablet, fcigtab
-      countiter > N * (5+100/lambda) && ...  
-      length(fitness.histbest) > 100 && ... 
-      median(fitness.histmedian(1:l)) >= median(fitness.histmedian(end-l:end)) && ...
-      median(fitness.histbest(1:l)) >= median(fitness.histbest(end-l:end))
-    stopflag(end+1) = {'stagnation'};
-  end
-
-  if counteval >= stopFunEvals || countiter >= stopIter
-    stopflag(end+1) = {'stoptoresume'};
-    if length(stopflag) == 1 && flgsaving == 0
-      error('To resume later the saving option needs to be set');
-    end
-  end
-  % read stopping message from file signals.par 
-  if flgreadsignals
-    fid = fopen('./signals.par', 'rt');  % can be performance critical 
-    while fid > 0
-      strline = fgetl(fid); %fgets(fid, 300);
-      if strline < 0 % fgets and fgetl returns -1 at end of file
-        break;
-      end
-      % 'stop filename' sets stopflag to manual
-      str = sscanf(strline, ' %s %s', 2);
-      if strcmp(str, ['stop' opts.LogFilenamePrefix]) 
-        stopflag(end+1) = {'manual'};
-        break;
-      end
-      % 'skip filename run 3' skips a run, but not the last
-      str = sscanf(strline, ' %s %s %s', 3);
-      if strcmp(str, ['skip' opts.LogFilenamePrefix 'run'])
-        i = strfind(strline, 'run');
-        if irun == sscanf(strline(i+3:end), ' %d ', 1) && irun <= myeval(opts.Restarts)
-          stopflag(end+1) = {'skipped'};
-        end      
-      end
-    end % while, break 
-    if fid > 0
-      fclose(fid);
-      clear fid; % prevents strange error under octave
-    end
-  end
-  
-  out.stopflag = stopflag;
-
-  % ----- output generation -----
-  if verbosemodulo > 0 && isfinite(verbosemodulo)
-    if countiter == 1 || mod(countiter, 10*verbosemodulo) < 1 
-      disp(['Iterat, #Fevals:   Function Value    (median,worst) ' ...
-	    '|Axis Ratio|' ...
-	    'idx:Min SD idx:Max SD']); 
-    end
-    if mod(countiter, verbosemodulo) < 1 ...
-	  || (verbosemodulo > 0 && isfinite(verbosemodulo) && ...
-	      (countiter < 3 || ~isempty(stopflag)))
-      [minstd minstdidx] = min(sigma*sqrt(diagC));
-      [maxstd maxstdidx] = max(sigma*sqrt(diagC));
-      % format display nicely
-      disp([repmat(' ',1,4-floor(log10(countiter))) ...
-	    num2str(countiter) ' , ' ...
-	    repmat(' ',1,5-floor(log10(counteval))) ...
-	    num2str(counteval) ' : ' ...
-            num2str(fitness.hist(1), '%.13e') ...
-	    ' +(' num2str(median(fitness.raw)-fitness.hist(1), '%.0e ') ...
-	    ',' num2str(max(fitness.raw)-fitness.hist(1), '%.0e ') ...
-	    ') | ' ...
-	    num2str(max(diagD)/min(diagD), '%4.2e') ' | ' ...
-	    repmat(' ',1,1-floor(log10(minstdidx))) num2str(minstdidx) ':' ...
-	    num2str(minstd, ' %.1e') ' ' ...
-	    repmat(' ',1,1-floor(log10(maxstdidx))) num2str(maxstdidx) ':' ...
-	    num2str(maxstd, ' %.1e')]);
-    end
-  end
-
-  % measure time for recording data
-  if countiter < 3 
-    time.c = 0.05;
-    time.nonoutput = 0;
-    time.recording = 0;
-    time.saving  = 0.15; % first saving after 3 seconds of 100 iterations
-    time.plotting = 0;
-  elseif countiter > 300
-    % set backward horizon, must be long enough to cover infrequent plotting etc
-    % time.c = min(1, time.nonoutput/3 + 1e-9); 
-    time.c = max(1e-5, 0.1/sqrt(countiter)); % mean over all or 1e-5
-  end
-  % get average time per iteration
-  time.t1 = clock;
-  time.act = max(0,etime(time.t1, time.t0));
-  time.nonoutput = (1-time.c) * time.nonoutput ...
-      + time.c * time.act; 
-
-  time.recording = (1-time.c) * time.recording;  % per iteration
-  time.saving  = (1-time.c) * time.saving;
-  time.plotting = (1-time.c) * time.plotting;
-  
-  % record output data, concerning time issues
-  if savemodulo && savetime && (countiter < 1e2 || ~isempty(stopflag) || ...
-	countiter >= outiter + savemodulo)
-    outiter = countiter; 
-      % Save output data to files  
-      for namecell = filenames(:)'
-        name = namecell{:};
-
-	[fid, err] = fopen(['./' filenameprefix name '.dat'], 'a');
-	if fid < 1 % err ~= 0 
-	  warning(['could not open ' filenameprefix name '.dat']);
-	else
-	  if strcmp(name, 'axlen')
-	    fprintf(fid, '%d %d %e %e %e ', countiter, counteval, sigma, ...
-		max(diagD), min(diagD)); 
-            fprintf(fid, '%e ', sort(diagD)); 
-            fprintf(fid, '\n');
-	  elseif strcmp(name, 'disp') % TODO
-	  elseif strcmp(name, 'fit')
-	    fprintf(fid, '%ld %ld %e %e %25.18e %25.18e %25.18e %25.18e', ...
-                    countiter, counteval, sigma, max(diagD)/min(diagD), ...
-                    out.solutions.bestever.f, ...
-                    fitness.raw(1), median(fitness.raw), fitness.raw(end)); 
-            if ~isempty(varargin) && length(varargin{1}) == 1 && isnumeric(varargin{1}) && varargin{1} ~= 0
-              fprintf(fid, ' %f', varargin{1});
-            end                    
-	    fprintf(fid, '\n');
-	  elseif strcmp(name, 'stddev')
-	    fprintf(fid, '%ld %ld %e 0 0 ', countiter, counteval, sigma); 
-	    fprintf(fid, '%e ', sigma*sqrt(diagC)); 
-            fprintf(fid, '\n');
-	  elseif strcmp(name, 'xmean')
-	    if isnan(fmean)
-	      fprintf(fid, '%ld %ld 0 0 0 ', countiter, counteval); 
-	    else
-	      fprintf(fid, '%ld %ld 0 0 %e ', countiter, counteval, fmean); 
-	    end
-	    fprintf(fid, '%e ', xmean); 
-            fprintf(fid, '\n');
-	  elseif strcmp(name, 'xrecentbest')
-            % TODO: fitness is inconsistent with x-value
-	    fprintf(fid, '%ld %ld %25.18e 0 0 ', countiter, counteval, fitness.raw(1)); 
-	    fprintf(fid, '%e ', arx(:,fitness.idx(1))); 
-            fprintf(fid, '\n');
-	  end
-	  fclose(fid); 
-	end
-      end
-
-    % get average time for recording data
-    time.t2 = clock;
-    time.recording = time.recording + time.c * max(0,etime(time.t2, time.t1)); 
-    
-    % plot
-    if flgplotting && countiter > 1
-      if countiter == 2
-        iterplotted = 0;
-      end
-      if ~isempty(stopflag) || ... 
-        ((time.nonoutput+time.recording) * (countiter - iterplotted) > 1 && ...
-          time.plotting < 0.05 * (time.nonoutput+time.recording))
-        local_plotcmaesdat(324, filenameprefix);
-        iterplotted = countiter;  
-        %  outplot(out); % outplot defined below
-        if time.plotting == 0  % disregard opening of the window
-          time.plotting = time.nonoutput+time.recording;
-        else
-          time.plotting = time.plotting + time.c * max(0,etime(clock, time.t2)); 
+        out.arstopflags{irun} = stopflag;
+        if any(strcmp(stopflag, 'fitness')) ...
+                || any(strcmp(stopflag, 'maxfunevals')) ...
+                || any(strcmp(stopflag, 'stoptoresume')) ...
+                || any(strcmp(stopflag, 'manual'))
+            break
         end
-      end
-    end
-    if countiter > 100 + 20 && savemodulo && ...
-          time.recording * countiter > 0.1 && ...  % absolute time larger 0.1 second
-	  time.recording > savetime * (time.nonoutput+time.recording) / 100 
-      savemodulo = floor(1.1 * savemodulo) + 1;
-      % disp('++savemodulo'); %qqq
-    end
-  end % if output
-
-  % save everything
-  time.t3 = clock;
-  if ~isempty(stopflag) || time.saving < 0.05 * time.nonoutput || countiter == 100
-    xmin = arxvalid(:, fitness.idx(1));
-    fmin = fitness.raw(1);
-    if flgsaving && countiter > 2
-      clear idx; % prevents error under octave
-      % -v6 : non-compressed non-unicode for version 6 and earlier
-      if ~isempty(strsaving) && ~isoctave
-	save('-mat', strsaving, opts.SaveFilename); % for inspection and possible restart	
-      else 
-	save('-mat', opts.SaveFilename); % for inspection and possible restart
-      end
-      time.saving = time.saving + time.c * max(0,etime(clock, time.t3)); 
-    end
-  end
-  time.t0 = clock;
-
-  % ----- end output generation -----
-
-end % while, end generation loop
-
-% -------------------- Final Procedures -------------------------------
-
-% Evaluate xmean and return best recent point in xmin
-fmin = fitness.raw(1);
-xmin = arxvalid(:, fitness.idx(1)); % Return best point of last generation.
-if length(stopflag) > sum(strcmp(stopflag, 'stoptoresume')) % final stopping
-  out.solutions.mean.f = ...
-      feval(fitfun, xintobounds(xmean, lbounds, ubounds), varargin{:});
-  counteval = counteval + 1;
-  out.solutions.mean.evals = counteval;
-  if out.solutions.mean.f < fitness.raw(1)
-    fmin = out.solutions.mean.f;
-    xmin = xintobounds(xmean, lbounds, ubounds); % Return xmean as best point
-  end
-  if out.solutions.mean.f < out.solutions.bestever.f
-    out.solutions.bestever = out.solutions.mean; % Return xmean as bestever point
-    out.solutions.bestever.x = xintobounds(xmean, lbounds, ubounds); 
-    bestever = out.solutions.bestever;
-  end
-end
-
-% Save everything and display final message
-if flgsavingfinal
-  clear idx; % prevents error under octave
-  if ~isempty(strsaving) && ~isoctave
-    save('-mat', strsaving, opts.SaveFilename); % for inspection and possible restart	
-  else 
-    save('-mat', opts.SaveFilename);    % for inspection and possible restart
-  end
-  message = [' (saved to ' opts.SaveFilename ')'];
-else
-  message = [];
-end
-
-if flgdisplay
-  disp(['#Fevals:   f(returned x)   |    bestever.f     | stopflag' ...
-        message]);
-  if isoctave
-    strstop = stopflag(:); 
-  else
-      strcat(stopflag(:), '.');
-  end
-  strstop = stopflag(:); %strcat(stopflag(:), '.');
-  disp([repmat(' ',1,6-floor(log10(counteval))) ...
-        num2str(counteval, '%6.0f') ': ' num2str(fmin, '%.11e') ' | ' ...
-        num2str(out.solutions.bestever.f, '%.11e') ' | ' ...
-	strstop{1:end}]);
-  if N < 102
-     disp(['mean solution:' sprintf(' %+.1e', xmean)]);
-     disp(['std deviation:' sprintf('  %.1e', sigma*sqrt(diagC))]);
-     disp(sprintf('use plotcmaesdat.m for plotting the output at any time (option LogModulo must not be zero)'));
-  end
-  if exist('sfile', 'var') 
-    disp(['Results saved in ' sfile]); 
-  end
-end
-
-  out.arstopflags{irun} = stopflag;
-  if any(strcmp(stopflag, 'fitness')) ...
-	|| any(strcmp(stopflag, 'maxfunevals')) ...
-	|| any(strcmp(stopflag, 'stoptoresume')) ...
-	|| any(strcmp(stopflag, 'manual'))
-    break; 
-  end
 end % while irun <= Restarts
 
-% ---------------------------------------------------------------  
-% ---------------------------------------------------------------  
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
 function [x, idx] = xintobounds(x, lbounds, ubounds)
 %
 % x can be a column vector or a matrix consisting of column vectors
 %
-  if ~isempty(lbounds)
+if ~isempty(lbounds)
     if length(lbounds) == 1
-      idx = x < lbounds;
-      x(idx) = lbounds;
+        idx = x < lbounds;
+        x(idx) = lbounds;
     else
-      arbounds = repmat(lbounds, 1, size(x,2));
-      idx = x < arbounds;
-      x(idx) = arbounds(idx);
+        arbounds = repmat(lbounds, 1, size(x,2));
+        idx = x < arbounds;
+        x(idx) = arbounds(idx);
     end
-  else
+else
     idx = 0;
-  end
-  if ~isempty(ubounds)
+end
+if ~isempty(ubounds)
     if length(ubounds) == 1
-      idx2 = x > ubounds;
-      x(idx2) = ubounds;
+        idx2 = x > ubounds;
+        x(idx2) = ubounds;
     else
-      arbounds = repmat(ubounds, 1, size(x,2));
-      idx2 = x > arbounds;
-      x(idx2) = arbounds(idx2);
+        arbounds = repmat(ubounds, 1, size(x,2));
+        idx2 = x > arbounds;
+        x(idx2) = arbounds(idx2);
     end
-  else
+else
     idx2 = 0;
-  end
-  idx = idx2-idx; 
-  
-% ---------------------------------------------------------------  
-% ---------------------------------------------------------------  
+end
+idx = idx2-idx;
+
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
 function opts=getoptions(inopts, defopts)
 % OPTS = GETOPTIONS(INOPTS, DEFOPTS) handles an arbitrary number of
 % optional arguments to a function. The given arguments are collected
@@ -1812,7 +1812,7 @@ function opts=getoptions(inopts, defopts)
 %     defopts.ParentNumber = 50;
 %     defopts.MaxIterations = 1e6;
 %     defopts.MaxSigma = 1;
-%  
+%
 %     % merge default options with input options
 %     opts = getoptions(inopts, defopts);
 %
@@ -1823,148 +1823,148 @@ function opts=getoptions(inopts, defopts)
 %         % do whatever
 %       end
 %     end
-%   
+%
 %   For calling the function myfunction with default options:
 %   myfunction(argument1, []);
 %   For calling the function myfunction with modified options:
 %   opt.pop = 100; % redefine PopulationSize option
 %   opt.PAR = 10;  % redefine ParentNumber option
-%   opt.maxiter = 2; % opt.max=2 is ambiguous and would result in an error 
+%   opt.maxiter = 2; % opt.max=2 is ambiguous and would result in an error
 %   myfunction(argument1, opt);
 
 %
 % 04/07/19: Entries can be structs itself leading to a recursive
-%           call to getoptions. 
+%           call to getoptions.
 %
 
 if nargin < 2 || isempty(defopts) % no default options available
-  opts=inopts;
-  return;
+    opts=inopts;
+    return
 elseif isempty(inopts) % empty inopts invoke default options
-  opts = defopts;
-  return;
-elseif ~isstruct(defopts) % handle a single option value
-  if isempty(inopts) 
     opts = defopts;
-  elseif ~isstruct(inopts)
-    opts = inopts;
-  else
-    error('Input options are a struct, while default options are not');
-  end
-  return;
+    return
+elseif ~isstruct(defopts) % handle a single option value
+    if isempty(inopts)
+        opts = defopts;
+    elseif ~isstruct(inopts)
+        opts = inopts;
+    else
+        error('Input options are a struct, while default options are not');
+    end
+    return
 elseif ~isstruct(inopts) % no valid input options
-  error('The options need to be a struct or empty');
+    error('The options need to be a struct or empty');
 end
 
-  opts = defopts; % start from defopts 
-  % if necessary overwrite opts fields by inopts values
-  defnames = fieldnames(defopts);
-  idxmatched = []; % indices of defopts that already matched
-  for name = fieldnames(inopts)'
+opts = defopts; % start from defopts
+                % if necessary overwrite opts fields by inopts values
+defnames = fieldnames(defopts);
+idxmatched = []; % indices of defopts that already matched
+for name = fieldnames(inopts)'
     name = name{1}; % name of i-th inopts-field
     if isoctave
-      for i = 1:size(defnames, 1)
-	idx(i) = strncmp(lower(defnames(i)), lower(name), length(name));
-      end
+        for i = 1:size(defnames, 1)
+            idx(i) = strncmp(lower(defnames(i)), lower(name), length(name));
+        end
     else
-	idx = strncmpi(defnames, name, length(name));
+        idx = strncmpi(defnames, name, length(name));
     end
     if sum(idx) > 1
-      error(['option "' name '" is not an unambigous abbreviation. ' ...
-	     'Use opts=RMFIELD(opts, ''' name, ...
-	     ''') to remove the field from the struct.']);
+        error(['option "' name '" is not an unambigous abbreviation. ' ...
+               'Use opts=RMFIELD(opts, ''' name, ...
+               ''') to remove the field from the struct.']);
     end
     if sum(idx) == 1
-      defname  = defnames{find(idx)}; 
-      if ismember(find(idx), idxmatched)
-	error(['input options match more than ones with "' ...
-	       defname '". ' ...
-	       'Use opts=RMFIELD(opts, ''' name, ...
-	       ''') to remove the field from the struct.']);
-      end
-      idxmatched = [idxmatched find(idx)];
-      val = getfield(inopts, name);
-      % next line can replace previous line from MATLAB version 6.5.0 on and in octave
-      % val = inopts.(name);
-      if isstruct(val) % valid syntax only from version 6.5.0
-	opts = setfield(opts, defname, ...
-	    getoptions(val, getfield(defopts, defname))); 
-      elseif isstruct(getfield(defopts, defname)) 
-      % next three lines can replace previous three lines from MATLAB 
-      % version 6.5.0 on
-      %   opts.(defname) = ...
-      %      getoptions(val, defopts.(defname)); 
-      % elseif isstruct(defopts.(defname)) 
-	warning(['option "' name '" disregarded (must be struct)']); 
-      elseif ~isempty(val) % empty value: do nothing, i.e. stick to default
-	opts = setfield(opts, defnames{find(idx)}, val);
-	% next line can replace previous line from MATLAB version 6.5.0 on
-	% opts.(defname) = inopts.(name); 
-      end
+        defname  = defnames{find(idx)};
+        if ismember(find(idx), idxmatched)
+            error(['input options match more than ones with "' ...
+                   defname '". ' ...
+                   'Use opts=RMFIELD(opts, ''' name, ...
+                   ''') to remove the field from the struct.']);
+        end
+        idxmatched = [idxmatched find(idx)];
+        val = getfield(inopts, name);
+        % next line can replace previous line from MATLAB version 6.5.0 on and in octave
+        % val = inopts.(name);
+        if isstruct(val) % valid syntax only from version 6.5.0
+            opts = setfield(opts, defname, ...
+                                  getoptions(val, getfield(defopts, defname)));
+        elseif isstruct(getfield(defopts, defname))
+            % next three lines can replace previous three lines from MATLAB
+            % version 6.5.0 on
+            %   opts.(defname) = ...
+            %      getoptions(val, defopts.(defname));
+            % elseif isstruct(defopts.(defname))
+            warning(['option "' name '" disregarded (must be struct)']);
+        elseif ~isempty(val) % empty value: do nothing, i.e. stick to default
+            opts = setfield(opts, defnames{find(idx)}, val);
+            % next line can replace previous line from MATLAB version 6.5.0 on
+            % opts.(defname) = inopts.(name);
+        end
     else
-      warning(['option "' name '" disregarded (unknown field name)']);
+        warning(['option "' name '" disregarded (unknown field name)']);
     end
-  end
+end
 
-% ---------------------------------------------------------------  
-% ---------------------------------------------------------------  
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
 function res=myeval(s)
-  if ischar(s)
+if ischar(s)
     res = evalin('caller', s);
-  else
+else
     res = s;
-  end
-  
-% ---------------------------------------------------------------  
-% ---------------------------------------------------------------  
+end
+
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
 function res=myevalbool(s)
-  if ~ischar(s) % s may not and cannot be empty
+if ~ischar(s) % s may not and cannot be empty
     res = s;
-  else % evaluation string s
+else % evaluation string s
     if strncmpi(lower(s), 'yes', 3) || strncmpi(s, 'on', 2) ...
-	  || strncmpi(s, 'true', 4) || strncmp(s, '1 ', 2)
-      res = 1;
+            || strncmpi(s, 'true', 4) || strncmp(s, '1 ', 2)
+        res = 1;
     elseif strncmpi(s, 'no', 2) || strncmpi(s, 'off', 3) ...
-	  || strncmpi(s, 'false', 5) || strncmp(s, '0 ', 2)
-      res = 0;
+            || strncmpi(s, 'false', 5) || strncmp(s, '0 ', 2)
+        res = 0;
     else
-      try res = evalin('caller', s); catch
-	error(['String value "' s '" cannot be evaluated']);
-      end
-      try res ~= 0; catch
-	error(['String value "' s '" cannot be evaluated reasonably']);
-      end
+        try res = evalin('caller', s); catch
+            error(['String value "' s '" cannot be evaluated']);
+        end
+        try res ~= 0; catch
+            error(['String value "' s '" cannot be evaluated reasonably']);
+        end
     end
-  end
-  
+end
 
-% ---------------------------------------------------------------  
-% ---------------------------------------------------------------  
+
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
 function res = isoctave
 % any hack to find out whether we are running octave
-  s = version;
-  res = 0;
-  if exist('fflush', 'builtin') && eval(s(1)) < 7
+s = version;
+res = 0;
+if exist('fflush', 'builtin') && eval(s(1)) < 7
     res = 1;
-  end
+end
 
-% ---------------------------------------------------------------  
-% ---------------------------------------------------------------  
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
 function flush
-  if isoctave
+if isoctave
     feval('fflush', stdout);
-  end
+end
 
-% ---------------------------------------------------------------  
-% ---------------------------------------------------------------  
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
 % ----- replacements for statistic toolbox functions ------------
-% ---------------------------------------------------------------  
-% ---------------------------------------------------------------  
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
 function res=myrange(x)
-  res = max(x) - min(x);
-  
-% ---------------------------------------------------------------  
-% ---------------------------------------------------------------  
+res = max(x) - min(x);
+
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
 function res = myprctile(inar, perc, idx)
 %
 % Computes the percentiles in vector perc from vector inar
@@ -1975,105 +1975,105 @@ function res = myprctile(inar, perc, idx)
 N = length(inar);
 flgtranspose = 0;
 
-% sizes 
+% sizes
 if size(perc,1) > 1
-  perc = perc';
-  flgtranspose = 1;
-  if size(perc,1) > 1
-    error('perc must not be a matrix');
-  end
+    perc = perc';
+    flgtranspose = 1;
+    if size(perc,1) > 1
+        error('perc must not be a matrix');
+    end
 end
 if size(inar, 1) > 1 && size(inar,2) > 1
-  error('data inar must not be a matrix');
+    error('data inar must not be a matrix');
 end
- 
+
 % sort inar
 if nargin < 3 || isempty(idx)
-  [sar idx] = sort(inar);
+    [sar, idx] = sort(inar);
 else
-  sar = inar(idx);
+    sar = inar(idx);
 end
 
 res = [];
 for p = perc
-  if p <= 100*(0.5/N)
-    res(end+1) = sar(1);
-  elseif p >= 100*((N-0.5)/N)
-    res(end+1) = sar(N);
-  else
-    % find largest index smaller than required percentile
-    availablepercentiles = 100*((1:N)-0.5)/N;
-    i = max(find(p > availablepercentiles));
-    % interpolate linearly
-    res(end+1) = sar(i) ...
-	+ (sar(i+1)-sar(i))*(p - availablepercentiles(i)) ...
-	/ (availablepercentiles(i+1) - availablepercentiles(i));
-
-  end
+    if p <= 100*(0.5/N)
+        res(end+1) = sar(1);
+    elseif p >= 100*((N-0.5)/N)
+        res(end+1) = sar(N);
+    else
+        % find largest index smaller than required percentile
+        availablepercentiles = 100*((1:N)-0.5)/N;
+        i = max(find(p > availablepercentiles));
+        % interpolate linearly
+        res(end+1) = sar(i) ...
+            + (sar(i+1)-sar(i))*(p - availablepercentiles(i)) ...
+            / (availablepercentiles(i+1) - availablepercentiles(i));
+
+    end
 end
 
 if flgtranspose
-  res = res';
+    res = res';
 end
 
 
-% ---------------------------------------------------------------  
-% ---------------------------------------------------------------  
-% ---------------------------------------------------------------  
-% ---------------------------------------------------------------  
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
 
 
 
-function [s ranks rankDelta] = local_noisemeasurement(arf1, arf2, lamreev, theta, cutlimit)
+function [s, ranks, rankDelta] = local_noisemeasurement(arf1, arf2, lamreev, theta, cutlimit)
 % function [s ranks rankDelta] = noisemeasurement(arf1, arf2, lamreev, theta)
 %
-% Input: 
-%   arf1, arf2 : two arrays of function values. arf1 is of size 1xlambda, 
-%       arf2 may be of size 1xlamreev or 1xlambda. The first lamreev values 
-%       in arf2 are (re-)evaluations of the respective solutions, i.e. 
+% Input:
+%   arf1, arf2 : two arrays of function values. arf1 is of size 1xlambda,
+%       arf2 may be of size 1xlamreev or 1xlambda. The first lamreev values
+%       in arf2 are (re-)evaluations of the respective solutions, i.e.
 %       arf1(1) and arf2(1) are two evaluations of "the first" solution.
-%    lamreev: number of reevaluated individuals in arf2 
-%    theta : parameter theta for the rank change limit, between 0 and 1, 
-%       typically between 0.2 and 0.7. 
-%    cutlimit (optional): output s is computed as a mean of rankchange minus 
-%       threshold, where rankchange is <=2*(lambda-1). cutlimit limits 
-%       abs(rankchange minus threshold) in this calculation to cutlimit. 
-%       cutlimit=1 evaluates basically the sign only. cutlimit=2 could be 
-%       the rank change with one solution (both evaluations of it). 
-% 
-% Output: 
+%    lamreev: number of reevaluated individuals in arf2
+%    theta : parameter theta for the rank change limit, between 0 and 1,
+%       typically between 0.2 and 0.7.
+%    cutlimit (optional): output s is computed as a mean of rankchange minus
+%       threshold, where rankchange is <=2*(lambda-1). cutlimit limits
+%       abs(rankchange minus threshold) in this calculation to cutlimit.
+%       cutlimit=1 evaluates basically the sign only. cutlimit=2 could be
+%       the rank change with one solution (both evaluations of it).
+%
+% Output:
 %   s : noise measurement, s>0 means the noise measure is above the
 %       acceptance threshold
-%   ranks : 2xlambda array, corresponding to [arf1; arf2], of ranks 
+%   ranks : 2xlambda array, corresponding to [arf1; arf2], of ranks
 %       of arf1 and arf2 in the set [arf1 arf2], values are in [1:2*lambda]
 %   rankDelta: 1xlambda array of rank movements of arf2 compared to
 %       arf1.  rankDelta(i) agrees with the number of values from
 %       the set [arf1 arf2] that lie between arf1(i) and arf2(i).
 %
 % Note: equal function values might lead to somewhat spurious results.
-%       For this case a revision is advisable. 
+%       For this case a revision is advisable.
 
 %%% verify input argument sizes
 if size(arf1,1) ~= 1
-  error('arf1 must be an 1xlambda array');
+    error('arf1 must be an 1xlambda array');
 elseif size(arf2,1) ~= 1
-  error('arf2 must be an 1xsomething array');
+    error('arf2 must be an 1xsomething array');
 elseif size(arf1,2) < size(arf2,2)  % not really necessary, but saver
-  error('arf2 must not be smaller than arf1 in length');
+    error('arf2 must not be smaller than arf1 in length');
 end
 lam = size(arf1, 2);
 if size(arf1,2) ~= size(arf2,2)
-   arf2(end+1:lam) = arf1((size(arf2,2)+1):lam);
+    arf2(end+1:lam) = arf1((size(arf2,2)+1):lam);
 end
 if nargin < 5
-  cutlimit = inf;
+    cutlimit = inf;
 end
 
 %%% capture unusual values
 if any(diff(arf1) == 0)
-  % this will presumably interpreted as rank change, because
-  % sort(ones(...)) returns 1,2,3,...
-  warning([num2str(sum(diff(arf1)==0)) ' equal function values']);
+    % this will presumably interpreted as rank change, because
+    % sort(ones(...)) returns 1,2,3,...
+    warning([num2str(sum(diff(arf1)==0)) ' equal function values']);
 end
 
 %%% compute rank changes into rankDelta
@@ -2086,12 +2086,12 @@ rankDelta = ranks(1,:) - ranks(2,:) - sign(ranks(1,:) - ranks(2,:));
 
 %%% compute rank change limits using both ranks(1,...) and ranks(2,...)
 for i = 1:lamreev
-  sumlim(i) = ...
-      0.5 * (...
-          myprctile(abs((1:2*lam-1) - (ranks(1,i) - (ranks(1,i)>ranks(2,i)))), ...
-                    theta*50) ...      
-          + myprctile(abs((1:2*lam-1) - (ranks(2,i) - (ranks(2,i)>ranks(1,i)))), ...
-                      theta*50)); 
+    sumlim(i) = ...
+        0.5 * (...
+            myprctile(abs((1:2*lam-1) - (ranks(1,i) - (ranks(1,i)>ranks(2,i)))), ...
+                      theta*50) ...
+            + myprctile(abs((1:2*lam-1) - (ranks(2,i) - (ranks(2,i)>ranks(1,i)))), ...
+                        theta*50));
 end
 
 %%% compute measurement
@@ -2101,235 +2101,235 @@ end
 s = abs(rankDelta(1:lamreev)) - max(1, sumlim); % lives roughly in 0..2*lambda
 
 % cut-off limit
-idx = abs(s) > cutlimit; 
+idx = abs(s) > cutlimit;
 s(idx) = sign(s(idx)) * cutlimit;
 s = mean(s);
 
-% ---------------------------------------------------------------  
-% ---------------------------------------------------------------  
-% ---------------------------------------------------------------  
-% ---------------------------------------------------------------  
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
+% ---------------------------------------------------------------
 % just a "local" copy of plotcmaesdat.m, with manual_mode set to zero
 function local_plotcmaesdat(figNb, filenameprefix, filenameextension, objectvarname)
 % PLOTCMAESDAT;
 % PLOTCMAES(FIGURENUMBER_iBEGIN_iEND, FILENAMEPREFIX, FILENAMEEXTENSION, OBJECTVARNAME);
-%   plots output from CMA-ES, e.g. cmaes.m, Java class CMAEvolutionStrategy... 
-%   mod(figNb,100)==1 plots versus iterations. 
+%   plots output from CMA-ES, e.g. cmaes.m, Java class CMAEvolutionStrategy...
+%   mod(figNb,100)==1 plots versus iterations.
 %
-% PLOTCMAES([101 300]) plots versus iteration, from iteration 300. 
-% PLOTCMAES([100 150 800]) plots versus function evaluations, between iteration 150 and 800. 
+% PLOTCMAES([101 300]) plots versus iteration, from iteration 300.
+% PLOTCMAES([100 150 800]) plots versus function evaluations, between iteration 150 and 800.
 %
-% Upper left subplot: blue/red: function value of the best solution in the 
+% Upper left subplot: blue/red: function value of the best solution in the
 %   recent population, cyan: same function value minus best
-%   ever seen function value, green: sigma, red: ratio between 
+%   ever seen function value, green: sigma, red: ratio between
 %   longest and shortest principal axis length which is equivalent
-%   to sqrt(cond(C)). 
+%   to sqrt(cond(C)).
 % Upper right plot: time evolution of the distribution mean (default) or
-%   the recent best solution vector. 
-% Lower left: principal axes lengths of the distribution ellipsoid, 
-%   equivalent with the sqrt(eig(C)) square root eigenvalues of C. 
-% Lower right: magenta: minimal and maximal "true" standard deviation 
-%   (with sigma included) in the coordinates, other colors: sqrt(diag(C)) 
+%   the recent best solution vector.
+% Lower left: principal axes lengths of the distribution ellipsoid,
+%   equivalent with the sqrt(eig(C)) square root eigenvalues of C.
+% Lower right: magenta: minimal and maximal "true" standard deviation
+%   (with sigma included) in the coordinates, other colors: sqrt(diag(C))
 %   of all diagonal elements of C, if C is diagonal they equal to the
-%   lower left. 
+%   lower left.
 %
-% Files [FILENAMEPREFIX name FILENAMEEXTENSION] are used, where 
+% Files [FILENAMEPREFIX name FILENAMEEXTENSION] are used, where
 %   name = axlen, OBJECTVARNAME (xmean|xrecentbest), fit, or stddev.
 %
 
 manual_mode = 0;
 
-  if nargin < 1 || isempty(figNb)
+if nargin < 1 || isempty(figNb)
     figNb = 325;
-  end
-  if nargin < 2 || isempty(filenameprefix)
+end
+if nargin < 2 || isempty(filenameprefix)
     filenameprefix = 'outcmaes';
-  end
-  if nargin < 3 || isempty(filenameextension)
+end
+if nargin < 3 || isempty(filenameextension)
     filenameextension = '.dat';
-  end
-  if nargin < 4 || isempty(objectvarname)
-    objectvarname = 'xmean';    
+end
+if nargin < 4 || isempty(objectvarname)
+    objectvarname = 'xmean';
     objectvarname = 'xrecentbest';
-  end
-  % load data
-  d.x = load([filenameprefix objectvarname filenameextension]); 
-  % d.x = load([filenameprefix 'xmean' filenameextension]); 
-  % d.x = load([filenameprefix 'xrecentbest' filenameextension]); 
-  d.f = load([filenameprefix 'fit' filenameextension]); 
-  d.std = load([filenameprefix 'stddev' filenameextension]);
-  d.D = load([filenameprefix 'axlen' filenameextension]);
-
-  % interpret entries in figNb for cutting out some data
-  if length(figNb) > 1
+end
+% load data
+d.x = load([filenameprefix objectvarname filenameextension]);
+% d.x = load([filenameprefix 'xmean' filenameextension]);
+% d.x = load([filenameprefix 'xrecentbest' filenameextension]);
+d.f = load([filenameprefix 'fit' filenameextension]);
+d.std = load([filenameprefix 'stddev' filenameextension]);
+d.D = load([filenameprefix 'axlen' filenameextension]);
+
+% interpret entries in figNb for cutting out some data
+if length(figNb) > 1
     iend = inf;
     istart = figNb(2);
     if length(figNb) > 2
-      iend = figNb(3);
+        iend = figNb(3);
     end
     figNb = figNb(1);
     d.x = d.x(d.x(:,1) >= istart & d.x(:,1) <= iend, :);
     d.f = d.f(d.f(:,1) >= istart & d.f(:,1) <= iend, :);
     d.std = d.std(d.std(:,1) >= istart & d.std(:,1) <= iend, :);
     d.D = d.D(d.D(:,1) >= istart & d.D(:,1) <= iend, :);
-  end
+end
 
-  % decide for x-axis
-  iabscissa = 2; % 1== versus iterations, 2==versus fevals
-  if mod(figNb,100) == 1
+% decide for x-axis
+iabscissa = 2; % 1== versus iterations, 2==versus fevals
+if mod(figNb,100) == 1
     iabscissa = 1; % a short hack
-  end
-  if iabscissa == 1
-    xlab ='iterations'; 
-  elseif iabscissa == 2
-    xlab = 'function evaluations'; 
-  end
-
-  if size(d.x, 2) < 1000
+end
+if iabscissa == 1
+    xlab ='iterations';
+elseif iabscissa == 2
+    xlab = 'function evaluations';
+end
+
+if size(d.x, 2) < 1000
     minxend = 1.03*d.x(end, iabscissa);
-  else
+else
     minxend = 0;
-  end
+end
 
-  % set up figure window
-  if manual_mode
+% set up figure window
+if manual_mode
     figure(figNb);  % just create and raise the figure window
-  else
-    if 1 < 3 && evalin('caller', 'iterplotted') == 0 && evalin('caller', 'irun') == 1 
-      figure(figNb);  % incomment this, if figure raise in the beginning is not desired
+else
+    if 1 < 3 && evalin('caller', 'iterplotted') == 0 && evalin('caller', 'irun') == 1
+        figure(figNb);  % incomment this, if figure raise in the beginning is not desired
     elseif ismember(figNb, findobj('Type', 'figure'))
-      set(0, 'CurrentFigure', figNb);  % prevents raise of existing figure window
+        set(0, 'CurrentFigure', figNb);  % prevents raise of existing figure window
     else
-      figure(figNb);
+        figure(figNb);
     end
-  end
-
-  % plot fitness etc
-  foffset = 1e-99;
-  dfit = d.f(:,6)-min(d.f(:,6)); 
-  [ignore idxbest] = min(dfit);
-  dfit(dfit<1e-98) = NaN;
-  subplot(2,2,1); hold off; 
-  dd = abs(d.f(:,7:8)) + foffset; 
-  dd(d.f(:,7:8)==0) = NaN;
-  semilogy(d.f(:,iabscissa), dd, '-k'); hold on;
-  % additional fitness data, for example constraints values
-  if size(d.f,2) > 8
+end
+
+% plot fitness etc
+foffset = 1e-99;
+dfit = d.f(:,6)-min(d.f(:,6));
+[ignore, idxbest] = min(dfit);
+dfit(dfit<1e-98) = NaN;
+subplot(2,2,1); hold off;
+dd = abs(d.f(:,7:8)) + foffset;
+dd(d.f(:,7:8)==0) = NaN;
+semilogy(d.f(:,iabscissa), dd, '-k'); hold on;
+% additional fitness data, for example constraints values
+if size(d.f,2) > 8
     dd = abs(d.f(:,9:end)) + 10*foffset;  % a hack
-    % dd(d.f(:,9:end)==0) = NaN; 
-    semilogy(d.f(:,iabscissa), dd, '-m'); hold on; 
+                                          % dd(d.f(:,9:end)==0) = NaN;
+    semilogy(d.f(:,iabscissa), dd, '-m'); hold on;
     if size(d.f,2) > 12
-      semilogy(d.f(:,iabscissa),abs(d.f(:,[7 8 11 13]))+foffset,'-k'); hold on;
+        semilogy(d.f(:,iabscissa),abs(d.f(:,[7 8 11 13]))+foffset,'-k'); hold on;
     end
-  end
-
-  idx = find(d.f(:,6)>1e-98);  % positive values
-  if ~isempty(idx)  % otherwise non-log plot gets hold
-    semilogy(d.f(idx,iabscissa), d.f(idx,6)+foffset, '.b'); hold on; 
-  end
-  idx = find(d.f(:,6) < -1e-98);  % negative values
-  if ~isempty(idx)
-    semilogy(d.f(idx, iabscissa), abs(d.f(idx,6))+foffset,'.r'); hold on; 
-  end
-  semilogy(d.f(:,iabscissa),abs(d.f(:,6))+foffset,'-b'); hold on;
-  semilogy(d.f(:,iabscissa),dfit,'-c'); hold on;
-  semilogy(d.f(:,iabscissa),(d.f(:,4)),'-r'); hold on; % AR
-  semilogy(d.std(:,iabscissa), [max(d.std(:,6:end)')' ...
-                      min(d.std(:,6:end)')'], '-m'); % max,min std
-  maxval = max(d.std(end,6:end));
-  minval = min(d.std(end,6:end));
-  text(d.std(end,iabscissa), maxval, sprintf('%.0e', maxval));
-  text(d.std(end,iabscissa), minval, sprintf('%.0e', minval));
-
-  semilogy(d.std(:,iabscissa),(d.std(:,3)),'-g'); % sigma
-  % plot best f
-  semilogy(d.f(idxbest,iabscissa),min(dfit),'*c'); hold on;
-  semilogy(d.f(idxbest,iabscissa),abs(d.f(idxbest,6))+foffset,'*r'); hold on;
-
-  ax = axis;
-  ax(2) = max(minxend, ax(2)); 
-  axis(ax);
-  
-  yannote = 10^(log10(ax(3)) + 0.05*(log10(ax(4))-log10(ax(3)))); 
-  text(ax(1), yannote, ...
-       [ 'f=' num2str(d.f(end,6), '%.15g') ]);
-
-  title('blue:abs(f), cyan:f-min(f), green:sigma, red:axis ratio');
-  grid on; 
-
-  subplot(2,2,2); hold off; 
-  plot(d.x(:,iabscissa), d.x(:,6:end),'-'); hold on;
-  ax = axis;
-  ax(2) = max(minxend, ax(2)); 
-  axis(ax); 
-
-  % add some annotation lines
-  [ignore idx] = sort(d.x(end,6:end));
-  % choose no more than 25 indices 
-  idxs = round(linspace(1, size(d.x,2)-5, min(size(d.x,2)-5, 25))); 
-  yy = repmat(NaN, 2, size(d.x,2)-5);
-  yy(1,:) = d.x(end, 6:end);
-  yy(2,idx(idxs)) = linspace(ax(3), ax(4), length(idxs));
-  plot([d.x(end,iabscissa) ax(2)], yy, '-'); 
-  plot(repmat(d.x(end,iabscissa),2), [ax(3) ax(4)], 'k-');
-  for i = idx(idxs)
+end
+
+idx = find(d.f(:,6)>1e-98);  % positive values
+if ~isempty(idx)  % otherwise non-log plot gets hold
+    semilogy(d.f(idx,iabscissa), d.f(idx,6)+foffset, '.b'); hold on;
+end
+idx = find(d.f(:,6) < -1e-98);  % negative values
+if ~isempty(idx)
+    semilogy(d.f(idx, iabscissa), abs(d.f(idx,6))+foffset,'.r'); hold on;
+end
+semilogy(d.f(:,iabscissa),abs(d.f(:,6))+foffset,'-b'); hold on;
+semilogy(d.f(:,iabscissa),dfit,'-c'); hold on;
+semilogy(d.f(:,iabscissa),(d.f(:,4)),'-r'); hold on; % AR
+semilogy(d.std(:,iabscissa), [max(d.std(:,6:end)')' ...
+                    min(d.std(:,6:end)')'], '-m'); % max,min std
+maxval = max(d.std(end,6:end));
+minval = min(d.std(end,6:end));
+text(d.std(end,iabscissa), maxval, sprintf('%.0e', maxval));
+text(d.std(end,iabscissa), minval, sprintf('%.0e', minval));
+
+semilogy(d.std(:,iabscissa),(d.std(:,3)),'-g'); % sigma
+                                                % plot best f
+semilogy(d.f(idxbest,iabscissa),min(dfit),'*c'); hold on;
+semilogy(d.f(idxbest,iabscissa),abs(d.f(idxbest,6))+foffset,'*r'); hold on;
+
+ax = axis;
+ax(2) = max(minxend, ax(2));
+axis(ax);
+
+yannote = 10^(log10(ax(3)) + 0.05*(log10(ax(4))-log10(ax(3))));
+text(ax(1), yannote, ...
+     [ 'f=' num2str(d.f(end,6), '%.15g') ]);
+
+title('blue:abs(f), cyan:f-min(f), green:sigma, red:axis ratio');
+grid on;
+
+subplot(2,2,2); hold off;
+plot(d.x(:,iabscissa), d.x(:,6:end),'-'); hold on;
+ax = axis;
+ax(2) = max(minxend, ax(2));
+axis(ax);
+
+% add some annotation lines
+[ignore idx] = sort(d.x(end,6:end));
+% choose no more than 25 indices
+idxs = round(linspace(1, size(d.x,2)-5, min(size(d.x,2)-5, 25)));
+yy = repmat(NaN, 2, size(d.x,2)-5);
+yy(1,:) = d.x(end, 6:end);
+yy(2,idx(idxs)) = linspace(ax(3), ax(4), length(idxs));
+plot([d.x(end,iabscissa) ax(2)], yy, '-');
+plot(repmat(d.x(end,iabscissa),2), [ax(3) ax(4)], 'k-');
+for i = idx(idxs)
     text(ax(2), yy(2,i), ...
          ['x(' num2str(i) ')=' num2str(yy(1,i))]);
-  end
-  
-  lam = 'NA'; 
-  if size(d.x, 1) > 1 && d.x(end, 1) > d.x(end-1, 1)
+end
+
+lam = 'NA';
+if size(d.x, 1) > 1 && d.x(end, 1) > d.x(end-1, 1)
     lam = num2str((d.x(end, 2) - d.x(end-1, 2)) / (d.x(end, 1) - d.x(end-1, 1)));
-  end
-  title(['Object Variables (' num2str(size(d.x, 2)-5) ...
-            '-D, popsize~' lam ')']);grid on;
-
-  subplot(2,2,3); hold off; semilogy(d.D(:,iabscissa), d.D(:,6:end), '-');
-  ax = axis;
-  ax(2) = max(minxend, ax(2)); 
-  axis(ax);
-  title('Principal Axes Lengths');grid on;
-  xlabel(xlab); 
-
-  subplot(2,2,4); hold off; 
-  % semilogy(d.std(:,iabscissa), d.std(:,6:end), 'k-'); hold on; 
-  % remove sigma from stds
-  d.std(:,6:end) = d.std(:,6:end) ./ (d.std(:,3) * ones(1,size(d.std,2)-5));
-  semilogy(d.std(:,iabscissa), d.std(:,6:end), '-'); hold on; 
-  if 11 < 3  % max and min std
+end
+title(['Object Variables (' num2str(size(d.x, 2)-5) ...
+       '-D, popsize~' lam ')']);grid on;
+
+subplot(2,2,3); hold off; semilogy(d.D(:,iabscissa), d.D(:,6:end), '-');
+ax = axis;
+ax(2) = max(minxend, ax(2));
+axis(ax);
+title('Principal Axes Lengths');grid on;
+xlabel(xlab);
+
+subplot(2,2,4); hold off;
+% semilogy(d.std(:,iabscissa), d.std(:,6:end), 'k-'); hold on;
+% remove sigma from stds
+d.std(:,6:end) = d.std(:,6:end) ./ (d.std(:,3) * ones(1,size(d.std,2)-5));
+semilogy(d.std(:,iabscissa), d.std(:,6:end), '-'); hold on;
+if 11 < 3  % max and min std
     semilogy(d.std(:,iabscissa), [d.std(:,3).*max(d.std(:,6:end)')' ...
                         d.std(:,3).*min(d.std(:,6:end)')'], '-m', 'linewidth', 2);
     maxval = max(d.std(end,6:end));
     minval = min(d.std(end,6:end));
     text(d.std(end,iabscissa), d.std(end,3)*maxval, sprintf('max=%.0e', maxval));
     text(d.std(end,iabscissa), d.std(end,3)*minval, sprintf('min=%.0e', minval));
-  end
-  ax = axis;
-  ax(2) = max(minxend, ax(2)); 
-  axis(ax);
-  % add some annotation lines
-  [ignore idx] = sort(d.std(end,6:end));
-  % choose no more than 25 indices 
-  idxs = round(linspace(1, size(d.x,2)-5, min(size(d.x,2)-5, 25))); 
-  yy = repmat(NaN, 2, size(d.std,2)-5);
-  yy(1,:) = d.std(end, 6:end);
-  yy(2,idx(idxs)) = logspace(log10(ax(3)), log10(ax(4)), length(idxs));
-  semilogy([d.std(end,iabscissa) ax(2)], yy, '-'); 
-  semilogy(repmat(d.std(end,iabscissa),2), [ax(3) ax(4)], 'k-');
-  for i = idx(idxs)
+end
+ax = axis;
+ax(2) = max(minxend, ax(2));
+axis(ax);
+% add some annotation lines
+[ignore, idx] = sort(d.std(end,6:end));
+% choose no more than 25 indices
+idxs = round(linspace(1, size(d.x,2)-5, min(size(d.x,2)-5, 25)));
+yy = repmat(NaN, 2, size(d.std,2)-5);
+yy(1,:) = d.std(end, 6:end);
+yy(2,idx(idxs)) = logspace(log10(ax(3)), log10(ax(4)), length(idxs));
+semilogy([d.std(end,iabscissa) ax(2)], yy, '-');
+semilogy(repmat(d.std(end,iabscissa),2), [ax(3) ax(4)], 'k-');
+for i = idx(idxs)
     text(ax(2), yy(2,i), [' ' num2str(i)]);
-  end
-  title('Standard Deviations in Coordinates divided by sigma');grid on;
-  xlabel(xlab);
+end
+title('Standard Deviations in Coordinates divided by sigma');grid on;
+xlabel(xlab);
 
-  if figNb ~= 324
+if figNb ~= 324
     % zoom on;  % does not work in Octave
-  end
-  drawnow;
+end
+drawnow;
 
-% ---------------------------------------------------------------  
-% --------------- TEST OBJECTIVE FUNCTIONS ----------------------  
-% ---------------------------------------------------------------  
+% ---------------------------------------------------------------
+% --------------- TEST OBJECTIVE FUNCTIONS ----------------------
+% ---------------------------------------------------------------
 
 %%% Unimodal functions
 
@@ -2337,652 +2337,652 @@ function f=fjens1(x)
 %
 % use population size about 2*N
 %
-  f = sum((x>0) .* x.^1, 1);
-  if any(any(x<0))
+f = sum((x>0) .* x.^1, 1);
+if any(any(x<0))
     idx = sum(x < 0, 1) > 0;
     f(idx) = 1e3;
-%    f = f + 1e3 * sum(x<0, 1);
-%    f = f + 10 * sum((x<0) .* x.^2, 1);
+    %    f = f + 1e3 * sum(x<0, 1);
+    %    f = f + 10 * sum((x<0) .* x.^2, 1);
     f(idx) = f(idx) + 1e-3*abs(randn(1,sum(idx)));
-%    f(idx) = NaN;
-  end
+    %    f(idx) = NaN;
+end
 
 function f=fsphere(x)
-  f = sum(x.^2,1);
+f = sum(x.^2,1);
 
 function f=fmax(x)
-  f = max(abs(x), [], 1);
+f = max(abs(x), [], 1);
 
 function f=fssphere(x)
-  f=sqrt(sum(x.^2, 1));
+f=sqrt(sum(x.^2, 1));
 
-%  lb = -0.512; ub = 512; 
-%  xfeas = x; 
+%  lb = -0.512; ub = 512;
+%  xfeas = x;
 %  xfeas(x<lb) = lb;
-%  xfeas(x>ub) = ub; 
+%  xfeas(x>ub) = ub;
 %  f=sum(xfeas.^2, 1);
-%  f = f + 1e-9 * sum((xfeas-x).^2); 
-  
+%  f = f + 1e-9 * sum((xfeas-x).^2);
+
 function f=fspherenoise(x, Nevals)
-  if nargin < 2 || isempty(Nevals)
+if nargin < 2 || isempty(Nevals)
     Nevals = 1;
-  end
-  [N,popsi] = size(x);
+end
+[N,popsi] = size(x);
 %  x = x .* (1 +  0.3e-0 * randn(N, popsi)/(2*N)); % actuator noise
-  fsum = 10.^(0*(0:N-1)/(N-1)) * x.^2; 
+fsum = 10.^(0*(0:N-1)/(N-1)) * x.^2;
 %  f = 0*rand(1,1) ...
 %      + fsum ...
 %      + fsum .* (2*randn(1,popsi) ./ randn(1,popsi).^0 / (2*N)) ...
-%      + 1*fsum.^0.9 .* 2*randn(1,popsi) / (2*N); % 
+%      + 1*fsum.^0.9 .* 2*randn(1,popsi) / (2*N); %
 
 %  f = fsum .* exp(0.1*randn(1,popsi));
-  f = fsum .* (1 + (10/(N+10)/sqrt(Nevals))*randn(1,popsi));
+f = fsum .* (1 + (10/(N+10)/sqrt(Nevals))*randn(1,popsi));
 %  f = fsum .* (1 + (0.1/N)*randn(1,popsi)./randn(1,popsi).^1);
 
-  idx = rand(1,popsi) < 0.0;
-  if sum(idx) > 0
+idx = rand(1,popsi) < 0.0;
+if sum(idx) > 0
     f(idx) = f(idx) + 1e3*exp(randn(1,sum(idx)));
-  end
-  
+end
+
 function f=fmixranks(x)
-  N = size(x,1);
-  f=(10.^(0*(0:(N-1))/(N-1))*x.^2).^0.5;
-  if size(x, 2) > 1 % compute ranks, if it is a population 
+N = size(x,1);
+f=(10.^(0*(0:(N-1))/(N-1))*x.^2).^0.5;
+if size(x, 2) > 1 % compute ranks, if it is a population
     [ignore, idx] = sort(f);
     [ignore, ranks] = sort(idx);
     k = 9; % number of solutions randomly permuted, lambda/2-1
            % works still quite well (two time slower)
     for i = k+1:k-0:size(x,2)
-      idx(i-k+(1:k)) = idx(i-k+randperm(k)); 
+        idx(i-k+(1:k)) = idx(i-k+randperm(k));
     end
     %disp([ranks' f'])
     [ignore, ranks] = sort(idx);
     %disp([ranks' f'])
     %pause
     f = ranks+1e-9*randn(1,1);
-  end
-  
+end
+
 function f = fsphereoneax(x)
-  f = x(1)^2;
-  f = mean(x)^2;
-  
+f = x(1)^2;
+f = mean(x)^2;
+
 function f=frandsphere(x)
-  N = size(x,1);
-  idx = ceil(N*rand(7,1));
-  f=sum(x(idx).^2);
+N = size(x,1);
+idx = ceil(N*rand(7,1));
+f=sum(x(idx).^2);
 
 function f=fspherelb0(x, M) % lbound at zero for 1:M needed
-  if nargin < 2 M = 0; end
-  N = size(x,1);
-  % M active bounds, f_i = 1 for x = 0
-  f = -M + sum((x(1:M) + 1).^2);
-  f = f + sum(x(M+1:N).^2);
-  
+if nargin < 2 M = 0; end
+N = size(x,1);
+% M active bounds, f_i = 1 for x = 0
+f = -M + sum((x(1:M) + 1).^2);
+f = f + sum(x(M+1:N).^2);
+
 function f=fspherehull(x)
-  % Patton, Dexter, Goodman, Punch
-  % in -500..500
-  % spherical ridge through zeros(N,1)
-  % worst case start point seems x = 2*100*sqrt(N)
-  % and small step size
-  N = size(x,1);
-  f = norm(x) + (norm(x-100*sqrt(N)) - 100*N)^2;
-  
+% Patton, Dexter, Goodman, Punch
+% in -500..500
+% spherical ridge through zeros(N,1)
+% worst case start point seems x = 2*100*sqrt(N)
+% and small step size
+N = size(x,1);
+f = norm(x) + (norm(x-100*sqrt(N)) - 100*N)^2;
+
 function f=fellilb0(x, idxM, scal) % lbound at zero for 1:M needed
-  N = size(x,1);
-  if nargin < 3 || isempty(scal)
+N = size(x,1);
+if nargin < 3 || isempty(scal)
     scal = 100;
-  end
-  scale=scal.^((0:N-1)/(N-1));
-  if nargin < 2 || isempty(idxM)
+end
+scale=scal.^((0:N-1)/(N-1));
+if nargin < 2 || isempty(idxM)
     idxM = 1:N;
-  end
-  %scale(N) = 1e0;
-  % M active bounds
-  xopt = 0.1;
-  x(idxM) = x(idxM) + xopt;
-  f = scale.^2*x.^2;
-  f = f - sum((xopt*scale(idxM)).^2); 
+end
+%scale(N) = 1e0;
+% M active bounds
+xopt = 0.1;
+x(idxM) = x(idxM) + xopt;
+f = scale.^2*x.^2;
+f = f - sum((xopt*scale(idxM)).^2);
 %  f = exp(f) - 1;
 %  f = log10(f+1e-19) + 19;
 
-  f = f + 1e-19;
-  
+f = f + 1e-19;
+
 function f=fcornersphere(x)
-  w = ones(size(x,1));
-  w(1) = 2.5; w(2)=2.5;
-  idx = x < 0;
-  f = sum(x(idx).^2);
-  idx = x > 0;
-  f = f + 2^2*sum(w(idx).*x(idx).^2);
-  
+w = ones(size(x,1));
+w(1) = 2.5; w(2)=2.5;
+idx = x < 0;
+f = sum(x(idx).^2);
+idx = x > 0;
+f = f + 2^2*sum(w(idx).*x(idx).^2);
+
 function f=fsectorsphere(x, scal)
 %
 % This is deceptive for cumulative sigma control CSA in large dimension:
 % The strategy (initially) diverges for N=50 and popsize = 150.  (Even
 % for cs==1 this can be observed for larger settings of N and
-% popsize.) The reason is obvious from the function topology. 
+% popsize.) The reason is obvious from the function topology.
 % Divergence can be avoided by setting boundaries or adding a
-% penalty for large ||x||. Then, convergence can be observed again. 
+% penalty for large ||x||. Then, convergence can be observed again.
 % Conclusion: for popsize>N cumulative sigma control is not completely
 % reasonable, but I do not know better alternatives. In particular:
-% TPA takes longer to converge than CSA when the latter still works. 
+% TPA takes longer to converge than CSA when the latter still works.
 %
-  if nargin < 2 || isempty (scal)
+if nargin < 2 || isempty (scal)
     scal = 1e3;
-  end
-  f=sum(x.^2,1);
-  idx = x<0;
-  f = f + (scal^2 - 1) * sum((idx.*x).^2,1);
-  if 11 < 3
+end
+f=sum(x.^2,1);
+idx = x<0;
+f = f + (scal^2 - 1) * sum((idx.*x).^2,1);
+if 11 < 3
     idxpen = find(f>1e9);
     if ~isempty(idxpen)
-      f(idxpen) = f(idxpen) + 1e8*sum(x(:,idxpen).^2,1);
+        f(idxpen) = f(idxpen) + 1e8*sum(x(:,idxpen).^2,1);
     end
-  end
-  
+end
+
 function f=fstepsphere(x, scal)
-  if nargin < 2 || isempty (scal)
+if nargin < 2 || isempty (scal)
     scal = 1e0;
-  end
-  N = size(x,1);
-  f=1e-11+sum(scal.^((0:N-1)/(N-1))*floor(x+0.5).^2);
-  f=1e-11+sum(floor(scal.^((0:N-1)/(N-1))'.*x+0.5).^2);
+end
+N = size(x,1);
+f=1e-11+sum(scal.^((0:N-1)/(N-1))*floor(x+0.5).^2);
+f=1e-11+sum(floor(scal.^((0:N-1)/(N-1))'.*x+0.5).^2);
 %  f=1e-11+sum(floor(x+0.5).^2);
 
 function f=fstep(x)
-  % in -5.12..5.12 (bounded)
-  N = size(x,1);
-  f=1e-11+6*N+sum(floor(x));
+% in -5.12..5.12 (bounded)
+N = size(x,1);
+f=1e-11+6*N+sum(floor(x));
 
 function f=flnorm(x, scal, e)
 if nargin < 2 || isempty(scal)
-  scal = 1;
+    scal = 1;
 end
 if nargin < 3 || isempty(e)
-  e = 1;
+    e = 1;
 end
 if e==inf
-  f = max(abs(x));
+    f = max(abs(x));
 else
-  N = size(x,1);
-  scale = scal.^((0:N-1)/(N-1))';
-  f=sum(abs(scale.*x).^e);
+    N = size(x,1);
+    scale = scal.^((0:N-1)/(N-1))';
+    f=sum(abs(scale.*x).^e);
 end
 
-function f=fneumaier3(x) 
-  % in -n^2..n^2
-  % x^*-i = i(n+1-i)
-  N = size(x,1);
+function f=fneumaier3(x)
+% in -n^2..n^2
+% x^*-i = i(n+1-i)
+N = size(x,1);
 %  f = N*(N+4)*(N-1)/6 + sum((x-1).^2) - sum(x(1:N-1).*x(2:N));
-  f = sum((x-1).^2) - sum(x(1:N-1).*x(2:N));
+f = sum((x-1).^2) - sum(x(1:N-1).*x(2:N));
 
 function f = fmaxmindist(y)
-  % y in [-1,1], y(1:2) is first point on a plane, y(3:4) second etc
-  % points best
-  %   5    1.4142
-  %   8    1.03527618 
-  %  10    0.842535997 
-  %  20    0.5997   
-  pop = size(y,2);
-  N = size(y,1)/2;
-  f = []; 
-  for ipop = 1:pop
+% y in [-1,1], y(1:2) is first point on a plane, y(3:4) second etc
+% points best
+%   5    1.4142
+%   8    1.03527618
+%  10    0.842535997
+%  20    0.5997
+pop = size(y,2);
+N = size(y,1)/2;
+f = [];
+for ipop = 1:pop
     if any(abs(y(:,ipop)) > 1)
-      f(ipop) = NaN; 
+        f(ipop) = NaN;
     else
-      x = reshape(y(:,ipop), [2, N]);
-      f(ipop) = inf;
-      for i = 1:N
-        f(ipop) = min(f(ipop), min(sqrt(sum((x(:,[1:i-1 i+1:N]) - repmat(x(:,i), 1, N-1)).^2, 1))));
-      end
+        x = reshape(y(:,ipop), [2, N]);
+        f(ipop) = inf;
+        for i = 1:N
+            f(ipop) = min(f(ipop), min(sqrt(sum((x(:,[1:i-1 i+1:N]) - repmat(x(:,i), 1, N-1)).^2, 1))));
+        end
     end
-  end
-  f = -f;
+end
+f = -f;
 
 function f=fchangingsphere(x)
-  N = size(x,1);
-  global scale_G; global count_G; if isempty(count_G) count_G=-1; end
-  count_G = count_G+1;
-  if mod(count_G,10) == 0
+N = size(x,1);
+global scale_G; global count_G; if isempty(count_G) count_G=-1; end
+count_G = count_G+1;
+if mod(count_G,10) == 0
     scale_G = 10.^(2*rand(1,N));
-  end
-  %disp(scale(1));
-  f = scale_G*x.^2;
-  
+end
+%disp(scale(1));
+f = scale_G*x.^2;
+
 function f= flogsphere(x)
- f = 1-exp(-sum(x.^2));
-  
+f = 1-exp(-sum(x.^2));
+
 function f= fexpsphere(x)
- f = exp(sum(x.^2)) - 1;
-  
+f = exp(sum(x.^2)) - 1;
+
 function f=fbaluja(x)
-  % in [-0.16 0.16]
-  y = x(1);
-  for i = 2:length(x)
+% in [-0.16 0.16]
+y = x(1);
+for i = 2:length(x)
     y(i) = x(i) + y(i-1);
-  end
-  f = 1e5 - 1/(1e-5 + sum(abs(y)));
+end
+f = 1e5 - 1/(1e-5 + sum(abs(y)));
 
 function f=fschwefel(x)
-  f = 0;
-  for i = 1:size(x,1),
+f = 0;
+for i = 1:size(x,1)
     f = f+sum(x(1:i))^2;
-  end
+end
 
 function f=fcigar(x, ar)
-  if nargin < 2 || isempty(ar)
+if nargin < 2 || isempty(ar)
     ar = 1e3;
-  end
-  f = x(1,:).^2 + ar^2*sum(x(2:end,:).^2,1);
-  
+end
+f = x(1,:).^2 + ar^2*sum(x(2:end,:).^2,1);
+
 function f=fcigtab(x)
-  f = x(1,:).^2 + 1e8*x(end,:).^2 + 1e4*sum(x(2:(end-1),:).^2, 1);
-  
+f = x(1,:).^2 + 1e8*x(end,:).^2 + 1e4*sum(x(2:(end-1),:).^2, 1);
+
 function f=ftablet(x)
-  f = 1e6*x(1,:).^2 + sum(x(2:end,:).^2, 1);
+f = 1e6*x(1,:).^2 + sum(x(2:end,:).^2, 1);
 
 function f=felli(x, lgscal, expon, expon2)
-  % lgscal: log10(axis ratio)
-  % expon: x_i^expon, sphere==2
-  N = size(x,1); if N < 2 error('dimension must be greater one'); end
+% lgscal: log10(axis ratio)
+% expon: x_i^expon, sphere==2
+N = size(x,1); if N < 2 error('dimension must be greater one'); end
 
 %  x = x - repmat(-0.5+(1:N)',1,size(x,2)); % optimum in 1:N
-  if nargin < 2 || isempty(lgscal), lgscal = 3; end
-  if nargin < 3 || isempty(expon), expon = 2; end
-  if nargin < 4 || isempty(expon2), expon2 = 1; end
+if nargin < 2 || isempty(lgscal), lgscal = 3; end
+if nargin < 3 || isempty(expon), expon = 2; end
+if nargin < 4 || isempty(expon2), expon2 = 1; end
 
-  f=((10^(lgscal*expon)).^((0:N-1)/(N-1)) * abs(x).^expon).^(1/expon2);
+f=((10^(lgscal*expon)).^((0:N-1)/(N-1)) * abs(x).^expon).^(1/expon2);
 %  if rand(1,1) > 0.015
 %    f = NaN;
 %  end
 %  f = f + randn(size(f));
 
 function f=fellitest(x)
-  beta = 0.9;
-  N = size(x,1);
-  f = (1e6.^((0:(N-1))/(N-1))).^beta * (x.^2).^beta; 
+beta = 0.9;
+N = size(x,1);
+f = (1e6.^((0:(N-1))/(N-1))).^beta * (x.^2).^beta;
+
 
-  
 function f=fellii(x, scal)
-  N = size(x,1); if N < 2 error('dimension must be greater one'); end
-  if nargin < 2
+N = size(x,1); if N < 2 error('dimension must be greater one'); end
+if nargin < 2
     scal = 1;
-  end
-  f= (scal*(1:N)).^2 * (x).^2;
+end
+f= (scal*(1:N)).^2 * (x).^2;
 
 function f=fellirot(x)
-  N = size(x,1);
-  global ORTHOGONALCOORSYSTEM_G
-  if isempty(ORTHOGONALCOORSYSTEM_G) ...
-	|| length(ORTHOGONALCOORSYSTEM_G) < N ...
-	|| isempty(ORTHOGONALCOORSYSTEM_G{N})
+N = size(x,1);
+global ORTHOGONALCOORSYSTEM_G
+if isempty(ORTHOGONALCOORSYSTEM_G) ...
+        || length(ORTHOGONALCOORSYSTEM_G) < N ...
+        || isempty(ORTHOGONALCOORSYSTEM_G{N})
     coordinatesystem(N);
-  end
-  f = felli(ORTHOGONALCOORSYSTEM_G{N}*x);
-  
+end
+f = felli(ORTHOGONALCOORSYSTEM_G{N}*x);
+
 function f=frot(x, fun, varargin)
-  N = size(x,1);
-  global ORTHOGONALCOORSYSTEM_G
-  if isempty(ORTHOGONALCOORSYSTEM_G) ...
-	|| length(ORTHOGONALCOORSYSTEM_G) < N ...
-	|| isempty(ORTHOGONALCOORSYSTEM_G{N})
+N = size(x,1);
+global ORTHOGONALCOORSYSTEM_G
+if isempty(ORTHOGONALCOORSYSTEM_G) ...
+        || length(ORTHOGONALCOORSYSTEM_G) < N ...
+        || isempty(ORTHOGONALCOORSYSTEM_G{N})
     coordinatesystem(N);
-  end
-  f = feval(fun, ORTHOGONALCOORSYSTEM_G{N}*x, varargin{:});
-  
+end
+f = feval(fun, ORTHOGONALCOORSYSTEM_G{N}*x, varargin{:});
+
 function coordinatesystem(N)
-  if nargin < 1 || isempty(N)
+if nargin < 1 || isempty(N)
     arN = 2:30;
-  else
+else
     arN = N;
-  end
-  global ORTHOGONALCOORSYSTEM_G
-  ORTHOGONALCOORSYSTEM_G{1} = 1; 
-  for N = arN
+end
+global ORTHOGONALCOORSYSTEM_G
+ORTHOGONALCOORSYSTEM_G{1} = 1;
+for N = arN
     ar = randn(N,N);
-    for i = 1:N 
-      for j = 1:i-1
-	ar(:,i) = ar(:,i) - ar(:,i)'*ar(:,j) * ar(:,j);
-      end
-      ar(:,i) = ar(:,i) / norm(ar(:,i));
+    for i = 1:N
+        for j = 1:i-1
+            ar(:,i) = ar(:,i) - ar(:,i)'*ar(:,j) * ar(:,j);
+        end
+        ar(:,i) = ar(:,i) / norm(ar(:,i));
     end
-    ORTHOGONALCOORSYSTEM_G{N} = ar; 
-  end
+    ORTHOGONALCOORSYSTEM_G{N} = ar;
+end
 
 function f=fplane(x)
-  f=x(1);
+f=x(1);
 
 function f=ftwoaxes(x)
-  f = sum(x(1:floor(end/2),:).^2, 1) + 1e6*sum(x(floor(1+end/2):end,:).^2, 1);
+f = sum(x(1:floor(end/2),:).^2, 1) + 1e6*sum(x(floor(1+end/2):end,:).^2, 1);
 
 function f=fparabR(x)
-  f = -x(1,:) + 100*sum(x(2:end,:).^2,1);
+f = -x(1,:) + 100*sum(x(2:end,:).^2,1);
 
 function f=fsharpR(x)
-  f = abs(-x(1, :)).^2 + 100 * sqrt(sum(x(2:end,:).^2, 1));
-  
+f = abs(-x(1, :)).^2 + 100 * sqrt(sum(x(2:end,:).^2, 1));
+
 function f=frosen(x)
-  if size(x,1) < 2 error('dimension must be greater one'); end
-  N = size(x,1); 
-  popsi = size(x,2); 
-  f = 1e2*sum((x(1:end-1,:).^2 - x(2:end,:)).^2,1) + sum((x(1:end-1,:)-1).^2,1);
-  % f = f + f^0.9 .* (2*randn(1,popsi) ./ randn(1,popsi).^0 / (2*N)); 
+if size(x,1) < 2, error('dimension must be greater one'); end
+N = size(x,1);
+popsi = size(x,2);
+f = 1e2*sum((x(1:end-1,:).^2 - x(2:end,:)).^2,1) + sum((x(1:end-1,:)-1).^2,1);
+% f = f + f^0.9 .* (2*randn(1,popsi) ./ randn(1,popsi).^0 / (2*N));
 
 function f=frosenlin(x)
-  if size(x,1) < 2 error('dimension must be greater one'); end
+if size(x,1) < 2 error('dimension must be greater one'); end
 
-  x_org = x;
-  x(x>30) = 30;
-  x(x<-30) = -30;
+x_org = x;
+x(x>30) = 30;
+x(x<-30) = -30;
 
-  f = 1e2*sum(-(x(1:end-1,:).^2 - x(2:end,:)),1) + ...
-      sum((x(1:end-1,:)-1).^2,1);
+f = 1e2*sum(-(x(1:end-1,:).^2 - x(2:end,:)),1) + ...
+    sum((x(1:end-1,:)-1).^2,1);
 
-  f = f + sum((x-x_org).^2,1);
-%  f(any(abs(x)>30,1)) = NaN; 
+f = f + sum((x-x_org).^2,1);
+%  f(any(abs(x)>30,1)) = NaN;
 
 function f=frosenrot(x)
-  N = size(x,1);
-  global ORTHOGONALCOORSYSTEM_G
-  if isempty(ORTHOGONALCOORSYSTEM_G) ...
-	|| length(ORTHOGONALCOORSYSTEM_G) < N ...
-	|| isempty(ORTHOGONALCOORSYSTEM_G{N})
+N = size(x,1);
+global ORTHOGONALCOORSYSTEM_G
+if isempty(ORTHOGONALCOORSYSTEM_G) ...
+        || length(ORTHOGONALCOORSYSTEM_G) < N ...
+        || isempty(ORTHOGONALCOORSYSTEM_G{N})
     coordinatesystem(N);
-  end
-  f = frosen(ORTHOGONALCOORSYSTEM_G{N}*x);
+end
+f = frosen(ORTHOGONALCOORSYSTEM_G{N}*x);
 
 function f=frosenmodif(x)
-  f = 74 + 100*(x(2)-x(1)^2)^2 + (1-x(1))^2 ...
-      - 400*exp(-sum((x+1).^2)/2/0.05);
-  
+f = 74 + 100*(x(2)-x(1)^2)^2 + (1-x(1))^2 ...
+    - 400*exp(-sum((x+1).^2)/2/0.05);
+
 function f=fschwefelrosen1(x)
-  % in [-10 10] 
-  f=sum((x.^2-x(1)).^2 + (x-1).^2);
-  
+% in [-10 10]
+f=sum((x.^2-x(1)).^2 + (x-1).^2);
+
 function f=fschwefelrosen2(x)
-  % in [-10 10] 
-  f=sum((x(2:end).^2-x(1)).^2 + (x(2:end)-1).^2);
+% in [-10 10]
+f=sum((x(2:end).^2-x(1)).^2 + (x(2:end)-1).^2);
 
 function f=fdiffpow(x)
-  [N popsi] = size(x); if N < 2 error('dimension must be greater one'); end
+[N, popsi] = size(x); if N < 2 error('dimension must be greater one'); end
 
-  f = sum(abs(x).^repmat(2+10*(0:N-1)'/(N-1), 1, popsi), 1);
-  f = sqrt(f); 
+f = sum(abs(x).^repmat(2+10*(0:N-1)'/(N-1), 1, popsi), 1);
+f = sqrt(f);
 
 function f=fabsprod(x)
-  f = sum(abs(x),1) + prod(abs(x),1);
+f = sum(abs(x),1) + prod(abs(x),1);
 
 function f=ffloor(x)
-  f = sum(floor(x+0.5).^2,1); 
+f = sum(floor(x+0.5).^2,1);
 
 function f=fmaxx(x)
-  f = max(abs(x), [], 1);
+f = max(abs(x), [], 1);
 
-%%% Multimodal functions 
+%%% Multimodal functions
 
 function f=fbirastrigin(x)
-% todo: the volume needs to be a constant 
-  N = size(x,1); 
-  idx = (sum(x, 1) < 0.5*N); % global optimum
-  f = zeros(1,size(x,2));
-  f(idx) = 10*(N-sum(cos(2*pi*x(:,idx)),1)) + sum(x(:,idx).^2,1); 
-  idx = ~idx;
-  f(idx) = 0.1 + 10*(N-sum(cos(2*pi*(x(:,idx)-2)),1)) + sum((x(:,idx)-2).^2,1); 
+% todo: the volume needs to be a constant
+N = size(x,1);
+idx = (sum(x, 1) < 0.5*N); % global optimum
+f = zeros(1,size(x,2));
+f(idx) = 10*(N-sum(cos(2*pi*x(:,idx)),1)) + sum(x(:,idx).^2,1);
+idx = ~idx;
+f(idx) = 0.1 + 10*(N-sum(cos(2*pi*(x(:,idx)-2)),1)) + sum((x(:,idx)-2).^2,1);
 
 function f=fackley(x)
-  % -32.768..32.768
-  % Adding a penalty outside the interval is recommended,  
-  % because for large step sizes, fackley imposes like frand
-  % 
-  N = size(x,1); 
-  f = 20-20*exp(-0.2*sqrt(sum(x.^2)/N)); 
-  f = f + (exp(1) - exp(sum(cos(2*pi*x))/N));
-  % add penalty outside the search interval
-  f = f + sum((x(x>32.768)-32.768).^2) + sum((x(x<-32.768)+32.768).^2);
-  
+% -32.768..32.768
+% Adding a penalty outside the interval is recommended,
+% because for large step sizes, fackley imposes like frand
+%
+N = size(x,1);
+f = 20-20*exp(-0.2*sqrt(sum(x.^2)/N));
+f = f + (exp(1) - exp(sum(cos(2*pi*x))/N));
+% add penalty outside the search interval
+f = f + sum((x(x>32.768)-32.768).^2) + sum((x(x<-32.768)+32.768).^2);
+
 function f = fbohachevsky(x)
- % -15..15
-  f = sum(x(1:end-1).^2 + 2 * x(2:end).^2 - 0.3 * cos(3*pi*x(1:end-1)) ...
-	  - 0.4 * cos(4*pi*x(2:end)) + 0.7);
-  
+% -15..15
+f = sum(x(1:end-1).^2 + 2 * x(2:end).^2 - 0.3 * cos(3*pi*x(1:end-1)) ...
+        - 0.4 * cos(4*pi*x(2:end)) + 0.7);
+
 function f=fconcentric(x)
-  % in  +-600
-  s = sum(x.^2);
-  f = s^0.25 * (sin(50*s^0.1)^2 + 1);
+% in  +-600
+s = sum(x.^2);
+f = s^0.25 * (sin(50*s^0.1)^2 + 1);
 
 function f=fgriewank(x)
-  % in [-600 600]
-  [N, P] = size(x);
-  f = 1 - prod(cos(x'./sqrt(1:N))) + sum(x.^2)/4e3;
-  scale = repmat(sqrt(1:N)', 1, P);
-  f = 1 - prod(cos(x./scale), 1) + sum(x.^2, 1)/4e3;
-  % f = f + 1e4*sum(x(abs(x)>5).^2);
-  % if sum(x(abs(x)>5).^2) > 0
-  %   f = 1e4 * sum(x(abs(x)>5).^2) + 1e8 * sum(x(x>5)).^2;
-  % end
+% in [-600 600]
+[N, P] = size(x);
+f = 1 - prod(cos(x'./sqrt(1:N))) + sum(x.^2)/4e3;
+scale = repmat(sqrt(1:N)', 1, P);
+f = 1 - prod(cos(x./scale), 1) + sum(x.^2, 1)/4e3;
+% f = f + 1e4*sum(x(abs(x)>5).^2);
+% if sum(x(abs(x)>5).^2) > 0
+%   f = 1e4 * sum(x(abs(x)>5).^2) + 1e8 * sum(x(x>5)).^2;
+% end
 
 function f=fgriewrosen(x)
 % F13 or F8F2
-  [N, P] = size(x);
-  scale = repmat(sqrt(1:N)', 1, P);
-  y = [x(2:end,:); x(1,:)];
-  x = 100 * (x.^2 - y) + (x - 1).^2;  % Rosenbrock part
-  f = 1 - prod(cos(x./scale), 1) + sum(x.^2, 1)/4e3;
-  f = sum(1 - cos(x) + x.^2/4e3, 1);
+[N, P] = size(x);
+scale = repmat(sqrt(1:N)', 1, P);
+y = [x(2:end,:); x(1,:)];
+x = 100 * (x.^2 - y) + (x - 1).^2;  % Rosenbrock part
+f = 1 - prod(cos(x./scale), 1) + sum(x.^2, 1)/4e3;
+f = sum(1 - cos(x) + x.^2/4e3, 1);
 
 function f=fspallpseudorastrigin(x, scal, skewfac, skewstart, amplitude)
 % by default multi-modal about between -30 and 30
-  if nargin < 5 || isempty(amplitude)
+if nargin < 5 || isempty(amplitude)
     amplitude = 40;
-  end
-  if nargin < 4 || isempty(skewstart)
+end
+if nargin < 4 || isempty(skewstart)
     skewstart = 0;
-  end
-  if nargin < 3 || isempty(skewfac)
+end
+if nargin < 3 || isempty(skewfac)
     skewfac = 1;
-  end
-  if nargin < 2 || isempty(scal)
+end
+if nargin < 2 || isempty(scal)
     scal = 1;
-  end
-  N = size(x,1); 
-  scale = 1;
-  if N > 1
-    scale=scal.^((0:N-1)'/(N-1)); 
-  end
-  % simple version: 
-  % f = amplitude*(N - sum(cos(2*pi*(scale.*x)))) + sum((scale.*x).^2);
-
-  % skew version: 
-  y = repmat(scale, 1, size(x,2)) .* x;
-  idx = find(x > skewstart);
-  if ~isempty(idx)
+end
+N = size(x,1);
+scale = 1;
+if N > 1
+    scale=scal.^((0:N-1)'/(N-1));
+end
+% simple version:
+% f = amplitude*(N - sum(cos(2*pi*(scale.*x)))) + sum((scale.*x).^2);
+
+% skew version:
+y = repmat(scale, 1, size(x,2)) .* x;
+idx = find(x > skewstart);
+if ~isempty(idx)
     y(idx) =  skewfac*y(idx);
-  end
-  f = amplitude * (0*N-prod(cos((2*pi)^0*y),1)) + 0.05 * sum(y.^2,1) ...
-      + randn(1,1);
+end
+f = amplitude * (0*N-prod(cos((2*pi)^0*y),1)) + 0.05 * sum(y.^2,1) ...
+    + randn(1,1);
 
 function f=frastrigin(x, scal, skewfac, skewstart, amplitude)
 % by default multi-modal about between -30 and 30
-  if nargin < 5 || isempty(amplitude)
+if nargin < 5 || isempty(amplitude)
     amplitude = 10;
-  end
-  if nargin < 4 || isempty(skewstart)
+end
+if nargin < 4 || isempty(skewstart)
     skewstart = 0;
-  end
-  if nargin < 3 || isempty(skewfac)
+end
+if nargin < 3 || isempty(skewfac)
     skewfac = 1;
-  end
-  if nargin < 2 || isempty(scal)
+end
+if nargin < 2 || isempty(scal)
     scal = 1;
-  end
-  N = size(x,1); 
-  scale = 1;
-  if N > 1
-    scale=scal.^((0:N-1)'/(N-1)); 
-  end
-  % simple version: 
-  % f = amplitude*(N - sum(cos(2*pi*(scale.*x)))) + sum((scale.*x).^2);
-
-  % skew version: 
-  y = repmat(scale, 1, size(x,2)) .* x;
-  idx = find(x > skewstart);
-  % idx = intersect(idx, 2:2:10); 
-  if ~isempty(idx)
+end
+N = size(x,1);
+scale = 1;
+if N > 1
+    scale=scal.^((0:N-1)'/(N-1));
+end
+% simple version:
+% f = amplitude*(N - sum(cos(2*pi*(scale.*x)))) + sum((scale.*x).^2);
+
+% skew version:
+y = repmat(scale, 1, size(x,2)) .* x;
+idx = find(x > skewstart);
+% idx = intersect(idx, 2:2:10);
+if ~isempty(idx)
     y(idx) =  skewfac*y(idx);
-  end
-  f = amplitude * (N-sum(cos(2*pi*y),1)) + sum(y.^2,1);
-  
+end
+f = amplitude * (N-sum(cos(2*pi*y),1)) + sum(y.^2,1);
+
 function f=frastriginmax(x)
-  N = size(x,1);
-  f = (N/20)*807.06580387678 - (10 * (N-sum(cos(2*pi*x),1)) + sum(x.^2,1));
-  f(any(abs(x) > 5.12)) = 1e2*N;
+N = size(x,1);
+f = (N/20)*807.06580387678 - (10 * (N-sum(cos(2*pi*x),1)) + sum(x.^2,1));
+f(any(abs(x) > 5.12)) = 1e2*N;
 
 function f = fschaffer(x)
- % -100..100
-  N = size(x,1);
-  s = x(1:N-1,:).^2 + x(2:N,:).^2;
-  f = sum(s.^0.25 .* (sin(50*s.^0.1).^2+1), 1);
+% -100..100
+N = size(x,1);
+s = x(1:N-1,:).^2 + x(2:N,:).^2;
+f = sum(s.^0.25 .* (sin(50*s.^0.1).^2+1), 1);
 
 function f=fschwefelmult(x)
-  % -500..500
-  % 
-  N = size(x,1); 
-  f = - sum(x.*sin(sqrt(abs(x))), 1);
-  f = 418.9829*N - 1.27275661e-5*N - sum(x.*sin(sqrt(abs(x))), 1);
-  % penalty term 
-  f = f + 1e4*sum((abs(x)>500) .* (abs(x)-500).^2, 1);
-  
+% -500..500
+%
+N = size(x,1);
+f = - sum(x.*sin(sqrt(abs(x))), 1);
+f = 418.9829*N - 1.27275661e-5*N - sum(x.*sin(sqrt(abs(x))), 1);
+% penalty term
+f = f + 1e4*sum((abs(x)>500) .* (abs(x)-500).^2, 1);
+
 function f=ftwomax(x)
-  % Boundaries at +/-5
-  N = size(x,1); 
-  f = -abs(sum(x)) + 5*N;
+% Boundaries at +/-5
+N = size(x,1);
+f = -abs(sum(x)) + 5*N;
 
 function f=ftwomaxtwo(x)
-  % Boundaries at +/-10
-  N = size(x,1); 
-  f = abs(sum(x));
-  if f > 30
+% Boundaries at +/-10
+N = size(x,1);
+f = abs(sum(x));
+if f > 30
     f = f - 30;
-  end
-  f = -f;
-  
+end
+f = -f;
+
 function f=frand(x)
-  f=1./(1-rand(1, size(x,2))) - 1;
+f=1./(1-rand(1, size(x,2))) - 1;
 
 % CHANGES
 % 12/02/19: "future" setting of ccum, correcting for large mueff, is default now
 % 11/11/15: bug-fix: max value for ccovmu_sep setting corrected
-% 10/11/11: (3.52.beta) boundary handling: replace max with min in change 
-%           rate formula. Active CMA: check of pos.def. improved. 
-%           Plotting: value of lambda appears in the title. 
+% 10/11/11: (3.52.beta) boundary handling: replace max with min in change
+%           rate formula. Active CMA: check of pos.def. improved.
+%           Plotting: value of lambda appears in the title.
 % 10/04/03: (3.51.beta) active CMA cleaned up. Equal fitness detection
-%           looks into history now. 
+%           looks into history now.
 % 10/03/08: (3.50.beta) "active CMA" revised and bug-fix of ambiguous
-%           option Noise.alpha -> Noise.alphasigma. 
-% 09/10/12: (3.40.beta) a slightly modified version of "active CMA", 
+%           option Noise.alpha -> Noise.alphasigma.
+% 09/10/12: (3.40.beta) a slightly modified version of "active CMA",
 %           that is a negative covariance matrix update, use option
-%           CMA.active. In 10;30;90-D the gain on ftablet is a factor 
-%           of 1.6;2.5;4.4 (the scaling improves by sqrt(N)). On 
-%           Rosenbrock the gain is about 25%. On sharp ridge the 
-%           behavior is improved. Cigar is unchanged. 
-% 09/08/10: local plotcmaesdat remains in backround  
-% 09/08/10: bug-fix in time management for data writing, logtime was not 
-%        considered properly (usually not at all). 
-% 09/07/05: V3.24: stagnation termination added 
+%           CMA.active. In 10;30;90-D the gain on ftablet is a factor
+%           of 1.6;2.5;4.4 (the scaling improves by sqrt(N)). On
+%           Rosenbrock the gain is about 25%. On sharp ridge the
+%           behavior is improved. Cigar is unchanged.
+% 09/08/10: local plotcmaesdat remains in backround
+% 09/08/10: bug-fix in time management for data writing, logtime was not
+%        considered properly (usually not at all).
+% 09/07/05: V3.24: stagnation termination added
 % 08/09/27: V3.23: momentum alignment is out-commented and de-preciated
 % 08/09/25: V3.22: re-alignment of sigma and C was buggy
 % 08/07/15: V3.20, CMA-parameters are options now. ccov and mucov were replaced
 %        by ccov1 \approx ccov/mucov and ccovmu \approx (1-1/mucov)*ccov
-% 08/06/30: file name xrecent was change to xrecentbest (compatible with other 
+% 08/06/30: file name xrecent was change to xrecentbest (compatible with other
 %        versions)
-% 08/06/29: time stamp added to output files 
-% 08/06/28: bug fixed with resume option, commentary did not work 
+% 08/06/29: time stamp added to output files
+% 08/06/28: bug fixed with resume option, commentary did not work
 % 08/06/28: V3.10, uncertainty (noise) handling added (re-implemented), according
 %        to reference "A Method for Handling Uncertainty..." from below.
-% 08/06/28: bug fix: file xrecent was empty 
-% 08/06/01: diagonalonly clean up. >1 means some iterations. 
+% 08/06/28: bug fix: file xrecent was empty
+% 08/06/01: diagonalonly clean up. >1 means some iterations.
 % 08/05/05: output is written to file preventing an increasing data
-%        array and ease long runs. 
-% 08/03/27: DiagonalOnly<0 learns for -DiagonalOnly iterations only the 
-%        diagonal with a larger learning rate. 
-% 08/03 (2.60): option DiagonalOnly>=1 invokes a time- and space-linear  
-%        variant with only diagonal elements of the covariance matrix 
-%        updating.  This can be useful for large dimensions, say > 100. 
+%        array and ease long runs.
+% 08/03/27: DiagonalOnly<0 learns for -DiagonalOnly iterations only the
+%        diagonal with a larger learning rate.
+% 08/03 (2.60): option DiagonalOnly>=1 invokes a time- and space-linear
+%        variant with only diagonal elements of the covariance matrix
+%        updating.  This can be useful for large dimensions, say > 100.
 % 08/02: diag(weights) * ... replaced with repmat(weights,1,N) .* ...
-%        in C update, implies O(mu*N^2) instead of O(mu^2*N + mu*N^2). 
+%        in C update, implies O(mu*N^2) instead of O(mu^2*N + mu*N^2).
 % 07/09: tolhistfun as termination criterion added, "<" changed to
-%        "<=" also for TolFun to allow for stopping on zero difference. 
-%        Name tolfunhist clashes with option tolfun. 
-% 07/07: hsig threshold made slighly smaller for large dimension, 
-%        useful for lambda < lambda_default. 
+%        "<=" also for TolFun to allow for stopping on zero difference.
+%        Name tolfunhist clashes with option tolfun.
+% 07/07: hsig threshold made slighly smaller for large dimension,
+%        useful for lambda < lambda_default.
 % 07/06: boundary handling: scaling in the boundary handling
 %        is omitted now, see bnd.flgscale. This seems not to
 %        have a big impact. Using the scaling is worse on rotated
-%        functions, but better on separable ones. 
+%        functions, but better on separable ones.
 % 07/05: boundary handling: weight i is not incremented anymore
 %        if xmean(i) moves towards the feasible space. Increment
-%        factor changed to 1.2 instead of 1.1. 
+%        factor changed to 1.2 instead of 1.1.
 % 07/05: boundary handling code simplified not changing the algorithm
 % 07/04: bug removed for saving in octave
 % 06/11/10: more testing of outcome of eig, fixed max(D) to max(diag(D))
-% 06/10/21: conclusive final bestever assignment in the end 
+% 06/10/21: conclusive final bestever assignment in the end
 % 06/10/21: restart and incpopsize option implemented for restarts
-%        with increasing population size, version 2.50. 
+%        with increasing population size, version 2.50.
 % 06/09/16: output argument bestever inserted again for convenience and
 %        backward compatibility
-% 06/08: output argument out and struct out reorganized. 
+% 06/08: output argument out and struct out reorganized.
 % 06/01: Possible parallel evaluation included as option EvalParallel
 % 05/11: Compatibility to octave implemented, package octave-forge
-%   is needed. 
+%   is needed.
 % 05/09: Raise of figure and waiting for first plots improved
-% 05/01: Function coordinatesystem cleaned up. 
+% 05/01: Function coordinatesystem cleaned up.
 % 05/01: Function prctile, which requires the statistics toolbox,
-%        replaced by myprctile. 
-% 05/01: Option warnonequalfunctionvalues included. 
-% 04/12: Decrease of sigma removed. Problems on fsectorsphere can 
-%        be addressed better by adding search space boundaries. 
-% 04/12: Boundary handling simpyfied. 
-% 04/12: Bug when stopping criteria tolx or tolupx are vectors. 
-% 04/11: Three input parameters are obligatory now. 
-% 04/11: Bug in boundary handling removed: Boundary weights can decrease now. 
-% 04/11: Normalization for boundary weights scale changed. 
-% 04/11: VerboseModulo option bug removed. Documentation improved. 
+%        replaced by myprctile.
+% 05/01: Option warnonequalfunctionvalues included.
+% 04/12: Decrease of sigma removed. Problems on fsectorsphere can
+%        be addressed better by adding search space boundaries.
+% 04/12: Boundary handling simpyfied.
+% 04/12: Bug when stopping criteria tolx or tolupx are vectors.
+% 04/11: Three input parameters are obligatory now.
+% 04/11: Bug in boundary handling removed: Boundary weights can decrease now.
+% 04/11: Normalization for boundary weights scale changed.
+% 04/11: VerboseModulo option bug removed. Documentation improved.
 % 04/11: Condition for increasing boundary weights changed.
 % 04/10: Decrease of sigma when fitness is getting consistenly
 %        worse. Addresses the problems appearing on fsectorsphere for
 %        large population size.
-% 04/10: VerboseModulo option included. 
+% 04/10: VerboseModulo option included.
 % 04/10: Bug for condition for increasing boundary weights removed.
 % 04/07: tolx depends on initial sigma to achieve scale invariance
-%        for this stopping criterion. 
+%        for this stopping criterion.
 % 04/06: Objective function value NaN is not counted as function
-%        evaluation and invokes resampling of the search point. 
+%        evaluation and invokes resampling of the search point.
 % 04/06: Error handling for eigenvalue beeing zero (never happens
 %        with default parameter setting)
-% 04/05: damps further tuned for large mueff 
-%      o Details for stall of pc-adaptation added (variable hsig 
-%        introduced). 
+% 04/05: damps further tuned for large mueff
+%      o Details for stall of pc-adaptation added (variable hsig
+%        introduced).
 % 04/05: Bug in boundary handling removed: A large initial SIGMA was
 %        corrected not until *after* the first iteration, which could
 %        lead to a complete failure.
-% 04/05: Call of function range (works with stats toolbox only) 
-%        changed to myrange. 
+% 04/05: Call of function range (works with stats toolbox only)
+%        changed to myrange.
 % 04/04: Parameter cs depends on mueff now and damps \propto sqrt(mueff)
-%        instead of \propto mueff. 
+%        instead of \propto mueff.
 %      o Initial stall to adapt C (flginiphase) is removed and
 %        adaptation of pc is stalled for large norm(ps) instead.
-%      o Returned default options include documentation. 
+%      o Returned default options include documentation.
 %      o Resume part reorganized.
-% 04/03: Stopflag becomes cell-array. 
+% 04/03: Stopflag becomes cell-array.
 
 % ---------------------------------------------------------------
 % CMA-ES: Evolution Strategy with Covariance Matrix Adaptation for
 % nonlinear function minimization. To be used under the terms of the
 % GNU General Public License (http://www.gnu.org/copyleft/gpl.html).
-% Author (copyright): Nikolaus Hansen, 2001-2008. 
+% Author (copyright): Nikolaus Hansen, 2001-2008.
 % e-mail: nikolaus.hansen AT inria.fr
 % URL:http://www.bionik.tu-berlin.de/user/niko
-% References: See below. 
+% References: See below.
 % ---------------------------------------------------------------
 %
 % GENERAL PURPOSE: The CMA-ES (Evolution Strategy with Covariance
@@ -2999,7 +2999,7 @@ function f=frand(x)
 % expected to take at least 30*N^2 and up to 300*N^2 function
 % evaluations.
 %
-% SOME MORE COMMENTS: 
+% SOME MORE COMMENTS:
 % The adaptation of the covariance matrix (e.g. by the CMA) is
 % equivalent to a general linear transformation of the problem
 % coding. Nevertheless every problem specific knowlegde about the best
@@ -3022,13 +3022,13 @@ function f=frand(x)
 % ---------------------------------------------------------------
 %%% REFERENCES
 %
-% The equation numbers refer to 
+% The equation numbers refer to
 % Hansen, N. and S. Kern (2004). Evaluating the CMA Evolution
 % Strategy on Multimodal Test Functions.  Eighth International
 % Conference on Parallel Problem Solving from Nature PPSN VIII,
-% Proceedings, pp. 282-291, Berlin: Springer. 
+% Proceedings, pp. 282-291, Berlin: Springer.
 % (http://www.bionik.tu-berlin.de/user/niko/ppsn2004hansenkern.pdf)
-% 
+%
 % Further references:
 % Hansen, N. and A. Ostermeier (2001). Completely Derandomized
 % Self-Adaptation in Evolution Strategies. Evolutionary Computation,
@@ -3050,6 +3050,3 @@ function f=frand(x)
 % Optimization with an Application to Feedback Control of
 % Combustion. To appear in IEEE Transactions on Evolutionary
 % Computation.
-
-
-
diff --git a/matlab/optimization/csminit1.m b/matlab/optimization/csminit1.m
index 1a07951957269e1ec3426f0d5e1fa5468f660965..22391027ebcbce9f5dcb4d3350c94474eb8aeb3f 100644
--- a/matlab/optimization/csminit1.m
+++ b/matlab/optimization/csminit1.m
@@ -1,7 +1,7 @@
 function [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,penalty,f0,g0,badg,H0,Verbose,varargin)
 % [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,penalty,f0,g0,badg,H0,Verbose,varargin)
-% 
-% Inputs: 
+%
+% Inputs:
 %   fcn:        [string]        string naming the objective function to be minimized
 %   x0:         [npar by 1]     initial value of the parameter vector
 %   penalty:    [scalar]        variable penalty in case of failure of objective function
@@ -20,7 +20,7 @@ function [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,penalty,f0,g0,badg,H0,Verb
 %   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.  
+%                               2,4: back and forth adjustment of stepsize didn't finish.
 %                               3: smallest stepsize still improves too slow
 %                               6: no improvement found
 %---------------------
@@ -33,12 +33,12 @@ function [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,penalty,f0,g0,badg,H0,Verb
 %
 % 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-2016 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -122,7 +122,7 @@ else
             disp_verbose(sprintf('Correct for low angle: %g',a),Verbose)
         end
     end
-        disp_verbose(sprintf('Predicted improvement: %18.9f',-dfhat/2),Verbose)
+    disp_verbose(sprintf('Predicted improvement: %18.9f',-dfhat/2),Verbose)
     %
     % Have OK dx, now adjust length of step (lambda) until min and
     % max improvement rate criteria are met.
@@ -145,7 +145,7 @@ else
         %ARGLIST
         %f = feval(fcn,dxtest,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,P13);
         % f = feval(fcn,x0+dx*lambda,P1,P2,P3,P4,P5,P6,P7,P8);
-            disp_verbose(sprintf('lambda = %10.5g; f = %20.7f',lambda,f ),Verbose)
+        disp_verbose(sprintf('lambda = %10.5g; f = %20.7f',lambda,f ),Verbose)
         %debug
         %disp(sprintf('Improvement too great? f0-f: %g, criterion: %g',f0-f,-(1-THETA)*dfhat*lambda))
         if f<fhat
@@ -183,7 +183,7 @@ else
                     if Verbose
                         lambda = -lambda*factor^6
                     else
-                        lambda = -lambda*factor^6;                        
+                        lambda = -lambda*factor^6;
                     end
                 else
                     if lambda < 0
@@ -216,7 +216,7 @@ else
                 end
             end
             lambda=lambda*factor;
-            if abs(lambda) > 1e20;
+            if abs(lambda) > 1e20
                 retcode = 5;
                 done =1;
             end
diff --git a/matlab/optimization/csminwel1.m b/matlab/optimization/csminwel1.m
index 52a018792979401f666456ea08cf7b34fe2415aa..cfa8699322bfb2d3fff98f4914f1ab86f9184f73 100644
--- a/matlab/optimization/csminwel1.m
+++ b/matlab/optimization/csminwel1.m
@@ -14,13 +14,13 @@ function [fh,xh,gh,H,itct,fcount,retcodeh] = csminwel1(fcn,x0,H0,grad,crit,nit,m
 %   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
 %        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
@@ -30,19 +30,19 @@ function [fh,xh,gh,H,itct,fcount,retcodeh] = csminwel1(fcn,x0,H0,grad,crit,nit,m
 %   fcount  [scalar]        function iteration count upon termination
 %   retcodeh [scalar]       return code:
 %                               0: normal step
-%                               1: zero gradient 
+%                               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-2015 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -59,7 +59,7 @@ function [fh,xh,gh,H,itct,fcount,retcodeh] = csminwel1(fcn,x0,H0,grad,crit,nit,m
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-% initialize variable penalty    
+% initialize variable penalty
 penalty = 1e8;
 fh = [];
 xh = [];
@@ -139,7 +139,7 @@ while ~done
         else
             if NumGrad
                 [g1, badg1]=get_num_grad(method,fcn,penalty,f1,x1,epsilon,varargin{:});
-            elseif ischar(grad),
+            elseif ischar(grad)
                 [g1, badg1] = grad(x1,varargin{:});
             else
                 [junk1,cost_flag,g1] = penalty_objective_function(x1,fcn,penalty,varargin{:});
@@ -166,7 +166,7 @@ while ~done
                 else
                     if NumGrad
                         [g2, badg2]=get_num_grad(method,fcn,penalty,f2,x2,epsilon,varargin{:});
-                    elseif ischar(grad),
+                    elseif ischar(grad)
                         [g2, badg2] = grad(x2,varargin{:});
                     else
                         [junk2,cost_flag,g2] = penalty_objective_function(x1,fcn,penalty,varargin{:});
@@ -193,12 +193,12 @@ while ~done
                         [f3, x3, fc, retcode3] = csminit1(fcn,x,penalty,f,gcliff,0,eye(nx),Verbose,varargin{:});
                         fcount = fcount+fc; % put by Jinill
                         if retcode3==2 || retcode3==4
-                            wall3=1; 
+                            wall3=1;
                             badg3=1;
                         else
                             if NumGrad
                                 [g3, badg3]=get_num_grad(method,fcn,penalty,f3,x3,epsilon,varargin{:});
-                            elseif ischar(grad),
+                            elseif ischar(grad)
                                 [g3, badg3] = grad(x3,varargin{:});
                             else
                                 [junk3,cost_flag,g3] = penalty_objective_function(x1,fcn,penalty,varargin{:});
@@ -258,7 +258,7 @@ while ~done
         if nogh
             if NumGrad
                 [gh, badgh]=get_num_grad(method,fcn,penalty,fh,xh,epsilon,varargin{:});
-            elseif ischar(grad),
+            elseif ischar(grad)
                 [gh, badgh] = grad(xh,varargin{:});
             else
                 [junkh,cost_flag,gh] = penalty_objective_function(x1,fcn,penalty,varargin{:});
@@ -302,7 +302,7 @@ while ~done
             error('Unaccounted Case, please contact the developers',Verbose)
         end
     end
-     
+
     f=fh;
     x=xh;
     g=gh;
@@ -312,18 +312,18 @@ end
 end
 
 function [g, badg]=get_num_grad(method,fcn,penalty,f0,x0,epsilon,varargin)
-    switch method
-      case 2
-        [g,badg] = numgrad2(fcn, f0, x0, penalty, epsilon, varargin{:});
-      case 3
-        [g,badg] = numgrad3(fcn, f0, x0, penalty, epsilon, varargin{:});
-      case 5
-        [g,badg] = numgrad5(fcn, f0, x0, penalty, epsilon, varargin{:});
-      case 13
-        [g,badg] = numgrad3_(fcn, f0, x0, penalty, epsilon, varargin{:});
-      case 15
-        [g,badg] = numgrad5_(fcn, f0, x0, penalty, epsilon, varargin{:});
-      otherwise
-        error('csminwel1: Unknown method for gradient evaluation!')
-    end
+switch method
+  case 2
+    [g,badg] = numgrad2(fcn, f0, x0, penalty, epsilon, varargin{:});
+  case 3
+    [g,badg] = numgrad3(fcn, f0, x0, penalty, epsilon, varargin{:});
+  case 5
+    [g,badg] = numgrad5(fcn, f0, x0, penalty, epsilon, varargin{:});
+  case 13
+    [g,badg] = numgrad3_(fcn, f0, x0, penalty, epsilon, varargin{:});
+  case 15
+    [g,badg] = numgrad5_(fcn, f0, x0, penalty, 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
index 0aebc6b50621e19577bd7879fb6af594f1c298d6..025d411899bb4112ad484210ca61ba9d4c0055a8 100644
--- a/matlab/optimization/dynare_minimize_objective.m
+++ b/matlab/optimization/dynare_minimize_objective.m
@@ -8,12 +8,12 @@ function [opt_par_values,fval,exitflag,hessian_mat,options_,Scale,new_rat_hess_i
 %   minimizer_algorithm [scalar double, or string]          code of the optimizer algorithm, or string for the name of a user defined optimization routine (not shipped with dynare).
 %   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   
+%   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
 %   new_rat_hess_info   [matlab structure]                  step size info used by algorith 5
 %   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
@@ -21,12 +21,12 @@ function [opt_par_values,fval,exitflag,hessian_mat,options_,Scale,new_rat_hess_i
 %   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-2016 Dynare Team
+%
+%
+% Copyright (C) 2014-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -77,7 +77,7 @@ switch minimizer_algorithm
     if options_.silent_optimizer
         optim_options = optimset(optim_options,'display','off');
     end
-    if options_.analytic_derivation,
+    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] = ...
@@ -148,7 +148,7 @@ switch minimizer_algorithm
     if ~isempty(options_.optim_opt)
         eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']);
     end
-    if options_.analytic_derivation,
+    if options_.analytic_derivation
         optim_options = optimset(optim_options,'GradObj','on');
     end
     if options_.silent_optimizer
@@ -188,16 +188,16 @@ switch minimizer_algorithm
               case 'verbosity'
                 Verbose = options_list{i,2};
               case 'SaveFiles'
-                Save_files = options_list{i,2};                
+                Save_files = options_list{i,2};
               otherwise
                 warning(['csminwel: Unknown option (' options_list{i,1} ')!'])
             end
         end
     end
     if options_.silent_optimizer
-        Save_files = 0; 
+        Save_files = 0;
         Verbose = 0;
-    end    
+    end
     % Set flag for analytical gradient.
     if options_.analytic_derivation
         analytic_grad=1;
@@ -232,23 +232,23 @@ switch minimizer_algorithm
                 if options_.analytic_derivation && flag~=0
                     error('newrat: analytic_derivation is incompatible with numerical Hessian. Using analytic Hessian')
                 else
-                    newratflag=flag; 
+                    newratflag=flag;
                 end
               case 'TolFun'
                 crit = options_list{i,2};
               case 'verbosity'
                 Verbose = options_list{i,2};
               case 'SaveFiles'
-                Save_files = options_list{i,2};                
+                Save_files = options_list{i,2};
               otherwise
                 warning(['newrat: Unknown option (' options_list{i,1} ')!'])
             end
         end
     end
     if options_.silent_optimizer
-        Save_files = 0; 
+        Save_files = 0;
         Verbose = 0;
-    end    
+    end
     hess_info.gstep=options_.gstep;
     hess_info.htol = 1.e-4;
     hess_info.h1=options_.gradient_epsilon*ones(n_params,1);
@@ -307,12 +307,15 @@ switch minimizer_algorithm
     end
     if options_.silent_optimizer
         simplexOptions.verbose = options_list{i,2};
-    end    
+    end
     [opt_par_values,fval,exitflag] = simplex_optimization_routine(objective_function,start_par_value,simplexOptions,parameter_names,varargin{:});
   case 9
     % Set defaults
     H0 = (bounds(:,2)-bounds(:,1))*0.2;
     H0(~isfinite(H0)) = 0.01;
+    while max(H0)/min(H0)>1e6 %make sure initial search volume (SIGMA) is not badly conditioned
+        H0(H0==max(H0))=0.9*H0(H0==max(H0));
+    end
     cmaesOptions = options_.cmaes;
     cmaesOptions.LBounds = bounds(:,1);
     cmaesOptions.UBounds = bounds(:,2);
@@ -336,14 +339,14 @@ switch minimizer_algorithm
                 end
               case 'SaveFiles'
                 if options_list{i,2}==0
-                  cmaesOptions.SaveVariables='off';
-                  cmaesOptions.LogModulo = '0';    % [0:Inf] if >1 record data less frequently after gen=100';
-                  cmaesOptions.LogTime   = '0';    % [0:100] max. percentage of time for recording data';
+                    cmaesOptions.SaveVariables='off';
+                    cmaesOptions.LogModulo = '0';    % [0:Inf] if >1 record data less frequently after gen=100';
+                    cmaesOptions.LogTime   = '0';    % [0:100] max. percentage of time for recording data';
                 end
               case 'CMAESResume'
-                  if options_list{i,2}==1
+                if options_list{i,2}==1
                     cmaesOptions.Resume = 'yes';
-                  end
+                end
               otherwise
                 warning(['cmaes: Unknown option (' options_list{i,1}  ')!'])
             end
@@ -355,7 +358,7 @@ switch minimizer_algorithm
         cmaesOptions.SaveVariables='off';
         cmaesOptions.LogModulo = '0';    % [0:Inf] if >1 record data less frequently after gen=100';
         cmaesOptions.LogTime   = '0';    % [0:100] max. percentage of time for recording data';
-    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{:});
@@ -383,11 +386,11 @@ switch minimizer_algorithm
               case 'MaxFunEvals'
                 simpsaOptions.MAX_FUN_EVALS = options_list{i,2};
               case 'verbosity'
-                  if options_list{i,2} == 0
+                if options_list{i,2} == 0
                     simpsaOptions.DISPLAY = 'none';
-                  else
+                else
                     simpsaOptions.DISPLAY = 'iter';
-                  end                      
+                end
               otherwise
                 warning(['simpsa: Unknown option (' options_list{i,1}  ')!'])
             end
@@ -411,10 +414,10 @@ switch minimizer_algorithm
     if ~isempty(options_.optim_opt)
         options_list = read_key_value_string(options_.optim_opt);
         SupportedListOfOptions = {'CreationFcn', 'Display', 'DisplayInterval', 'FunctionTolerance', ...
-                                    'FunValCheck', 'HybridFcn', 'InertiaRange', 'InitialSwarmMatrix', 'InitialSwarmSpan', ...
-                                    'MaxIterations', 'MaxStallIterations', 'MaxStallTime', 'MaxTime', ...
-                                    'MinNeighborsFraction', 'ObjectiveLimit', 'OutputFcn', 'PlotFcn', 'SelfAdjustmentWeight', ...
-                                    'SocialAdjustmentWeight', 'SwarmSize', 'UseParallel', 'UseVectorized'};
+                            'FunValCheck', 'HybridFcn', 'InertiaRange', 'InitialSwarmMatrix', 'InitialSwarmSpan', ...
+                            'MaxIterations', 'MaxStallIterations', 'MaxStallTime', 'MaxTime', ...
+                            'MinNeighborsFraction', 'ObjectiveLimit', 'OutputFcn', 'PlotFcn', 'SelfAdjustmentWeight', ...
+                            'SocialAdjustmentWeight', 'SwarmSize', 'UseParallel', 'UseVectorized'};
         for i=1:rows(options_list)
             if ismember(options_list{i,1}, SupportedListOfOptions)
                 particleswarmOptions = optimoptions(particleswarmOptions, options_list{i,1}, options_list{i,2});
@@ -511,8 +514,8 @@ 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;
+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
index 3710d8d65ef7b0fd4065170a30e0fe499ddab3c9..4f1db628d06cf6070678076d47a8d36daa8dbe08 100644
--- a/matlab/optimization/gmhmaxlik.m
+++ b/matlab/optimization/gmhmaxlik.m
@@ -1,6 +1,6 @@
 function [PostMode, HessianMatrix, Scale, ModeValue] = gmhmaxlik(fun, xinit, Hinit, iscale, bounds, priorstd, gmhmaxlikOptions, OptimizationOptions, varargin)
 
-% Copyright (C) 2006-2015 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -16,10 +16,10 @@ function [PostMode, HessianMatrix, Scale, ModeValue] = gmhmaxlik(fun, xinit, Hin
 %
 % 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);
+if ~isempty(Hinit)
     gmhmaxlikOptions.varinit = 'previous';
 else
     gmhmaxlikOptions.varinit = 'prior';
diff --git a/matlab/optimization/gmhmaxlik_core.m b/matlab/optimization/gmhmaxlik_core.m
index 2d7a3cb814fe1db262ff8ab597ecf24049e5bcff..3e94d30ab983dc0ed312fa5bf14d26b8e8173706 100644
--- a/matlab/optimization/gmhmaxlik_core.m
+++ b/matlab/optimization/gmhmaxlik_core.m
@@ -1,8 +1,8 @@
-function [PostMod,PostVar,Scale,PostMean] = gmhmaxlik_core(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)
 
-% (Dirty) Global minimization routine of (minus) a likelihood (or posterior density) function. 
-% 
-% INPUTS 
+% (Dirty) Global minimization routine of (minus) a likelihood (or posterior density) function.
+%
+% INPUTS
 %   o ObjFun     [char]     string specifying the name of the objective function.
 %   o xparam1    [double]   (p*1) vector of parameters to be estimated.
 %   o mh_bounds  [double]   (p*2) matrix defining lower and upper bounds for the parameters.
@@ -10,29 +10,29 @@ function [PostMod,PostVar,Scale,PostMean] = gmhmaxlik_core(ObjFun,xparam1,mh_bou
 %   o iScale     [double]   scalar specifying the initial of the jumping distribution's scale parameter.
 %   o info       [char]     string, empty or equal to 'LastCall'.
 %   o MeanPar    [double]   (p*1) vector specifying the initial posterior mean.
-%   o VarCov     [double]   (p*p) matrix specifying the initial posterior covariance matrix. 
+%   o VarCov     [double]   (p*p) matrix specifying the initial posterior covariance matrix.
 %   o gend       [integer]  scalar specifying the number of observations ==> varargin{1}.
 %   o data       [double]   (T*n) matrix of data ==> varargin{2}.
-%  
-% OUTPUTS 
+%
+% OUTPUTS
 %   o PostMod    [double]   (p*1) vector, evaluation of the posterior mode.
 %   o PostVar    [double]   (p*p) matrix, evaluation of the posterior covariance matrix.
-%   o Scale      [double]   scalar specifying the scale parameter that should be used in 
-%                           an eventual metropolis-hastings algorithm. 
-%   o PostMean   [double]   (p*1) vector, evaluation of the posterior mean.  
+%   o Scale      [double]   scalar specifying the scale parameter that should be used in
+%                           an eventual metropolis-hastings algorithm.
+%   o PostMean   [double]   (p*1) vector, evaluation of the posterior mean.
 %
-% ALGORITHM 
+% ALGORITHM
 %   Metropolis-Hastings with an constantly updated covariance matrix for
 %   the jump distribution. The posterior mean, variance and mode are
 %   updated (in step 2) with the following rules:
 %
-%   \[ 
-%       \mu_t = \mu_{t-1} + \frac{1}{t}\left(\theta_t-\mu_{t-1}\right) 
-%   \]    
+%   \[
+%       \mu_t = \mu_{t-1} + \frac{1}{t}\left(\theta_t-\mu_{t-1}\right)
+%   \]
 %
-%   \[ 
-%       \Sigma_t = \Sigma_{t-1} + \mu_{t-1}\mu_{t-1}'-\mu_{t}\mu_{t}' + 
-%                  \frac{1}{t}\left(\theta_t\theta_t'-\Sigma_{t-1}-\mu_{t-1}\mu_{t-1}'\right) 
+%   \[
+%       \Sigma_t = \Sigma_{t-1} + \mu_{t-1}\mu_{t-1}'-\mu_{t}\mu_{t}' +
+%                  \frac{1}{t}\left(\theta_t\theta_t'-\Sigma_{t-1}-\mu_{t-1}\mu_{t-1}'\right)
 %   \]
 %
 %   and
@@ -43,7 +43,7 @@ function [PostMod,PostVar,Scale,PostMean] = gmhmaxlik_core(ObjFun,xparam1,mh_bou
 %                         \theta_t, & \hbox{if } p(\theta_t|\mathcal Y) > p(\mathrm{mode}_{t-1}|\mathcal Y) \\
 %                         \mathrm{mode}_{t-1}, & \hbox{otherwise.}
 %                       \end{array}
-%                     \right. 
+%                     \right.
 %   \]
 %
 %   where $t$ is the iteration, $\mu_t$ the estimate of the posterior mean
@@ -51,12 +51,12 @@ function [PostMod,PostVar,Scale,PostMean] = gmhmaxlik_core(ObjFun,xparam1,mh_bou
 %   covariance matrix after $t$ iterations, $\mathrm{mode}_t$ is the
 %   evaluation of the posterior mode after $t$ iterations and
 %   $p(\theta_t|\mathcal Y)$ is the posterior density of parameters
-%   (specified by the user supplied function "fun").       
+%   (specified by the user supplied function "fun").
 %
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2006-2015 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -94,7 +94,7 @@ isux = 0; jsux = 0; test = 0;
 ix2 = ModePar;% initial condition!
 ilogpo2 = - feval(ObjFun,ix2,varargin{:});% initial posterior density
 mlogpo2 = ilogpo2;
-try 
+try
     dd = transpose(chol(CovJump));
 catch
     dd = eye(length(CovJump));
@@ -108,7 +108,7 @@ while j<=MaxNumberOfTuningSimulations
     end
     % I move if the proposal is enough likely...
     if logpo2 > -inf && log(rand) < logpo2 - ilogpo2
-        ix2 = proposal; 
+        ix2 = proposal;
         if logpo2 > mlogpo2
             ModePar = proposal;
             mlogpo2 = logpo2;
@@ -165,7 +165,7 @@ while j<= NumberOfIterations
         ilogpo2 = logpo2;
         isux = isux + 1;
         jsux = jsux + 1;
-    end% ... otherwise I don't move.    
+    end% ... otherwise I don't move.
     prtfrc = j/NumberOfIterations;
     if mod(j, 10)==0
         dyn_waitbar(prtfrc,hh,sprintf('Acceptance ratio: %f',isux/j));
@@ -184,7 +184,7 @@ PostMean = MeanPar;
 %% this is the last call to the routine, and I climb the hill (without
 %% updating the covariance matrix)...
 if strcmpi(info,'LastCall')
-    
+
     hh = dyn_waitbar(0,'Tuning of the scale parameter...');
     set(hh,'Name','Tuning of the scale parameter.'),
     j = 1; jj  = 1;
@@ -214,8 +214,8 @@ if strcmpi(info,'LastCall')
         if mod(j, 10)==0
             dyn_waitbar(prtfrc,hh,sprintf('Acceptance ratio [during last 1000]: %f [%f]',isux/j,jsux/jj));
         end
-        if j/1000 == round(j/1000) 
-            test1 = jsux/jj;  
+        if j/1000 == round(j/1000)
+            test1 = jsux/jj;
             cfactor = test1/AcceptanceTarget;
             iScale = iScale*cfactor;
             jsux = 0; jj = 0;
diff --git a/matlab/optimization/mr_gstep.m b/matlab/optimization/mr_gstep.m
index 605508d2c0d53186f0431c251d2dd9be2f964849..0836a7a87efb99a604844ab967a06000466d1e82 100644
--- a/matlab/optimization/mr_gstep.m
+++ b/matlab/optimization/mr_gstep.m
@@ -11,7 +11,7 @@ function [f0, x, ig] = mr_gstep(h1,x,bounds,func0,penalty,htol0,Verbose,Save_fil
 % varargin{6} --> BayesInfo
 % varargin{1} --> DynareResults
 
-% Copyright (C) 2006-2016 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -29,7 +29,7 @@ function [f0, x, ig] = mr_gstep(h1,x,bounds,func0,penalty,htol0,Verbose,Save_fil
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 n=size(x,1);
-if isempty(h1),
+if isempty(h1)
     h1=varargin{3}.gradient_epsilon*ones(n,1);
 end
 
@@ -39,7 +39,7 @@ if isempty(htol0)
 else
     htol = htol0;
 end
-if length(htol)==1,
+if length(htol)==1
     htol=htol*ones(n,1);
 end
 f0=penalty_objective_function(x,func0,penalty,varargin{:});
@@ -72,7 +72,7 @@ while i<n
         gg(i)=(f1(i)'-f_1(i)')./(2.*h1(i));
         hh(i) = 1/max(1.e-9,abs( (f1(i)+f_1(i)-2*f0)./(h1(i)*h1(i)) ));
         if gg(i)*(hh(i)*gg(i))/2 > htol(i)
-            [f0 x fc retcode] = csminit1(func0,x,penalty,f0,gg,0,diag(hh),Verbose,varargin{:});
+            [f0, x, fc, retcode] = csminit1(func0,x,penalty,f0,gg,0,diag(hh),Verbose,varargin{:});
             ig(i)=1;
             if Verbose
                 fprintf(['Done for param %s = %8.4f\n'],varargin{6}.name{i},x(i))
@@ -95,13 +95,11 @@ return
 function x = check_bounds(x,bounds)
 
 inx = find(x>=bounds(:,2));
-if ~isempty(inx),
+if ~isempty(inx)
     x(inx) = bounds(inx,2)-eps;
 end
 
 inx = find(x<=bounds(:,1));
-if ~isempty(inx),
+if ~isempty(inx)
     x(inx) = bounds(inx,1)+eps;
 end
-
-
diff --git a/matlab/optimization/mr_hessian.m b/matlab/optimization/mr_hessian.m
index eb1c0752e6e594ed9314c47b83ea67a9bb2dff9f..b234df9b7c2c19c265294cbb22381e53728c7bd1 100644
--- a/matlab/optimization/mr_hessian.m
+++ b/matlab/optimization/mr_hessian.m
@@ -33,7 +33,7 @@ function [hessian_mat, gg, htol1, ihh, hh_mat0, hh1, hess_info] = mr_hessian(x,f
 %                           varargin{6} --> BayesInfo
 %                           varargin{7} --> Bounds
 %                           varargin{8} --> DynareResults
-% 
+%
 % Outputs
 %  - hessian_mat        hessian
 %  - gg                 Jacobian
@@ -44,7 +44,7 @@ function [hessian_mat, gg, htol1, ihh, hh_mat0, hh1, hess_info] = mr_hessian(x,f
 %  - hh1                updated hess_info.h1
 %  - hess_info          structure with updated step length
 
-% Copyright (C) 2004-2016 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -67,7 +67,7 @@ n=size(x,1);
 h2=varargin{7}.ub-varargin{7}.lb;
 hmax=varargin{7}.ub-x;
 hmax=min(hmax,x-varargin{7}.lb);
-if isempty(ff0),
+if isempty(ff0)
     outer_product_gradient=0;
 else
     outer_product_gradient=1;
@@ -109,7 +109,7 @@ while i<n
     while (abs(dx(it))<0.5*hess_info.htol || abs(dx(it))>(3*hess_info.htol)) && icount<10 && ic==0
         icount=icount+1;
         if abs(dx(it))<0.5*hess_info.htol
-            if abs(dx(it)) ~= 0,
+            if abs(dx(it)) ~= 0
                 hess_info.h1(i)=min(max(1.e-10,0.3*abs(x(i))), 0.9*hess_info.htol/abs(dx(it))*hess_info.h1(i));
             else
                 hess_info.h1(i)=2.1*hess_info.h1(i);
@@ -147,8 +147,8 @@ while i<n
         end
     end
     f1(:,i)=fx;
-    if outer_product_gradient,
-        if any(isnan(ffx)) || isempty(ffx),
+    if outer_product_gradient
+        if any(isnan(ffx)) || isempty(ffx)
             ff1=ones(size(ff0)).*fx/length(ff0);
         else
             ff1=ffx;
@@ -157,8 +157,8 @@ while i<n
     xh1(i)=x(i)-hess_info.h1(i);
     [fx,exit_flag,ffx]=penalty_objective_function(xh1,func,penalty,varargin{:});
     f_1(:,i)=fx;
-    if outer_product_gradient,
-        if any(isnan(ffx)) || isempty(ffx),
+    if outer_product_gradient
+        if any(isnan(ffx)) || isempty(ffx)
             ff_1=ones(size(ff0)).*fx/length(ff0);
         else
             ff_1=ffx;
@@ -180,7 +180,7 @@ xh_1=xh1;
 
 gg=(f1'-f_1')./(2.*hess_info.h1);
 
-if outer_product_gradient,
+if outer_product_gradient
     if hflag==2
         gg=(f1'-f_1')./(2.*hess_info.h1);
         hessian_mat = zeros(size(f0,1),n*n);
@@ -223,7 +223,7 @@ if outer_product_gradient,
     hh_mat=gga'*gga;  % rescaled outer product hessian
     hh_mat0=ggh'*ggh;  % outer product hessian
     A=diag(2.*hess_info.h1);  % rescaling matrix
-    % igg=inv(hh_mat);  % inverted rescaled outer product hessian
+                              % igg=inv(hh_mat);  % inverted rescaled outer product hessian
     ihh=A'*(hh_mat\A);  % inverted outer product hessian
     if hflag>0 && min(eig(reshape(hessian_mat,n,n)))>0
         hh0 = A*reshape(hessian_mat,n,n)*A';  %rescaled second order derivatives
@@ -244,12 +244,12 @@ if outer_product_gradient,
         igg=inv(A)'*ihh*inv(A);  % inverted rescaled outer product hessian with modified std's
         hh_mat=inv(igg);   % outer product rescaled hessian with modified std's
         hh_mat0=inv(A)'*hh_mat*inv(A);  % outer product hessian with modified std's
-        %     sd0=sqrt(1./diag(hh0));   %rescaled 'standard errors' using second order derivatives
-        %     sd=sqrt(diag(igg));  %rescaled 'standard errors' using outer product
-        %     igg=igg./(sd*sd').*(sd0*sd0');  %rescaled inverse outer product with 'true' std's
-        %     hh_mat=inv(igg);   % rescaled outer product hessian with 'true' std's
-        %     ihh=A'*igg*A;  % inverted outer product hessian
-        %     hh_mat0=inv(A)'*hh_mat*inv(A);  % outer product hessian with 'true' std's
+                                        %     sd0=sqrt(1./diag(hh0));   %rescaled 'standard errors' using second order derivatives
+                                        %     sd=sqrt(diag(igg));  %rescaled 'standard errors' using outer product
+                                        %     igg=igg./(sd*sd').*(sd0*sd0');  %rescaled inverse outer product with 'true' std's
+                                        %     hh_mat=inv(igg);   % rescaled outer product hessian with 'true' std's
+                                        %     ihh=A'*igg*A;  % inverted outer product hessian
+                                        %     hh_mat0=inv(A)'*hh_mat*inv(A);  % outer product hessian with 'true' std's
     end
     if hflag<2
         hessian_mat=hh_mat0(:);
diff --git a/matlab/optimization/newrat.m b/matlab/optimization/newrat.m
index 8085316d057f8d280720a51263c1f485fdd3d680..c554a22dc14a5111342e9c9281f7749d6eca3a9d 100644
--- a/matlab/optimization/newrat.m
+++ b/matlab/optimization/newrat.m
@@ -11,14 +11,14 @@ function [xparam1, hh, gg, fval, igg, hess_info] = newrat(func0, x, bounds, anal
 %  - analytic_derivation    1 if analytic derivatives, 0 otherwise
 %  - ftol0                  termination criterion for function change
 %  - nit                    maximum number of iterations
-%  - flagg                  Indicator how to compute final Hessian (In each iteration, Hessian is computed with outer product gradient)  
+%  - flagg                  Indicator how to compute final Hessian (In each iteration, Hessian is computed with outer product gradient)
 %                           0: final Hessian computed with outer product gradient
-%                           1: final 'mixed' Hessian: diagonal elements computed with 
-%                               numerical second order derivatives with correlation structure 
+%                           1: final 'mixed' Hessian: diagonal elements computed with
+%                               numerical second order derivatives with correlation structure
 %                               as from outer product gradient
 %                           2: full numerical Hessian
 %  - Verbose                1 if explicit output is requested
-%  - Save_files             1 if intermediate output is to be saved 
+%  - Save_files             1 if intermediate output is to be saved
 %  - hess_info              structure storing the step sizes for
 %                           computation of Hessian
 %  - varargin               other inputs:
@@ -30,7 +30,7 @@ function [xparam1, hh, gg, fval, igg, hess_info] = newrat(func0, x, bounds, anal
 %                           varargin{6} --> BayesInfo
 %                           varargin{7} --> Bounds
 %                           varargin{8} --> DynareResults
-% 
+%
 % Outputs
 % - xparam1                 parameter vector at optimum
 % - hh                      hessian
@@ -39,7 +39,7 @@ function [xparam1, hh, gg, fval, igg, hess_info] = newrat(func0, x, bounds, anal
 % - igg                     inverted outer product hessian
 % - hess_info               structure with updated step length
 
-% Copyright (C) 2004-2016 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -56,7 +56,7 @@ function [xparam1, hh, gg, fval, igg, hess_info] = newrat(func0, x, bounds, anal
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-% initialize variable penalty    
+% initialize variable penalty
 penalty = 1e8;
 
 icount=0;
@@ -86,7 +86,7 @@ fval=fval0;
 outer_product_gradient=1;
 if isempty(hh)
     [dum, gg, htol0, igg, hhg, h1, hess_info]=mr_hessian(x,func0,penalty,flagit,htol,hess_info,varargin{:});
-    if isempty(dum),
+    if isempty(dum)
         outer_product_gradient=0;
         igg = 1e-4*eye(nx);
     else
@@ -154,7 +154,7 @@ while norm(gg)>gtol && check==0 && jit<nit
     if length(find(ig))<nx
         ggx=ggx*0;
         ggx(find(ig))=gg(find(ig));
-        if analytic_derivation,
+        if analytic_derivation
             hhx=hh;
         else
             hhx = reshape(dum,nx,nx);
@@ -195,26 +195,26 @@ while norm(gg)>gtol && check==0 && jit<nit
     if (fval0(icount)-fval)<ftol
         disp_verbose('No further improvement is possible!',Verbose)
         check=1;
-        if analytic_derivation,
+        if analytic_derivation
             [fvalx,exit_flag,gg,hh]=penalty_objective_function(xparam1,func0,penalty,varargin{:});
             hhg=hh;
             H = inv(hh);
         else
-        if flagit==2
-            hh=hh0;
-        elseif flagg>0
-            [dum, gg, htol0, igg, hhg, h1, hess_info]=mr_hessian(xparam1,func0,penalty,flagg,ftol0,hess_info,varargin{:});
-            if flagg==2
-                hh = reshape(dum,nx,nx);
-                ee=eig(hh);
-                if min(ee)<0
+            if flagit==2
+                hh=hh0;
+            elseif flagg>0
+                [dum, gg, htol0, igg, hhg, h1, hess_info]=mr_hessian(xparam1,func0,penalty,flagg,ftol0,hess_info,varargin{:});
+                if flagg==2
+                    hh = reshape(dum,nx,nx);
+                    ee=eig(hh);
+                    if min(ee)<0
+                        hh=hhg;
+                    end
+                else
                     hh=hhg;
                 end
-            else
-                hh=hhg;
             end
         end
-        end
         disp_verbose(['Actual dxnorm ',num2str(norm(x(:,end)-x(:,end-1)))],Verbose)
         disp_verbose(['FVAL          ',num2str(fval)],Verbose)
         disp_verbose(['Improvement   ',num2str(fval0(icount)-fval)],Verbose)
@@ -233,7 +233,7 @@ while norm(gg)>gtol && check==0 && jit<nit
         disp_verbose(['Ftol          ',num2str(ftol)],Verbose)
         disp_verbose(['Htol          ',num2str(max(htol0))],Verbose)
         htol=htol_base;
-        if norm(x(:,icount)-xparam1)>1.e-12 && analytic_derivation==0,
+        if norm(x(:,icount)-xparam1)>1.e-12 && analytic_derivation==0
             try
                 if Save_files
                     save('m1.mat','x','fval0','nig','-append')
@@ -244,7 +244,7 @@ while norm(gg)>gtol && check==0 && jit<nit
                 end
             end
             [dum, gg, htol0, igg, hhg, h1, hess_info]=mr_hessian(xparam1,func0,penalty,flagit,htol,hess_info,varargin{:});
-            if isempty(dum),
+            if isempty(dum)
                 outer_product_gradient=0;
             end
             if max(htol0)>htol
@@ -253,7 +253,7 @@ while norm(gg)>gtol && check==0 && jit<nit
                 disp_verbose('Tolerance has to be relaxed',Verbose)
                 skipline()
             end
-            if ~outer_product_gradient,
+            if ~outer_product_gradient
                 H = bfgsi1(H,gg-g(:,icount),xparam1-x(:,icount),Verbose,Save_files);
                 hh=inv(H);
                 hhg=hh;
@@ -270,7 +270,7 @@ while norm(gg)>gtol && check==0 && jit<nit
                 end
                 H = igg;
             end
-        elseif analytic_derivation,
+        elseif analytic_derivation
             [fvalx,exit_flag,gg,hh]=penalty_objective_function(xparam1,func0,penalty,varargin{:});
             hhg=hh;
             H = inv(hh);
@@ -311,7 +311,7 @@ if norm(gg)<=gtol
     disp_verbose(['Estimation ended:'],Verbose)
     disp_verbose(['Gradient norm < ', num2str(gtol)],Verbose)
 end
-if check==1,
+if check==1
     disp_verbose(['Estimation successful.'],Verbose)
 end
 
@@ -321,11 +321,11 @@ return
 function x = check_bounds(x,bounds)
 
 inx = find(x>=bounds(:,2));
-if ~isempty(inx),
+if ~isempty(inx)
     x(inx) = bounds(inx,2)-eps;
 end
 
 inx = find(x<=bounds(:,1));
-if ~isempty(inx),
+if ~isempty(inx)
     x(inx) = bounds(inx,1)+eps;
 end
diff --git a/matlab/optimization/penalty_objective_function.m b/matlab/optimization/penalty_objective_function.m
index c245800c2f2ff93eef829c7d245a44594150034d..e0c24925123eaeeae03c06d9eeca8972fa2fe8d1 100644
--- a/matlab/optimization/penalty_objective_function.m
+++ b/matlab/optimization/penalty_objective_function.m
@@ -2,13 +2,13 @@ function [fval, exit_flag, arg1, arg2] = penalty_objective_function(x, fcn, base
 
 % Encapsulates an objective function to be minimized, adding a penalty if necessary.
 %
-% INPUTS 
+% INPUTS
 % - x             [double]    n*1 vector of instrument values.
 % - fcn           [fhandle]   objective function.
 % - base_penalty  [double]    scalar, base of the penality (typically the value of the objective at the previous iteration).
 % - varagin       [cell]      additional parameters for fcn.
 %
-% OUTPUTS 
+% OUTPUTS
 % - fval          [double]    scalar, value of the objective function at x.
 % - exit_flag     [integer]   scalar, flag returned by fcn (third output).
 % - arg1, arg2                fourth and fifth output arguments of the objective function.
diff --git a/matlab/optimization/simplex_optimization_routine.m b/matlab/optimization/simplex_optimization_routine.m
index 58b3ff1b097a9a633d74dc8bfbc4cf03a01c6e27..ccd81367eb4a329ff116fa37cac8d65abee83dbe 100644
--- a/matlab/optimization/simplex_optimization_routine.m
+++ b/matlab/optimization/simplex_optimization_routine.m
@@ -7,7 +7,7 @@ function [x,fval,exitflag] = simplex_optimization_routine(objective_function,x,o
 %
 % The routine automatically restarts from the current solution while amelioration is possible.
 %
-% INPUTS 
+% INPUTS
 %  o objective_function     [string]                  Name of the objective function to be minimized.
 %  o x                      [double]                  n*1 vector, starting guess of the optimization routine.
 %  o options                [structure]               Options of this implementation of the simplex algorithm.
@@ -23,13 +23,13 @@ function [x,fval,exitflag] = simplex_optimization_routine(objective_function,x,o
 %     varargin{6} --> BayesInfo
 %     varargin{1} --> DynareResults
 %
-% OUTPUTS 
+% OUTPUTS
 %  o x                      [double]                  n*1 vector, estimate of the optimal inputs.
 %  o fval                   [double]                  scalar, value of the objective at the optimum.
 %  o exitflag               [integer]                 scalar equal to 0 or 1 (0 if the algorithm did not converge to
 %                                                     a minimum).
 
-% Copyright (C) 2010-2013 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -251,7 +251,7 @@ while (func_count < max_func_calls) && (iter_count < max_iterations) && (simplex
     fxr = feval(objective_function,x,varargin{:});
     func_count = func_count+1;
     if fxr < fv(1)% xr is better than previous best point v(:,1).
-        % Calculate the expansion point
+                  % Calculate the expansion point
         xe = xbar + rho*chi*(xbar-v(:,end));
         x  = xe;
         fxe = feval(objective_function,x,varargin{:});
@@ -396,7 +396,7 @@ while (func_count < max_func_calls) && (iter_count < max_iterations) && (simplex
         disp(['Crit. x:                  ' num2str(critX)])
         skipline()
     end
-    if verbose && max(abs(best_point-v(:,1)))>x_tolerance;
+    if verbose && max(abs(best_point-v(:,1)))>x_tolerance
         if verbose<2
             disp(['Simplex iteration number: ' int2str(simplex_iterations) '-' int2str(simplex_init) '-' int2str(simplex_algo_iterations)])
             disp(['Objective function value: ' num2str(fv(1))])
@@ -499,7 +499,7 @@ while (func_count < max_func_calls) && (iter_count < max_iterations) && (simplex
         else
             break
         end
-   end
+    end
 end% while loop.
 
 x(:) = v(:,1);
@@ -520,43 +520,43 @@ end
 
 
 function [v,fv,delta] = simplex_initialization(objective_function,point,point_score,delta,zero_delta,check_delta,varargin)
-    n = length(point);
-    v  = zeros(n,n+1);
-    v(:,1) = point;
-    fv = zeros(n+1,1);
-    fv(1) = point_score;
-    if length(delta)==1
-        delta = repmat(delta,n,1);
+n = length(point);
+v  = zeros(n,n+1);
+v(:,1) = point;
+fv = zeros(n+1,1);
+fv(1) = point_score;
+if length(delta)==1
+    delta = repmat(delta,n,1);
+end
+for j = 1:n
+    y = point;
+    if y(j) ~= 0
+        y(j) = (1 + delta(j))*y(j);
+    else
+        y(j) = zero_delta;
     end
-    for j = 1:n
-        y = point;
-        if y(j) ~= 0
-            y(j) = (1 + delta(j))*y(j);
-        else
-            y(j) = zero_delta;
-        end
-        v(:,j+1) = y;
-        x = y;
-        [fv(j+1),junk1,junk2,nopenalty_flag] = feval(objective_function,x,varargin{:});
-        if check_delta
-            while ~nopenalty_flag
-                if y(j)~=0
-                    delta(j) = delta(j)/1.1;
-                else
-                    zero_delta = zero_delta/1.1;
-                end
-                y = point;
-                if y(j) ~= 0
-                    y(j) = (1 + delta(j))*y(j);
-                else
-                    y(j) = zero_delta;
-                end
-                v(:,j+1) = y;
-                x = y;
-                [fv(j+1),junk1,junk2,nopenalty_flag] = feval(objective_function,x,varargin{:});
+    v(:,j+1) = y;
+    x = y;
+    [fv(j+1),junk1,junk2,nopenalty_flag] = feval(objective_function,x,varargin{:});
+    if check_delta
+        while ~nopenalty_flag
+            if y(j)~=0
+                delta(j) = delta(j)/1.1;
+            else
+                zero_delta = zero_delta/1.1;
             end
+            y = point;
+            if y(j) ~= 0
+                y(j) = (1 + delta(j))*y(j);
+            else
+                y(j) = zero_delta;
+            end
+            v(:,j+1) = y;
+            x = y;
+            [fv(j+1),junk1,junk2,nopenalty_flag] = feval(objective_function,x,varargin{:});
         end
     end
-    % Sort by increasing order of the objective function values.
-    [fv,sort_idx] = sort(fv);
-    v = v(:,sort_idx);
\ No newline at end of file
+end
+% Sort by increasing order of the objective function values.
+[fv,sort_idx] = sort(fv);
+v = v(:,sort_idx);
\ No newline at end of file
diff --git a/matlab/optimization/simpsa.m b/matlab/optimization/simpsa.m
index 260607a24097cbf598990a1d3b8dd141a15d6f2e..87b881a2cb9992cb92eda20fbc4a38c554b700ca 100644
--- a/matlab/optimization/simpsa.m
+++ b/matlab/optimization/simpsa.m
@@ -1,8 +1,8 @@
 function [X,FVAL,EXITFLAG,OUTPUT] = simpsa(FUN,X0,LB,UB,OPTIONS,varargin)
 
-% Finds a minimum of a function of several variables using an algorithm 
-% that is based on the combination of the non-linear smplex and the simulated 
-% annealing algorithm (the SIMPSA algorithm, Cardoso et al., 1996). 
+% Finds a minimum of a function of several variables using an algorithm
+% that is based on the combination of the non-linear smplex and the simulated
+% annealing algorithm (the SIMPSA algorithm, Cardoso et al., 1996).
 % In this paper, the algorithm is shown to be adequate for the global optimi-
 % zation of an example set of unconstrained and constrained NLP functions.
 %
@@ -11,54 +11,54 @@ function [X,FVAL,EXITFLAG,OUTPUT] = simpsa(FUN,X0,LB,UB,OPTIONS,varargin)
 %        X
 %
 % Algorithm partly is based on paper of Cardoso et al, 1996.
-%                                                                             
-%   X=SIMPSA(FUN,X0) start at X0 and finds a minimum X to the function FUN. 
+%
+%   X=SIMPSA(FUN,X0) start at X0 and finds a minimum X to the function FUN.
 %   FUN accepts input X and returns a scalar function value F evaluated at X.
 %   X0 may be a scalar, vector, or matrix.
-%   
-%   X=SIMPSA(FUN,X0,LB,UB) defines a set of lower and upper bounds on the 
-%   design variables, X, so that a solution is found in the range 
-%   LB <= X <= UB. Use empty matrices for LB and UB if no bounds exist. 
-%   Set LB(i) = -Inf if X(i) is unbounded below; set UB(i) = Inf if X(i) is 
+%
+%   X=SIMPSA(FUN,X0,LB,UB) defines a set of lower and upper bounds on the
+%   design variables, X, so that a solution is found in the range
+%   LB <= X <= UB. Use empty matrices for LB and UB if no bounds exist.
+%   Set LB(i) = -Inf if X(i) is unbounded below; set UB(i) = Inf if X(i) is
 %   unbounded above.
-%   
+%
 %   X=SIMPSA(FUN,X0,LB,UB,OPTIONS) minimizes with the default optimization
-%   parameters replaced by values in the structure OPTIONS, an argument 
-%   created with the SIMPSASET function. See SIMPSASET for details. 
+%   parameters replaced by values in the structure OPTIONS, an argument
+%   created with the SIMPSASET function. See SIMPSASET for details.
 %   Used options are TEMP_START, TEMP_END, COOL_RATE, INITIAL_ACCEPTANCE_RATIO,
 %   MIN_COOLING_FACTOR, MAX_ITER_TEMP_FIRST, MAX_ITER_TEMP_LAST, MAX_ITER_TEMP,
 %   MAX_ITER_TOTAL, MAX_TIME, MAX_FUN_EVALS, TOLX, TOLFUN, DISPLAY and OUTPUT_FCN.
 %   Use OPTIONS = [] as a place holder if no options are set.
-%   
-%   X=SIMPSA(FUN,X0,LB,UB,OPTIONS,varargin) is used to supply a variable 
+%
+%   X=SIMPSA(FUN,X0,LB,UB,OPTIONS,varargin) is used to supply a variable
 %   number of input arguments to the objective function FUN.
-%   
-%   [X,FVAL]=SIMPSA(FUN,X0,...) returns the value of the objective 
+%
+%   [X,FVAL]=SIMPSA(FUN,X0,...) returns the value of the objective
 %   function FUN at the solution X.
-%   
-%   [X,FVAL,EXITFLAG]=SIMPSA(FUN,X0,...) returns an EXITFLAG that describes the 
-%   exit condition of SIMPSA. Possible values of EXITFLAG and the corresponding 
+%
+%   [X,FVAL,EXITFLAG]=SIMPSA(FUN,X0,...) returns an EXITFLAG that describes the
+%   exit condition of SIMPSA. Possible values of EXITFLAG and the corresponding
 %   exit conditions are:
-%   
+%
 %     1  Change in the objective function value less than the specified tolerance.
 %     2  Change in X less than the specified tolerance.
 %     0  Maximum number of function evaluations or iterations reached.
 %    -1  Maximum time exceeded.
-%   
-%   [X,FVAL,EXITFLAG,OUTPUT]=SIMPSA(FUN,X0,...) returns a structure OUTPUT with 
+%
+%   [X,FVAL,EXITFLAG,OUTPUT]=SIMPSA(FUN,X0,...) returns a structure OUTPUT with
 %   the number of iterations taken in OUTPUT.nITERATIONS, the number of function
 %   evaluations in OUTPUT.nFUN_EVALS, the temperature profile in OUTPUT.TEMPERATURE,
-%   the simplexes that were evaluated in OUTPUT.SIMPLEX and the best one in 
-%   OUTPUT.SIMPLEX_BEST, the costs associated with each simplex in OUTPUT.COSTS and 
-%   from the best simplex at that iteration in OUTPUT.COST_BEST, the amount of time 
+%   the simplexes that were evaluated in OUTPUT.SIMPLEX and the best one in
+%   OUTPUT.SIMPLEX_BEST, the costs associated with each simplex in OUTPUT.COSTS and
+%   from the best simplex at that iteration in OUTPUT.COST_BEST, the amount of time
 %   needed in OUTPUT.TIME and the options used in OUTPUT.OPTIONS.
-% 
+%
 %   See also SIMPSASET, SIMPSAGET
 
 
 % Copyright (C) 2005 Henning Schmidt, FCC, henning@fcc.chalmers.se
 % Copyright (C) 2006 Brecht Donckels, BIOMATH, brecht.donckels@ugent.be
-% Copyright (C) 2013 Dynare Team.
+% Copyright (C) 2013-2017 Dynare Team.
 %
 % This file is part of Dynare.
 %
@@ -77,11 +77,11 @@ function [X,FVAL,EXITFLAG,OUTPUT] = simpsa(FUN,X0,LB,UB,OPTIONS,varargin)
 
 % handle variable input arguments
 
-if nargin < 5,
+if nargin < 5
     OPTIONS = [];
-    if nargin < 4,
+    if nargin < 4
         UB = 1e5;
-        if nargin < 3,
+        if nargin < 3
             LB = -1e5;
         end
     end
@@ -89,22 +89,22 @@ end
 
 % check input arguments
 
-if ~ischar(FUN),
+if ~ischar(FUN)
     error('''FUN'' incorrectly specified in ''SIMPSA''');
 end
-if ~isfloat(X0),
+if ~isfloat(X0)
     error('''X0'' incorrectly specified in ''SIMPSA''');
 end
-if ~isfloat(LB),
+if ~isfloat(LB)
     error('''LB'' incorrectly specified in ''SIMPSA''');
 end
-if ~isfloat(UB),
+if ~isfloat(UB)
     error('''UB'' incorrectly specified in ''SIMPSA''');
 end
-if length(X0) ~= length(LB),
+if length(X0) ~= length(LB)
     error('''LB'' and ''X0'' have incompatible dimensions in ''SIMPSA''');
 end
-if length(X0) ~= length(UB),
+if length(X0) ~= length(UB)
     error('''UB'' and ''X0'' have incompatible dimensions in ''SIMPSA''');
 end
 
@@ -122,20 +122,20 @@ NDIM = length(X0);
 
 % set default options
 DEFAULT_OPTIONS = simpsaset('TEMP_START',[],...  % starting temperature (if none provided, an optimal one will be estimated)
-             'TEMP_END',.1,...                    % end temperature
-             'COOL_RATE',10,...                  % small values (<1) means slow convergence,large values (>1) means fast convergence
-             'INITIAL_ACCEPTANCE_RATIO',0.95,... % when initial temperature is estimated, this will be the initial acceptance ratio in the first round
-             'MIN_COOLING_FACTOR',0.9,...        % minimum cooling factor (<1)
-             'MAX_ITER_TEMP_FIRST',50,...        % number of iterations in the preliminary temperature loop
-             'MAX_ITER_TEMP_LAST',2000,...         % number of iterations in the last temperature loop (pure simplex)
-             'MAX_ITER_TEMP',10,...              % number of iterations in the remaining temperature loops
-             'MAX_ITER_TOTAL',2500,...           % maximum number of iterations tout court
-             'MAX_TIME',2500,...                 % maximum duration of optimization
-             'MAX_FUN_EVALS',20000,...            % maximum number of function evaluations
-             'TOLX',1e-6,...                     % maximum difference between best and worst function evaluation in simplex
-             'TOLFUN',1e-6,...                   % maximum difference between the coordinates of the vertices
-             'DISPLAY','iter',...                % 'iter' or 'none' indicating whether user wants feedback
-             'OUTPUT_FCN',[]);                   % string with output function name
+                            'TEMP_END',.1,...                    % end temperature
+                            'COOL_RATE',10,...                  % small values (<1) means slow convergence,large values (>1) means fast convergence
+                            'INITIAL_ACCEPTANCE_RATIO',0.95,... % when initial temperature is estimated, this will be the initial acceptance ratio in the first round
+                            'MIN_COOLING_FACTOR',0.9,...        % minimum cooling factor (<1)
+                            'MAX_ITER_TEMP_FIRST',50,...        % number of iterations in the preliminary temperature loop
+                            'MAX_ITER_TEMP_LAST',2000,...         % number of iterations in the last temperature loop (pure simplex)
+                            'MAX_ITER_TEMP',10,...              % number of iterations in the remaining temperature loops
+                            'MAX_ITER_TOTAL',2500,...           % maximum number of iterations tout court
+                            'MAX_TIME',2500,...                 % maximum duration of optimization
+                            'MAX_FUN_EVALS',20000,...            % maximum number of function evaluations
+                            'TOLX',1e-6,...                     % maximum difference between best and worst function evaluation in simplex
+                            'TOLFUN',1e-6,...                   % maximum difference between the coordinates of the vertices
+                            'DISPLAY','iter',...                % 'iter' or 'none' indicating whether user wants feedback
+                            'OUTPUT_FCN',[]);                   % string with output function name
 
 % update default options with supplied options
 
@@ -167,7 +167,7 @@ TEMP_LOOP_NUMBER = 1;
 % loop as described by Cardoso et al., 1996 (recommended)
 
 % therefore, the temperature is set to YBEST*1e5 in the first loop
-if isempty(OPTIONS.TEMP_START),
+if isempty(OPTIONS.TEMP_START)
     TEMP = abs(YBEST)*1e5;
 else
     TEMP = OPTIONS.TEMP_START;
@@ -195,51 +195,51 @@ nITERATIONS = 0;
 % temperature loop: run SIMPSA till stopping criterion is met
 % -----------------------------------------------------------
 
-while 1,
-    
+while 1
+
     % detect if termination criterium was met
     % ---------------------------------------
-    
+
     % if a termination criterium was met, the value of EXITFLAG should have changed
     % from its default value of -2 to -1, 0, 1 or 2
-    
-    if EXITFLAG ~= -2,
+
+    if EXITFLAG ~= -2
         break
     end
-    
+
     % set MAXITERTEMP: maximum number of iterations at current temperature
     % --------------------------------------------------------------------
-    
-    if TEMP_LOOP_NUMBER == 1,
+
+    if TEMP_LOOP_NUMBER == 1
         MAXITERTEMP = OPTIONS.MAX_ITER_TEMP_FIRST*NDIM;
-        % The initial temperature is estimated (is requested) as described in 
-        % Cardoso et al. (1996). Therefore, we need to store the number of 
-        % successful and unsuccessful moves, as well as the increase in cost 
+        % The initial temperature is estimated (is requested) as described in
+        % Cardoso et al. (1996). Therefore, we need to store the number of
+        % successful and unsuccessful moves, as well as the increase in cost
         % for the unsuccessful moves.
-        if isempty(OPTIONS.TEMP_START),
+        if isempty(OPTIONS.TEMP_START)
             [SUCCESSFUL_MOVES,UNSUCCESSFUL_MOVES,UNSUCCESSFUL_COSTS] = deal(0);
         end
-    elseif TEMP < OPTIONS.TEMP_END,
+    elseif TEMP < OPTIONS.TEMP_END
         TEMP = 0;
         MAXITERTEMP = OPTIONS.MAX_ITER_TEMP_LAST*NDIM;
     else
         MAXITERTEMP = OPTIONS.MAX_ITER_TEMP*NDIM;
     end
-    
+
     % construct initial simplex
     % -------------------------
-    
+
     % 1st vertex of initial simplex
     P(1,:) = PBEST;
     Y(1) = CALCULATE_COST(FUN,P(1,:),LB,UB,varargin{:});
-    
+
     % if output function given then run output function to plot intermediate result
-    if ~isempty(OPTIONS.OUTPUT_FCN),
+    if ~isempty(OPTIONS.OUTPUT_FCN)
         feval(OPTIONS.OUTPUT_FCN,transpose(P(1,:)),Y(1));
     end
-    
+
     % remaining vertices of simplex
-    for k = 1:NDIM,
+    for k = 1:NDIM
         % copy first vertex in new vertex
         P(k+1,:) = P(1,:);
         % alter new vertex
@@ -247,20 +247,20 @@ while 1,
         % calculate value of objective function at new vertex
         Y(k+1) = CALCULATE_COST(FUN,P(k+1,:),LB,UB,varargin{:});
     end
-    
+
     % store information on what step the algorithm just did
     ALGOSTEP = 'initial simplex';
-    
+
     % add NDIM+1 to number of function evaluations
     nFUN_EVALS = nFUN_EVALS + NDIM;
-    
+
     % note:
     %  dimensions of matrix P: (NDIM+1) x NDIM
     %  dimensions of vector Y: (NDIM+1) x 1
-    
+
     % give user feedback if requested
-    if strcmp(OPTIONS.DISPLAY,'iter'),
-        if nITERATIONS == 0,
+    if strcmp(OPTIONS.DISPLAY,'iter')
+        if nITERATIONS == 0
             disp(' Nr Iter  Nr Fun Eval    Min function       Best function        TEMP           Algorithm Step');
         else
             disp(sprintf('%5.0f      %5.0f       %12.6g     %15.6g      %12.6g       %s',nITERATIONS,nFUN_EVALS,Y(1),YBEST,TEMP,'best point'));
@@ -269,111 +269,111 @@ while 1,
 
     % run full metropolis cycle at current temperature
     % ------------------------------------------------
-    
+
     % initialize vector COSTS, needed to calculate new temperature using cooling
     % schedule as described by Cardoso et al. (1996)
     COSTS = zeros((NDIM+1)*MAXITERTEMP,1);
-    
+
     % initialize ITERTEMP to zero
-    
+
     ITERTEMP = 0;
-    
+
     % start
 
-    for ITERTEMP = 1:MAXITERTEMP,
-        
+    for ITERTEMP = 1:MAXITERTEMP
+
         % add one to number of iterations
         nITERATIONS = nITERATIONS + 1;
-        
+
         % Press and Teukolsky (1991) add a positive logarithmic distributed variable,
-        % proportional to the control temperature T to the function value associated with 
-        % every vertex of the simplex. Likewise,they subtract a similar random variable 
+        % proportional to the control temperature T to the function value associated with
+        % every vertex of the simplex. Likewise,they subtract a similar random variable
         % from the function value at every new replacement point.
         % Thus, if the replacement point corresponds to a lower cost, this method always
-        % accepts a true down hill step. If, on the other hand, the replacement point 
+        % accepts a true down hill step. If, on the other hand, the replacement point
         % corresponds to a higher cost, an uphill move may be accepted, depending on the
         % relative COSTS of the perturbed values.
         % (taken from Cardoso et al.,1996)
-        
+
         % add random fluctuations to function values of current vertices
         YFLUCT = Y+TEMP*abs(log(rand(NDIM+1,1)));
-        
+
         % reorder YFLUCT, Y and P so that the first row corresponds to the lowest YFLUCT value
         help = sortrows([YFLUCT,Y,P],1);
         YFLUCT = help(:,1);
         Y = help(:,2);
         P = help(:,3:end);
-        
+
         % store temperature at current iteration
         OUTPUT.TEMPERATURE(nITERATIONS) = TEMP;
 
         % store information about simplex at the current iteration
         OUTPUT.SIMPLEX(:,:,nITERATIONS) = P;
         OUTPUT.SIMPLEX_BEST(nITERATIONS,:) = PBEST;
-        
+
         % store cost function value of best vertex in current iteration
         OUTPUT.COSTS(nITERATIONS,:) = Y;
         OUTPUT.COST_BEST(nITERATIONS) = YBEST;
-        
-        if strcmp(OPTIONS.DISPLAY,'iter'),
+
+        if strcmp(OPTIONS.DISPLAY,'iter')
             disp(sprintf('%5.0f      %5.0f       %12.6g     %15.6g      %12.6g       %s',nITERATIONS,nFUN_EVALS,Y(1),YBEST,TEMP,ALGOSTEP));
         end
-        
+
         % if output function given then run output function to plot intermediate result
-        if ~isempty(OPTIONS.OUTPUT_FCN),
+        if ~isempty(OPTIONS.OUTPUT_FCN)
             feval(OPTIONS.OUTPUT_FCN,transpose(P(1,:)),Y(1));
         end
-        
+
         % end the optimization if one of the stopping criteria is met
-        %% 1. difference between best and worst function evaluation in simplex is smaller than TOLFUN 
+        %% 1. difference between best and worst function evaluation in simplex is smaller than TOLFUN
         %% 2. maximum difference between the coordinates of the vertices in simplex is less than TOLX
         %% 3. no convergence,but maximum number of iterations has been reached
         %% 4. no convergence,but maximum time has been reached
-            
-        if (abs(max(Y)-min(Y)) < OPTIONS.TOLFUN) && (TEMP_LOOP_NUMBER ~= 1),
-            if strcmp(OPTIONS.DISPLAY,'iter'),
+
+        if (abs(max(Y)-min(Y)) < OPTIONS.TOLFUN) && (TEMP_LOOP_NUMBER ~= 1)
+            if strcmp(OPTIONS.DISPLAY,'iter')
                 disp('Change in the objective function value less than the specified tolerance (TOLFUN).')
             end
             EXITFLAG = 1;
-            break;
+            break
         end
-        
-        if (max(max(abs(P(2:NDIM+1,:)-P(1:NDIM,:)))) < OPTIONS.TOLX) && (TEMP_LOOP_NUMBER ~= 1),
-            if strcmp(OPTIONS.DISPLAY,'iter'),
+
+        if (max(max(abs(P(2:NDIM+1,:)-P(1:NDIM,:)))) < OPTIONS.TOLX) && (TEMP_LOOP_NUMBER ~= 1)
+            if strcmp(OPTIONS.DISPLAY,'iter')
                 disp('Change in X less than the specified tolerance (TOLX).')
             end
             EXITFLAG = 2;
-            break;
+            break
         end
-        
-        if (nITERATIONS >= OPTIONS.MAX_ITER_TOTAL*NDIM) || (nFUN_EVALS >= OPTIONS.MAX_FUN_EVALS*NDIM*(NDIM+1)),
-            if strcmp(OPTIONS.DISPLAY,'iter'),
+
+        if (nITERATIONS >= OPTIONS.MAX_ITER_TOTAL*NDIM) || (nFUN_EVALS >= OPTIONS.MAX_FUN_EVALS*NDIM*(NDIM+1))
+            if strcmp(OPTIONS.DISPLAY,'iter')
                 disp('Maximum number of function evaluations or iterations reached.');
             end
             EXITFLAG = 0;
-            break;
+            break
         end
-        
-        if toc/60 > OPTIONS.MAX_TIME,
-            if strcmp(OPTIONS.DISPLAY,'iter'),
+
+        if toc/60 > OPTIONS.MAX_TIME
+            if strcmp(OPTIONS.DISPLAY,'iter')
                 disp('Exceeded maximum time.');
             end
             EXITFLAG = -1;
-            break;
+            break
         end
-        
+
         % begin a new iteration
-        
+
         %% first extrapolate by a factor -1 through the face of the simplex
         %% across from the high point,i.e.,reflect the simplex from the high point
         [YFTRY,YTRY,PTRY] = AMOTRY(FUN,P,-1,LB,UB,varargin{:});
-        
+
         %% check the result
-        if YFTRY <= YFLUCT(1),
+        if YFTRY <= YFLUCT(1)
             %% gives a result better than the best point,so try an additional
             %% extrapolation by a factor 2
             [YFTRYEXP,YTRYEXP,PTRYEXP] = AMOTRY(FUN,P,-2,LB,UB,varargin{:});
-            if YFTRYEXP < YFTRY,
+            if YFTRYEXP < YFTRY
                 P(end,:) = PTRYEXP;
                 Y(end) = YTRYEXP;
                 ALGOSTEP = 'reflection and expansion';
@@ -382,12 +382,12 @@ while 1,
                 Y(end) = YTRY;
                 ALGOSTEP = 'reflection';
             end
-        elseif YFTRY >= YFLUCT(NDIM),
+        elseif YFTRY >= YFLUCT(NDIM)
             %% the reflected point is worse than the second-highest, so look
             %% for an intermediate lower point, i.e., do a one-dimensional
             %% contraction
             [YFTRYCONTR,YTRYCONTR,PTRYCONTR] = AMOTRY(FUN,P,-0.5,LB,UB,varargin{:});
-            if YFTRYCONTR < YFLUCT(end),
+            if YFTRYCONTR < YFLUCT(end)
                 P(end,:) = PTRYCONTR;
                 Y(end) = YTRYCONTR;
                 ALGOSTEP = 'one dimensional contraction';
@@ -396,7 +396,7 @@ while 1,
                 %% around the lowest (best) point
                 X = ones(NDIM,NDIM)*diag(P(1,:));
                 P(2:end,:) = 0.5*(P(2:end,:)+X);
-                for k=2:NDIM,
+                for k=2:NDIM
                     Y(k) = CALCULATE_COST(FUN,P(k,:),LB,UB,varargin{:});
                 end
                 ALGOSTEP = 'multiple contraction';
@@ -407,15 +407,15 @@ while 1,
             Y(end) = YTRY;
             ALGOSTEP = 'reflection';
         end
-        
-        % the initial temperature is estimated in the first loop from 
-        % the number of successfull and unsuccesfull moves, and the average 
+
+        % the initial temperature is estimated in the first loop from
+        % the number of successfull and unsuccesfull moves, and the average
         % increase in cost associated with the unsuccessful moves
-        
-        if TEMP_LOOP_NUMBER == 1 && isempty(OPTIONS.TEMP_START),
-            if Y(1) > Y(end),
+
+        if TEMP_LOOP_NUMBER == 1 && isempty(OPTIONS.TEMP_START)
+            if Y(1) > Y(end)
                 SUCCESSFUL_MOVES = SUCCESSFUL_MOVES+1;
-            elseif Y(1) <= Y(end),
+            elseif Y(1) <= Y(end)
                 UNSUCCESSFUL_MOVES = UNSUCCESSFUL_MOVES+1;
                 UNSUCCESSFUL_COSTS = UNSUCCESSFUL_COSTS+(Y(end)-Y(1));
             end
@@ -424,28 +424,28 @@ while 1,
     end
 
     % stop if previous for loop was broken due to some stop criterion
-    if ITERTEMP < MAXITERTEMP,
-        break;
+    if ITERTEMP < MAXITERTEMP
+        break
     end
-    
+
     % store cost function values in COSTS vector
     COSTS((ITERTEMP-1)*NDIM+1:ITERTEMP*NDIM+1) = Y;
-    
-    % calculated initial temperature or recalculate temperature 
+
+    % calculated initial temperature or recalculate temperature
     % using cooling schedule as proposed by Cardoso et al. (1996)
     % -----------------------------------------------------------
-    
-    if TEMP_LOOP_NUMBER == 1 && isempty(OPTIONS.TEMP_START),
+
+    if TEMP_LOOP_NUMBER == 1 && isempty(OPTIONS.TEMP_START)
         TEMP = -(UNSUCCESSFUL_COSTS/(SUCCESSFUL_MOVES+UNSUCCESSFUL_MOVES))/log(((SUCCESSFUL_MOVES+UNSUCCESSFUL_MOVES)*OPTIONS.INITIAL_ACCEPTANCE_RATIO-SUCCESSFUL_MOVES)/UNSUCCESSFUL_MOVES);
-    elseif TEMP_LOOP_NUMBER ~= 0,
+    elseif TEMP_LOOP_NUMBER ~= 0
         STDEV_Y = std(COSTS);
         COOLING_FACTOR = 1/(1+TEMP*log(1+OPTIONS.COOL_RATE)/(3*STDEV_Y));
         TEMP = TEMP*min(OPTIONS.MIN_COOLING_FACTOR,COOLING_FACTOR);
     end
-    
+
     % add one to temperature loop number
     TEMP_LOOP_NUMBER = TEMP_LOOP_NUMBER+1;
-    
+
 end
 
 % return solution
@@ -476,8 +476,8 @@ return
 % ---------------
 
 function [YFTRY,YTRY,PTRY] = AMOTRY(FUN,P,fac,LB,UB,varargin)
-% Extrapolates by a factor fac through the face of the simplex across from 
-% the high point, tries it, and replaces the high point if the new point is 
+% Extrapolates by a factor fac through the face of the simplex across from
+% the high point, tries it, and replaces the high point if the new point is
 % better.
 
 global NDIM TEMP
@@ -502,14 +502,14 @@ function [YTRY] = CALCULATE_COST(FUN,PTRY,LB,UB,varargin)
 
 global YBEST PBEST NDIM nFUN_EVALS
 
-for i = 1:NDIM,
+for i = 1:NDIM
     % check lower bounds
-    if PTRY(i) < LB(i),
+    if PTRY(i) < LB(i)
         YTRY = 1e12+(LB(i)-PTRY(i))*1e6;
         return
     end
     % check upper bounds
-    if PTRY(i) > UB(i),
+    if PTRY(i) > UB(i)
         YTRY = 1e12+(PTRY(i)-UB(i))*1e6;
         return
     end
@@ -522,7 +522,7 @@ YTRY = feval(FUN,PTRY(:),varargin{:});
 nFUN_EVALS = nFUN_EVALS + 1;
 
 % save the best point ever
-if YTRY < YBEST,
+if YTRY < YBEST
     YBEST = YTRY;
     PBEST = PTRY;
 end
diff --git a/matlab/optimization/simpsaget.m b/matlab/optimization/simpsaget.m
index e482a3e0011ca3dd6d4f533c69a6e32bd696ceb2..96eb36dc98f2f10fa8216ccae667ac5e8de39aa6 100644
--- a/matlab/optimization/simpsaget.m
+++ b/matlab/optimization/simpsaget.m
@@ -18,7 +18,7 @@ function o = simpsaget(options,name,default,flag)
 %   See also SIMPSASET, SIMPSA
 
 % Copyright (C) 2006 Brecht Donckels, BIOMATH, brecht.donckels@ugent.be
-% Copyright (C) 2013-2016 Dynare Team.
+% Copyright (C) 2013-2017 Dynare Team.
 %
 % This file is part of Dynare.
 %
@@ -38,25 +38,25 @@ function o = simpsaget(options,name,default,flag)
 
 % undocumented usage for fast access with no error checking
 if (nargin == 4) && isequal(flag,'fast')
-   o = getknownfield(options,name,default);
-   return
+    o = getknownfield(options,name,default);
+    return
 end
 
 if nargin < 2
-  error('MATLAB:odeget:NotEnoughInputs','Not enough input arguments.');
+    error('MATLAB:odeget:NotEnoughInputs','Not enough input arguments.');
 end
 if nargin < 3
-  default = [];
+    default = [];
 end
 
 if ~isempty(options) && ~isa(options,'struct')
-  error('MATLAB:odeget:Arg1NotODESETstruct',...
-        'First argument must be an options structure created with ODESET.');
+    error('MATLAB:odeget:Arg1NotODESETstruct',...
+          'First argument must be an options structure created with ODESET.');
 end
 
 if isempty(options)
-  o = default;
-  return;
+    o = default;
+    return
 end
 
 Names = [
@@ -75,39 +75,39 @@ Names = [
     'TOLFUN                   '
     'DISPLAY                  '
     'OUTPUT_FCN               '
-    ];
+        ];
 
 names = lower(Names);
 
 lowName = lower(name);
 j = strmatch(lowName,names);
 if isempty(j)               % if no matches
-  error('MATLAB:odeget:InvalidPropName',...
-        ['Unrecognized property name ''%s''.  ' ...
-         'See ODESET for possibilities.'], name);
+    error('MATLAB:odeget:InvalidPropName',...
+          ['Unrecognized property name ''%s''.  ' ...
+           'See ODESET for possibilities.'], name);
 elseif length(j) > 1            % if more than one match
-  % Check for any exact matches (in case any names are subsets of others)
-  k = strmatch(lowName,names,'exact');
-  if length(k) == 1
-    j = k;
-  else
-    msg = sprintf('Ambiguous property name ''%s'' ', name);
-    msg = [msg '(' deblank(Names(j(1),:))];
-    for k = j(2:length(j))'
-      msg = [msg ', ' deblank(Names(k,:))];
+                                % Check for any exact matches (in case any names are subsets of others)
+    k = strmatch(lowName,names,'exact');
+    if length(k) == 1
+        j = k;
+    else
+        msg = sprintf('Ambiguous property name ''%s'' ', name);
+        msg = [msg '(' deblank(Names(j(1),:))];
+        for k = j(2:length(j))'
+            msg = [msg ', ' deblank(Names(k,:))];
+        end
+        msg = sprintf('%s).', msg);
+        error('MATLAB:odeget:AmbiguousPropName', msg);
     end
-    msg = sprintf('%s).', msg);
-    error('MATLAB:odeget:AmbiguousPropName', msg);
-  end
 end
 
 if any(strcmp(fieldnames(options),deblank(Names(j,:))))
-  o = options.(deblank(Names(j,:)));
-  if isempty(o)
-    o = default;
-  end
+    o = options.(deblank(Names(j,:)));
+    if isempty(o)
+        o = default;
+    end
 else
-  o = default;
+    o = default;
 end
 
 % --------------------------------------------------------------------------
@@ -115,11 +115,10 @@ function v = getknownfield(s, f, d)
 %GETKNOWNFIELD  Get field f from struct s, or else yield default d.
 
 if isfield(s,f)   % s could be empty.
-  v = subsref(s, struct('type','.','subs',f));
-  if isempty(v)
-    v = d;
-  end
+    v = subsref(s, struct('type','.','subs',f));
+    if isempty(v)
+        v = d;
+    end
 else
-  v = d;
+    v = d;
 end
-
diff --git a/matlab/optimization/simpsaset.m b/matlab/optimization/simpsaset.m
index ca687891a8d1e3d127d208ed933c237aee4c4db8..1d63c7bdc9bc94572de13a2cfe60892d03b51f75 100644
--- a/matlab/optimization/simpsaset.m
+++ b/matlab/optimization/simpsaset.m
@@ -28,7 +28,7 @@ function options = simpsaset(varargin)
 
 % Copyright (C) 2005 Henning Schmidt, FCC, henning@fcc.chalmers.se
 % Copyright (C) 2006 Brecht Donckels, BIOMATH, brecht.donckels@ugent.be
-% Copyright (C) 2013 Dynare Team.
+% Copyright (C) 2013-2017 Dynare Team.
 %
 % This file is part of Dynare.
 %
@@ -64,7 +64,7 @@ if (nargin == 0) && (nargout == 0)
     fprintf('                      DISPLAY: [ ''iter'' or ''none'' {''iter''} ]\n');
     fprintf('                   OUTPUT_FCN: [ function_handle ]\n');
     fprintf('\n');
-return;
+    return
 end
 
 Names = [
@@ -83,7 +83,7 @@ Names = [
     'TOLFUN                   '
     'DISPLAY                  '
     'OUTPUT_FCN               '
-    ];
+        ];
 
 m = size(Names,1);
 names = lower(Names);
@@ -91,82 +91,82 @@ names = lower(Names);
 % Combine all leading options structures o1, o2, ... in odeset(o1,o2,...).
 options = [];
 for j = 1:m
-  options.(deblank(Names(j,:))) = [];
+    options.(deblank(Names(j,:))) = [];
 end
 i = 1;
 while i <= nargin
-  arg = varargin{i};
-  if ischar(arg)                         % arg is an option name
-    break;
-  end
-  if ~isempty(arg)                      % [] is a valid options argument
-    if ~isa(arg,'struct')
-      error('MATLAB:odeset:NoPropNameOrStruct',...
-            ['Expected argument %d to be a string property name ' ...
-                     'or an options structure\ncreated with SIMANSET.'], i);
+    arg = varargin{i};
+    if ischar(arg)                         % arg is an option name
+        break
     end
-    for j = 1:m
-      if any(strcmp(fieldnames(arg),deblank(Names(j,:))))
-        val = arg.(deblank(Names(j,:)));
-      else
-        val = [];
-      end
-      if ~isempty(val)
-        options.(deblank(Names(j,:))) = val;
-      end
+    if ~isempty(arg)                      % [] is a valid options argument
+        if ~isa(arg,'struct')
+            error('MATLAB:odeset:NoPropNameOrStruct',...
+                  ['Expected argument %d to be a string property name ' ...
+                   'or an options structure\ncreated with SIMANSET.'], i);
+        end
+        for j = 1:m
+            if any(strcmp(fieldnames(arg),deblank(Names(j,:))))
+                val = arg.(deblank(Names(j,:)));
+            else
+                val = [];
+            end
+            if ~isempty(val)
+                options.(deblank(Names(j,:))) = val;
+            end
+        end
     end
-  end
-  i = i + 1;
+    i = i + 1;
 end
 
 % A finite state machine to parse name-value pairs.
 if rem(nargin-i+1,2) ~= 0
-  error('MATLAB:odeset:ArgNameValueMismatch',...
-        'Arguments must occur in name-value pairs.');
+    error('MATLAB:odeset:ArgNameValueMismatch',...
+          'Arguments must occur in name-value pairs.');
 end
 expectval = 0;                          % start expecting a name, not a value
 while i <= nargin
-  arg = varargin{i};
-    
-  if ~expectval
-    if ~ischar(arg)
-      error('MATLAB:odeset:NoPropName',...
-            'Expected argument %d to be a string property name.', i);
-    end
-    
-    lowArg = lower(arg);
-    j = strmatch(lowArg,names);
-    if isempty(j)                       % if no matches
-      error('MATLAB:odeset:InvalidPropName',...
-            'Unrecognized property name ''%s''.', arg);
-    elseif length(j) > 1                % if more than one match
-      % Check for any exact matches (in case any names are subsets of others)
-      k = strmatch(lowArg,names,'exact');
-      if length(k) == 1
-        j = k;
-      else
-        msg = sprintf('Ambiguous property name ''%s'' ', arg);
-        msg = [msg '(' deblank(Names(j(1),:))];
-        for k = j(2:length(j))'
-          msg = [msg ', ' deblank(Names(k,:))];
+    arg = varargin{i};
+
+    if ~expectval
+        if ~ischar(arg)
+            error('MATLAB:odeset:NoPropName',...
+                  'Expected argument %d to be a string property name.', i);
         end
-        msg = sprintf('%s).', msg);
-        error('MATLAB:odeset:AmbiguousPropName', msg);
-      end
+
+        lowArg = lower(arg);
+        j = strmatch(lowArg,names);
+        if isempty(j)                       % if no matches
+            error('MATLAB:odeset:InvalidPropName',...
+                  'Unrecognized property name ''%s''.', arg);
+        elseif length(j) > 1                % if more than one match
+                                            % Check for any exact matches (in case any names are subsets of others)
+            k = strmatch(lowArg,names,'exact');
+            if length(k) == 1
+                j = k;
+            else
+                msg = sprintf('Ambiguous property name ''%s'' ', arg);
+                msg = [msg '(' deblank(Names(j(1),:))];
+                for k = j(2:length(j))'
+                    msg = [msg ', ' deblank(Names(k,:))];
+                end
+                msg = sprintf('%s).', msg);
+                error('MATLAB:odeset:AmbiguousPropName', msg);
+            end
+        end
+        expectval = 1;                      % we expect a value next
+
+    else
+        options.(deblank(Names(j,:))) = arg;
+        expectval = 0;
+
     end
-    expectval = 1;                      % we expect a value next
-    
-  else
-    options.(deblank(Names(j,:))) = arg;
-    expectval = 0;
-      
-  end
-  i = i + 1;
+    i = i + 1;
 end
 
 if expectval
-  error('MATLAB:odeset:NoValueForProp',...
-        'Expected value for property ''%s''.', arg);
+    error('MATLAB:odeset:NoValueForProp',...
+          'Expected value for property ''%s''.', arg);
 end
 
 end
diff --git a/matlab/optimization/simulated_annealing.m b/matlab/optimization/simulated_annealing.m
index 5b505b71d6246d288da9c2e72b60e2c46dafaaf1..7088685b3a8e66c0a6f754a32a353c43a2f991f8 100644
--- a/matlab/optimization/simulated_annealing.m
+++ b/matlab/optimization/simulated_annealing.m
@@ -5,7 +5,7 @@ function [xopt, fopt,exitflag, n_accepted_draws, n_total_draws, n_out_of_bounds_
 %
 % 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
@@ -49,17 +49,17 @@ function [xopt, fopt,exitflag, n_accepted_draws, n_total_draws, n_out_of_bounds_
 %    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.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
@@ -104,11 +104,11 @@ function [xopt, fopt,exitflag, n_accepted_draws, n_total_draws, n_out_of_bounds_
 %                               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. 
+%
+%    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. 
+%         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
@@ -116,8 +116,8 @@ function [xopt, fopt,exitflag, n_accepted_draws, n_total_draws, n_out_of_bounds_
 %         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:
@@ -142,28 +142,28 @@ function [xopt, fopt,exitflag, n_accepted_draws, n_total_draws, n_out_of_bounds_
 %    t:     On output, the final temperature.
 %    vm:    Final step length vector
 %
-% Algorithm: 
+% 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 
+%  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) 1995 E.G.Tsionas
+% Copyright (C) 1995-2002 Thomas Werner
 % Copyright (C) 2002-2015 Giovanni Lombardo
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -194,17 +194,17 @@ 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);
+if(t<=0.0)
     fprintf('\nThe initial temperature is not positive. Reset the variable t\n');
     exitflag=3;
-    return;
-end;
+    return
+end
 %*  If the initial value is out of bounds, notify the user and abort. *
-if(sum(x>ub)+sum(x<lb)>0);
+if(sum(x>ub)+sum(x<lb)>0)
     fprintf('\nInitial condition out of bounds\n');
     exitflag=2;
-    return;
-end;
+    return
+end
 %*  Evaluate the function with input x and return value as f. *
 f=feval(fcn,x,varargin{:});
 %*
@@ -212,98 +212,98 @@ f=feval(fcn,x,varargin{:});
 %  Note that all intermediate and final output switches the sign back
 %  to eliminate any possible confusion for the user.
 %*
-if(optim.maximizer_indicator==0);
+if(optim.maximizer_indicator==0)
     f=-f;
-end;
+end
 n_total_draws=n_total_draws+1;
 fopt=f;
 fstar(1)=f;
-if(optim.verbosity >1);
+if(optim.verbosity >1)
     disp '  ';
     disp(['initial x    ' num2str(x(:)')]);
-    if(optim.maximizer_indicator);
+    if(optim.maximizer_indicator)
         disp(['initial f    ' num2str(f)]);
     else
         disp(['initial f    ' num2str(-f)]);
-    end;
-end;
+    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);
+while (1>0)
     nup=0;
     nrej=0;
     nnew=0;
     ndown=0;
     lnobds=0;
     m=1;
-    while m<=optim.nt;
+    while m<=optim.nt
         j=1;
-        while j<=optim.ns;
+        while j<=optim.ns
             h=1;
-            while h<=n;
+            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);
+                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;
+                    end
                     %*  If xp is out of bounds, select a point in bounds for the trial. *
-                    if((xp(i)<lb(i) || xp(i)>ub(i)));
+                    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(optim.verbosity >=3)
                             if exist('fp','var')
                                 print_current_invalid_try(optim.maximizer_indicator,xp,x,fp,f);
                             end
-                        end;
-                    end;
+                        end
+                    end
                     i=i+1;
-                end;
+                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);
+                if(optim.maximizer_indicator==0)
                     fp=-fp;
-                end;
+                end
                 n_total_draws=n_total_draws+1;
-                if(optim.verbosity >=3);
+                if(optim.verbosity >=3)
                     print_current_valid_try(optim.maximizer_indicator,xp,x,fp,f);
-                end;
+                end
                 %*  If too many function evaluations occur, terminate the algorithm. *
-                if(n_total_draws>=optim.MaxIter);
+                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);
+                    if(optim.maximizer_indicator==0)
                         fopt=-fopt;
-                    end;
+                    end
                     exitflag=1;
-                    return;
-                end;
+                    return
+                end
                 %*  Accept the new point if the function value increases. *
-                if(fp>=f);
-                    if(optim.verbosity >=3);
+                if(fp>=f)
+                    if(optim.verbosity >=3)
                         fprintf('point accepted\n');
-                    end;
+                    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);
+                    if(fp>fopt)
+                        if(optim.verbosity >=3)
                             fprintf('new optimum\n');
-                        end;
+                        end
                         xopt=xp;
                         fopt=fp;
                         nnew=nnew+1;
-                    end;
+                    end
                     %*
                     % If the point is lower, use the Metropolis criteria to decide on
                     % acceptance or rejection.
@@ -311,14 +311,14 @@ while (1>0);
                 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');
+                    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;
+                                fprintf('though higher, point accepted\n');
+                            end
+                        end
                         x=xp;
                         f=fp;
                         n_accepted_draws=n_accepted_draws+1;
@@ -326,87 +326,87 @@ while (1>0);
                         ndown=ndown+1;
                     else
                         nrej=nrej+1;
-                        if(optim.verbosity >=3);
-                            if(optim.maximizer_indicator);
+                        if(optim.verbosity >=3)
+                            if(optim.maximizer_indicator)
                                 fprintf('lower point rejected\n');
                             else
                                 fprintf('higher point rejected\n');
-                            end;
-                        end;
-                    end;
-                end;
+                            end
+                        end
+                    end
+                end
                 h=h+1;
-            end;
+            end
             j=j+1;
-        end;
+        end
         %*  Adjust vm so that approximately half of all evaluations are accepted. *
         i=1;
-        while i<=n;
+        while i<=n
             ratio=nacp(i)/optim.ns;
-            if(ratio>.6);
+            if(ratio>.6)
                 vm(i)=vm(i)*(1.+c(i)*(ratio-.6)/.4);
-            elseif(ratio<.4);
+            elseif(ratio<.4)
                 vm(i)=vm(i)/(1.+c(i)*((.4-ratio)/.4));
-            end;
-            if(vm(i)>(ub(i)-lb(i)));
+            end
+            if(vm(i)>(ub(i)-lb(i)))
                 vm(i)=ub(i)-lb(i);
-            end;
+            end
             i=i+1;
-        end;
-        if(optim.verbosity >=2);
+        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;
+        end
         nacp=zeros(n,1);
         m=m+1;
-    end;
-    if(optim.verbosity >=1);
+    end
+    if(optim.verbosity >=1)
         print_intermediate_statistics(optim.maximizer_indicator,t,xopt,vm,fopt,nup,ndown,nrej,lnobds,nnew);
-    end;
+    end
     %*  Check termination criteria. *
     quit=0;
     fstar(1)=f;
-    if((fopt-fstar(1))<=optim.TolFun);
+    if((fopt-fstar(1))<=optim.TolFun)
         quit=1;
-    end;
-    if(sum(abs(f-fstar)>optim.TolFun)>0);
+    end
+    if(sum(abs(f-fstar)>optim.TolFun)>0)
         quit=0;
-    end;
+    end
     %*  Terminate SA if appropriate. *
-    if(quit);
+    if(quit)
         exitflag=0;
-        if(optim.maximizer_indicator==0);
+        if(optim.maximizer_indicator==0)
             fopt=-fopt;
-        end;
-        if(optim.verbosity >=1);
+        end
+        if(optim.verbosity >=1)
             fprintf('SA achieved termination criteria.exitflag=0\n');
-        end;
-        return;        
-    end;
+        end
+        return
+    end
     %*  If termination criteria are not met, prepare for another loop. *
     t=optim.rt*t;
     i=optim.neps;
-    while i>=2;
+    while i>=2
         fstar(i)=fstar(i-1);
         i=i-1;
-    end;
+    end
     f=fopt;
     x=xopt;
     %*  Loop again. *
-end;
+end
 
 end
 
 function  print_current_invalid_try(max,xp,x,fp,f)
 fprintf('\n');
-    disp(['Current x    ' num2str(x(:)')]);
-if(max);
+disp(['Current x    ' num2str(x(:)')]);
+if(max)
     disp(['Current f    ' num2str(f)]);
 else
     disp(['Current f    ' num2str(-f)]);
-end;
+end
 disp(['Trial x      ' num2str(xp(:)')]);
 disp 'Point rejected since out of bounds';
 end
@@ -414,7 +414,7 @@ end
 function print_current_valid_try(max,xp,x,fp,f)
 
 disp(['Current x    ' num2str(x(:)')]);
-if(max);
+if(max)
     disp(['Current f   ' num2str(f)]);
     disp(['Trial x     ' num2str(xp(:)')]);
     disp(['Resulting f ' num2str(fp)]);
@@ -422,7 +422,7 @@ else
     disp(['Current f   ' num2str(-f)]);
     disp(['Trial x     ' num2str(xp(:)')]);
     disp(['Resulting f ' num2str(-fp)]);
-end;
+end
 end
 
 
diff --git a/matlab/optimization/solvopt.m b/matlab/optimization/solvopt.m
index 6d5693e8643b1ee218cb8d5b1abbc37968f1a44a..c4a819a26d48fbb72bf347451aa0ef6aa8b24f0a 100644
--- a/matlab/optimization/solvopt.m
+++ b/matlab/optimization/solvopt.m
@@ -1,10 +1,10 @@
 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,  
+%
+% 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 
+% 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) }
 %
@@ -41,7 +41,7 @@ function [x,f,exitflag,n_f_evals,n_grad_evals,n_constraint_evals,n_constraint_gr
 %   *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
@@ -51,15 +51,15 @@ function [x,f,exitflag,n_f_evals,n_grad_evals,n_constraint_evals,n_constraint_gr
 % 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 
+%
+%
+% 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
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -162,7 +162,7 @@ if isempty(func)
     constr=0;
 else
     constr=1;                  % Constrained problem
-    if isempty(gradc),
+    if isempty(gradc)
         appconstr=1;
     else
         appconstr=0;            % Exact gradients of constraints are supplied
@@ -201,7 +201,7 @@ end
 epsnorm=1.e-15;
 epsnorm2=1.e-30;    % epsilon & epsilon^2
 
-if constr, h1=-1;                  % NLP: restricted to minimization
+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
@@ -217,10 +217,10 @@ 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<=0, dispdata=0
     if optim.verbosity==-1
         dispwarn=0;
     else
@@ -243,7 +243,7 @@ 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
@@ -253,7 +253,7 @@ 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
+                                   % 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;
@@ -276,30 +276,79 @@ 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
+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,
+                    % 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
+    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
@@ -318,13 +367,13 @@ if app
         if trx
             g=apprgrdn(x',fp,fun,deltax',1,varargin{:});
         else
-            g=apprgrdn(x ,fp,fun,deltax,1,varargin{:}); 
+            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{:}); 
+            g=apprgrdn(x ,f,fun,deltax,1,varargin{:});
         end
     end
     n_f_evals=n_f_evals+n;
@@ -332,114 +381,151 @@ else
     if trx
         g=feval(grad,x',varargin{:});
     else
-        g=feval(grad,x,varargin{:});   
+        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
+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,
+        if appconstr
             deltax=sign(x); idx=find(deltax==0);
-            deltax(idx)=ones(size(idx));  
+            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); 
+                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); 
+                gc=feval(gradc,x);
             end
             n_constraint_gradient_evals=n_constraint_gradient_evals+1;
         end
         if size(gc,2)==1
-            gc=gc'; 
+            gc=gc';
         end
         ngc=norm(gc);
-        if size(gc,2)~=n,
+        if size(gc,2)~=n
             if dispwarn
-                disp(errmes);
-                disp(error60);
+                disp(errmes)
+                disp(error60)
             end
-            exitflag=-6; 
+            exitflag=-6;
             if trx
                 x=x';
             end
             return
-        elseif isnan(ngc),
+        elseif isnan(ngc)
             if dispwarn
-                disp(errmes);
-                disp(error61);
-                disp(error6);
+                disp(errmes)
+                disp(error61)
+                disp(error6)
             end
-            exitflag=-6; 
+            exitflag=-6;
             if trx
                 x=x';
             end
             return
-        elseif ngc==Inf,
+        elseif ngc==Inf
             if dispwarn
-                disp(errmes);
-                disp(error62);
-                disp(error6);
+                disp(errmes)
+                disp(error62)
+                disp(error6)
             end
-            exitflag=-6; 
+            exitflag=-6;
             if trx
                 x=x';
             end
             return
-        elseif ngc<ZeroGrad,
+        elseif ngc<ZeroGrad
             if dispwarn
-                disp(errmes);
-                disp(error63);
+                disp(errmes)
+                disp(error63)
             end
-            exitflag=-6; 
+            exitflag=-6;
             if trx
                 x=x';
             end
             return
         end
         g=g+PenCoef*gc; ng=norm(g);
-    end, end
+    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,
+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,
+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,
+
+    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)])]);
@@ -447,11 +533,21 @@ while 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,
+            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
+            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
@@ -465,8 +561,8 @@ while 1,
             z=z/nrmz;
             g1=gt+w*(z*gt')*z;  B=B+w*(B*z')*z;
         else
-            z=zeros(1,n); 
-            nrmz=0; 
+            z=zeros(1,n);
+            nrmz=0;
             g1=gt;
         end
         d1=norm(g1);  g0=(g1/d1)*B';
@@ -474,15 +570,18 @@ while 1,
         % 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 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; 
+                        ajp=ajpp;
                     end
-                    h=h1*dx/3; 
+                    h=h1*dx/3;
                     k=k-1;
                     break
                 end
@@ -493,23 +592,26 @@ while 1,
         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,
+        while 1
             x1=x;f1=f;
-            if constr, FP1=FP; fp1=fp; end
+            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{:});  
+                f=feval(fun,x,varargin{:});
             end
             n_f_evals=n_f_evals+1;
             if h1*f==Inf
                 if dispwarn
-                    disp(errmes); 
-                    disp(error5); 
+                    disp(errmes)
+                    disp(error5)
                 end
-                exitflag=-7; 
+                exitflag=-7;
                 if trx
                     x=x';
                 end
@@ -522,15 +624,31 @@ while 1,
                     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
+                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; 
+                    FP=1;
                     fc=0;
                 else
                     FP=0;
@@ -538,7 +656,7 @@ while 1,
                     if fp_rate<-epsnorm
                         if ~FP1
                             PenCoefNew=-15*fp_rate/norm(x-x1);
-                            if PenCoefNew>1.2*PenCoef,
+                            if PenCoefNew>1.2*PenCoef
                                 PenCoef=PenCoefNew; Reset=1; kless=0; f=f+PenCoef*fc; break
                             end
                         end
@@ -547,98 +665,123 @@ while 1,
                 f=f+PenCoef*fc;
             end
             if abs(f)==Inf || isnan(f)
-                if dispwarn, disp(wrnmes);
+                if dispwarn, disp(wrnmes)
                     if isnan(f)
-                        disp(error31); 
+                        disp(error31)
                     else
-                        disp(error32); 
+                        disp(error32)
                     end
                 end
                 if ksm || kc>=mxtc
-                    exitflag=-3; 
+                    exitflag=-3;
                     if trx
                         x=x';
                     end
                     return
                 else
                     k2=k2+1;
-                    k1=0; 
-                    hp=hp/dq; 
+                    k1=0;
+                    hp=hp/dq;
                     x=x1;
-                    f=f1; 
+                    f=f1;
                     knan=1;
                     if constr
-                        FP=FP1; 
-                        fp=fp1; 
+                        FP=FP1;
+                        fp=fp1;
                     end
                 end
                 % STEP SIZE IS ZERO TO THE EXTENT OF EPSNORM
-            elseif all(abs(x-x1)<abs(x)*epsnorm),
+            elseif all(abs(x-x1)<abs(x)*epsnorm)
                 stepvanish=stepvanish+1;
-                if stepvanish>=5,
+                if stepvanish>=5
                     exitflag=-14;
-                    if dispwarn, disp(termwarn1);
-                        disp(endwarn(4,:)); end
-                    if trx,x=x';end,  return
+                    if dispwarn
+                        disp(termwarn1)
+                        disp(endwarn(4,:))
+                    end
+                    if trx
+                        x=x';
+                    end
+                    return
                 else
-                    x=x1; 
-                    f=f1; 
-                    hp=hp*10; 
+                    x=x1;
+                    f=f1;
+                    hp=hp*10;
                     ksm=1;
                     if constr
-                        FP=FP1; 
-                        fp=fp1; 
+                        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 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
+            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;
+                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
+        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); 
+                h=h*sqrt(kk-des+1);
             end
         elseif kk<des
             h=h*sqrt(kk/des);
         end
-        
+
         stepvanish=stepvanish+ksm;
         % ----}
         % COMPUTE THE GRADIENT ----{
-        if app,
+        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{:});    
+                    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{:});    
+                    g=apprgrdn(x ,f,fun,deltax ,1,varargin{:});
                 end
             end
             n_f_evals=n_f_evals+n;
@@ -646,19 +789,39 @@ while 1,
             if trx
                 g=feval(grad,x',varargin{:});
             else
-                g=feval(grad,x,varargin{:}); 
+                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
+        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:
@@ -666,52 +829,93 @@ while 1,
             if ~FP
                 if ng<.01*PenCoef
                     kless=kless+1;
-                    if kless>=20, PenCoef=PenCoef/10; Reset=1; kless=0; end
+                    if kless>=20
+                        PenCoef=PenCoef/10;
+                        Reset=1;
+                        kless=0;
+                    end
                 else
                     kless=0;
                 end
-                if appconstr,
+                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); 
+                        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 ); 
+                        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
+                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
+                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
+            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
+        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 ');
@@ -721,10 +925,20 @@ while 1,
         %----}
         % 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
+        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);
@@ -737,40 +951,48 @@ while 1,
                         ~constr
                     if any(abs(xrec(idx)-x(idx))> detxr * abs(x(idx)))
                         if dispwarn
-                            disp(wrnmes);
-                            disp(warn09);
+                            disp(wrnmes)
+                            disp(warn09)
                         end
-                        x=xrec; 
-                        f=frec; 
-                        g=grec; 
-                        ng=norm(g); 
+                        x=xrec;
+                        f=frec;
+                        g=grec;
+                        ng=norm(g);
                         krerun=krerun+1;
                         h=h1*max([dx,detxr*norm(x)])/krerun;
-                        warnno=2; 
+                        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==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
+                                if dispwarn, disp(termwarn1)
+                                    disp(endwarn(warnno,:))
+                                    if app
+                                        disp(appwarn);
+                                    end
                                 end
                             else
                                 exitflag=k;
                                 if dispwarn
-                                    disp(termwarn0); 
+                                    disp(termwarn0);
                                 end
                             end
                             if trx
@@ -783,11 +1005,18 @@ while 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
+                    if dispwarn
+                        disp(termwarn1)
+                        disp(endwarn(4,:))
+                        if app
+                            disp(appwarn)
+                        end
                     end
                     x=xrec; f=frec;
-                    if trx,x=x';end,  return
+                    if trx
+                        x=x';
+                    end
+                    return
                 else
                     stopf=0;
                 end
@@ -795,57 +1024,67 @@ while 1,
         end
         % ITERATIONS LIMIT
         if(k==optim.MaxIter)
-            exitflag=-9; 
+            exitflag=-9;
             if trx
-                x=x'; 
-            end,
-            if dispwarn, disp(wrnmes);  disp(warn4); end
+                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 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 ng<=ZeroGrad
+                nzero=nzero+1;
+                if dispwarn
+                    disp(wrnmes)
+                    disp(warn1)
+                end
                 if nzero>=3
-                    exitflag=-8; 
+                    exitflag=-8;
                     if trx
                         x=x';
                     end
                     return
                 end
                 g0=-h*g0/2;
-                for i=1:10,
+                for i=1:10
                     x=x+g0;
                     if trx
                         f=feval(fun,x',varargin{:});
                     else
-                        f=feval(fun,x,varargin{:}); 
+                        f=feval(fun,x,varargin{:});
                     end
                     n_f_evals=n_f_evals+1;
                     if abs(f)==Inf
                         if dispwarn
-                            disp(errmes);  
-                            disp(error32);  
+                            disp(errmes)
+                            disp(error32)
                         end
                         exitflag=-3;
                         if trx
                             x=x';
                         end
                         return
-                    elseif isnan(f),
+                    elseif isnan(f)
                         if dispwarn
-                            disp(errmes);  
-                            disp(error32);  
+                            disp(errmes)
+                            disp(error32)
                         end
                         exitflag=-3;
                         if trx
@@ -853,47 +1092,47 @@ while 1,
                         end
                         return
                     end
-                    if app,
-                        deltax=sign(g0); 
+                    if app
+                        deltax=sign(g0);
                         idx=find(deltax==0);
-                        deltax(idx)=ones(size(idx));  
+                        deltax(idx)=ones(size(idx));
                         deltax=h1*ddx*deltax;
-                        if trx  
+                        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  
+                        if trx
                             g=feval(grad,x',varargin{:});
                         else
-                            g=feval(grad,x,varargin{:});   
+                            g=feval(grad,x,varargin{:});
                         end
                         n_grad_evals=n_grad_evals+1;
                     end
                     if size(g,2)==1
-                        g=g'; 
+                        g=g';
                     end
                     ng=norm(g);
                     if ng==Inf
                         if dispwarn
-                            disp(errmes);  
-                            disp(error42); 
+                            disp(errmes)
+                            disp(error42)
                         end
-                        exitflag=-4; 
+                        exitflag=-4;
                         if trx
-                            x=x'; 
+                            x=x';
                         end
                         return
                     elseif isnan(ng)
                         if dispwarn
-                            disp(errmes);  
-                            disp(error41); 
+                            disp(errmes)
+                            disp(error41)
                         end
-                        exitflag=-4; 
+                        exitflag=-4;
                         if trx
-                            x=x'; 
+                            x=x';
                         end
                         return
                     end
@@ -901,41 +1140,54 @@ while 1,
                         break
                     end
                 end
-                if ng<=ZeroGrad,
+                if ng<=ZeroGrad
                     if dispwarn
-                        disp(termwarn1);  
-                        disp(warn1); 
+                        disp(termwarn1)
+                        disp(warn1)
                     end
-                    exitflag=-8; 
+                    exitflag=-8;
                     if trx
                         x=x';
                     end
                     return
                 end
-                h=h1*dx; 
+                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); 
+            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;
+            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;
+                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{:}); 
+                            f1=feval(fun,x1,varargin{:});
                         end
                         n_f_evals=n_f_evals+1;
-                        if abs(f1)~=Inf && ~isnan(f1),
+                        if abs(f1)~=Inf && ~isnan(f1)
                             if h1*f1>h1*fm
-                                y=x1(j); 
+                                y=x1(j);
                                 fm=f1;
                             elseif h1*f2>h1*f1
                                 break
@@ -948,36 +1200,36 @@ while 1,
                     x1(j)=y;
                 end
                 if h1*fm>h1*f
-                    if app,
+                    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{:});    
+                            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{:}); 
+                            gt=feval(grad,x1,varargin{:});
                         end
                         n_grad_evals=n_grad_evals+1;
                     end
                     if size(gt,2)==1
-                        gt=gt'; 
+                        gt=gt';
                     end
                     ngt=norm(gt);
-                    if ~isnan(ngt) && ngt>epsnorm2,
+                    if ~isnan(ngt) && ngt>epsnorm2
                         if dispwarn
-                            disp(warn32); 
+                            disp(warn32)
                         end
                         optim.TolFun=optim.TolFun/5;
-                        x=x1; 
-                        g=gt; 
-                        ng=ngt; 
-                        f=fm; 
-                        h=h1*dx/3; 
+                        x=x1;
+                        g=gt;
+                        ng=ngt;
+                        f=fm;
+                        h=h1*dx/3;
                         break
                     end
                 end
@@ -986,6 +1238,6 @@ while 1,
         % ----}
     end % iterations
 end % restart
-% end of the function
-%
-end
\ No newline at end of file
+    % end of the function
+    %
+    end
\ No newline at end of file
diff --git a/matlab/optimize_prior.m b/matlab/optimize_prior.m
index cdb03ecff2f5e659787683c5e2407e43f0094044..adf4d9c0ed1a632b79595bdaac73a801dbe2c818 100644
--- a/matlab/optimize_prior.m
+++ b/matlab/optimize_prior.m
@@ -2,7 +2,7 @@ function optimize_prior(DynareOptions, ModelInfo, DynareResults, BayesInfo, Esti
 
 % This routine computes the mode of the prior density using an optimization algorithm.
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -34,7 +34,7 @@ while look_for_admissible_initial_condition
             look_for_admissible_initial_condition = 0;
         end
     else
-        if iter == 2000;
+        if iter == 2000
             scale = scale/1.1;
             iter  = 0;
         else
diff --git a/matlab/options2cell.m b/matlab/options2cell.m
index 3ff8ef22741e7e39030dd162f9afde04acd8c8b5..697c24b87f9baa7e9b841df6bde932c19a15d2bb 100644
--- a/matlab/options2cell.m
+++ b/matlab/options2cell.m
@@ -2,13 +2,13 @@ function c = options2cell(o)
 
 % Converts an option structure as a cell of NAME and VALUE pairs.
 %
-% INPUTS 
+% INPUTS
 %  o o       matlab's structure holding a set of options (each field name is the name of an option and the associated content is the value of the option).
 %
-% OUTPUTS 
+% OUTPUTS
 %  o c       matlab's cell row array of the form {NAME1, VALUE1, NAME2, VALUE2, NAME3, VALUE3, ...}.
 
-% Copyright (C) 2013 Dynare Team.
+% Copyright (C) 2013-2017 Dynare Team.
 %
 % This file is part of Dynare.
 %
@@ -27,10 +27,10 @@ function c = options2cell(o)
 
 s = fieldnames(o);
 c = {};
-j = 1; 
- 
+j = 1;
+
 for i=1:length(s)
-    c(j) = {s{i}}; 
-    c(j+1) = {o.(s{i})}; 
-    j = j+2; 
+    c(j) = {s{i}};
+    c(j+1) = {o.(s{i})};
+    j = j+2;
 end
\ No newline at end of file
diff --git a/matlab/osr.m b/matlab/osr.m
index d579c63ec90b20c6dc650c1ed47b300175ec01d5..60039ac45369fe059034bbe820a428861f85b119 100644
--- a/matlab/osr.m
+++ b/matlab/osr.m
@@ -9,19 +9,19 @@ function osr_res = osr(var_list,params,i_var,W)
 %                                           optimal simple rule
 %   i_var       [n_osr_vars by 1 double]    indices of osr-variable in
 %                                           specified in optim_weights in declaration order
-%   W           [M_.endo_nbr by M_.endo_nbr sparse matrix] Weighting matrix for variance of endogenous variables             
-%    
+%   W           [M_.endo_nbr by M_.endo_nbr sparse matrix] Weighting matrix for variance of endogenous variables
+%
 % OUTPUTS
 %   osr_res:    [structure] results structure containing:
 %    - objective_function [scalar double]   value of the objective
 %                                               function at the optimum
-%    - optim_params       [structure]       parameter values at the optimum 
-% 
-%       
+%    - optim_params       [structure]       parameter values at the optimum
+%
+%
 % SPECIAL REQUIREMENTS
 %   none.
-%  
-% Copyright (C) 2001-2016 Dynare Team
+%
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -38,7 +38,7 @@ function osr_res = osr(var_list,params,i_var,W)
 % 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_  
+global M_ options_ oo_
 
 options_.order = 1;
 
diff --git a/matlab/osr1.m b/matlab/osr1.m
index cf13da166d40e449c149e8df76ef72d90323086b..b73db2b244019944a09428b602a08d2136bb3256 100644
--- a/matlab/osr1.m
+++ b/matlab/osr1.m
@@ -9,14 +9,14 @@ function osr_res = osr1(i_params,i_var,weights)
 %   osr_res:    [structure] results structure containing:
 %    - objective_function [scalar double]   value of the objective
 %                                               function at the optimum
-%    - optim_params       [structure]       parameter values at the optimum 
-% 
+%    - optim_params       [structure]       parameter values at the optimum
+%
 % Algorithm:
-% 
+%
 %   Uses Newton-type optimizer csminwel to directly solve quadratic
 %   osr-problem
-% 
-% Copyright (C) 2005-2014 Dynare Team
+%
+% Copyright (C) 2005-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -80,7 +80,7 @@ if isfield(options_.osr,'maxit') || isfield(options_.osr,'tolf')
                 options_.optim_opt=[options_.optim_opt,','];
             end
             options_.optim_opt=[options_.optim_opt,'''TolFun'',',num2str(options_.osr.tolf),''];
-        end  
+        end
     end
 end
 
@@ -101,17 +101,17 @@ i_var=unique(i_var);
 %% do initial checks
 [loss,info,exit_flag,vx]=osr_obj(t0,i_params,inv_order_var(i_var),weights(i_var,i_var));
 if info~=0
-   print_info(info, options_.noprint, options_);
-   else 
-       if ~options_.noprint
-           fprintf('\nOSR: Initial value of the objective function: %g \n\n',loss);
-       end
+    print_info(info, options_.noprint, options_);
+else
+    if ~options_.noprint
+        fprintf('\nOSR: Initial value of the objective function: %g \n\n',loss);
+    end
 end
-if ~options_.noprint && isinf(loss) 
-   fprintf('\nOSR: The initial value of the objective function is infinite.\n');
-   fprintf('\nOSR: Check whether the unconditional variance of a target variable is infinite\n');
-   fprintf('\nOSR: due to the presence of a unit root.\n');
-   error('OSR: Initial likelihood is infinite')
+if ~options_.noprint && isinf(loss)
+    fprintf('\nOSR: The initial value of the objective function is infinite.\n');
+    fprintf('\nOSR: Check whether the unconditional variance of a target variable is infinite\n');
+    fprintf('\nOSR: due to the presence of a unit root.\n');
+    error('OSR: Initial likelihood is infinite')
 end
 
 
@@ -120,17 +120,17 @@ if isequal(options_.osr.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.')    
+    error('OSR: OSR does not support opt_algo=10.')
 elseif isequal(options_.osr.opt_algo,11)
-    error('OSR: OSR does not support opt_algo=11.')    
+    error('OSR: OSR does not support opt_algo=11.')
 else
-    
-if ~isempty(M_.osr.param_bounds) && ~(ismember(options_.osr.opt_algo,[1,2,5,9]) || ischar(options_.osr.opt_algo))
-    error('OSR: OSR with bounds on parameters requires a constrained optimizer, i.e. 1,2,5, or 9.')    
-end
-%%do actual optimization
-[p, f, exitflag] = dynare_minimize_objective(str2func('osr_obj'),t0,options_.osr.opt_algo,options_,M_.osr.param_bounds,cellstr(M_.param_names(i_params,:)),[],[], i_params,...
-                inv_order_var(i_var),weights(i_var,i_var));
+
+    if ~isempty(M_.osr.param_bounds) && ~(ismember(options_.osr.opt_algo,[1,2,5,9]) || ischar(options_.osr.opt_algo))
+        error('OSR: OSR with bounds on parameters requires a constrained optimizer, i.e. 1,2,5, or 9.')
+    end
+    %%do actual optimization
+    [p, f, exitflag] = dynare_minimize_objective(str2func('osr_obj'),t0,options_.osr.opt_algo,options_,M_.osr.param_bounds,cellstr(M_.param_names(i_params,:)),[],[], i_params,...
+                                                 inv_order_var(i_var),weights(i_var,i_var));
 end
 
 osr_res.objective_function = f;
diff --git a/matlab/osr_obj.m b/matlab/osr_obj.m
index 67efbbbc08a6a669413d4ab2d6aa9768a9af4f53..76db1da69c80b9230dfe74fd6daffa2889937aeb 100644
--- a/matlab/osr_obj.m
+++ b/matlab/osr_obj.m
@@ -17,7 +17,7 @@ function [loss,info,exit_flag,vx,junk]=osr_obj(x,i_params,i_var,weights)
 %
 % SPECIAL REQUIREMENTS
 %   none
-% Copyright (C) 2005-2016 Dynare Team
+% Copyright (C) 2005-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -51,14 +51,14 @@ it_ = M_.maximum_lag+1;
 
 if info(1)
     if info(1) == 3 || info(1) == 4 || info(1) == 5 || info(1)==6 ||info(1) == 19 ||...
-            info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1) == 26 || ...
-            info(1) == 81 || info(1) == 84 ||  info(1) == 85
+                info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1) == 26 || ...
+                info(1) == 81 || info(1) == 84 ||  info(1) == 85
         loss = 1e8;
         info(4)=info(2);
         return
     else
         loss = 1e8;
-        info(4)=0.1;        
+        info(4)=0.1;
         return
     end
 end
diff --git a/matlab/parallel/AnalyseComputationalEnvironment.m b/matlab/parallel/AnalyseComputationalEnvironment.m
index e5d2a87f530e2b3ef276bcbb6a52cc80bb06ff96..d00ca1b699c5144ea7a72f364dc49dc3f89024ed 100644
--- a/matlab/parallel/AnalyseComputationalEnvironment.m
+++ b/matlab/parallel/AnalyseComputationalEnvironment.m
@@ -1,657 +1,658 @@
-function [ErrorCode] = AnalyseComputationalEnvironment(DataInput, DataInputAdd)
-% PARALLEL CONTEXT
-% In a parallel context, this function is used to check the cluster defined by the user.
-% If no error happen the function returns 0. The function complies with
-% Windows/Linux operating systems and Matlab/Octave software.
-%
-%
-% INPUT/OUTPUT description:
-%
-%
-% DataInput
-%   is the strcture option_.parallel, with the follow fields:
-%
-%             Local         1 is on local machine, 0 remote
-%      ComputerName         the computer name.
-%            CPUnbr         the CPU's
-%          UserName         the user name for the ComputerName.
-%          Password         the password for the user name in ComputerName.
-%       RemoteDrive         Drive used for Remote computation (data exchange, etc): must be contain 'RemoteFolder'.
-%   RemoteDirectory         Folder in RemoteDrive used for Remote computation.
-%  MatlabOctavePath         Path to MATLAB or Octave executable.
-%        DynarePath         Path to matlab directory within the Dynare installation directory.
-%
-%   This information is typed by the user in the DYNARE configuration file and is parsed by the preprocessor,
-%   the goal of this function is to check if configuration is correct and if dynare
-%   can be executed successfully in parallel mode.
-%
-%
-% DataInputAdd
-%   it is the structure options_.parallel_info. Currently , only the string in the
-%   field RemoteTmpFolder (the temporary directory created/destroyed on remote
-%   computer) is used.
-
-if ispc, 
-    [tempo, MasterName]=system('hostname');
-    MasterName=deblank(MasterName);
-end
-
-RemoteTmpFolder=DataInputAdd.RemoteTmpFolder;
-dynareParallelMkDir(RemoteTmpFolder,DataInput);
-
-
-% The variable ErrorCode is initialized at 0. If there are non problems with
-% Local, ComputerName connections,... in general with parallel software execution,
-% the ErrorCode is unchanged, in the others cases 1, 2 , ... The values
-% table is below.
-%
-%
-%   Table for ErrorCode Values.
-%
-%   ErrorCode -> 0      Initial Value -> No Error Detected!!!
-%   ErrorCode -> 1 ...  When an error is detected, the values 1, 2, 3... are
-%   used to specify the type of error or warning.
-%
-%   Value 1:    The variable 'Local' has a bad value!
-%
-%   Value 2:    The variable 'CPUnbr' has a bad value. For more information
-%               see http://www.dynare.org/DynareWiki/ParallelDynare.
-%         2.1   [warning] The user asks to use more CPU's than those available.
-%         2.2   [warning] There are unused CPU's!
-%         2.3   [error] NumberOfThreadsPerJob is not a divisor of CPUnbr
-%
-%
-%   Value 3:    The remote computer is unreachable!!!
-%
-%   Value 4:    The fields user name and/or password are/is empty!
-%
-%   Value 5:    Remote Drive and/or Remote Folder do not exist!
-%
-%   Value 6:    It is impossible write/read files on the remote computer.
-%
-%   Value 7:    The values user and/or passwd are incorrect or the user has
-%               no permissions to execute a Matlab session. Or simply
-%               Matlab path (MatlabOctavePath) is incorrect!
-%
-%   Value 8:    Dynare path (DynarePath) is incorrect!
-%
-%   Value 9:    It is impossible delete remote computational temporary files!
-%
-%
-%
-%
-% Currently when errors are detected execution simply stops and users can
-% fix configuration errors according to the error type.
-
-% Copyright (C) 2009-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/>.
-
-
-ErrorCode=0;
-
-
-for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
-    % and use AnalyseComputationalEnvironment with differents input!
-    
-    
-    % Determine the operating system or software version when necessary
-    % for different command types.
-   
-    OScallerUnix=~ispc;
-    OScallerWindows=ispc;
-    OStargetUnix=strcmpi('unix',DataInput(Node).OperatingSystem);
-    if isempty(DataInput(Node).OperatingSystem),
-        OStargetUnix=OScallerUnix;
-    end
-    OStargetWindows=strcmpi('windows',DataInput(Node).OperatingSystem);
-    if isempty(DataInput(Node).OperatingSystem),
-        OStargetWindows=OScallerWindows;
-    end
-    
-    Environment= (OScallerUnix || OStargetUnix);
-    
-    skipline(2)
-    disp(['Testing computer -> ',DataInput(Node).ComputerName,' <- ...']);
-    skipline(2)
-    
-    % The function is composed by two main blocks, determined by the 'Local'
-    % variable.
-    
-    % This check can be removed ... according to the dynare parser
-    % strategy.
-    
-    if ((DataInput(Node).Local == 0) |(DataInput(Node).Local == 1))
-        % Continue it is Ok!
-        disp('Check on Local Variable ..... Ok!');
-        skipline()    
-    else
-        disp('The variable "Local" has a bad value!');
-        skipline()
-        disp('ErrorCode 1.');
-        skipline()
-        ErrorCode=1;
-        return
-    end
-    
-    %         %%%%%%%%%%  Local (No Network) Computing   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-    %         Here only the multi-core, or multi-processor avaiable on local
-    %         machine are involved in parallel computing. No network
-    %         comunications are required!
-    
-    
-    % In this case we need to check only the variable 'CPUnbr'.
-    
-    % We run the parallel code on local computer, so the others fields are automatically
-    % fixed by Dynare parser. Then the user can also fill them with wrong values.
-    
-    
-    %         %%%%%%%%%%  Cluster Computing   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-    %         Here we can have many computer with multi-core, or multi-processor avaiable on the
-    %         network and involved in parallel computing.
-    %         So in this case we need more sophisticated check.
-    
-    
-    if (DataInput(Node).Local == 0)
-        
-        % Now we verify if it is possibile to be connected with the
-        % remote computer.
-        
-        si1=[];
-        de1=[];
-        
-        if Environment
-            if OScallerWindows
-                [si1 de1]=system(['ping ', DataInput(Node).ComputerName]);
-            else
-                [si1 de1]=system(['ping ', DataInput(Node).ComputerName, ' -c 4']);
-            end
-        else
-            [si1 de1]=system(['ping ', DataInput(Node).ComputerName]);
-        end
-        
-        if (si1)
-            disp(['It is impossibile to ping to the computer with name "',DataInput(Node).ComputerName,'" using the network!'])
-            skipline()
-            disp('ErrorCode 3.')
-            ErrorCode=3;
-            skipline(2)
-        else
-            disp('Check on ComputerName Variable ..... Ok!')
-            skipline(2)
-        end
-        
-        
-        % Now we verify if user name and password are correct and if remote
-        % drive and remote folder exist on the remote computer and it is
-        % possible to exchange data with them.
-        
-        if Environment
-            % This check can be removed ... according to the dynare parser
-            % strategy.
-            
-            if (isempty(DataInput(Node).UserName))
-                disp('The fields UserName is empty!')
-                skipline()
-                disp('ErrorCode 4.')
-                skipline(2)
-                ErrorCode=4;
-                return
-            end
-            disp('Check on UserName Variable ..... Ok!')
-            skipline(2)
-            
-            % This check can be removed ... according to the dynare parser
-            % strategy.           
-                if (~isempty(DataInput(Node).Password))
-                    disp('[WARNING] The field Password should be empty under unix or mac!');
-                    skipline()
-                    disp(['Remove the string ',DataInput(Node).Password,' from this field!'])
-                    skipline()
-                    disp('ErrorCode 4.')
-                    skipline(2)
-                    ErrorCode=4;
-                else
-                    disp('Check on Password Variable ..... Ok!')
-                    skipline(2)
-                end
-        else
-            
-            % This check can be removed ... according to the dynare parser
-            % strategy.
-            
-            if (isempty(DataInput(Node).UserName)) || (isempty(DataInput(Node).Password))
-                disp('The fields UserName and/or Password are/is empty!');
-                skipline()
-                disp('ErrorCode 4.')
-                skipline(2)
-                ErrorCode=4;
-                return
-            end
-            disp('Check on UserName Variable ..... Ok!');
-            skipline()
-            disp('Check on Password Variable ..... Ok!');
-            skipline()
-        end
-        
-        % Now we very if RemoteDrive and/or RemoteDirectory exist on remote
-        % computer!
-        
-        if Environment
-            
-            % This check can be removed ... according to the dynare parser
-            % strategy.
-            
-            if  isempty(DataInput(Node).RemoteDirectory)
-                disp('The field RemoteDirectory is empty!')
-                skipline()
-                disp('ErrorCode 5.')
-                skipline()
-                ErrorCode=5;
-                return
-            end
-            
-            % This check can be removed ... according to the dynare parser
-            % strategy.
-            
-                if (~isempty(DataInput(Node).RemoteDrive))
-                    disp('[WARNING] The fields RemoteDrive should be empty under unix or mac!')
-                    skipline()
-                    disp(['remove the string ',DataInput(Node).RemoteDrive,' from this field!'])
-                    skipline()
-                    disp('ErrorCode 5.')
-                    skipline(2)
-                    ErrorCode=5;
-                end
-            
-            si2=[];
-            de2=[];
-            if ~isempty(DataInput(Node).Port),
-                ssh_token = ['-p ',DataInput(Node).Port];
-            else
-                ssh_token = '';
-            end
-            
-            [si2 de2]=system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' ls ',DataInput(Node).RemoteDirectory,'/',RemoteTmpFolder,'/']);
-            
-            if (si2)
-                disp ('Remote Directory does not exist or is not reachable!')
-                skipline()
-                disp('ErrorCode 5.')
-                skipline(2)
-                ErrorCode=5;
-                return
-            end
-            
-            disp('Check on RemoteDirectory Variable ..... Ok!')
-            skipline(2)
-            disp('Check on RemoteDrive Variable ..... Ok!')
-            skipline(2)
-            
-        else
-            % This check can be removed ... according to the dynare parser
-            % strategy.
-            
-            if (isempty(DataInput(Node).RemoteDrive)||isempty(DataInput(Node).RemoteDirectory))
-                disp('Remote RemoteDrive and/or RemoteDirectory is/are empty!')
-                skipline()
-                disp('ErrorCode 5.')
-                skipline(2)
-                ErrorCode=5;
-                return
-            end
-            
-            
-            si2=[];
-            de2=[];
-            [si2 de2]=system(['dir \\',DataInput(Node).ComputerName,'\',DataInput(Node).RemoteDrive,'$\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder]);
-            
-            if (si2)
-                disp ('Remote Directory does not exist or it is not reachable!')
-                skipline()
-                disp('ErrorCode 5.')
-                skipline(2)
-                ErrorCode=5;
-                return
-            end
-            
-            disp('Check on RemoteDirectory Variable ..... Ok!')
-            skipline(2)
-            disp('Check on RemoteDrive Variable ..... Ok!')
-            skipline(2)
-            
-        end
-        
-        
-        % Now we verify if it possible to exchange data with the remote
-        % computer:
-        
-        
-        % Build a command file to test the matlab execution and dynare path ...
-        
-        fid = fopen('Tracing.m', 'w+');
-        s1=(['fT = fopen(''MatlabOctaveIsOk.txt'',''w+'');\n']);
-        s2='fclose(fT);\n';
-        SBS=strfind(DataInput(Node).DynarePath,'\');
-        DPStr=DataInput(Node).DynarePath;
-        if isempty(SBS),
-            DPStrNew=DPStr;
-        else
-            DPStrNew=[DPStr(1:SBS(1)),'\'];
-            for j=2:length(SBS),
-                DPStrNew=[DPStrNew,DPStr(SBS(j-1)+1:SBS(j)),'\'];
-            end
-            DPStrNew=[DPStrNew,DPStr(SBS(end)+1:end)];
-        end
-        s3=['addpath(''',DPStrNew,'''),\n'];
-        s4=['try,\n  dynareroot = dynare_config();\n'];
-        s41=(['  fT = fopen(''DynareIsOk.txt'',''w+'');\n']);
-        s42='  fclose(fT);\n';
-        s5=['catch,\n'];
-        s51=(['  fT = fopen(''DynareFailed.txt'',''w+'');\n']);
-        s52='  fclose(fT);\n';
-        s6=['end,\n'];
-        s7=['if ismac,\n'];
-        s71=(['  fT = fopen(''IsMac.txt'',''w+'');\n']);
-        s72='  fclose(fT);\n';
-        s8=['end,\n'];
-        send='exit';
-        StrCommand=([s1,s2,s3,s4,s41,s42,s5,s51,s52,s6,s7,s71,s72,s8,send]);
-        
-        % Mettere controllo su NbW ...
-        % if isoctave
-        %     NbW = fprintf(fid,StrCommand, '%s');
-        % else
-        NbW = fprintf(fid,StrCommand, '%s');
-        % end
-        fclose(fid);
-        
-        dynareParallelSendFiles('Tracing.m', RemoteTmpFolder,DataInput(Node));
-        FindTracing = dynareParallelDir('Tracing.m', RemoteTmpFolder,DataInput(Node));
-        
-        delete ('Tracing.m');
-        
-        if (isempty(FindTracing))
-            disp('It is impossible to exchange data with Remote Drive and/or Remote Directory! ErrorCode 6.')
-            skipline()
-            disp('ErrorCode 6.')
-            skipline(2)
-            ErrorCode=6;
-            return
-        else
-            disp('Check on Exchange File with Remote Computer ..... Ok!')
-            skipline(2)
-        end
-        
-        
-        % Now we verify if it is possible execute a matlab/octave section on remote
-        % machine when the user is .UserName with password .Password and
-        % the path is MatlabOctavePath.
-        
-        if Environment,
-            if ~isempty(DataInput(Node).Port),
-                ssh_token = ['-p ',DataInput(Node).Port];
-            else
-                ssh_token = '';
-            end
-            if strfind([DataInput(Node).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
-                system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' "cd ',DataInput(Node).RemoteDirectory,'/',RemoteTmpFolder,  '; ', DataInput(Node).MatlabOctavePath, ' Tracing.m;" &']);
-            else
-                system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' "cd ',DataInput(Node).RemoteDirectory,'/',RemoteTmpFolder,  '; ', DataInput(Node).MatlabOctavePath, ' -nosplash -nodesktop -minimize -r Tracing;" &']);
-            end
-        else
-            if ~strcmp(DataInput(Node).ComputerName,MasterName), % run on remote machine
-                if  strfind([DataInput(Node).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
-                    [NonServeS NenServeD]=system(['start /B psexec \\',DataInput(Node).ComputerName,' -e -u ',DataInput(Node).UserName,' -p ',DataInput(Node).Password,' -W ',DataInput(Node).RemoteDrive,':\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder ' -low   ',DataInput(Node).MatlabOctavePath,' Tracing.m']);
-                else
-                    [NonServeS NenServeD]=system(['start /B psexec \\',DataInput(Node).ComputerName,' -e -u ',DataInput(Node).UserName,' -p ',DataInput(Node).Password,' -W ',DataInput(Node).RemoteDrive,':\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder ' -low   ',DataInput(Node).MatlabOctavePath,' -nosplash -nodesktop -minimize -r Tracing']);
-                end
-            else % run on local machine via the network: user and passwd cannot be used!
-                if  strfind([DataInput(Node).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
-                    [NonServeS NenServeD]=system(['start /B psexec \\',DataInput(Node).ComputerName,' -e ',' -W ',DataInput(Node).RemoteDrive,':\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder ' -low   ',DataInput(Node).MatlabOctavePath,' Tracing.m']);
-                else
-                    [NonServeS NenServeD]=system(['start /B psexec \\',DataInput(Node).ComputerName,' -e ',' -W ',DataInput(Node).RemoteDrive,':\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder ' -low   ',DataInput(Node).MatlabOctavePath,' -nosplash -nodesktop -minimize -r Tracing']);
-                end
-            end
-                
-        end
-        
-        % Timer da fissare, nei valori di attesa!
-        
-        t1=fix(clock);
-        
-        if t1(5)+1>60;
-            t2=2;
-        else t2=t1(5)+1;
-        end
-        
-        Flag=0;
-        
-        while (1);
-            if Flag==0
-                disp('Try to run matlab/octave on remote machine ... ')
-                skipline()
-                disp('please wait ... ')
-                skipline()
-                Flag=1;
-            end
-            nt=fix(clock);
-            nt(5)-t2;
-            
-            if (~isempty (dynareParallelDir('MatlabOctaveIsOk.txt',RemoteTmpFolder,DataInput(Node)))) || ((nt(5)-t2)>0)
-                if ((nt(5)-t2)>0)
-                    ErrorCode=7;
-                end
-                break
-            end
-            
-        end
-        
-        if  (ErrorCode==7)
-            
-            disp ('It is not possible execute a matlab session on remote machine!')
-            skipline()
-            disp('ErrorCode 7.')
-            skipline(2)
-            ErrorCode=7;
-            dynareParallelRmDir(RemoteTmpFolder,DataInput(Node));
-            return
-        else
-            disp('Check on MatlabOctave Path and MatlabOctave Program Execution on remote machine ..... Ok!')
-            skipline(2)
-            
-            % Now we verify if the DynarePath is correct ...
-            disp('Check the Dynare path on remote machine ... ')
-            skipline()
-            disp('please wait ... ')
-            skipline(2)
-            pause(2)
-            
-            if isempty(dynareParallelDir('DynareIsOk.txt',RemoteTmpFolder,DataInput(Node)))
-                ErrorCode=8;
-            end
-            
-            if  (ErrorCode==8)
-                disp ('The DynarePath is incorrect!')
-                skipline()
-                disp('ErrorCode 8.')
-                skipline(2)
-                ErrorCode=8;
-                dynareParallelRmDir(RemoteTmpFolder,DataInput(Node));
-                return
-            else
-                disp('Check on Dynare Path remote machine ..... Ok!')
-            if isempty(dynareParallelDir('IsMac.txt',RemoteTmpFolder,DataInput(Node)))
-                RemoteEnvironment=Environment;
-            else
-                RemoteEnvironment=2;                
-            end
-                skipline(2)
-            end
-        end
-        
-        
-        % Now we verify if it is possible delete remote computational traces!
-        
-        dynareParallelRmDir(RemoteTmpFolder,DataInput(Node));
-        
-        si3=[];
-        
-        si3=dynareParallelDir('Tracing.m', RemoteTmpFolder,DataInput(Node));
-        
-        if (isempty(si3))
-            disp ('Check on Delete Remote Computational Traces ..... Ok!')
-            skipline(2)
-        else
-            disp ('It is impossible to delete temporary files on remote machine!')
-            skipline()
-            disp('ErrorCode 9.')
-            skipline(2)
-            ErrorCode=9;
-            return
-        end
-        
-        
-    end
-    % Now we check the variable 'CPUnbr'.
-    
-    % This check can be removed ... according to the dynare parser
-    % strategy.
-    
-    yn=isempty(DataInput(Node).CPUnbr);
-    
-    if yn==1
-        % The field is empty!
-        disp('The field "CPUnbr" is empty!')
-        skipline()
-        disp('ErrorCode 2.')
-        skipline(2)
-        ErrorCode=2;
-        return
-    end
-    
-    % This check can be removed ... according to the dynare parser
-    % strategy.
-    
-    
-    
-    % We look for the information on local computer hardware.
-    
-    si0=[];
-    de0=[];
-    
-    Environment1=Environment;
-    disp('Checking Hardware please wait ...');
-    if (DataInput(Node).Local == 1)
-        if Environment,
-            if ~ismac
-                [si0 de0]=system('grep processor /proc/cpuinfo');
-            else
-                [si0 de0]=system('sysctl -n hw.ncpu');
-                Environment1=2;
-            end
-        else
-            [si0 de0]=system(['psinfo \\']);
-        end
-    else
-        if Environment,
-            if ~isempty(DataInput(Node).Port),
-                ssh_token = ['-p ',DataInput(Node).Port];
-            else
-                ssh_token = '';
-            end
-            if OStargetUnix,
-                if RemoteEnvironment ==1 , 
-                    [si0 de0]=system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' grep processor /proc/cpuinfo']);
-                else % it is MAC
-                    [si0 de0]=system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' sysctl -n hw.ncpu']);
-                    Environment1=2;
-                end
-            else
-                [si0 de0]=system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' psinfo']);
-            end
-        else
-            [si0 de0]=system(['psinfo \\',DataInput(Node).ComputerName,' -u ',DataInput(Node).UserName,' -p ',DataInput(Node).Password]);
-        end
-    end
-    
-    
-    RealCPUnbr='';
-%    keyboard;
-    RealCPUnbr=GiveCPUnumber(de0,Environment1);
-    
-    % Questo controllo penso che si possa MIGLIORARE!!!!!
-    if  isempty (RealCPUnbr) && Environment1==0,
-        [si0 de0]=system(['psinfo \\',DataInput(Node).ComputerName]);
-    end        
-    RealCPUnbr=GiveCPUnumber(de0,Environment1);
-
-    if  isempty (RealCPUnbr)
-        % An error occurred when we try to know the Cpu/Cores
-        % numbers.
-        disp('It is impossible determine the number of Cpu/Processor avaiable on this machine!')
-        skipline()
-        disp('ErrorCode 2.')
-        skipline()
-        if Environment
-            disp('Check the command "$less /proc/cpuinfo" ... !')
-        else
-            disp('Check if the pstools are installed and are in machine path! And check the command "psinfo \\"')
-        end
-        skipline()
-        ErrorCode=2;
-        return
-    end
-    
-    
-    % Trasforming the input data provided in a form [n1:n2] in a single numerical
-    % value.
-    
-    
-    CPUnbrUser=length(DataInput(Node).CPUnbr);
-    maxCPUnbrUser=max(DataInput(Node).CPUnbr)+1;
-    
-    disp(['Hardware has ', num2str(RealCPUnbr),' Cpu/Cores!'])
-    disp(['User requires ',num2str(CPUnbrUser),' Cpu/Cores!'])
-    if  CPUnbrUser==RealCPUnbr,
-        % It is Ok!
-        disp('Check on CPUnbr Variable ..... Ok!')
-        skipline(3)
-    end
-    
-    if CPUnbrUser > RealCPUnbr
-        disp('Warning! The user asks to use more CPU''s than those available.')
-        skipline(2)
-        ErrorCode=2.1;
-    end
-    if CPUnbrUser < RealCPUnbr
-        disp('Warning! There are unused CPU''s!')
-        skipline(2)
-        ErrorCode=2.2;
-    end
-    
-    if mod(length(DataInput(Node).CPUnbr),DataInput(Node).NumberOfThreadsPerJob)
-        skipline()
-        disp(['NumberOfThreadsPerJob = ',int2str(DataInput(Node).NumberOfThreadsPerJob),' is not an exact divisor of number of CPUs = ',int2str(DataInput(Node).CPUnbr),'!'])
-        disp(['    You must re-set properly NumberOfThreadsPerJob of node ' int2str(Node) ' ' DataInput(Node).ComputerName])
-        disp('    in your configuration file')
-        skipline()
-        ErrorCode=2.3;
-    end
-    
-    disp(['Test for Cluster computation, computer ',DataInput(Node).ComputerName, ' ..... Passed!'])
-    skipline(2)    
+function [ErrorCode] = AnalyseComputationalEnvironment(DataInput, DataInputAdd)
+% PARALLEL CONTEXT
+% In a parallel context, this function is used to check the cluster defined by the user.
+% If no error happen the function returns 0. The function complies with
+% Windows/Linux operating systems and Matlab/Octave software.
+%
+%
+% INPUT/OUTPUT description:
+%
+%
+% DataInput
+%   is the strcture option_.parallel, with the follow fields:
+%
+%             Local         1 is on local machine, 0 remote
+%      ComputerName         the computer name.
+%            CPUnbr         the CPU's
+%          UserName         the user name for the ComputerName.
+%          Password         the password for the user name in ComputerName.
+%       RemoteDrive         Drive used for Remote computation (data exchange, etc): must be contain 'RemoteFolder'.
+%   RemoteDirectory         Folder in RemoteDrive used for Remote computation.
+%  MatlabOctavePath         Path to MATLAB or Octave executable.
+%        DynarePath         Path to matlab directory within the Dynare installation directory.
+%
+%   This information is typed by the user in the DYNARE configuration file and is parsed by the preprocessor,
+%   the goal of this function is to check if configuration is correct and if dynare
+%   can be executed successfully in parallel mode.
+%
+%
+% DataInputAdd
+%   it is the structure options_.parallel_info. Currently , only the string in the
+%   field RemoteTmpFolder (the temporary directory created/destroyed on remote
+%   computer) is used.
+
+if ispc
+    [tempo, MasterName]=system('hostname');
+    MasterName=deblank(MasterName);
+end
+
+RemoteTmpFolder=DataInputAdd.RemoteTmpFolder;
+dynareParallelMkDir(RemoteTmpFolder,DataInput);
+
+
+% The variable ErrorCode is initialized at 0. If there are non problems with
+% Local, ComputerName connections,... in general with parallel software execution,
+% the ErrorCode is unchanged, in the others cases 1, 2 , ... The values
+% table is below.
+%
+%
+%   Table for ErrorCode Values.
+%
+%   ErrorCode -> 0      Initial Value -> No Error Detected!!!
+%   ErrorCode -> 1 ...  When an error is detected, the values 1, 2, 3... are
+%   used to specify the type of error or warning.
+%
+%   Value 1:    The variable 'Local' has a bad value!
+%
+%   Value 2:    The variable 'CPUnbr' has a bad value. For more information
+%               see http://www.dynare.org/DynareWiki/ParallelDynare.
+%         2.1   [warning] The user asks to use more CPU's than those available.
+%         2.2   [warning] There are unused CPU's!
+%         2.3   [error] NumberOfThreadsPerJob is not a divisor of CPUnbr
+%
+%
+%   Value 3:    The remote computer is unreachable!!!
+%
+%   Value 4:    The fields user name and/or password are/is empty!
+%
+%   Value 5:    Remote Drive and/or Remote Folder do not exist!
+%
+%   Value 6:    It is impossible write/read files on the remote computer.
+%
+%   Value 7:    The values user and/or passwd are incorrect or the user has
+%               no permissions to execute a Matlab session. Or simply
+%               Matlab path (MatlabOctavePath) is incorrect!
+%
+%   Value 8:    Dynare path (DynarePath) is incorrect!
+%
+%   Value 9:    It is impossible delete remote computational temporary files!
+%
+%
+%
+%
+% Currently when errors are detected execution simply stops and users can
+% fix configuration errors according to the error type.
+
+% Copyright (C) 2009-2017 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/>.
+
+
+ErrorCode=0;
+
+
+for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
+                             % and use AnalyseComputationalEnvironment with differents input!
+
+
+    % Determine the operating system or software version when necessary
+    % for different command types.
+
+    OScallerUnix=~ispc;
+    OScallerWindows=ispc;
+    OStargetUnix=strcmpi('unix',DataInput(Node).OperatingSystem);
+    if isempty(DataInput(Node).OperatingSystem)
+        OStargetUnix=OScallerUnix;
+    end
+    OStargetWindows=strcmpi('windows',DataInput(Node).OperatingSystem);
+    if isempty(DataInput(Node).OperatingSystem)
+        OStargetWindows=OScallerWindows;
+    end
+
+    Environment= (OScallerUnix || OStargetUnix);
+
+    skipline(2)
+    disp(['Testing computer -> ',DataInput(Node).ComputerName,' <- ...']);
+    skipline(2)
+
+    % The function is composed by two main blocks, determined by the 'Local'
+    % variable.
+
+    % This check can be removed ... according to the dynare parser
+    % strategy.
+
+    if ((DataInput(Node).Local == 0) |(DataInput(Node).Local == 1))
+        % Continue it is Ok!
+        disp('Check on Local Variable ..... Ok!');
+        skipline()
+    else
+        disp('The variable "Local" has a bad value!');
+        skipline()
+        disp('ErrorCode 1.');
+        skipline()
+        ErrorCode=1;
+        return
+    end
+
+    %         %%%%%%%%%%  Local (No Network) Computing   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    %         Here only the multi-core, or multi-processor avaiable on local
+    %         machine are involved in parallel computing. No network
+    %         comunications are required!
+
+
+    % In this case we need to check only the variable 'CPUnbr'.
+
+    % We run the parallel code on local computer, so the others fields are automatically
+    % fixed by Dynare parser. Then the user can also fill them with wrong values.
+
+
+    %         %%%%%%%%%%  Cluster Computing   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    %         Here we can have many computer with multi-core, or multi-processor avaiable on the
+    %         network and involved in parallel computing.
+    %         So in this case we need more sophisticated check.
+
+
+    if (DataInput(Node).Local == 0)
+
+        % Now we verify if it is possibile to be connected with the
+        % remote computer.
+
+        si1=[];
+        de1=[];
+
+        if Environment
+            if OScallerWindows
+                [si1 de1]=system(['ping ', DataInput(Node).ComputerName]);
+            else
+                [si1 de1]=system(['ping ', DataInput(Node).ComputerName, ' -c 4']);
+            end
+        else
+            [si1 de1]=system(['ping ', DataInput(Node).ComputerName]);
+        end
+
+        if (si1)
+            disp(['It is impossibile to ping to the computer with name "',DataInput(Node).ComputerName,'" using the network!'])
+            skipline()
+            disp('ErrorCode 3.')
+            ErrorCode=3;
+            skipline(2)
+        else
+            disp('Check on ComputerName Variable ..... Ok!')
+            skipline(2)
+        end
+
+
+        % Now we verify if user name and password are correct and if remote
+        % drive and remote folder exist on the remote computer and it is
+        % possible to exchange data with them.
+
+        if Environment
+            % This check can be removed ... according to the dynare parser
+            % strategy.
+
+            if (isempty(DataInput(Node).UserName))
+                disp('The fields UserName is empty!')
+                skipline()
+                disp('ErrorCode 4.')
+                skipline(2)
+                ErrorCode=4;
+                return
+            end
+            disp('Check on UserName Variable ..... Ok!')
+            skipline(2)
+
+            % This check can be removed ... according to the dynare parser
+            % strategy.
+            if (~isempty(DataInput(Node).Password))
+                disp('[WARNING] The field Password should be empty under unix or mac!');
+                skipline()
+                disp(['Remove the string ',DataInput(Node).Password,' from this field!'])
+                skipline()
+                disp('ErrorCode 4.')
+                skipline(2)
+                ErrorCode=4;
+            else
+                disp('Check on Password Variable ..... Ok!')
+                skipline(2)
+            end
+        else
+
+            % This check can be removed ... according to the dynare parser
+            % strategy.
+
+            if (isempty(DataInput(Node).UserName)) || (isempty(DataInput(Node).Password))
+                disp('The fields UserName and/or Password are/is empty!');
+                skipline()
+                disp('ErrorCode 4.')
+                skipline(2)
+                ErrorCode=4;
+                return
+            end
+            disp('Check on UserName Variable ..... Ok!');
+            skipline()
+            disp('Check on Password Variable ..... Ok!');
+            skipline()
+        end
+
+        % Now we very if RemoteDrive and/or RemoteDirectory exist on remote
+        % computer!
+
+        if Environment
+
+            % This check can be removed ... according to the dynare parser
+            % strategy.
+
+            if  isempty(DataInput(Node).RemoteDirectory)
+                disp('The field RemoteDirectory is empty!')
+                skipline()
+                disp('ErrorCode 5.')
+                skipline()
+                ErrorCode=5;
+                return
+            end
+
+            % This check can be removed ... according to the dynare parser
+            % strategy.
+
+            if (~isempty(DataInput(Node).RemoteDrive))
+                disp('[WARNING] The fields RemoteDrive should be empty under unix or mac!')
+                skipline()
+                disp(['remove the string ',DataInput(Node).RemoteDrive,' from this field!'])
+                skipline()
+                disp('ErrorCode 5.')
+                skipline(2)
+                ErrorCode=5;
+            end
+
+            si2=[];
+            de2=[];
+            if ~isempty(DataInput(Node).Port)
+                ssh_token = ['-p ',DataInput(Node).Port];
+            else
+                ssh_token = '';
+            end
+
+            [si2 de2]=system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' ls ',DataInput(Node).RemoteDirectory,'/',RemoteTmpFolder,'/']);
+
+            if (si2)
+                disp ('Remote Directory does not exist or is not reachable!')
+                skipline()
+                disp('ErrorCode 5.')
+                skipline(2)
+                ErrorCode=5;
+                return
+            end
+
+            disp('Check on RemoteDirectory Variable ..... Ok!')
+            skipline(2)
+            disp('Check on RemoteDrive Variable ..... Ok!')
+            skipline(2)
+
+        else
+            % This check can be removed ... according to the dynare parser
+            % strategy.
+
+            if (isempty(DataInput(Node).RemoteDrive)||isempty(DataInput(Node).RemoteDirectory))
+                disp('Remote RemoteDrive and/or RemoteDirectory is/are empty!')
+                skipline()
+                disp('ErrorCode 5.')
+                skipline(2)
+                ErrorCode=5;
+                return
+            end
+
+
+            si2=[];
+            de2=[];
+            [si2 de2]=system(['dir \\',DataInput(Node).ComputerName,'\',DataInput(Node).RemoteDrive,'$\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder]);
+
+            if (si2)
+                disp ('Remote Directory does not exist or it is not reachable!')
+                skipline()
+                disp('ErrorCode 5.')
+                skipline(2)
+                ErrorCode=5;
+                return
+            end
+
+            disp('Check on RemoteDirectory Variable ..... Ok!')
+            skipline(2)
+            disp('Check on RemoteDrive Variable ..... Ok!')
+            skipline(2)
+
+        end
+
+
+        % Now we verify if it possible to exchange data with the remote
+        % computer:
+
+
+        % Build a command file to test the matlab execution and dynare path ...
+
+        fid = fopen('Tracing.m', 'w+');
+        s1=(['fT = fopen(''MatlabOctaveIsOk.txt'',''w+'');\n']);
+        s2='fclose(fT);\n';
+        SBS=strfind(DataInput(Node).DynarePath,'\');
+        DPStr=DataInput(Node).DynarePath;
+        if isempty(SBS)
+            DPStrNew=DPStr;
+        else
+            DPStrNew=[DPStr(1:SBS(1)),'\'];
+            for j=2:length(SBS)
+                DPStrNew=[DPStrNew,DPStr(SBS(j-1)+1:SBS(j)),'\'];
+            end
+            DPStrNew=[DPStrNew,DPStr(SBS(end)+1:end)];
+        end
+        s3=['addpath(''',DPStrNew,'''),\n'];
+        s4=['try,\n  dynareroot = dynare_config();\n'];
+        s41=(['  fT = fopen(''DynareIsOk.txt'',''w+'');\n']);
+        s42='  fclose(fT);\n';
+        s5=['catch,\n'];
+        s51=(['  fT = fopen(''DynareFailed.txt'',''w+'');\n']);
+        s52='  fclose(fT);\n';
+        s6=['end,\n'];
+        s7=['if ismac,\n'];
+        s71=(['  fT = fopen(''IsMac.txt'',''w+'');\n']);
+        s72='  fclose(fT);\n';
+        s8=['end,\n'];
+        send='exit';
+        StrCommand=([s1,s2,s3,s4,s41,s42,s5,s51,s52,s6,s7,s71,s72,s8,send]);
+
+        % Mettere controllo su NbW ...
+        % if isoctave
+        %     NbW = fprintf(fid,StrCommand, '%s');
+        % else
+        NbW = fprintf(fid,StrCommand, '%s');
+        % end
+        fclose(fid);
+
+        dynareParallelSendFiles('Tracing.m', RemoteTmpFolder,DataInput(Node));
+        FindTracing = dynareParallelDir('Tracing.m', RemoteTmpFolder,DataInput(Node));
+
+        delete ('Tracing.m');
+
+        if (isempty(FindTracing))
+            disp('It is impossible to exchange data with Remote Drive and/or Remote Directory! ErrorCode 6.')
+            skipline()
+            disp('ErrorCode 6.')
+            skipline(2)
+            ErrorCode=6;
+            return
+        else
+            disp('Check on Exchange File with Remote Computer ..... Ok!')
+            skipline(2)
+        end
+
+
+        % Now we verify if it is possible execute a matlab/octave section on remote
+        % machine when the user is .UserName with password .Password and
+        % the path is MatlabOctavePath.
+
+        if Environment
+            if ~isempty(DataInput(Node).Port)
+                ssh_token = ['-p ',DataInput(Node).Port];
+            else
+                ssh_token = '';
+            end
+            if strfind([DataInput(Node).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
+                system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' "cd ',DataInput(Node).RemoteDirectory,'/',RemoteTmpFolder,  '; ', DataInput(Node).MatlabOctavePath, ' Tracing.m;" &']);
+            else
+                system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' "cd ',DataInput(Node).RemoteDirectory,'/',RemoteTmpFolder,  '; ', DataInput(Node).MatlabOctavePath, ' -nosplash -nodesktop -minimize -r Tracing;" &']);
+            end
+        else
+            if ~strcmp(DataInput(Node).ComputerName,MasterName) % run on remote machine
+                if  strfind([DataInput(Node).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
+                    [NonServeS NenServeD]=system(['start /B psexec \\',DataInput(Node).ComputerName,' -e -u ',DataInput(Node).UserName,' -p ',DataInput(Node).Password,' -W ',DataInput(Node).RemoteDrive,':\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder ' -low   ',DataInput(Node).MatlabOctavePath,' Tracing.m']);
+                else
+                    [NonServeS NenServeD]=system(['start /B psexec \\',DataInput(Node).ComputerName,' -e -u ',DataInput(Node).UserName,' -p ',DataInput(Node).Password,' -W ',DataInput(Node).RemoteDrive,':\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder ' -low   ',DataInput(Node).MatlabOctavePath,' -nosplash -nodesktop -minimize -r Tracing']);
+                end
+            else % run on local machine via the network: user and passwd cannot be used!
+                if  strfind([DataInput(Node).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
+                    [NonServeS NenServeD]=system(['start /B psexec \\',DataInput(Node).ComputerName,' -e ',' -W ',DataInput(Node).RemoteDrive,':\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder ' -low   ',DataInput(Node).MatlabOctavePath,' Tracing.m']);
+                else
+                    [NonServeS NenServeD]=system(['start /B psexec \\',DataInput(Node).ComputerName,' -e ',' -W ',DataInput(Node).RemoteDrive,':\',DataInput(Node).RemoteDirectory,'\',RemoteTmpFolder ' -low   ',DataInput(Node).MatlabOctavePath,' -nosplash -nodesktop -minimize -r Tracing']);
+                end
+            end
+
+        end
+
+        % Timer da fissare, nei valori di attesa!
+
+        t1=fix(clock);
+
+        if t1(5)+1>60
+            t2=2;
+        else
+            t2=t1(5)+1;
+        end
+
+        Flag=0;
+
+        while (1)
+            if Flag==0
+                disp('Try to run matlab/octave on remote machine ... ')
+                skipline()
+                disp('please wait ... ')
+                skipline()
+                Flag=1;
+            end
+            nt=fix(clock);
+            nt(5)-t2;
+
+            if (~isempty (dynareParallelDir('MatlabOctaveIsOk.txt',RemoteTmpFolder,DataInput(Node)))) || ((nt(5)-t2)>0)
+                if ((nt(5)-t2)>0)
+                    ErrorCode=7;
+                end
+                break
+            end
+
+        end
+
+        if  (ErrorCode==7)
+
+            disp ('It is not possible execute a matlab session on remote machine!')
+            skipline()
+            disp('ErrorCode 7.')
+            skipline(2)
+            ErrorCode=7;
+            dynareParallelRmDir(RemoteTmpFolder,DataInput(Node));
+            return
+        else
+            disp('Check on MatlabOctave Path and MatlabOctave Program Execution on remote machine ..... Ok!')
+            skipline(2)
+
+            % Now we verify if the DynarePath is correct ...
+            disp('Check the Dynare path on remote machine ... ')
+            skipline()
+            disp('please wait ... ')
+            skipline(2)
+            pause(2)
+
+            if isempty(dynareParallelDir('DynareIsOk.txt',RemoteTmpFolder,DataInput(Node)))
+                ErrorCode=8;
+            end
+
+            if  (ErrorCode==8)
+                disp ('The DynarePath is incorrect!')
+                skipline()
+                disp('ErrorCode 8.')
+                skipline(2)
+                ErrorCode=8;
+                dynareParallelRmDir(RemoteTmpFolder,DataInput(Node));
+                return
+            else
+                disp('Check on Dynare Path remote machine ..... Ok!')
+                if isempty(dynareParallelDir('IsMac.txt',RemoteTmpFolder,DataInput(Node)))
+                    RemoteEnvironment=Environment;
+                else
+                    RemoteEnvironment=2;
+                end
+                skipline(2)
+            end
+        end
+
+
+        % Now we verify if it is possible delete remote computational traces!
+
+        dynareParallelRmDir(RemoteTmpFolder,DataInput(Node));
+
+        si3=[];
+
+        si3=dynareParallelDir('Tracing.m', RemoteTmpFolder,DataInput(Node));
+
+        if (isempty(si3))
+            disp ('Check on Delete Remote Computational Traces ..... Ok!')
+            skipline(2)
+        else
+            disp ('It is impossible to delete temporary files on remote machine!')
+            skipline()
+            disp('ErrorCode 9.')
+            skipline(2)
+            ErrorCode=9;
+            return
+        end
+
+
+    end
+    % Now we check the variable 'CPUnbr'.
+
+    % This check can be removed ... according to the dynare parser
+    % strategy.
+
+    yn=isempty(DataInput(Node).CPUnbr);
+
+    if yn==1
+        % The field is empty!
+        disp('The field "CPUnbr" is empty!')
+        skipline()
+        disp('ErrorCode 2.')
+        skipline(2)
+        ErrorCode=2;
+        return
+    end
+
+    % This check can be removed ... according to the dynare parser
+    % strategy.
+
+
+
+    % We look for the information on local computer hardware.
+
+    si0=[];
+    de0=[];
+
+    Environment1=Environment;
+    disp('Checking Hardware please wait ...');
+    if (DataInput(Node).Local == 1)
+        if Environment
+            if ~ismac
+                [si0 de0]=system('grep processor /proc/cpuinfo');
+            else
+                [si0 de0]=system('sysctl -n hw.ncpu');
+                Environment1=2;
+            end
+        else
+            [si0 de0]=system(['psinfo \\']);
+        end
+    else
+        if Environment
+            if ~isempty(DataInput(Node).Port)
+                ssh_token = ['-p ',DataInput(Node).Port];
+            else
+                ssh_token = '';
+            end
+            if OStargetUnix
+                if RemoteEnvironment ==1
+                    [si0 de0]=system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' grep processor /proc/cpuinfo']);
+                else % it is MAC
+                    [si0 de0]=system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' sysctl -n hw.ncpu']);
+                    Environment1=2;
+                end
+            else
+                [si0 de0]=system(['ssh ',ssh_token,' ',DataInput(Node).UserName,'@',DataInput(Node).ComputerName,' psinfo']);
+            end
+        else
+            [si0 de0]=system(['psinfo \\',DataInput(Node).ComputerName,' -u ',DataInput(Node).UserName,' -p ',DataInput(Node).Password]);
+        end
+    end
+
+
+    RealCPUnbr='';
+    %    keyboard;
+    RealCPUnbr=GiveCPUnumber(de0,Environment1);
+
+    % Questo controllo penso che si possa MIGLIORARE!!!!!
+    if  isempty (RealCPUnbr) && Environment1==0
+        [si0 de0]=system(['psinfo \\',DataInput(Node).ComputerName]);
+    end
+    RealCPUnbr=GiveCPUnumber(de0,Environment1);
+
+    if  isempty (RealCPUnbr)
+        % An error occurred when we try to know the Cpu/Cores
+        % numbers.
+        disp('It is impossible determine the number of Cpu/Processor avaiable on this machine!')
+        skipline()
+        disp('ErrorCode 2.')
+        skipline()
+        if Environment
+            disp('Check the command "$less /proc/cpuinfo" ... !')
+        else
+            disp('Check if the pstools are installed and are in machine path! And check the command "psinfo \\"')
+        end
+        skipline()
+        ErrorCode=2;
+        return
+    end
+
+
+    % Trasforming the input data provided in a form [n1:n2] in a single numerical
+    % value.
+
+
+    CPUnbrUser=length(DataInput(Node).CPUnbr);
+    maxCPUnbrUser=max(DataInput(Node).CPUnbr)+1;
+
+    disp(['Hardware has ', num2str(RealCPUnbr),' Cpu/Cores!'])
+    disp(['User requires ',num2str(CPUnbrUser),' Cpu/Cores!'])
+    if  CPUnbrUser==RealCPUnbr
+        % It is Ok!
+        disp('Check on CPUnbr Variable ..... Ok!')
+        skipline(3)
+    end
+
+    if CPUnbrUser > RealCPUnbr
+        disp('Warning! The user asks to use more CPU''s than those available.')
+        skipline(2)
+        ErrorCode=2.1;
+    end
+    if CPUnbrUser < RealCPUnbr
+        disp('Warning! There are unused CPU''s!')
+        skipline(2)
+        ErrorCode=2.2;
+    end
+
+    if mod(length(DataInput(Node).CPUnbr),DataInput(Node).NumberOfThreadsPerJob)
+        skipline()
+        disp(['NumberOfThreadsPerJob = ',int2str(DataInput(Node).NumberOfThreadsPerJob),' is not an exact divisor of number of CPUs = ',int2str(DataInput(Node).CPUnbr),'!'])
+        disp(['    You must re-set properly NumberOfThreadsPerJob of node ' int2str(Node) ' ' DataInput(Node).ComputerName])
+        disp('    in your configuration file')
+        skipline()
+        ErrorCode=2.3;
+    end
+
+    disp(['Test for Cluster computation, computer ',DataInput(Node).ComputerName, ' ..... Passed!'])
+    skipline(2)
 end
\ No newline at end of file
diff --git a/matlab/parallel/CreateTimeString.m b/matlab/parallel/CreateTimeString.m
index 8b82b1cc6d0e5c7681fdcb3006ac34bc5f45cc50..e78f8836aeb6ebf353eb625e815029175a86d662 100644
--- a/matlab/parallel/CreateTimeString.m
+++ b/matlab/parallel/CreateTimeString.m
@@ -6,9 +6,9 @@ function [TiSt] = CreateTimeString()
 % None
 %
 %  OUTPUTS
-%  o TiSt    []   ...  
+%  o TiSt    []   ...
 %
-% Copyright (C) 2009-2010 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/parallel/GiveCPUnumber.m b/matlab/parallel/GiveCPUnumber.m
index 00b7fc451b5dc9327865ae2df934c18289dcf027..cc2d45aa38e3674b234239e9d1f93a1edd65ef49 100644
--- a/matlab/parallel/GiveCPUnumber.m
+++ b/matlab/parallel/GiveCPUnumber.m
@@ -1,76 +1,76 @@
-function [nCPU]= GiveCPUnumber (ComputerInformations, Environment)
-% PARALLEL CONTEXT
-% In a parallel context this function return the CPUs or cores numer avaiable
-% on the computer used for run parallel code.
-%
-% INPUTS
-% an array contained several fields that describe the hardaware
-% software enviroments of a generic computer.
-%
-% OUTPUTS
-% The CPUs or Cores numbers of computer.
-%
-% SPECIAL REQUIREMENTS
-% none
-
-% Copyright (C) 2010-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/>.
-
-
-nCPU='';
-
-if nargin < 2,
-% Determine a specific operating system or software version when necessary
-% for different command (sintax, name, ...).
-Environment=~ispc;
-end
-
-switch Environment
-  case 0          %WINDOWS OPERATING SYSTEM
-    
-    OffSet=27;
-
-    SringPosition=strfind(ComputerInformations, 'Processors:');
-    nCPU=ComputerInformations(SringPosition+OffSet);
-
-    % We check if there are Processors/Cores more than 9.
-
-
-    t0=ComputerInformations(SringPosition+OffSet+1);
-    t1=str2num(t0);
-    t1=isempty(t1);
-
-    % if t1 is 0 the machine have more than 9 CPU.
-
-    if t1==0
-        nCPU=strcat(nCPU,t0);
-    end
-
-    nCPU=str2num(nCPU);
-
-    return
-  case 1            %LIKE UNIX OPERATING SYSTEM
-    
-    % Da generalizzare a un numero di CPu maggiore di 9!!!
-
-    nCPU=str2num(ComputerInformations(length(ComputerInformations)-1))+1;
-
-  case 2            %MAC-OS OPERATING SYSTEM
-
-    nCPU=str2num(ComputerInformations);
-
-end
+function [nCPU]= GiveCPUnumber (ComputerInformations, Environment)
+% PARALLEL CONTEXT
+% In a parallel context this function return the CPUs or cores numer avaiable
+% on the computer used for run parallel code.
+%
+% INPUTS
+% an array contained several fields that describe the hardaware
+% software enviroments of a generic computer.
+%
+% OUTPUTS
+% The CPUs or Cores numbers of computer.
+%
+% SPECIAL REQUIREMENTS
+% none
+
+% Copyright (C) 2010-2017 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/>.
+
+
+nCPU='';
+
+if nargin < 2
+    % Determine a specific operating system or software version when necessary
+    % for different command (sintax, name, ...).
+    Environment=~ispc;
+end
+
+switch Environment
+  case 0          %WINDOWS OPERATING SYSTEM
+
+    OffSet=27;
+
+    SringPosition=strfind(ComputerInformations, 'Processors:');
+    nCPU=ComputerInformations(SringPosition+OffSet);
+
+    % We check if there are Processors/Cores more than 9.
+
+
+    t0=ComputerInformations(SringPosition+OffSet+1);
+    t1=str2num(t0);
+    t1=isempty(t1);
+
+    % if t1 is 0 the machine have more than 9 CPU.
+
+    if t1==0
+        nCPU=strcat(nCPU,t0);
+    end
+
+    nCPU=str2num(nCPU);
+
+    return
+  case 1            %LIKE UNIX OPERATING SYSTEM
+
+    % Da generalizzare a un numero di CPu maggiore di 9!!!
+
+    nCPU=str2num(ComputerInformations(length(ComputerInformations)-1))+1;
+
+  case 2            %MAC-OS OPERATING SYSTEM
+
+    nCPU=str2num(ComputerInformations);
+
+end
diff --git a/matlab/parallel/InitializeComputationalEnvironment.m b/matlab/parallel/InitializeComputationalEnvironment.m
index 02df7aad432c08f154ef490c287b1fcf35cb4f61..18ce19f113331bfb87e7e5c325c8b331685e6db9 100644
--- a/matlab/parallel/InitializeComputationalEnvironment.m
+++ b/matlab/parallel/InitializeComputationalEnvironment.m
@@ -10,7 +10,7 @@ function InitializeComputationalEnvironment()
 % OUTPUTS
 % None
 %
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -37,7 +37,7 @@ function InitializeComputationalEnvironment()
 % Comment the line 'warning('off');' in order to view the warning message
 % in Octave!
 
-if isoctave 
+if isoctave
     warning('off');
 end
 
@@ -46,15 +46,15 @@ end
 global options_
 
 isHybridMatlabOctave = false;
-for j=1:length(options_.parallel),
-    if isempty(options_.parallel(j).MatlabOctavePath),
+for j=1:length(options_.parallel)
+    if isempty(options_.parallel(j).MatlabOctavePath)
         if isoctave
             options_.parallel(j).MatlabOctavePath = 'octave';
         else
             options_.parallel(j).MatlabOctavePath = 'matlab';
         end
     end
-    if options_.parallel(j).Local && isempty(options_.parallel(j).DynarePath),
+    if options_.parallel(j).Local && isempty(options_.parallel(j).DynarePath)
         dynareroot = strrep(which('dynare'),'dynare.m','');
         options_.parallel(j).DynarePath=dynareroot;
     end
@@ -62,7 +62,7 @@ for j=1:length(options_.parallel),
 end
 isHybridMatlabOctave = isHybridMatlabOctave && ~isoctave;
 options_.parallel_info.isHybridMatlabOctave = isHybridMatlabOctave;
-if isHybridMatlabOctave,
+if isHybridMatlabOctave
     % Reset dynare random generator and seed.
     set_dynare_seed('default');
 end
@@ -94,7 +94,7 @@ CPUWeightTemp=ones(1,lP)*(-1);
 CPUWeightTemp=CPUWeight;
 
 for i=1:lP
-    [NoNServes mP]=max(CPUWeightTemp);
+    [NoNServes, mP]=max(CPUWeightTemp);
     NewPosition(i)=mP;
     CPUWeightTemp(mP)=-1;
 end
diff --git a/matlab/parallel/closeSlave.m b/matlab/parallel/closeSlave.m
index 339d776bb2f4a8a07cc239f0804893867e35504f..49c14deb3eac395502e8979b8e87b1275f7d12bc 100644
--- a/matlab/parallel/closeSlave.m
+++ b/matlab/parallel/closeSlave.m
@@ -1,4 +1,4 @@
-function closeSlave(Parallel,TmpFolder,partial),
+function closeSlave(Parallel,TmpFolder,partial)
 % PARALLEL CONTEXT
 % In parallel context, this utility closes all remote matlab instances
 % called by masterParallel when strategy (1) is active i.e. always open (which leaves
@@ -10,12 +10,12 @@ function closeSlave(Parallel,TmpFolder,partial),
 %                               This directory is named using current date
 %                               and is used only one time and then deleted.
 %                               If islocal==1, TmpFolder=''.
-% 
+%
 %
 % OUTPUTS
 %   None
 %
-% Copyright (C) 2010-2013 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -32,7 +32,7 @@ function closeSlave(Parallel,TmpFolder,partial),
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-if nargin<3,
+if nargin<3
     partial=0;
 end
 
@@ -40,50 +40,49 @@ s=warning('off');
 
 if partial==1
     save('slaveParallel_break.mat','partial')
-    for indPC=1:length(Parallel),
-        if (Parallel(indPC).Local==0),
+    for indPC=1:length(Parallel)
+        if (Parallel(indPC).Local==0)
             dynareParallelSendFiles('slaveParallel_break.mat',TmpFolder,Parallel(indPC));
         end
     end
-%     delete('slaveParallel_break')
+    %     delete('slaveParallel_break')
     return
 end
 if partial==-1
     delete('slaveParallel_break.mat')
-    for indPC=1:length(Parallel),
-        if (Parallel(indPC).Local==0),
+    for indPC=1:length(Parallel)
+        if (Parallel(indPC).Local==0)
             dynareParallelDelete( 'slaveParallel_break.mat',TmpFolder,Parallel(indPC));
         end
     end
-%     delete('slaveParallel_break')
+    %     delete('slaveParallel_break')
     return
 end
 
-for indPC=1:length(Parallel),
-    if (Parallel(indPC).Local==0),
+for indPC=1:length(Parallel)
+    if (Parallel(indPC).Local==0)
         dynareParallelDelete( 'slaveParallel_input*.mat',TmpFolder,Parallel(indPC));
     end
-    
-   
+
+
     delete( 'slaveParallel_input*.mat');
     delete( 'slaveJob*.mat');
     pause(1)
     delete(['slaveParallel_*.log']);
     delete ConcurrentCommand1.bat;
-    
+
 end
 
 while(1)
-    if isempty(dynareParallelDir(['P_slave_',int2str(j),'End.txt'],TmpFolder,Parallel));
-        for indPC=1:length(Parallel),
-            if (Parallel(indPC).Local==0),
-                dynareParallelRmDir(TmpFolder,Parallel(indPC)),
+    if isempty(dynareParallelDir(['P_slave_',int2str(j),'End.txt'],TmpFolder,Parallel))
+        for indPC=1:length(Parallel)
+            if (Parallel(indPC).Local==0)
+                dynareParallelRmDir(TmpFolder,Parallel(indPC))
             end
         end
         break
-        
+
     end
 end
 
-s=warning('on');
- 
+s=warning('on');
\ No newline at end of file
diff --git a/matlab/parallel/distributeJobs.m b/matlab/parallel/distributeJobs.m
index 0667d902f76240812504435977f3b4abce0897d9..c0c41925f7db2b3b96005d8741d81799ecbcdb89 100644
--- a/matlab/parallel/distributeJobs.m
+++ b/matlab/parallel/distributeJobs.m
@@ -21,7 +21,7 @@ function [nCPU, totCPU, nBlockPerCPU, totSLAVES] = distributeJobs(Parallel, fBlo
 %                               It is a number between 1 and length(Parallel).
 
 
-% Copyright (C) 2010-2011 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -40,7 +40,7 @@ function [nCPU, totCPU, nBlockPerCPU, totSLAVES] = distributeJobs(Parallel, fBlo
 
 
 % The Parallel vector has already been sorted
-% (in accord with the CPUWeight values) in DESCENDING order in 
+% (in accord with the CPUWeight values) in DESCENDING order in
 % InitializeComputationalEnvironment!
 
 totCPU=0;
@@ -48,7 +48,7 @@ totCPU=0;
 lP=length(Parallel);
 CPUWeight=ones(1,length(Parallel))*(-1);
 
-for j=1:lP,    
+for j=1:lP
     if mod(length(Parallel(j).CPUnbr),Parallel(j).NumberOfThreadsPerJob)
         skipline()
         disp(['PARALLEL_ERROR:: NumberOfThreadsPerJob = ',int2str(Parallel(j).NumberOfThreadsPerJob),' is not an exact divisor of number of CPUs = ',int2str(length(Parallel(j).CPUnbr)),'!'])
@@ -57,7 +57,7 @@ for j=1:lP,
         error(['PARALLEL_ERROR:: NumberOfThreadsPerJob is not an exact divisor of CPUnbr'])
     end
     nCPU(j)=length(Parallel(j).CPUnbr)/Parallel(j).NumberOfThreadsPerJob;
-    totCPU=totCPU+nCPU(j);    
+    totCPU=totCPU+nCPU(j);
     CPUWeight(j)=str2num(Parallel(j).NodeWeight);
 end
 
@@ -77,7 +77,7 @@ NumbersOfJobs=nBlock-fBlock+1;
 SumOfJobs=0;
 JobsForNode=zeros(1,nC);
 
-for j=1:lP,
+for j=1:lP
     CPUWeight(j)=str2num(Parallel(j).NodeWeight)*nCPUoriginal(j);
 end
 CPUWeight=CPUWeight./sum(CPUWeight);
@@ -85,15 +85,15 @@ CPUWeight=CPUWeight./sum(CPUWeight);
 % Redistributing the jobs among the cluster nodes according to the
 % CPUWeight.
 for i=1:nC
-    
+
     JobsForNode(i)=CPUWeight(i)*NumbersOfJobs;
-    
+
     % Many choices are possible:
-    
+
     % JobsForNode(i)=round(JobsForNode(i));
     % JobsForNode(i)=floor(JobsForNode(i));
-      JobsForNode(i)=ceil(JobsForNode(i));
-    
+    JobsForNode(i)=ceil(JobsForNode(i));
+
 end
 
 % Check if there are more (fewer) jobs.
@@ -101,19 +101,19 @@ end
 SumOfJobs=sum(JobsForNode);
 
 if SumOfJobs~=NumbersOfJobs
-    
+
     if SumOfJobs>NumbersOfJobs
-        
+
         % Many choices are possible:
-        
+
         % - Remove the excess works at the node that has the greatest
         %   number of jobs.
         % - Remove the excess works at the node slower.
-        
+
         VerySlow=nC;
-        
+
         while SumOfJobs>NumbersOfJobs
-            
+
             if JobsForNode(VerySlow)==0
                 VerySlow=VerySlow-1;
                 continue
@@ -121,21 +121,21 @@ if SumOfJobs~=NumbersOfJobs
             JobsForNode(VerySlow)=JobsForNode(VerySlow)-1;
             SumOfJobs=SumOfJobs-1;
         end
-        
+
     end
-    
+
     if SumOfJobs<NumbersOfJobs
-        
+
         % Many choices are possible:
         % - ... (see above).
-        
+
         [NonServe VeryFast]= min(CPUWeight);
-        
+
         while SumOfJobs<NumbersOfJobs
             JobsForNode(VeryFast)=JobsForNode(VeryFast)+1;
             SumOfJobs=SumOfJobs+1;
         end
-        
+
     end
 end
 
@@ -148,36 +148,36 @@ JobAssignedCpu=0;
 RelativePosition=1;
 
 for i=1:nC
-    
+
     % Many choices are possible:
     % - ... (see above).
-     
+
     JobAssignedCpu=max(1,floor(JobsForNode(i)/nCPUoriginal(i)));
-    
+
     ChekOverFlow=0;
-    
+
     for j=RelativePosition:nCPU(i)
         JobsForCpu(j)=JobAssignedCpu;
         ChekOverFlow=ChekOverFlow+JobAssignedCpu;
-        
+
         if ChekOverFlow>=JobsForNode(i)
-            break;
+            break
         end
-        
+
     end
-    
+
     % Check if there are more (fewer) jobs.
     % This can happen when we use ceil, round, ... functions.
-    
+
     if ChekOverFlow ~=(JobsForNode(i))
-        
+
         if ChekOverFlow >(JobsForNode(i))
             while ChekOverFlow>JobsForNode(i)
                 JobsForCpu(nCPU(i))=JobsForCpu(nCPU(i))-1;
                 ChekOverFlow=ChekOverFlow-1;
             end
         end
-        
+
         if ChekOverFlow <(JobsForNode(i))
             while ChekOverFlow<JobsForNode(i)
                 JobsForCpu(nCPU(i))=JobsForCpu(nCPU(i))+1;
@@ -185,9 +185,9 @@ for i=1:nC
             end
         end
     end
-    
+
     RelativePosition=nCPU(i)+1;
-    
+
 end
 
 % Reshape the variables totCPU,totSLAVES and nBlockPerCPU in accord with
@@ -204,7 +204,7 @@ for i=1:nCPU(nC)
 end
 
 for i=1:nC
-    if JobsForNode(i)~=0;
+    if JobsForNode(i)~=0
         totSLAVES=totSLAVES+1;
     end
 end
@@ -216,5 +216,3 @@ for i=1:nCPU(nC)
         RelativeCounter=RelativeCounter+1;
     end
 end
-
-
diff --git a/matlab/parallel/dynareParallelDelete.m b/matlab/parallel/dynareParallelDelete.m
index 060a35f13f33e83be31dc9a4374eecb3d4db5a56..478b8c8e46ba30db186b75a523066feeff20329b 100644
--- a/matlab/parallel/dynareParallelDelete.m
+++ b/matlab/parallel/dynareParallelDelete.m
@@ -4,14 +4,14 @@ function dynareParallelDelete(fname,pname,Parallel)
 %
 % INPUTS
 %  o fname      []   ...
-%  o pname      []   ... 
-%  o Parallel   []   ...  
+%  o pname      []   ...
+%  o Parallel   []   ...
 %
 %  OUTPUTS
 %  None
 %
 %
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -28,20 +28,20 @@ function dynareParallelDelete(fname,pname,Parallel)
 % 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 ==0,
+if nargin ==0
     disp('dynareParallelDelete(fname)')
     return
 end
 
-if nargin ==1,
+if nargin ==1
     pname='';
 else
     pname=[pname,filesep];
 end
 
-for indPC=1:length(Parallel),
-    if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem),
-        if ~isempty(Parallel(indPC).Port),
+for indPC=1:length(Parallel)
+    if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)
+        if ~isempty(Parallel(indPC).Port)
             ssh_token = ['-p ',Parallel(indPC).Port];
         else
             ssh_token = '';
@@ -53,5 +53,5 @@ for indPC=1:length(Parallel),
             delete(fname_temp);
         end
     end
-    
+
 end
diff --git a/matlab/parallel/dynareParallelDeleteNewFiles.m b/matlab/parallel/dynareParallelDeleteNewFiles.m
index e28cd77da7b5ccd209e32b73bcf349da579658bf..34fdab44be274f5434a34401ca4c8fe42196c6df 100644
--- a/matlab/parallel/dynareParallelDeleteNewFiles.m
+++ b/matlab/parallel/dynareParallelDeleteNewFiles.m
@@ -15,7 +15,7 @@ function dynareParallelDeleteNewFiles(PRCDir,Parallel,PRCDirSnapshot,varargin)
 %
 %
 %
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -35,11 +35,11 @@ function dynareParallelDeleteNewFiles(PRCDir,Parallel,PRCDirSnapshot,varargin)
 NewFilesFromSlaves={};
 
 % try
-for indPC=1:length(Parallel),
-    
-    if Parallel(indPC).Local==0;
+for indPC=1:length(Parallel)
+
+    if Parallel(indPC).Local==0
         [NewFilesFromSlaves, PRCDirSnapshot{indPC}]=dynareParallelFindNewFiles(PRCDirSnapshot{indPC},Parallel(indPC), PRCDir);
-        if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem),
+        if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)
             fS='/';
         else
             fS='\';
@@ -59,12 +59,12 @@ for indPC=1:length(Parallel),
                 for indexc=1:length(varargin)
                     exception_flag=exception_flag+(~isempty(strfind(fileaddress{2},varargin{indexc})));
                 end
-                if exception_flag==0,
-                dynareParallelDelete(fileaddress{2},[PRCDir,fS,fileaddress{1}],Parallel(indPC));
+                if exception_flag==0
+                    dynareParallelDelete(fileaddress{2},[PRCDir,fS,fileaddress{1}],Parallel(indPC));
 
-                disp('New file deleted in remote -->');
-                disp(fileaddress{2});
-                disp('<--');
+                    disp('New file deleted in remote -->');
+                    disp(fileaddress{2});
+                    disp('<--');
                 end
 
             end
@@ -75,6 +75,3 @@ for indPC=1:length(Parallel),
 
     end
 end
-
-
-
diff --git a/matlab/parallel/dynareParallelDir.m b/matlab/parallel/dynareParallelDir.m
index daecfe6cd49707b955f7fc1d25ca55987d4d3423..0625dd8e7b97b7588fb3e16f1c444ae8a44e870d 100644
--- a/matlab/parallel/dynareParallelDir.m
+++ b/matlab/parallel/dynareParallelDir.m
@@ -10,7 +10,7 @@ function dirlist = dynareParallelDir(filename,PRCDir,Parallel)
 %  OUTPUTS
 %  o dirlist    []   ...
 %
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -28,24 +28,24 @@ function dirlist = dynareParallelDir(filename,PRCDir,Parallel)
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 dirlist=[];
-for indPC=1:length(Parallel),
-    if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem),
-        if Parallel(indPC).Local==0,
-            if ~isempty(Parallel(indPC).Port),
+for indPC=1:length(Parallel)
+    if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)
+        if Parallel(indPC).Local==0
+            if ~isempty(Parallel(indPC).Port)
                 ssh_token = ['-p ',Parallel(indPC).Port];
             else
                 ssh_token = '';
             end
             if isoctave % Patch for peculiar behaviour of ssh-ls under Linux.
-                % It is necessary to capture the ls warning message.
-                % To do it under the ssh protocol it is necessary to redirect the ls message in a text file.
-                % The file is 'OctaveStandardOutputMessage.txt' and it is
-                % saved in the Model directory.
+                        % It is necessary to capture the ls warning message.
+                        % To do it under the ssh protocol it is necessary to redirect the ls message in a text file.
+                        % The file is 'OctaveStandardOutputMessage.txt' and it is
+                        % saved in the Model directory.
                 [check, ax]=system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' ls ',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',filename, ' 2> OctaveStandardOutputMessage.txt']);
             else
                 [check, ax]=system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' ls ',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',filename]);
             end
-            if check ~= 0 || ~isempty(strfind(ax,'No such file or directory'));
+            if check ~= 0 || ~isempty(strfind(ax,'No such file or directory'))
                 ax=[];
             else
                 indax=regexp(ax,'\n');
@@ -57,11 +57,11 @@ for indPC=1:length(Parallel),
         else
 
             if isoctave % Patch for peculiar behaviour of ls under Linux.
-                
+
                 % It is necessary to capture the ls warning message and properly manage the jolly char '*'!
                 [check ax]=system(['ls ' ,filename, ' 2> OctaveStandardOutputMessage.txt']);
-                
-                if check ~= 0 || ~isempty(strfind(ax,'No such file or directory'));
+
+                if check ~= 0 || ~isempty(strfind(ax,'No such file or directory'))
                     ax=[];
                 end
             else
@@ -75,32 +75,32 @@ for indPC=1:length(Parallel),
         end
     else
         if isoctave     % Patch for peculiar behaviour of ls under Windows.
-            if Parallel(indPC).Local==0,
+            if Parallel(indPC).Local==0
                 ax0=dir(['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',filename]);
             else
                 ax0=dir(filename);
             end
-            if isempty(ax0),
+            if isempty(ax0)
                 ax='';
             else
                 clear ax1;
-                for jax=1:length(ax0);
+                for jax=1:length(ax0)
                     ax1{jax}=ax0(jax).name;
                 end
                 ax=char(ax1{:});
             end
 
         else
-            if Parallel(indPC).Local==0,
+            if Parallel(indPC).Local==0
                 ax=ls(['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',filename]);
             else
                 ax=ls(filename);
             end
         end
     end
-    if isempty(dirlist),
+    if isempty(dirlist)
         dirlist=ax;
-    elseif ~isempty(ax),
+    elseif ~isempty(ax)
         dirlist = char(dirlist, ax);
     end
 end
diff --git a/matlab/parallel/dynareParallelFindNewFiles.m b/matlab/parallel/dynareParallelFindNewFiles.m
index 4c6dabf36e3781ef039d8a916e48c9860ddf6cb5..d8cb6a9d71609ded5d3e3fa62b06a8a49170cebc 100644
--- a/matlab/parallel/dynareParallelFindNewFiles.m
+++ b/matlab/parallel/dynareParallelFindNewFiles.m
@@ -15,7 +15,7 @@ function [NewFilesFrom, NewFileList]=dynareParallelFindNewFiles(FileList,Paralle
 %  o NewFilesFrom          []   ...
 %  o NewFileList           []   ...
 %
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -36,7 +36,7 @@ function [NewFilesFrom, NewFileList]=dynareParallelFindNewFiles(FileList,Paralle
 NewFilesFrom={};
 
 LfL=length(FileList);
-                                        % The first call ...
+% The first call ...
 NewFileList = dynareParallelListAllFiles('Root',PRCDir,Parallel);
 
 
@@ -45,35 +45,34 @@ LnFl=length(NewFileList);
 RelativePosition=1;
 
 for i=1:LnFl
-    
+
     % Exception Handling
-    
+
     % If you comment the code below all new file will be copied!
-    
+
     % 1. The comp_status* files are managed separately.
-    
+
     FiCoS=strfind(NewFileList{i},'comp_status_');
     if ~isempty(FiCoS)
         continue
     end
-    
+
     % 2. For the time being is not necessary to always copy *.log
     %    and *.txt files.
-    
+
     nC1 = strfind(NewFileList{i}, '.log');
     nC2 = strfind(NewFileList{i}, '.txt');
-    
+
     if (~isempty(nC1) || ~isempty(nC2))
         continue
     end
-    
+
     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-    
-    
+
+
     N=strmatch(NewFileList{i},FileList,'exact');
     if isempty(N)
         NewFilesFrom{RelativePosition}=NewFileList{i};
         RelativePosition=RelativePosition+1;
     end
 end
-
diff --git a/matlab/parallel/dynareParallelGetFiles.m b/matlab/parallel/dynareParallelGetFiles.m
index 6dbf0539e4953a49a1d5d90f5c5f14e5859617f8..6669f21a85f0e5315540d9afaf8fc0663ed8fb06 100644
--- a/matlab/parallel/dynareParallelGetFiles.m
+++ b/matlab/parallel/dynareParallelGetFiles.m
@@ -14,7 +14,7 @@ function dynareParallelGetFiles(NamFileInput,PRCDir,Parallel)
 %
 %
 %
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -33,32 +33,32 @@ function dynareParallelGetFiles(NamFileInput,PRCDir,Parallel)
 
 NamFileInput0=NamFileInput;
 
-for indPC=1:length(Parallel),
-    if Parallel(indPC).Local==0,
-        if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem),
-            if ~isempty(Parallel(indPC).Port),
+for indPC=1:length(Parallel)
+    if Parallel(indPC).Local==0
+        if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)
+            if ~isempty(Parallel(indPC).Port)
                 ssh_token = ['-p ',Parallel(indPC).Port];
             else
                 ssh_token = '';
             end
-            if ~isempty(Parallel(indPC).Port),
+            if ~isempty(Parallel(indPC).Port)
                 scp_token = ['-P ',Parallel(indPC).Port];
             else
                 scp_token = '';
             end
-            if ischar(NamFileInput0),
-                for j=1:size(NamFileInput0,1),
+            if ischar(NamFileInput0)
+                for j=1:size(NamFileInput0,1)
                     NamFile(j,:)={['./'],deblank(NamFileInput0(j,:))};
                 end
                 NamFileInput = NamFile;
             end
-            for jfil=1:size(NamFileInput,1),
+            for jfil=1:size(NamFileInput,1)
 
                 if isoctave % Patch for peculiar behaviour of ls under Linux.
-                    % It is necessary to manage the jolly char '*'!
+                            % It is necessary to manage the jolly char '*'!
 
                     FindAst=strfind(NamFileInput{jfil,2},'comp_status_posterior_sampler_core*');
-                    
+
                     if isempty (FindAst)
 
                         [NonServeL NonServeR]= system(['scp ',scp_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,':',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',NamFileInput{jfil,1},NamFileInput{jfil,2},' ',NamFileInput{jfil,1}]);
@@ -66,9 +66,9 @@ for indPC=1:length(Parallel),
                     else
 
                         filenameTemp=NamFileInput{jfil,2};
-                        
+
                         [NotUsed FlI]=system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' ls ',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',filenameTemp, ' 2> OctaveStandardOutputMessage.txt']);
-                        
+
                         if isempty (FlI)
                             return
                         end
@@ -92,14 +92,14 @@ for indPC=1:length(Parallel),
 
             end
         else
-            if ischar(NamFileInput0),
-                for j=1:size(NamFileInput0,1),
+            if ischar(NamFileInput0)
+                for j=1:size(NamFileInput0,1)
                     NamFile(j,:)={['.\'],deblank(NamFileInput0(j,:))};
                 end
                 NamFileInput = NamFile;
             end
-            for jfil=1:size(NamFileInput,1),
-                if ~isempty(dynareParallelDir(NamFileInput{jfil,2},[PRCDir,filesep,NamFileInput{jfil,1}],Parallel(indPC))),
+            for jfil=1:size(NamFileInput,1)
+                if ~isempty(dynareParallelDir(NamFileInput{jfil,2},[PRCDir,filesep,NamFileInput{jfil,1}],Parallel(indPC)))
                     copyfile(['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',NamFileInput{jfil,1},NamFileInput{jfil,2}],NamFileInput{jfil,1});
                 end
             end
diff --git a/matlab/parallel/dynareParallelGetNewFiles.m b/matlab/parallel/dynareParallelGetNewFiles.m
index 5f7eb43a3b9c5cf653096e7e8fe6bca32c9dd8d0..8d42bd3759f3379e7785e481c288b7e9757c8e18 100644
--- a/matlab/parallel/dynareParallelGetNewFiles.m
+++ b/matlab/parallel/dynareParallelGetNewFiles.m
@@ -15,7 +15,7 @@ function [PRCDirSnapshot]=dynareParallelGetNewFiles(PRCDir,Parallel,PRCDirSnapsh
 %
 %
 %
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -36,11 +36,11 @@ function [PRCDirSnapshot]=dynareParallelGetNewFiles(PRCDir,Parallel,PRCDirSnapsh
 NewFilesFromSlaves={};
 
 % try
-for indPC=1:length(Parallel),
-    
-    if Parallel(indPC).Local==0;
+for indPC=1:length(Parallel)
+
+    if Parallel(indPC).Local==0
         [NewFilesFromSlaves, PRCDirSnapshot{indPC}]=dynareParallelFindNewFiles(PRCDirSnapshot{indPC},Parallel(indPC), PRCDir);
-        if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem),
+        if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)
             fS='/';
         else
             fS='\';
@@ -71,6 +71,3 @@ for indPC=1:length(Parallel),
 
     end
 end
-
-
-
diff --git a/matlab/parallel/dynareParallelListAllFiles.m b/matlab/parallel/dynareParallelListAllFiles.m
index 53e893e15c71a65a1d2bea014d8692eb55375b1f..eab7134223aff237ddd42c190908943dbbdba5b1 100644
--- a/matlab/parallel/dynareParallelListAllFiles.m
+++ b/matlab/parallel/dynareParallelListAllFiles.m
@@ -14,7 +14,7 @@ function fileList = dynareParallelListAllFiles(dirName,PRCDir,Parallel)
 %  OUTPUTS
 %  o fileList          []   ...
 %
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -34,33 +34,33 @@ function fileList = dynareParallelListAllFiles(dirName,PRCDir,Parallel)
 
 
 if (~ispc || strcmpi('unix',Parallel.OperatingSystem))
-   
+
     fileList={};
     currentPath=[];
-    if ~isempty(Parallel.Port),
+    if ~isempty(Parallel.Port)
         ssh_token = ['-p ',Parallel.Port];
     else
         ssh_token = '';
     end
 
-     % Get the data for the current remote directory.
-    [Flag fL]=system(['ssh ',ssh_token,' ',' ',Parallel.UserName,'@',Parallel.ComputerName,' ls ',Parallel.RemoteDirectory,'/',PRCDir, ' -R -p -1']);
+    % Get the data for the current remote directory.
+    [Flag, fL]=system(['ssh ',ssh_token,' ',' ',Parallel.UserName,'@',Parallel.ComputerName,' ls ',Parallel.RemoteDirectory,'/',PRCDir, ' -R -p -1']);
 
     % Format the return value fL.
-    
+
     nL=regexp(fL,'\n');
     start=1;
     j=1;
 
     for (i=1:length(nL))
-        
+
         stringProcessed=fL(start:nL(i)-1);
-        
+
         if isempty(stringProcessed)
             start=nL(i)+1;
             continue
         end
-            
+
         if strfind(stringProcessed,'/')
             if strfind(stringProcessed,PRCDir)
                 DD=strfind(stringProcessed,':');
@@ -70,11 +70,11 @@ if (~ispc || strcmpi('unix',Parallel.OperatingSystem))
             start=nL(i)+1;
             continue
         end
-        
+
         fileList{j,1}=[currentPath stringProcessed];
         start=nL(i)+1;
         j=j+1;
-    end 
+    end
 
 
 else
@@ -92,7 +92,7 @@ else
     % Build the path files:
     if ~isempty(fileList)
         fileList = cellfun(@(x) fullfile(dirName,x),...
-            fileList,'UniformOutput',false);
+                           fileList,'UniformOutput',false);
     end
 
     % Get a list of the subdirectories:
@@ -112,5 +112,3 @@ else
         fileList = [fileList; dynareParallelListAllFiles(nextDir,PRCDir,Parallel)];
     end
 end
-
-
diff --git a/matlab/parallel/dynareParallelMkDir.m b/matlab/parallel/dynareParallelMkDir.m
index 9e8d7b7de75573706fc875d9a72a64ec3c7cad33..e85d1af3a206dfd49315efc4bd86788c354b8b0a 100644
--- a/matlab/parallel/dynareParallelMkDir.m
+++ b/matlab/parallel/dynareParallelMkDir.m
@@ -3,14 +3,14 @@ function dynareParallelMkDir(PRCDir,Parallel)
 % In a parallel context, this is a specialized version of rmdir() function.
 %
 % INPUTS
-%  o PRCDir         []   ... 
-%  o Parallel       []   ...  
+%  o PRCDir         []   ...
+%  o Parallel       []   ...
 %
 %  OUTPUTS
 %  None
 %
 %
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -29,24 +29,22 @@ function dynareParallelMkDir(PRCDir,Parallel)
 
 
 
-if nargin ==0,
+if nargin ==0
     disp('dynareParallelMkDir(dirname,Parallel)')
     return
 end
 
 for indPC=1:length(Parallel)
-    if Parallel(indPC).Local==0,
-        if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem),
-            if ~isempty(Parallel(indPC).Port),
+    if Parallel(indPC).Local==0
+        if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)
+            if ~isempty(Parallel(indPC).Port)
                 ssh_token = ['-p ',Parallel(indPC).Port];
             else
                 ssh_token = '';
             end
-            [NonServeS NonServeD]=system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' mkdir -p ',Parallel(indPC).RemoteDirectory,'/',PRCDir]);
+            [NonServeS, NonServeD]=system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' mkdir -p ',Parallel(indPC).RemoteDirectory,'/',PRCDir]);
         else
-            [NonServeS NonServeD]=mkdir(['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir]);
+            [NonServeS, NonServeD]=mkdir(['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir]);
         end
     end
-end
-
-return
\ No newline at end of file
+end
\ No newline at end of file
diff --git a/matlab/parallel/dynareParallelRmDir.m b/matlab/parallel/dynareParallelRmDir.m
index fbf7b7790182732813e70f41dcce2d488652593f..64f3c4fdecba38b0c93514aa9fbe408f242f3ad9 100644
--- a/matlab/parallel/dynareParallelRmDir.m
+++ b/matlab/parallel/dynareParallelRmDir.m
@@ -3,15 +3,15 @@ function dynareParallelRmDir(PRCDir,Parallel)
 % In a parallel context, this is a specialized version of rmdir() function.
 %
 % INPUTS
-%  o PRCDir         []   ... 
-%  o Parallel       []   ...  
+%  o PRCDir         []   ...
+%  o Parallel       []   ...
 %
 %  OUTPUTS
 %  None
 %
 %
 %
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -30,7 +30,7 @@ function dynareParallelRmDir(PRCDir,Parallel)
 
 
 
-if nargin ==0,
+if nargin ==0
     disp('dynareParallelRmDir(fname)')
     return
 end
@@ -45,7 +45,7 @@ ok(5)=~isempty(strfind(PRCDir,'m'));
 ok(6)=~isempty(strfind(PRCDir,'s'));
 ok(7)=~isempty(PRCDir);
 
-if sum(ok)<7,
+if sum(ok)<7
     error('The name of the remote tmp folder does not comply the security standards!'),
 end
 
@@ -53,34 +53,32 @@ if isoctave
     confirm_recursive_rmdir(false, 'local');
 end
 
-for indPC=1:length(Parallel),
+for indPC=1:length(Parallel)
     ok(1)=isempty(strfind(Parallel(indPC).RemoteDirectory,'..'));
-    if sum(ok)<7,
+    if sum(ok)<7
         error('The remote folder path structure does not comply the security standards!'),
     end
     while (1)
-        if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem),
-            if ~isempty(Parallel(indPC).Port),
+        if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)
+            if ~isempty(Parallel(indPC).Port)
                 ssh_token = ['-p ',Parallel(indPC).Port];
             else
                 ssh_token = '';
             end
-            [stat NonServe] = system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' rm -fr ',Parallel(indPC).RemoteDirectory,'/',PRCDir,]);
-            break;
+            [stat, NonServe] = system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' rm -fr ',Parallel(indPC).RemoteDirectory,'/',PRCDir,]);
+            break
         else
             [stat, mess, id] = rmdir(['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir],'s');
 
-            if stat==1,
-                break,
+            if stat==1
+                break
             else
-                if isempty(dynareParallelDir(PRCDir,'',Parallel));
-                    break,
+                if isempty(dynareParallelDir(PRCDir,'',Parallel))
+                    break
                 else
                     pause(1);
                 end
             end
         end
     end
-end
-
-return
\ No newline at end of file
+end
\ No newline at end of file
diff --git a/matlab/parallel/dynareParallelSendFiles.m b/matlab/parallel/dynareParallelSendFiles.m
index 6f7e645f55fa916888713603587c8b44f1a627a6..6a3c8904cee2a34223d225c211c441b57b5afb6b 100644
--- a/matlab/parallel/dynareParallelSendFiles.m
+++ b/matlab/parallel/dynareParallelSendFiles.m
@@ -14,7 +14,7 @@ function dynareParallelSendFiles(NamFileInput,PRCDir,Parallel)
 %
 %
 %
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -32,83 +32,83 @@ function dynareParallelSendFiles(NamFileInput,PRCDir,Parallel)
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 
-if ischar(NamFileInput),
-    for j=1:size(NamFileInput,1),
+if ischar(NamFileInput)
+    for j=1:size(NamFileInput,1)
         NamFile(j,:)={'',deblank(NamFileInput(j,:))};
     end
     NamFileInput = NamFile;
 end
 
-for indPC=1:length(Parallel),
-    if Parallel(indPC).Local==0,
-        if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem),
-            if ~isempty(Parallel(indPC).Port),
+for indPC=1:length(Parallel)
+    if Parallel(indPC).Local==0
+        if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)
+            if ~isempty(Parallel(indPC).Port)
                 ssh_token = ['-p ',Parallel(indPC).Port];
             else
                 ssh_token = '';
             end
-            if ~isempty(Parallel(indPC).Port),
+            if ~isempty(Parallel(indPC).Port)
                 scp_token = ['-P ',Parallel(indPC).Port];
             else
                 scp_token = '';
             end
-            for jfil=1:size(NamFileInput,1),
+            for jfil=1:size(NamFileInput,1)
                 if ~isempty(NamFileInput{jfil,1})
-                    [NonServeL NonServeR]=system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' mkdir -p ',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',NamFileInput{jfil,1}]);
+                    [NonServeL, NonServeR]=system(['ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' mkdir -p ',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',NamFileInput{jfil,1}]);
                 end
-                [NonServeL NonServeR]=system(['scp ',scp_token,' ',NamFileInput{jfil,1},NamFileInput{jfil,2},' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,':',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',NamFileInput{jfil,1}]);
+                [NonServeL, NonServeR]=system(['scp ',scp_token,' ',NamFileInput{jfil,1},NamFileInput{jfil,2},' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,':',Parallel(indPC).RemoteDirectory,'/',PRCDir,'/',NamFileInput{jfil,1}]);
             end
         else
             for jfil=1:size(NamFileInput,1)
                 if ~isempty(NamFileInput{jfil,1})
                     if isempty(dynareParallelDir(NamFileInput{jfil,1},PRCDir,Parallel(indPC)))
-                        
+
                         if isoctave % Patch for peculiar behaviour of mkdir under Windows.
-                            
+
                             % It is Necessary because Octave is not able to
                             % create two nested directory at the same time.
-                            
-                           % Remove (if present) the '/' chars. Can be easily transformed
-                           % in a function.
-                           
+
+                            % Remove (if present) the '/' chars. Can be easily transformed
+                            % in a function.
+
                             NamFileInputTemp=NamFileInput{jfil,1};
                             while(1)
                                 Bs=strfind(NamFileInputTemp,'/');
-                                if isempty(Bs),
-                                    break;
+                                if isempty(Bs)
+                                    break
                                 else
                                     NamFileInputTemp(1,Bs)='\';
                                 end
                             end
-                            
-                            [NonServeL NonServeR]=system(['mkdir \\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',NamFileInputTemp]);
+
+                            [NonServeL, NonServeR]=system(['mkdir \\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',NamFileInputTemp]);
 
                         else
                             mkdir(['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',NamFileInput{jfil,1}]);
                         end
                     end
                 end
-                
+
                 if isoctave % Patch for peculiar behaviour copyfile ls under Windows.
-                    
+
                     % It is Necessary because Octave is not able to
                     % use the jolly char '*' with copyfile.
-                    
-                      % Remove (if present) the '/' chars. Can be easily transformed
-                      % in a function.
-                    
+
+                    % Remove (if present) the '/' chars. Can be easily transformed
+                    % in a function.
+
                     NamFileInputTemp=NamFileInput{jfil,1};
                     while(1)
                         Bs=strfind(NamFileInputTemp,'/');
-                        if isempty(Bs),
-                            break;
+                        if isempty(Bs)
+                            break
                         else
                             NamFileInputTemp(1,Bs)='\';
                         end
                     end
-                    
-                    [NonServeS NonServeD]=system(['copy ',NamFileInputTemp, NamFileInput{jfil,2},' \\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',NamFileInputTemp]);
-                    
+
+                    [NonServeS, NonServeD]=system(['copy ',NamFileInputTemp, NamFileInput{jfil,2},' \\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',NamFileInputTemp]);
+
                 else
                     copyfile([NamFileInput{jfil,1},NamFileInput{jfil,2}],['\\',Parallel(indPC).ComputerName,'\',Parallel(indPC).RemoteDrive,'$\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\',NamFileInput{jfil,1}]);
                 end
diff --git a/matlab/parallel/dynareParallelSnapshot.m b/matlab/parallel/dynareParallelSnapshot.m
index 4f07b04df80e9df127ee1cfb565eb8696a272a85..8566ebfe05b61bc7646456acaae5d98a34cdd6a4 100644
--- a/matlab/parallel/dynareParallelSnapshot.m
+++ b/matlab/parallel/dynareParallelSnapshot.m
@@ -14,7 +14,7 @@ function [PRCDirSnapshot]=dynareParallelSnapshot(PRCDir,Parallel)
 %
 %
 %
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -33,10 +33,10 @@ function [PRCDirSnapshot]=dynareParallelSnapshot(PRCDir,Parallel)
 
 PRCDirSnapshot={};
 
-for indPC=1:length(Parallel),
-    if Parallel(indPC).Local==0;
-                                                       % The first call ...
+for indPC=1:length(Parallel)
+    if Parallel(indPC).Local==0
+        % The first call ...
         PRCDirSnapshot{indPC}=dynareParallelListAllFiles('Root',PRCDir,Parallel(indPC));
-        
+
     end
 end
diff --git a/matlab/parallel/fMessageStatus.m b/matlab/parallel/fMessageStatus.m
index 6d84705ab5cca65455d3c16bb9c43e6365ff5c6b..2c9f8ab5f4a5643f16e7e7ae78c7c696bdf4cf8d 100644
--- a/matlab/parallel/fMessageStatus.m
+++ b/matlab/parallel/fMessageStatus.m
@@ -3,18 +3,18 @@ function fMessageStatus(prtfrc, njob, waitbarString, waitbarTitle, Parallel)
 % In parallel context, this function is launched on slave
 % machines, and acts as a message passing device for the master machine.
 
-% INPUTS 
+% INPUTS
 % o prtfrc          [double]     fraction of iteration performed
 % o njob            [int]        index number of this CPU among all CPUs in the
 %                                cluster
-% o waitbarString   [char]       running message string to be displayed in the monitor window on master machine 
+% o waitbarString   [char]       running message string to be displayed in the monitor window on master machine
 % o waitbarTitle    [char]       title to be displayed in the monitor window on master machine
 % o Parallel        [struct]     options_.parallel(ThisMatlab), i.e. the parallel settings for this slave machine in the cluster.
 %
-% OUTPUTS 
-% o None 
+% OUTPUTS
+% o None
 
-% Copyright (C) 2006-2012 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -33,18 +33,17 @@ function fMessageStatus(prtfrc, njob, waitbarString, waitbarTitle, Parallel)
 
 global funcName
 
-if nargin<5,
+if nargin<5
     Parallel.Local=1;
 end
 
 try
     save(['comp_status_',funcName,int2str(njob),'.mat'],'prtfrc','njob','waitbarString','waitbarTitle');
-catch  
+catch
 end
 
 fslave = dir( ['slaveParallel_input',int2str(njob),'.mat']);
 fbreak = dir( ['slaveParallel_break.mat']);
-if isempty(fslave) || ~isempty(fbreak),
+if isempty(fslave) || ~isempty(fbreak)
     error('Master asked to break the job');
 end
-
diff --git a/matlab/parallel/fParallel.m b/matlab/parallel/fParallel.m
index 51e6ebe16fd65640ad0a973eeb88b30abacdb888..4bce41008496693d7b03c4b2e5376a344ea38898 100644
--- a/matlab/parallel/fParallel.m
+++ b/matlab/parallel/fParallel.m
@@ -18,7 +18,7 @@ function fParallel(fblck,nblck,whoiam,ThisMatlab,fname)
 % OUTPUTS
 %   None
 %
-% Copyright (C) 2006-2012 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -53,7 +53,7 @@ load( [fname,'_input'])
 
 if exist('fGlobalVar') && ~isempty (fGlobalVar)
     globalVars = fieldnames(fGlobalVar);
-    for j=1:length(globalVars),
+    for j=1:length(globalVars)
         eval(['global ',globalVars{j},';'])
         evalin('base',['global ',globalVars{j},';'])
     end
@@ -67,12 +67,12 @@ fInputVar.Parallel = Parallel;
 
 
 % Launch the routine to be run in parallel.
-try,
-    tic,
-    
+try
+    tic
+
     fOutputVar = feval(fname, fInputVar ,fblck, nblck, whoiam, ThisMatlab);
-    toc,
-    if isfield(fOutputVar,'OutputFileName'),
+    toc
+    if isfield(fOutputVar,'OutputFileName')
         OutputFileName = fOutputVar.OutputFileName;
     else
         OutputFileName = '';
@@ -81,15 +81,15 @@ try,
         % Save the output result.
         save([ fname,'_output_',int2str(whoiam),'.mat'],'fOutputVar' )
     end
-    if isfield(fOutputVar,'CloseAllSlaves'),
+    if isfield(fOutputVar,'CloseAllSlaves')
         CloseAllSlaves = 1;
         fOutputVar = rmfield(fOutputVar,'CloseAllSlaves');
         save([ fname,'_output_',int2str(whoiam),'.mat'],'fOutputVar' )
         save(['comp_status_',funcName,int2str(whoiam),'.mat'],'CloseAllSlaves');
     end
-    
+
     disp(['fParallel ',int2str(whoiam),' completed.'])
-catch,
+catch
     theerror = lasterror;
     if strfind(theerror.message,'Master asked to break the job')
         fOutputVar.message = theerror;
@@ -101,14 +101,14 @@ catch,
         save([ fname,'_output_',int2str(whoiam),'.mat'],'fOutputVar' )
         waitbarString = theerror.message;
         %       waitbarTitle=['Metropolis-Hastings ',options_.parallel(ThisMatlab).ComputerName];
-        if Parallel(ThisMatlab).Local,
+        if Parallel(ThisMatlab).Local
             waitbarTitle='Local ';
         else
             waitbarTitle=[Parallel(ThisMatlab).ComputerName];
         end
         fMessageStatus(NaN,whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab));
     end
-    
+
 end
 diary off;
 delete(['P_',fname,'_',int2str(whoiam),'End.txt']);
diff --git a/matlab/parallel/masterParallel.m b/matlab/parallel/masterParallel.m
index 902b237dc3ede9cefdbd67b9ec2fa7664f30254f..e51c6d02335c4637b3a612d51f8174b9cd10b173 100644
--- a/matlab/parallel/masterParallel.m
+++ b/matlab/parallel/masterParallel.m
@@ -3,37 +3,37 @@ 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):
-% 
+%
 % 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.
-% 
+%
 % 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.
-% 
+%
 % 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 are wrapped and passed by storing their 
+%   Global variables used within the called function 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. 
-% 
+%   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
@@ -62,7 +62,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-2015 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -91,11 +91,11 @@ Strategy=Parallel_info.leaveSlaveOpen;
 
 islocal = 1;
 isHybridMatlabOctave = Parallel_info.isHybridMatlabOctave;
-for j=1:length(Parallel),
+for j=1:length(Parallel)
     islocal=islocal*Parallel(j).Local;
 end
 if nargin>8 && initialize==1
-    if islocal == 0,
+    if islocal == 0
         PRCDir=CreateTimeString();
         assignin('base','PRCDirTmp',PRCDir),
         evalin('base','options_.parallel_info.RemoteTmpFolder=PRCDirTmp;')
@@ -108,7 +108,7 @@ if nargin>8 && initialize==1
 end
 
 if isfield(Parallel_info,'local_files')
-    if isempty(NamFileInput),
+    if isempty(NamFileInput)
         NamFileInput=Parallel_info.local_files;
     else
         NamFileInput=[NamFileInput;Parallel_info.local_files];
@@ -120,31 +120,31 @@ end
 % in Octave!
 
 if isoctave
-    warning('off');
+    warning('off')
 end
 
 % check if there are function_handles in the input or global vars when
 % octave is used
 if isHybridMatlabOctave || isoctave
     fInputNames = fieldnames(fInputVar);
-    for j=1:length(fInputNames),
+    for j=1:length(fInputNames)
         TargetVar = fInputVar.(fInputNames{j});
-        if isa(TargetVar,'function_handle'),
+        if isa(TargetVar,'function_handle')
             TargetVar=func2str(TargetVar);
             fInputVar.(fInputNames{j})=TargetVar;
         end
     end
-    
-    if exist('fGlobalVar','var') && ~isempty(fGlobalVar),
-    fInputNames = fieldnames(fGlobalVar);
-    for j=1:length(fInputNames),
-        TargetVar = fGlobalVar.(fInputNames{j});
-        if isa(TargetVar,'function_handle'),
-            TargetVar=func2str(TargetVar);
-            fGlobalVar.(fInputNames{j})=TargetVar;
+
+    if exist('fGlobalVar','var') && ~isempty(fGlobalVar)
+        fInputNames = fieldnames(fGlobalVar);
+        for j=1:length(fInputNames)
+            TargetVar = fGlobalVar.(fInputNames{j});
+            if isa(TargetVar,'function_handle')
+                TargetVar=func2str(TargetVar);
+                fGlobalVar.(fInputNames{j})=TargetVar;
+            end
         end
     end
-    end
 end
 
 if Strategy==1
@@ -156,7 +156,7 @@ end
 
 DyMo=pwd;
 % fInputVar.DyMo=DyMo;
-if ispc,
+if ispc
     [tempo, MasterName]=system('hostname');
     MasterName=deblank(MasterName);
 end
@@ -165,18 +165,18 @@ end
 
 % Save input data for use by the slaves.
 switch Strategy
-    case 0
-        storeGlobalVars([fname,'_input.mat']);
-        save([fname,'_input.mat'],'fInputVar','Parallel','-append')
-        
-    case 1
-        if exist('fGlobalVar','var'),
-            save(['temp_input.mat'],'fInputVar','fGlobalVar')
-        else
-            save(['temp_input.mat'],'fInputVar')
-        end
-        save(['temp_input.mat'],'Parallel','-append')
-        closeSlave(Parallel,PRCDir,-1);
+  case 0
+    storeGlobalVars([fname,'_input.mat']);
+    save([fname,'_input.mat'],'fInputVar','Parallel','-append')
+
+  case 1
+    if exist('fGlobalVar','var')
+        save(['temp_input.mat'],'fInputVar','fGlobalVar')
+    else
+        save(['temp_input.mat'],'fInputVar')
+    end
+    save(['temp_input.mat'],'Parallel','-append')
+    closeSlave(Parallel,PRCDir,-1);
 end
 
 
@@ -184,7 +184,7 @@ end
 % to run on each CPU.
 
 [nCPU, totCPU, nBlockPerCPU, totSlaves] = distributeJobs(Parallel, fBlock, nBlock);
-for j=1:totSlaves,
+for j=1:totSlaves
     PRCDirSnapshot{j}={};
 end
 offset0 = fBlock-1;
@@ -206,7 +206,7 @@ fid = fopen('ConcurrentCommand1.bat','w+');
 
 
 % Create the directory devoted to remote computation.
-if isempty(PRCDir) && ~islocal,
+if isempty(PRCDir) && ~islocal
     error('PRCDir not initialized!')
 else
     dynareParallelMkDir(PRCDir,Parallel(1:totSlaves));
@@ -238,27 +238,27 @@ end
 
 % End
 
-for j=1:totCPU,
-    
+for j=1:totCPU
+
     if Strategy==1
         command1 = ' ';
     end
-    
+
     indPC=min(find(nCPU>=j));
-    
+
     % According to the information contained in configuration file, compThread can limit MATLAB
     % to a single computational thread. By default, MATLAB makes use of the multithreading
     % capabilities of the computer on which it is running. Nevertheless
     % exsperimental results show as matlab native
     % multithreading limit the performaces when the parallel computing is active.
-    
-    
-    if strcmp('true',Parallel(indPC).SingleCompThread),
+
+
+    if strcmp('true',Parallel(indPC).SingleCompThread)
         compThread = '-singleCompThread';
     else
         compThread = '';
     end
-    
+
     nthreads=Parallel(indPC).NumberOfThreadsPerJob;
     if indPC>1
         nCPU0 = nCPU(indPC-1);
@@ -266,20 +266,20 @@ for j=1:totCPU,
         nCPU0=0;
     end
     offset = sum(nBlockPerCPU(1:j-1))+offset0;
-    
+
     % Create a file used to monitoring if a parallel block (core)
     % computation is finished or not.
-    
+
     fid1=fopen(['P_',fname,'_',int2str(j),'End.txt'],'w+');
     fclose(fid1);
-    
-    if Strategy==1,
-        
+
+    if Strategy==1
+
         fblck = offset+1;
         nblck = sum(nBlockPerCPU(1:j));
         save temp_input.mat fblck nblck fname -append;
         copyfile('temp_input.mat',['slaveJob',int2str(j),'.mat']);
-        if Parallel(indPC).Local ==0,
+        if Parallel(indPC).Local ==0
             fid1=fopen(['stayalive',int2str(j),'.txt'],'w+');
             fclose(fid1);
             dynareParallelSendFiles(['stayalive',int2str(j),'.txt'],PRCDir,Parallel(indPC));
@@ -289,80 +289,157 @@ for j=1:totCPU,
         % internal criteria.
         pause(1);
         newInstance = 0;
-        
+
         % Check if j CPU is already alive.
-        if isempty(dynareParallelDir(['P_slave_',int2str(j),'End.txt'],PRCDir,Parallel(indPC)));
+        if isempty(dynareParallelDir(['P_slave_',int2str(j),'End.txt'],PRCDir,Parallel(indPC)))
             fid1=fopen(['P_slave_',int2str(j),'End.txt'],'w+');
             fclose(fid1);
-            if Parallel(indPC).Local==0,
+            if Parallel(indPC).Local==0
                 dynareParallelSendFiles(['P_slave_',int2str(j),'End.txt'],PRCDir,Parallel(indPC));
                 delete(['P_slave_',int2str(j),'End.txt']);
             end
-            
+
             newInstance = 1;
             storeGlobalVars( ['slaveParallel_input',int2str(j),'.mat']);
             save( ['slaveParallel_input',int2str(j),'.mat'],'Parallel','-append');
             % Prepare global vars for Slave.
         end
     else
-        
+
         % If the computation is executed remotely all the necessary files
         % are created localy, then copied in remote directory and then
         % deleted (loacal)!
-        
+
         save( ['slaveParallel_input',int2str(j),'.mat'],'j');
-        
-        if Parallel(indPC).Local==0,
+
+        if Parallel(indPC).Local==0
             dynareParallelSendFiles(['P_',fname,'_',int2str(j),'End.txt'],PRCDir,Parallel(indPC));
             delete(['P_',fname,'_',int2str(j),'End.txt']);
-            
+
             dynareParallelSendFiles(['slaveParallel_input',int2str(j),'.mat'],PRCDir,Parallel(indPC));
             delete(['slaveParallel_input',int2str(j),'.mat']);
-            
+
         end
-        
+
     end
-    
+
     % set affinity range on win CPU's
     affinity_range = [1:nthreads]+(j-1-nCPU0)*nthreads;
     my_affinity = int2str(Parallel(indPC).CPUnbr(affinity_range(1)));
-    for jaff=2:length(affinity_range),
+    for jaff=2:length(affinity_range)
         my_affinity = [my_affinity ',' int2str(Parallel(indPC).CPUnbr(affinity_range(jaff)))];
     end
-% % %                   int2str(Parallel(indPC).CPUnbr(j-nCPU0))
+    % % %                   int2str(Parallel(indPC).CPUnbr(j-nCPU0))
     % DA SINTETIZZARE:
-    
+
     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
     % The following 'switch - case' code is the core of this function!
     switch Strategy
-        case 0
-            
-            if Parallel(indPC).Local == 1,                                  % 0.1 Run on the local machine (localhost).
-                
-                if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem), % Hybrid computing Windows <-> Unix!
-                    if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
-                        command1=[Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')" &'];
+      case 0
+
+        if Parallel(indPC).Local == 1                                  % 0.1 Run on the local machine (localhost).
+
+            if ~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem) % Hybrid computing Windows <-> Unix!
+                if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
+                    command1=[Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')" &'];
+                else
+                    command1=[Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')" &'];
+                end
+            else    % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
+                if  regexpi([Parallel(indPC).MatlabOctavePath], 'octave')
+                    command1=['psexec -d -W "',DyMo, '" -a ',my_affinity,' -low  ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"'];
+                else
+                    command1=['psexec -d -W "',DyMo, '" -a ',my_affinity,' -low  ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"'];
+                end
+            end
+        else                                                            % 0.2 Parallel(indPC).Local==0: Run using network on remote machine or also on local machine.
+            if j==nCPU0+1
+                dynareParallelSendFiles([fname,'_input.mat'],PRCDir,Parallel(indPC));
+                dynareParallelSendFiles(NamFileInput,PRCDir,Parallel(indPC));
+            end
+
+            if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)) % Hybrid computing Windows <-> Unix!
+                if ispc
+                    token='start /B ';
+                else
+                    token = '';
+                end
+                if ~isempty(Parallel(indPC).Port)
+                    ssh_token = ['-p ',Parallel(indPC).Port];
+                else
+                    ssh_token = '';
+                end
+                % To manage the diferences in Unix/Windows OS syntax.
+                remoteFile=['remoteDynare',int2str(j)];
+                fidRemote=fopen([remoteFile,'.m'],'w+');
+                if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
+                    remoteString=['default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')'];
+                    command1=[token, 'ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' "cd ',Parallel(indPC).RemoteDirectory,'/',PRCDir, '; ',Parallel(indPC).MatlabOctavePath,' -f --eval ',remoteFile,' " &'];
+                else
+                    remoteString=['addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')'];
+                    command1=[token, 'ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' "cd ',Parallel(indPC).RemoteDirectory,'/',PRCDir, '; ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r ',remoteFile,';" &'];
+                end
+                fprintf(fidRemote,'%s\n',remoteString);
+                fclose(fidRemote);
+                dynareParallelSendFiles([remoteFile,'.m'],PRCDir,Parallel(indPC));
+                delete([remoteFile,'.m']);
+            else
+                if ~strcmpi(Parallel(indPC).ComputerName,MasterName)  % 0.3 Run on a remote machine!
+                                                                      % Hybrid computing Matlab(Master)-> Octave(Slaves) and Vice Versa!
+                    if  regexpi([Parallel(indPC).MatlabOctavePath], 'octave')
+                        command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -u ',Parallel(indPC).UserName,' -p ',Parallel(indPC).Password,' -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ...
+                                  ' -low  ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"'];
                     else
-                        command1=[Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')" &'];
+
+                        command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -u ',Parallel(indPC).UserName,' -p ',Parallel(indPC).Password,' -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ...
+                                  ' -low  ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"'];
                     end
-                else    % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
+                else                                                  % 0.4 Run on the local machine via the network
+                                                                      % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
                     if  regexpi([Parallel(indPC).MatlabOctavePath], 'octave')
-                        command1=['psexec -d -W "',DyMo, '" -a ',my_affinity,' -low  ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"'];
+                        command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ...
+                                  ' -low  ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"'];
                     else
-                        command1=['psexec -d -W "',DyMo, '" -a ',my_affinity,' -low  ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"'];
+                        command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ...
+                                  ' -low  ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"'];
                     end
                 end
-            else                                                            % 0.2 Parallel(indPC).Local==0: Run using network on remote machine or also on local machine.
-                if j==nCPU0+1,
-                    dynareParallelSendFiles([fname,'_input.mat'],PRCDir,Parallel(indPC));
-                    dynareParallelSendFiles(NamFileInput,PRCDir,Parallel(indPC));
+            end
+        end
+
+
+      case 1
+        if Parallel(indPC).Local == 1 && newInstance                       % 1.1 Run on the local machine.
+            if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem))  % Hybrid computing Windows <-> Unix!
+                if regexpi([Parallel(indPC).MatlabOctavePath], 'octave')    % Hybrid computing Matlab(Master)-> Octave(Slaves) and Vice Versa!
+                    command1=[Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')" &'];
+                else
+                    command1=[Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')" &'];
+                end
+            else    % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
+                if  regexpi([Parallel(indPC).MatlabOctavePath], 'octave')
+                    command1=['psexec -d -W "',DyMo, '" -a ',my_affinity,' -low  ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7'');addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"'];
+                else
+                    command1=['psexec -d -W "',DyMo, '" -a ',my_affinity,' -low  ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"'];
                 end
-                
-                if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)), % Hybrid computing Windows <-> Unix!
-                    if ispc, token='start /B ';
-                    else token = '';
+            end
+        elseif Parallel(indPC).Local==0                                % 1.2 Run using network on remote machine or also on local machine.
+            if j==nCPU0+1
+                dynareParallelSendFiles(NamFileInput,PRCDir,Parallel(indPC));
+            end
+            dynareParallelSendFiles(['P_',fname,'_',int2str(j),'End.txt'],PRCDir,Parallel(indPC));
+            delete(['P_',fname,'_',int2str(j),'End.txt']);
+            if newInstance
+                dynareParallelSendFiles(['slaveJob',int2str(j),'.mat'],PRCDir,Parallel(indPC));
+                delete(['slaveJob',int2str(j),'.mat']);
+                dynareParallelSendFiles(['slaveParallel_input',int2str(j),'.mat'],PRCDir,Parallel(indPC))
+                if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)) % Hybrid computing Windows <-> Unix!
+                    if ispc
+                        token='start /B ';
+                    else
+                        token = '';
                     end
-                    if ~isempty(Parallel(indPC).Port),
+                    if ~isempty(Parallel(indPC).Port)
                         ssh_token = ['-p ',Parallel(indPC).Port];
                     else
                         ssh_token = '';
@@ -370,132 +447,59 @@ for j=1:totCPU,
                     % To manage the diferences in Unix/Windows OS syntax.
                     remoteFile=['remoteDynare',int2str(j)];
                     fidRemote=fopen([remoteFile,'.m'],'w+');
-                    if regexpi([Parallel(indPC).MatlabOctavePath], 'octave'),% Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
-                        remoteString=['default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')'];
-                        command1=[token, 'ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' "cd ',Parallel(indPC).RemoteDirectory,'/',PRCDir, '; ',Parallel(indPC).MatlabOctavePath,' -f --eval ',remoteFile,' " &'];
+                    if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)-> Octave(Slaves) and Vice Versa!
+                        remoteString=['default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),');'];
+                        command1=[token, 'ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' "cd ',Parallel(indPC).RemoteDirectory,'/',PRCDir '; ',Parallel(indPC).MatlabOctavePath,' -f --eval ',remoteFile,' " &'];
                     else
-                        remoteString=['addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')'];
-                        command1=[token, 'ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' "cd ',Parallel(indPC).RemoteDirectory,'/',PRCDir, '; ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r ',remoteFile,';" &'];
+                        remoteString=['addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),');'];
+                        command1=[token, 'ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' "cd ',Parallel(indPC).RemoteDirectory,'/',PRCDir '; ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r ',remoteFile,';" &'];
                     end
                     fprintf(fidRemote,'%s\n',remoteString);
                     fclose(fidRemote);
                     dynareParallelSendFiles([remoteFile,'.m'],PRCDir,Parallel(indPC));
                     delete([remoteFile,'.m']);
                 else
-                    if ~strcmpi(Parallel(indPC).ComputerName,MasterName),  % 0.3 Run on a remote machine!
-                        % Hybrid computing Matlab(Master)-> Octave(Slaves) and Vice Versa!
+                    if ~strcmpi(Parallel(indPC).ComputerName,MasterName) % 1.3 Run on a remote machine.
+                                                                         % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
                         if  regexpi([Parallel(indPC).MatlabOctavePath], 'octave')
                             command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -u ',Parallel(indPC).UserName,' -p ',Parallel(indPC).Password,' -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ...
-                                ' -low  ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"'];
+                                      ' -low  ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7'');addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"'];
                         else
-             
                             command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -u ',Parallel(indPC).UserName,' -p ',Parallel(indPC).Password,' -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ...
-                                ' -low  ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"'];
+                                      ' -low  ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"'];
                         end
-                    else                                                  % 0.4 Run on the local machine via the network
-                        % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
+                    else                                                % 1.4 Run on the local machine via the network.
+                                                                        % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
                         if  regexpi([Parallel(indPC).MatlabOctavePath], 'octave')
                             command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ...
-                                ' -low  ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"'];
+                                      ' -low  ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"'];
                         else
                             command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ...
-                                ' -low  ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); fParallel(',int2str(offset+1),',',int2str(sum(nBlockPerCPU(1:j))),',',int2str(j),',',int2str(indPC),',''',fname,''')"'];
+                                      ' -low  ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"'];
                         end
                     end
                 end
-            end
-            
-            
-        case 1
-            if Parallel(indPC).Local == 1 && newInstance,                       % 1.1 Run on the local machine.
-                if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)),  % Hybrid computing Windows <-> Unix!                   
-                    if regexpi([Parallel(indPC).MatlabOctavePath], 'octave')    % Hybrid computing Matlab(Master)-> Octave(Slaves) and Vice Versa!
-                        command1=[Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')" &'];
-                    else
-                        command1=[Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')" &'];
-                    end
-                else    % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
-                    if  regexpi([Parallel(indPC).MatlabOctavePath], 'octave')
-                        command1=['psexec -d -W "',DyMo, '" -a ',my_affinity,' -low  ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7'');addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"'];
-                    else
-                        command1=['psexec -d -W "',DyMo, '" -a ',my_affinity,' -low  ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"'];
-                    end
-                end
-            elseif Parallel(indPC).Local==0,                                % 1.2 Run using network on remote machine or also on local machine.
-                if j==nCPU0+1,
-                    dynareParallelSendFiles(NamFileInput,PRCDir,Parallel(indPC));
-                end
-                dynareParallelSendFiles(['P_',fname,'_',int2str(j),'End.txt'],PRCDir,Parallel(indPC));
-                delete(['P_',fname,'_',int2str(j),'End.txt']);
-                if newInstance,
-                    dynareParallelSendFiles(['slaveJob',int2str(j),'.mat'],PRCDir,Parallel(indPC));
-                    delete(['slaveJob',int2str(j),'.mat']);
-                    dynareParallelSendFiles(['slaveParallel_input',int2str(j),'.mat'],PRCDir,Parallel(indPC))
-                    if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)), % Hybrid computing Windows <-> Unix!
-                        if ispc, token='start /B ';
-                        else token = '';
-                        end
-                        if ~isempty(Parallel(indPC).Port),
-                            ssh_token = ['-p ',Parallel(indPC).Port];
-                        else
-                            ssh_token = '';
-                        end
-                        % To manage the diferences in Unix/Windows OS syntax.
-                        remoteFile=['remoteDynare',int2str(j)];
-                        fidRemote=fopen([remoteFile,'.m'],'w+');
-                        if regexpi([Parallel(indPC).MatlabOctavePath], 'octave') % Hybrid computing Matlab(Master)-> Octave(Slaves) and Vice Versa!
-                            remoteString=['default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),');'];
-                            command1=[token, 'ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' "cd ',Parallel(indPC).RemoteDirectory,'/',PRCDir '; ',Parallel(indPC).MatlabOctavePath,' -f --eval ',remoteFile,' " &'];
-                        else
-                            remoteString=['addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),');'];
-                            command1=[token, 'ssh ',ssh_token,' ',Parallel(indPC).UserName,'@',Parallel(indPC).ComputerName,' "cd ',Parallel(indPC).RemoteDirectory,'/',PRCDir '; ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r ',remoteFile,';" &'];
-                        end
-                        fprintf(fidRemote,'%s\n',remoteString);
-                        fclose(fidRemote);
-                        dynareParallelSendFiles([remoteFile,'.m'],PRCDir,Parallel(indPC));
-                        delete([remoteFile,'.m']);
-                    else
-                        if ~strcmpi(Parallel(indPC).ComputerName,MasterName), % 1.3 Run on a remote machine.
-                            % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
-                            if  regexpi([Parallel(indPC).MatlabOctavePath], 'octave')
-                                command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -u ',Parallel(indPC).UserName,' -p ',Parallel(indPC).Password,' -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ...
-                                    ' -low  ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7'');addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"'];
-                            else
-                                command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -u ',Parallel(indPC).UserName,' -p ',Parallel(indPC).Password,' -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ...
-                                    ' -low  ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"'];
-                            end
-                        else                                                % 1.4 Run on the local machine via the network.
-                            % Hybrid computing Matlab(Master)->Octave(Slaves) and Vice Versa!
-                            if  regexpi([Parallel(indPC).MatlabOctavePath], 'octave')
-                                command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ...
-                                    ' -low  ',Parallel(indPC).MatlabOctavePath,' -f --eval "default_save_options(''-v7''); addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"'];
-                            else
-                                command1=['psexec \\',Parallel(indPC).ComputerName,' -d -e -W "',Parallel(indPC).RemoteDrive,':\',Parallel(indPC).RemoteDirectory,'\',PRCDir,'\" -a ',my_affinity, ...
-                                    ' -low  ',Parallel(indPC).MatlabOctavePath,' -nosplash -nodesktop -minimize ',compThread,' -r "addpath(''',Parallel(indPC).DynarePath,'''), dynareroot = dynare_config(); slaveParallel(',int2str(j),',',int2str(indPC),')"'];
-                            end
-                        end
-                    end
+            else
+                % When the user user strategy is equal to 1, you must
+                % do PRCDirSnapshot here to to avoid problems of
+                % synchronization.
+
+                if isempty(PRCDirSnapshot{indPC})
+                    PRCDirSnapshot(indPC)=dynareParallelSnapshot(PRCDir,Parallel(indPC));
+                    PRCDirSnapshotInit(indPC) = PRCDirSnapshot(indPC);
                 else
-                    % When the user user strategy is equal to 1, you must
-                    % do PRCDirSnapshot here to to avoid problems of
-                    % synchronization.
-                    
-                    if isempty(PRCDirSnapshot{indPC}),
-                        PRCDirSnapshot(indPC)=dynareParallelSnapshot(PRCDir,Parallel(indPC));
-                        PRCDirSnapshotInit(indPC) = PRCDirSnapshot(indPC);
-                    else
-                        PRCDirSnapshot(indPC)=dynareParallelGetNewFiles(PRCDir,Parallel(indPC),PRCDirSnapshot(indPC));
-                    end
-                    dynareParallelSendFiles(['slaveJob',int2str(j),'.mat'],PRCDir,Parallel(indPC));
-                    delete(['slaveJob',int2str(j),'.mat']);
-                    
+                    PRCDirSnapshot(indPC)=dynareParallelGetNewFiles(PRCDir,Parallel(indPC),PRCDirSnapshot(indPC));
                 end
+                dynareParallelSendFiles(['slaveJob',int2str(j),'.mat'],PRCDir,Parallel(indPC));
+                delete(['slaveJob',int2str(j),'.mat']);
+
             end
-            
+        end
+
     end
-    
+
     fprintf(fid,'%s\n',command1);
-    
+
 end
 
 % In This way we are sure that the file 'ConcurrentCommand1.bat' is
@@ -511,16 +515,16 @@ end
 % the slaves ...
 % If the compuation is 'Local' it is not necessary to do it ...
 
-if Strategy==0 || newInstance, % See above.
+if Strategy==0 || newInstance % See above.
     PRCDirSnapshot=dynareParallelSnapshot(PRCDir,Parallel(1:totSlaves));
     PRCDirSnapshotInit = PRCDirSnapshot;
-    
+
     % Run the slaves.
-    if  ~ispc,
+    if  ~ispc
         system('sh ConcurrentCommand1.bat &');
         pause(1)
     else
-        
+
         if isoctave
             % Redirect the standard output to the file 'OctaveStandardOutputMessage.txt'!
             % This file is saved in the Model directory.
@@ -549,18 +553,18 @@ if isoctave || options_.console_mode
     end
 else
     hfigstatus = figure('name',['Parallel ',fname],...
-        'DockControls','off', ...
-        'IntegerHandle','off', ...
-        'Interruptible','off', ...
-        'MenuBar', 'none', ...
-        'NumberTitle','off', ...
-        'Renderer','Painters', ...
-        'Resize','off');
-    
+                        'DockControls','off', ...
+                        'IntegerHandle','off', ...
+                        'Interruptible','off', ...
+                        'MenuBar', 'none', ...
+                        'NumberTitle','off', ...
+                        'Renderer','Painters', ...
+                        'Resize','off');
+
     ncol = ceil(totCPU/10);
     hspace = 0.9/ncol;
     hstatus(1) = axes('position',[0.05/ncol 0.92 0.9/ncol 0.03], ...
-        'box','on','xtick',[],'ytick',[],'xlim',[0 1],'ylim',[0 1]);
+                      'box','on','xtick',[],'ytick',[],'xlim',[0 1],'ylim',[0 1]);
     set(hstatus(1),'Units','pixels')
     hpixel = get(hstatus(1),'Position');
     hfigure = get(hfigstatus,'Position');
@@ -569,16 +573,16 @@ else
     set(hstatus(1),'Units','normalized'),
     vspace = max(0.1,1/totCPU);
     vstart = 1-vspace+0.2*vspace;
-    for j=1:totCPU,
+    for j=1:totCPU
         jrow = mod(j-1,10)+1;
         jcol = ceil(j/10);
         hstatus(j) = axes('position',[0.05/ncol+(jcol-1)/ncol vstart-vspace*(jrow-1) 0.9/ncol 0.3*vspace], ...
-            'box','on','xtick',[],'ytick',[],'xlim',[0 1],'ylim',[0 1]);
+                          'box','on','xtick',[],'ytick',[],'xlim',[0 1],'ylim',[0 1]);
         hpat(j) = patch([0 0 0 0],[0 1 1 0],'r','EdgeColor','r');
         htit(j) = title(['Initialize ...']);
-        
+
     end
-    
+
     cumBlockPerCPU = cumsum(nBlockPerCPU);
 end
 pcerdone = NaN(1,totCPU);
@@ -592,20 +596,20 @@ idCPU = NaN(1,totCPU);
 % Caption for console mode computing ...
 
 if options_.console_mode ||  isoctave
-    
+
     if ~isoctave
         if strcmpi([Parallel(indPC).MatlabOctavePath], 'octave')
             RjInformation='Hybrid Computing Is Active: Remote jobs are computed by Octave!';
             fprintf([RjInformation,'\n\n']);
         end
     end
-    
+
     fnameTemp=fname;
-    
+
     L=length(fnameTemp);
-    
+
     PoCo=strfind(fnameTemp,'_core');
-    
+
     for i=PoCo:L
         if i==PoCo
             fnameTemp(i)=' ';
@@ -613,27 +617,27 @@ if options_.console_mode ||  isoctave
             fnameTemp(i)='.';
         end
     end
-    
+
     for i=1:L
-        if  fnameTemp(i)=='_';
+        if  fnameTemp(i)=='_'
             fnameTemp(i)=' ';
         end
     end
-    
+
     fnameTemp(L)='';
-    
+
     Information=['Parallel ' fnameTemp ' Computing ...'];
     if isoctave
         if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem)) && (Strategy==0)
             printf('\n');
             pause(2);
         end
-        
+
         printf([Information,'\n\n']);
     else
         fprintf([Information,'\n\n']);
     end
-    
+
 end
 
 
@@ -649,26 +653,26 @@ statusString = '';
 flag_CloseAllSlaves=0;
 
 while (ForEver)
-    
+
     waitbarString = '';
     statusString0 = repmat('\b',1,length(sprintf(statusString, 100 .* pcerdone)));
     statusString = '';
-    
+
     pause(1)
-    
+
     try
-        if islocal ==0,
+        if islocal ==0
             dynareParallelGetFiles(['comp_status_',fname,'*.mat'],PRCDir,Parallel(1:totSlaves));
         end
     catch
     end
-    
-    for j=1:totCPU,
+
+    for j=1:totCPU
         try
             if ~isempty(['comp_status_',fname,int2str(j),'.mat'])
                 load(['comp_status_',fname,int2str(j),'.mat']);
-%                 whoCloseAllSlaves = who(['comp_status_',fname,int2str(j),'.mat','CloseAllSlaves']);
-                if exist('CloseAllSlaves') && flag_CloseAllSlaves==0,
+                %                 whoCloseAllSlaves = who(['comp_status_',fname,int2str(j),'.mat','CloseAllSlaves']);
+                if exist('CloseAllSlaves') && flag_CloseAllSlaves==0
                     flag_CloseAllSlaves=1;
                     whoiamCloseAllSlaves=j;
                     closeSlave(Parallel(1:totSlaves),PRCDir,1);
@@ -687,7 +691,7 @@ while (ForEver)
                 status_Title{j} = waitbarTitle;
             end
         catch % ME
-            % To define!
+              % To define!
             if isoctave || options_.console_mode
                 if (~ispc || strcmpi('unix',Parallel(indPC).OperatingSystem))
                     statusString = [statusString, int2str(j), ' %3.f%% done! '];
@@ -706,20 +710,20 @@ while (ForEver)
             end
         end
     else
-        for j=1:totCPU,
+        for j=1:totCPU
             try
                 set(hpat(j),'XData',[0 0 pcerdone(j) pcerdone(j)]);
                 set(htit(j),'String',[status_Title{j},' - ',status_String{j}]);
             catch
-                
+
             end
         end
     end
-    
+
     % Check if the slave(s) has generated some new files remotely.
     % 1. The files .log and .txt are not copied.
     % 2. The comp_status_*.mat files are managed separately.
-    
+
     if isoctave % to avoid synchronism problems
         try
             PRCDirSnapshot=dynareParallelGetNewFiles(PRCDir,Parallel(1:totSlaves),PRCDirSnapshot);
@@ -728,11 +732,11 @@ while (ForEver)
     else
         PRCDirSnapshot=dynareParallelGetNewFiles(PRCDir,Parallel(1:totSlaves),PRCDirSnapshot);
     end
-    
-    if isempty(dynareParallelDir(['P_',fname,'_*End.txt'],PRCDir,Parallel(1:totSlaves)));
+
+    if isempty(dynareParallelDir(['P_',fname,'_*End.txt'],PRCDir,Parallel(1:totSlaves)))
         HoTuttiGliOutput=0;
-        for j=1:totCPU,
-            
+        for j=1:totCPU
+
             % Checking if the remote computation is finished and if we copied all the output here.
             if ~isempty(dir([fname,'_output_',int2str(j),'.mat']))
                 HoTuttiGliOutput=HoTuttiGliOutput+1;
@@ -741,8 +745,8 @@ while (ForEver)
                 dynareParallelGetFiles([fname,'_output_',int2str(j),'.mat'],PRCDir,Parallel(indPC));
             end
         end
-        
-        if HoTuttiGliOutput==totCPU,
+
+        if HoTuttiGliOutput==totCPU
             mydelete(['comp_status_',fname,'*.mat']);
             if isoctave || options_.console_mode
                 if isoctave
@@ -754,15 +758,15 @@ while (ForEver)
                 end
                 diary on;
             else
-                close(hfigstatus),
+                close(hfigstatus)
             end
-            
+
             break
         else
             disp('Waiting for output files from slaves ...')
         end
     end
-    
+
 end
 
 
@@ -770,19 +774,19 @@ end
 iscrash = 0;
 PRCDirSnapshot=dynareParallelGetNewFiles(PRCDir,Parallel(1:totSlaves),PRCDirSnapshot);
 
-for j=1:totCPU,
+for j=1:totCPU
     indPC=min(find(nCPU>=j));
     load([fname,'_output_',int2str(j),'.mat'],'fOutputVar');
     delete([fname,'_output_',int2str(j),'.mat']);
-    if isfield(fOutputVar,'OutputFileName') && Parallel(indPC).Local==0,
+    if isfield(fOutputVar,'OutputFileName') && Parallel(indPC).Local==0
         %   Check if input files have been updated!
-        OutputFileName=fOutputVar.OutputFileName;        
+        OutputFileName=fOutputVar.OutputFileName;
         tmp0='';
-        for i=1:size(NamFileInput,1),
+        for i=1:size(NamFileInput,1)
             FileList = regexp(strrep(PRCDirSnapshot{indPC},'\','/'),strrep(strrep([NamFileInput{i,:}],'\','/'),'*','(\w*)'),'match');
-            for k=1:length(FileList),
-                if ~isempty(FileList{k}),
-                    if isempty(tmp0),
+            for k=1:length(FileList)
+                if ~isempty(FileList{k})
+                    if isempty(tmp0)
                         tmp0=FileList{k}{1};
                     else
                         tmp0=char(tmp0,FileList{k}{1});
@@ -790,112 +794,112 @@ for j=1:totCPU,
                 end
             end
         end
-        for i=1:size(OutputFileName,1),
+        for i=1:size(OutputFileName,1)
             tmp1='';
             FileList = regexp(cellstr(tmp0),strrep(strrep([OutputFileName{i,:}],'\','/'),'*','(\w*)'),'match');
             FileList0 = regexp(cellstr(tmp0),strrep([OutputFileName{i,2}],'*','(\w*)'),'match');
-            for k=1:length(FileList),
-                if ~isempty(FileList{k}),
-                    if isempty(tmp1),
+            for k=1:length(FileList)
+                if ~isempty(FileList{k})
+                    if isempty(tmp1)
                         tmp1=FileList0{k}{1};
                     else
                         tmp1=char(tmp1,FileList0{k}{1});
                     end
                 end
             end
-            for k=1:size(tmp1,1),
-                    dynareParallelGetFiles([OutputFileName(i,1) {tmp1(k,:)}],PRCDir,Parallel(indPC));
+            for k=1:size(tmp1,1)
+                dynareParallelGetFiles([OutputFileName(i,1) {tmp1(k,:)}],PRCDir,Parallel(indPC));
             end
         end
         % check if some output file is missing!
-        for i=1:size(OutputFileName,1),
+        for i=1:size(OutputFileName,1)
             tmp1=dynareParallelDir([OutputFileName{i,:}],PRCDir,Parallel(indPC));
             tmp1 = regexp(cellstr(tmp1),strrep([OutputFileName{i,2}],'*','(\w*)'),'match');
             tmp1 = char(tmp1{:});
             tmp2=ls([OutputFileName{i,:}]);
-            for ij=1:size(tmp1,1),
+            for ij=1:size(tmp1,1)
                 icheck = regexp(cellstr(tmp2),tmp1(ij,:),'once');
                 isOutputFileMissing=1;
-                for ik=1:size(tmp2,1),
-                    if ~isempty(icheck{ik}),
+                for ik=1:size(tmp2,1)
+                    if ~isempty(icheck{ik})
                         isOutputFileMissing=0;
                     end
                 end
-                if isOutputFileMissing,
+                if isOutputFileMissing
                     dynareParallelGetFiles([OutputFileName(i,1) {tmp1(ij,:)}],PRCDir,Parallel(indPC));
                 end
             end
         end
 
     end
-    if isfield(fOutputVar,'error'),
+    if isfield(fOutputVar,'error')
         disp(['Job number ',int2str(j),' crashed with error:']);
         iscrash=1;
         disp([fOutputVar.error.message]);
         for jstack=1:length(fOutputVar.error.stack)
-            fOutputVar.error.stack(jstack),
+            fOutputVar.error.stack(jstack)
         end
-    elseif flag_CloseAllSlaves==0,
+    elseif flag_CloseAllSlaves==0
         fOutVar(j)=fOutputVar;
-    elseif j==whoiamCloseAllSlaves,
-        fOutVar=fOutputVar;        
+    elseif j==whoiamCloseAllSlaves
+        fOutVar=fOutputVar;
     end
 end
 
-if flag_CloseAllSlaves==1,
+if flag_CloseAllSlaves==1
     closeSlave(Parallel(1:totSlaves),PRCDir,-1);
 end
 
-if iscrash,
+if iscrash
     error('Remote jobs crashed');
 end
 
-pause(1), % Wait for all remote diary off completed
+pause(1) % Wait for all remote diary off completed
 
 % Cleanup.
 dynareParallelGetFiles('*.log',PRCDir,Parallel(1:totSlaves));
 
 switch Strategy
-    case 0
-        for indPC=1:min(find(nCPU>=totCPU)),
-            if Parallel(indPC).Local == 0
-                dynareParallelRmDir(PRCDir,Parallel(indPC));
-            end
-            
-            if isempty(dir('dynareParallelLogFiles'))
-                [A B C]=rmdir('dynareParallelLogFiles');
-                mkdir('dynareParallelLogFiles');
-            end
-            try
-                copyfile('*.log','dynareParallelLogFiles');
-                mydelete([fname,'*.log']);
-            catch
-            end
-            
-            mydelete(['*_core*_input*.mat']);
-            
+  case 0
+    for indPC=1:min(find(nCPU>=totCPU))
+        if Parallel(indPC).Local == 0
+            dynareParallelRmDir(PRCDir,Parallel(indPC));
         end
-        
-        delete ConcurrentCommand1.bat
-    case 1
-        delete(['temp_input.mat'])
-        if newInstance,
-            if isempty(dir('dynareParallelLogFiles'))
-                [A B C]=rmdir('dynareParallelLogFiles');
-                mkdir('dynareParallelLogFiles');
-            end
+
+        if isempty(dir('dynareParallelLogFiles'))
+            [A B C]=rmdir('dynareParallelLogFiles');
+            mkdir('dynareParallelLogFiles');
         end
-        copyfile('*.log','dynareParallelLogFiles');
-        if newInstance,
-            delete ConcurrentCommand1.bat
+        try
+            copyfile('*.log','dynareParallelLogFiles');
+            mydelete([fname,'*.log']);
+        catch
         end
-        dynareParallelDelete(['comp_status_',fname,'*.mat'],PRCDir,Parallel);
-        for indPC=1:min(find(nCPU>=totCPU)),
-            if Parallel(indPC).Local == 0,
-                dynareParallelDeleteNewFiles(PRCDir,Parallel(indPC),PRCDirSnapshotInit(indPC),'.log');
-                for ifil=1:size(NamFileInput,1),
-                    dynareParallelDelete([NamFileInput{ifil,:}],PRCDir,Parallel(indPC));
-                end
+
+        mydelete(['*_core*_input*.mat']);
+
+    end
+
+    delete ConcurrentCommand1.bat
+  case 1
+    delete(['temp_input.mat'])
+    if newInstance
+        if isempty(dir('dynareParallelLogFiles'))
+            [A B C]=rmdir('dynareParallelLogFiles');
+            mkdir('dynareParallelLogFiles');
+        end
+    end
+    copyfile('*.log','dynareParallelLogFiles');
+    if newInstance
+        delete ConcurrentCommand1.bat
+    end
+    dynareParallelDelete(['comp_status_',fname,'*.mat'],PRCDir,Parallel);
+    for indPC=1:min(find(nCPU>=totCPU))
+        if Parallel(indPC).Local == 0
+            dynareParallelDeleteNewFiles(PRCDir,Parallel(indPC),PRCDirSnapshotInit(indPC),'.log');
+            for ifil=1:size(NamFileInput,1)
+                dynareParallelDelete([NamFileInput{ifil,:}],PRCDir,Parallel(indPC));
             end
         end
+    end
 end
\ No newline at end of file
diff --git a/matlab/parallel/slaveParallel.m b/matlab/parallel/slaveParallel.m
index d7275a4fdb10f9a07a17d81a521c96d3cec9ce4b..5e3fe460cea6960cba4c62f478bc18c41162e000 100644
--- a/matlab/parallel/slaveParallel.m
+++ b/matlab/parallel/slaveParallel.m
@@ -2,7 +2,7 @@ function slaveParallel(whoiam,ThisMatlab)
 % PARALLEL CONTEXT
 % In a parallelization context, this function is launched on slave
 % machines, to initialize MATLAB and DYNARE environment and waits for
-% instructions sent by the Master. 
+% instructions sent by the Master.
 % This function is invoked by masterParallel only when the strategy (1),
 % i.e. always open, is actived.
 %
@@ -12,10 +12,10 @@ function slaveParallel(whoiam,ThisMatlab)
 %                       cluster.
 %  o ThisMatlab [int]   index number of this slave machine in the cluster.
 %
-% OUTPUTS 
-%   None  
+% OUTPUTS
+%   None
 
-% Copyright (C) 2006-2012 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -48,9 +48,9 @@ dynareroot = dynare_config();
 load( ['slaveParallel_input',int2str(whoiam)]);
 
 %Loads fGlobalVar Parallel.
-if exist('fGlobalVar'),
+if exist('fGlobalVar')
     globalVars = fieldnames(fGlobalVar);
-    for j=1:length(globalVars),
+    for j=1:length(globalVars)
         eval(['global ',globalVars{j},';']);
         evalin('base',['global ',globalVars{j},';']);
     end
@@ -65,50 +65,50 @@ end
 t0=clock;
 fslave = dir( ['slaveParallel_input',int2str(whoiam),'.mat']);
 
-while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',int2str(whoiam),'.txt'])),
-    if ~isempty(dir(['stayalive',int2str(whoiam),'.txt'])),
+while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',int2str(whoiam),'.txt']))
+    if ~isempty(dir(['stayalive',int2str(whoiam),'.txt']))
         t0=clock;
         delete(['stayalive',int2str(whoiam),'.txt']);
     end
     % I wait for 20 min or while mater asks to exit (i.e. it cancels fslave file)
-    pause(1);
-    
+    pause(1)
+
     fjob = dir(['slaveJob',int2str(whoiam),'.mat']);
-    
-    if ~isempty(fjob),
+
+    if ~isempty(fjob)
         clear fGlobalVar fInputVar fblck nblck fname
-        
+
         while(1)
             Go=0;
-            
+
             Go=fopen(['slaveJob',int2str(whoiam),'.mat']);
-            
-            if Go>0    
+
+            if Go>0
                 fclose(Go);
-                pause(1);
+                pause(1)
                 load(['slaveJob',int2str(whoiam),'.mat']);
                 break
             else
                 % Only for testing, will be remouved!
-                
+
                 %                if isunix
                 %                  E1=fopen('/home/ivano/Works/Errore-slaveParallel.txt','w+');
                 %                  fclose(E1);
-                %                else            
+                %                else
                 %                  E1=fopen('c:\dynare_calcs\Errore-slaveParallel.txt','w+');
                 %                  fclose(E1);
                 %                end
-                
+
             end
         end
-        
+
         funcName=fname;  % Update global job name.
 
         if exist('fGlobalVar') && ~isempty (fGlobalVar)
             globalVars = fieldnames(fGlobalVar);
-            for j=1:length(globalVars),
+            for j=1:length(globalVars)
                 info_whos = whos(globalVars{j});
-                if isempty(info_whos) || ~info_whos.global,
+                if isempty(info_whos) || ~info_whos.global
                     eval(['global ',globalVars{j},';']);
                     evalin('base',['global ',globalVars{j},';']);
                 end
@@ -120,13 +120,13 @@ while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',in
         end
         delete(['slaveJob',int2str(whoiam),'.mat']);
         fInputVar.Parallel = Parallel;
-        
+
         % Launch the routine to be run in parallel.
-        try,
-            tic,
+        try
+            tic
             fOutputVar = feval(fname, fInputVar ,fblck, nblck, whoiam, ThisMatlab);
-            toc,
-            if isfield(fOutputVar,'OutputFileName'),
+            toc
+            if isfield(fOutputVar,'OutputFileName')
                 OutputFileName = fOutputVar.OutputFileName;
             else
                 OutputFileName = '';
@@ -136,8 +136,8 @@ while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',in
 
                 % Save the output result.
                 save([ fname,'_output_',int2str(whoiam),'.mat'],'fOutputVar' );
-%                 keyboard,
-                if isfield(fOutputVar,'CloseAllSlaves'),
+                %                 keyboard,
+                if isfield(fOutputVar,'CloseAllSlaves')
                     CloseAllSlaves = 1;
                     fOutputVar = rmfield(fOutputVar,'CloseAllSlaves');
                     save([ fname,'_output_',int2str(whoiam),'.mat'],'fOutputVar' )
@@ -150,7 +150,7 @@ while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',in
 
             disp(['Job ',fname,' on CPU ',int2str(whoiam),' completed.']);
             t0 =clock; % Re-set waiting time of 20 mins
-        catch,
+        catch
             theerror = lasterror;
             if strfind(theerror.message,'Master asked to break the job')
                 disp(['Job ',fname,' on CPU ',int2str(whoiam),' broken from master.']);
@@ -162,7 +162,7 @@ while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',in
                 fOutputVar.error = lasterror;
                 save([ fname,'_output_',int2str(whoiam),'.mat'],'fOutputVar' );
                 waitbarString = fOutputVar.error.message;
-                if Parallel(ThisMatlab).Local,
+                if Parallel(ThisMatlab).Local
                     waitbarTitle='Local ';
                 else
                     waitbarTitle=[Parallel(ThisMatlab).ComputerName];
@@ -171,7 +171,7 @@ while (etime(clock,t0)<1200 && ~isempty(fslave)) || ~isempty(dir(['stayalive',in
                 delete(['P_',fname,'_',int2str(whoiam),'End.txt']);
                 break
             end
-            
+
         end
     end
     fslave = dir( ['slaveParallel_input',int2str(whoiam),'.mat']); % Check if Master asks to exit
diff --git a/matlab/parallel/storeGlobalVars.m b/matlab/parallel/storeGlobalVars.m
index cd0470c37a1e809801bd1c05c9f2199b214b4064..79b86aa35198cb1d143f962f88345b2afe83b8c7 100644
--- a/matlab/parallel/storeGlobalVars.m
+++ b/matlab/parallel/storeGlobalVars.m
@@ -1,6 +1,6 @@
 function storeGlobalVars(fname,append)
 % PARALLEL CONTEXT
-% In a parallel context, this function stores all global vars in structure 
+% In a parallel context, this function stores all global vars in structure
 % fGlobalVar and saves it in the file fname.mat
 %
 % INPUTS
@@ -12,7 +12,7 @@ function storeGlobalVars(fname,append)
 % None
 %
 %
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -32,12 +32,12 @@ function storeGlobalVars(fname,append)
 
 GlobalNames = who('global');
 % varlist = '';
-for j=1:length(GlobalNames);
+for j=1:length(GlobalNames)
     eval(['global ',GlobalNames{j},';']);
     eval(['fGlobalVar.',GlobalNames{j},'=',GlobalNames{j},';']);
 end
 
-if nargin<2,
+if nargin<2
     save(fname,'fGlobalVar');
 else
     save(fname,'fGlobalVar','-append');
diff --git a/matlab/parallel/struct2local.m b/matlab/parallel/struct2local.m
index fbe9666f0ba19b093c3db128ddbb31ad4ac8c48d..d45bc12b8c47bd55935f71b287546981f4942763 100644
--- a/matlab/parallel/struct2local.m
+++ b/matlab/parallel/struct2local.m
@@ -6,11 +6,11 @@ function struct2local(S)
 %
 % INPUTS
 %  o S [struc]   This structure possibly containing several fields ...
-%  
+%
 %  OUTPUTS
 %  None
 %
-% Copyright (C) 2009-2010 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -30,6 +30,6 @@ function struct2local(S)
 
 vnam = fieldnames(S);
 
-for j=1:length(vnam),
+for j=1:length(vnam)
     assignin('caller',vnam{j},getfield(S,vnam{j}));
 end
diff --git a/matlab/partial_information/PCL_Part_info_irf.m b/matlab/partial_information/PCL_Part_info_irf.m
index 2fc0ff1d8f3bc374797c9b58f3845598650927f2..0c3c17c2be822567c1cee3067f3d0520356cd693 100644
--- a/matlab/partial_information/PCL_Part_info_irf.m
+++ b/matlab/partial_information/PCL_Part_info_irf.m
@@ -1,11 +1,11 @@
 function  y=PCL_Part_info_irf( H, varobs, ivar, M_, dr, irfpers,ii)
 % sets up parameters and calls part-info kalman filter
-% developed by G Perendia, July 2006 for implementation from notes by Prof. Joe Pearlman to 
-% suit partial information RE solution in accordance with, and based on, the 
+% developed by G Perendia, July 2006 for implementation from notes by Prof. Joe Pearlman to
+% suit partial information RE solution in accordance with, and based on, the
 % Pearlman, Currie and Levine 1986 solution.
-% 22/10/06 - Version 2 for new Riccati with 4 params instead 5 
+% 22/10/06 - Version 2 for new Riccati with 4 params instead 5
 
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -23,8 +23,8 @@ function  y=PCL_Part_info_irf( H, varobs, ivar, M_, dr, irfpers,ii)
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 
-% Recall that the state space is given by the 
-% predetermined variables s(t-1), x(t-1) 
+% Recall that the state space is given by the
+% predetermined variables s(t-1), x(t-1)
 % and the jump variables x(t).
 % The jump variables have dimension NETA
 
@@ -66,7 +66,7 @@ U22=0;
 % determine K1 and K2 observation mapping matrices
 % This uses the fact that measurements are given by L1*s(t)+L2*x(t)
 % and s(t) is expressed in the dynamics as
-% H1*eps(t)+G11*s(t-1)+G12*x(t-1)+G13*x(t).  
+% H1*eps(t)+G11*s(t-1)+G12*x(t-1)+G13*x(t).
 % Thus the observations o(t) can be written in the form
 % o(t)=K1*[eps(t)' s(t-1)' x(t-1)']' + K2*x(t) where
 % K1=[L1*H1 L1*G11 L1*G12] K2=L1*G13+L2
@@ -84,18 +84,18 @@ A21=G1(pd+1:end,1:pd);
 Lambda= nmat*A12+A22;
 I_L=inv(Lambda);
 BB=A12*inv(A22);
-FF=K2*inv(A22);       
-QQ=BB*U22*BB' + U11;        
+FF=K2*inv(A22);
+QQ=BB*U22*BB' + U11;
 UFT=U22*FF';
 AA=A11-BB*A21;
 CCCC=A11-A12*nmat; % F in new notation
 DD=K1-FF*A21; % H in new notation
 EE=K1-K2*nmat;
 RR=FF*UFT+VV;
-if ~any(RR) 
-    % if zero add some dummy measurement err. variance-covariances 
+if ~any(RR)
+    % if zero add some dummy measurement err. variance-covariances
     % with diagonals 0.000001. This would not be needed if we used
-    % the slow solver, or the generalised eigenvalue approach, 
+    % the slow solver, or the generalised eigenvalue approach,
     % but these are both slower.
     RR=eye(size(RR,1))*1.0e-6;
 end
@@ -128,14 +128,14 @@ imp=[impact(1:ss-FL_RANK,:); impact(1:ss-FL_RANK,:)];
 I_PD=(eye(ss-FL_RANK)-PDIDPDRD);
 LL0=[ EE (DD-EE)*I_PD];
 VV = [  dr.PI_TT1 dr.PI_TT2];
-stderr=diag(M_.Sigma_e^0.5);        
+stderr=diag(M_.Sigma_e^0.5);
 irfmat=zeros(size(dr.PI_TT1 ,1),irfpers+1);
-irfst=zeros(size(GG,1),irfpers+1); 
+irfst=zeros(size(GG,1),irfpers+1);
 irfst(:,1)=stderr(ii)*imp(:,ii);
-for jj=2:irfpers+1;
+for jj=2:irfpers+1
     irfst(:,jj)=GG*irfst(:,jj-1);
     irfmat(:,jj-1)=VV*irfst(NX+1:ss-FL_RANK,jj);
-end   
+end
 y = irfmat(:,1:irfpers);
 
 save ([M_.fname '_PCL_PtInfoIRFs_' num2str(ii) '_' deblank(exo_names(ii,:))], 'irfmat','irfst');
diff --git a/matlab/partial_information/PCL_Part_info_moments.m b/matlab/partial_information/PCL_Part_info_moments.m
index fdebe317f737ef6aaed2e89e0934ae05f8ba15cf..bb16b66043251ccb2b49b214d41a6ba726dc4494 100644
--- a/matlab/partial_information/PCL_Part_info_moments.m
+++ b/matlab/partial_information/PCL_Part_info_moments.m
@@ -1,11 +1,11 @@
 function  AutoCOR_YRk=PCL_Part_info_moments( H, varobs, dr,ivar)
 % sets up parameters and calls part-info kalman filter
-% developed by G Perendia, July 2006 for implementation from notes by Prof. Joe Pearlman to 
-% suit partial information RE solution in accordance with, and based on, the 
+% developed by G Perendia, July 2006 for implementation from notes by Prof. Joe Pearlman to
+% suit partial information RE solution in accordance with, and based on, the
 % Pearlman, Currie and Levine 1986 solution.
-% 22/10/06 - Version 2 for new Riccati with 4 params instead 5 
+% 22/10/06 - Version 2 for new Riccati with 4 params instead 5
 
-% Copyright (C) 2006-2012 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -22,8 +22,8 @@ function  AutoCOR_YRk=PCL_Part_info_moments( H, varobs, dr,ivar)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-% Recall that the state space is given by the 
-% predetermined variables s(t-1), x(t-1) 
+% Recall that the state space is given by the
+% predetermined variables s(t-1), x(t-1)
 % and the jump variables x(t).
 % The jump variables have dimension NETA
 
@@ -48,13 +48,13 @@ LL = sparse(1:NOBS,OBS,ones(NOBS,1),NY,NY);
 
 if exist( 'irfpers')==1
     if ~isempty(irfpers)
-        if irfpers<=0, irfpers=20, end;
+        if irfpers<=0, irfpers=20, end
     else
         irfpers=20;
     end
 else
     irfpers=20;
-end      
+end
 
 ss=size(G1,1);
 
@@ -78,7 +78,7 @@ U22=0;
 % determine K1 and K2 observation mapping matrices
 % This uses the fact that measurements are given by L1*s(t)+L2*x(t)
 % and s(t) is expressed in the dynamics as
-% H1*eps(t)+G11*s(t-1)+G12*x(t-1)+G13*x(t).  
+% H1*eps(t)+G11*s(t-1)+G12*x(t-1)+G13*x(t).
 % Thus the observations o(t) can be written in the form
 % o(t)=K1*[eps(t)' s(t-1)' x(t-1)']' + K2*x(t) where
 % K1=[L1*H1 L1*G11 L1*G12] K2=L1*G13+L2
@@ -96,8 +96,8 @@ A21=G1(pd+1:end,1:pd);
 Lambda= nmat*A12+A22;
 I_L=inv(Lambda);
 BB=A12*inv(A22);
-FF=K2*inv(A22);       
-QQ=BB*U22*BB' + U11;        
+FF=K2*inv(A22);
+QQ=BB*U22*BB' + U11;
 UFT=U22*FF';
 % kf_param structure:
 AA=A11-BB*A21;
@@ -105,10 +105,10 @@ CCCC=A11-A12*nmat; % F in new notation
 DD=K1-FF*A21; % H in new notation
 EE=K1-K2*nmat;
 RR=FF*UFT+VV;
-if ~any(RR) 
-    % if zero add some dummy measurement err. variance-covariances 
+if ~any(RR)
+    % if zero add some dummy measurement err. variance-covariances
     % with diagonals 0.000001. This would not be needed if we used
-    % the slow solver, or the generalised eigenvalue approach, 
+    % the slow solver, or the generalised eigenvalue approach,
     % but these are both slower.
     RR=eye(size(RR,1))*1.0e-6;
 end
@@ -150,7 +150,7 @@ diagCovYR0=diag(COV_YR0);
 labels = deblank(M_.endo_names(ivar,:));
 
 if options_.nomoments == 0
-    z = [ sqrt(diagCovYR0(ivar)) diagCovYR0(ivar) ]; 
+    z = [ sqrt(diagCovYR0(ivar)) diagCovYR0(ivar) ];
     title='THEORETICAL MOMENTS';
     headers=char('VARIABLE','STD. DEV.','VARIANCE');
     dyntable(options_,title,headers,labels,z,size(labels,2)+2,16,10);
@@ -168,9 +168,9 @@ end
 
 ar = options_.ar;
 if ar > 0
-    COV_YRk= zeros(nn,ar); 
-    AutoCOR_YRk= zeros(nn,ar); 
-    for k=1:ar;
+    COV_YRk= zeros(nn,ar);
+    AutoCOR_YRk= zeros(nn,ar);
+    for k=1:ar
         COV_P=GAM*COV_P;
         COV_OMEGA= COV_P( end-nn+1:end, end-nn+1:end);
         COV_YRk = VV*COV_OMEGA*VV';
diff --git a/matlab/partial_information/PCL_resol.m b/matlab/partial_information/PCL_resol.m
index ba0b1666fefd3611995a07c304f5029bc14d4bef..8f6bf423926bdb1d19ccb1b64dccaf11645297d3 100644
--- a/matlab/partial_information/PCL_resol.m
+++ b/matlab/partial_information/PCL_resol.m
@@ -17,7 +17,7 @@ function [dr,info]=PCL_resol(ys,check_flag)
 %    info=6:         The jacobian evaluated at the steady state is complex.
 %    info=19:        The steadystate file did not compute the steady state (inconsistent deep parameters).
 %    info=20:        can't find steady state info(2) contains sum of sqare residuals
-%    info=21:        steady state is complex 
+%    info=21:        steady state is complex
 %                               info(2) contains sum of sqare of
 %                               imaginary part of steady state
 %    info=30:        Variance can't be computed
@@ -25,7 +25,7 @@ function [dr,info]=PCL_resol(ys,check_flag)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2001-2012 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -45,7 +45,7 @@ function [dr,info]=PCL_resol(ys,check_flag)
 global M_ options_ oo_
 global it_
 
-jacobian_flag = 0; 
+jacobian_flag = 0;
 
 info = 0;
 
@@ -58,7 +58,7 @@ end
 % check if ys is steady state
 tempex = oo_.exo_simul;
 oo_.exo_simul = repmat(oo_.exo_steady_state',M_.maximum_lag+M_.maximum_lead+1,1);
-if M_.exo_det_nbr > 0 
+if M_.exo_det_nbr > 0
     tempexdet = oo_.exo_det_simul;
     oo_.exo_det_simul = repmat(oo_.exo_det_steady_state',M_.maximum_lag+M_.maximum_lead+1,1);
 end
@@ -70,7 +70,7 @@ if options_.steadystate_flag
     [dr.ys,check1] = feval([M_.fname '_steadystate'],dr.ys,...
                            [oo_.exo_steady_state; ...
                         oo_.exo_det_steady_state]);
-    if size(dr.ys,1) < M_.endo_nbr 
+    if size(dr.ys,1) < M_.endo_nbr
         if length(M_.aux_vars) > 0
             dr.ys = add_auxiliary_variables_to_steadystate(dr.ys,M_.aux_vars,...
                                                            M_.fname,...
@@ -143,5 +143,5 @@ tempex = [];
 
 % 01/01/2003 MJ added dr_algo == 1
 % 08/24/2001 MJ uses Schmitt-Grohe and Uribe (2001) constant correction
-%               in dr.ghs2 
+%               in dr.ghs2
 % 05/26/2003 MJ added temporary values for oo_.exo_simul
diff --git a/matlab/partial_information/PI_gensys.m b/matlab/partial_information/PI_gensys.m
index c46d45d0729af627efd2ffbc1ffac8728cd6c480..589e39dc1b33107ca9512f94a2c7257dc8633cdb 100644
--- a/matlab/partial_information/PI_gensys.m
+++ b/matlab/partial_information/PI_gensys.m
@@ -16,7 +16,7 @@ function [G1pi,C,impact,nmat,TT1,TT2,gev,eu, DD, E2, E5, GAMMA, FL_RANK ]=PI_gen
 % Corrected 10/28/96 by CAS
 
 % Copyright (C) 1996-2009 Christopher Sims
-% Copyright (C) 2010-2011 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -83,12 +83,12 @@ try
     end
     if singular == 1 || strcmp('MATLAB:nearlySingularMatrix',LastWarningID) == 1 || ...
                  strcmp('MATLAB:illConditionedMatrix',LastWarningID)==1 || ...
-                 strcmp('MATLAB:singularMatrix',LastWarningID)==1 
+                 strcmp('MATLAB:singularMatrix',LastWarningID)==1
         [C1,C2,C3,C4, C5, F1, F2, F3, F4, F5, M1, M2, UAVinv, FL_RANK, V01, V02] = PI_gensys_singularC(C1,C2,C3,C4, C5, F1, F2, F3, F4, F5, V01, V02, 0);
     end
     warning('on','MATLAB:singularMatrix');
     warning('on','MATLAB:nearlySingularMatrix');
-    if (any(any(isinf(UAVinv))) || any(any(isnan(UAVinv)))) 
+    if (any(any(isinf(UAVinv))) || any(any(isnan(UAVinv))))
         if(options_.ACES_solver==1)
             disp('ERROR! saving PI_gensys_data_dump');
             save PI_gensys_data_dump
@@ -96,7 +96,7 @@ try
         else
             warning('PI_gensys: Evading inversion of zero matrix UAVinv=inv(U02''*a1*V02)!');
             eu=[0,0];
-            return;
+            return
         end
     end
 catch
@@ -131,8 +131,8 @@ G23=eye(FL_RANK);
 num_inst=0;
 
 % New Definitions
-Ze11=zeros(NX,NX); 
-Ze12=zeros(NX,(n-FL_RANK)); 
+Ze11=zeros(NX,NX);
+Ze12=zeros(NX,(n-FL_RANK));
 Ze134=zeros(NX,FL_RANK);
 Ze31=zeros(FL_RANK,NX);
 
@@ -149,7 +149,7 @@ impact=[eye(NX,NX); zeros(n+FL_RANK,NX)];
 if(options_.ACES_solver==1)
     if isfield(lq_instruments,'names')
         num_inst=size(lq_instruments.names,1);
-        if num_inst>0 
+        if num_inst>0
             i_var=lq_instruments.inst_var_indices;
             N1=UAVinv*U02'*lq_instruments.B1;
             N3=-FF*N1+Sinv*U01'*lq_instruments.B1;
@@ -171,14 +171,14 @@ if(options_.ACES_solver==1)
             zeros(num_inst,size(E3,2)), II;
           ];
     eu =[1; 1], nmat=[], gev=[];
-    return; % do not check B&K compliancy
+    return % do not check B&K compliancy
 end
 
 G0pi=eye(n+FL_RANK+NX);
 try
-    % In Matlab: [aa bb q z v w] = qz(a,b) s.t. qaz = aa, qbz = bb % 
+    % In Matlab: [aa bb q z v w] = qz(a,b) s.t. qaz = aa, qbz = bb %
     % In Octave: [aa bb q z v w] = qz(a,b) s.t. q'az = aa, q'bz=bb %
-    % and qzcomplex() extension based on lapack zgges produces same 
+    % and qzcomplex() extension based on lapack zgges produces same
     % qz output for Octave as Matlab qz() does for Matlab thus:
     if isoctave
         [a b q z]=qzcomplex(G0pi,G1pi);
@@ -192,12 +192,12 @@ catch
         disp(['PI_Gensys: ' lerror.message]);
         if 0==strcmp('MATLAB:qz:matrixWithNaNInf',lerror.identifier)
             disp '** Unexpected Error PI_Gensys:qz: ** :';
-            button=questdlg('Continue Y/N?','Unexpected Error in qz','No','Yes','Yes'); 
-            switch button 
-              case 'No' 
+            button=questdlg('Continue Y/N?','Unexpected Error in qz','No','Yes','Yes');
+            switch button
+              case 'No'
                 error ('Terminated')
                 %case 'Yes'
-                
+
             end
         end
         G1pi=[];impact=[];nmat=[]; gev=[];
@@ -206,11 +206,11 @@ catch
     catch
         disp '** Unexpected Error in qz ** :';
         disp lerror.message;
-        button=questdlg('Continue Y/N?','Unexpected Error in qz','No','Yes','Yes'); 
-        switch button 
-          case 'No' 
-            error ('Terminated') 
-          case 'Yes' 
+        button=questdlg('Continue Y/N?','Unexpected Error in qz','No','Yes','Yes');
+        switch button
+          case 'No'
+            error ('Terminated')
+          case 'Yes'
             G1pi=[];impact=[];nmat=[]; gev=[];
             eu=[-2;-2];
             return
@@ -257,7 +257,7 @@ if zxz
 end
 if (FL_RANK ~= nunstab && options_.ACES_solver~=1)
     disp(['Number of unstable variables ' num2str(nunstab)]);
-    disp( ['does not match number of expectational equations ' num2str(FL_RANK)]); 
+    disp( ['does not match number of expectational equations ' num2str(FL_RANK)]);
     nmat=[];% gev=[];
     eu=[-2;-2];
     return
diff --git a/matlab/partial_information/PI_gensys_singularC.m b/matlab/partial_information/PI_gensys_singularC.m
index 5dc26ec63aae5c94b0ff02de4b03745a81922127..b0c085fafcf3a6e98106f871b2a657805ce389c7 100644
--- a/matlab/partial_information/PI_gensys_singularC.m
+++ b/matlab/partial_information/PI_gensys_singularC.m
@@ -1,13 +1,13 @@
 function [C1,C2,C3,C4, C5, F1, F2, F3, F4, F5, M1, M2, UAVinv, FL_RANK, V01, V02]=PI_gensys_singularC(C1in, C2in, C3in, C4in, C5in, F1, F2, F3, F4, F5, V01, V02, level)
 % [C1,C2,C3,C4, C5, F1, F2, F3, F4, F5, M1, M2, UAVinv,FL_RANK, V01, V02]...
 %         =PI_gensys_singularC(C1in, C2in, C3in, C4in, C5in, F1, F2, F3, F4, F5, V01, V02, level)
-% 
+%
 % Recursive extension for PI_gensys function PCL general DSGE solver
-% devised by Prof. Joseph Pearlman 
+% devised by Prof. Joseph Pearlman
 % developed by George Perendia
 % December 2010
 
-% Copyright (C) 1996-2011 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -86,7 +86,4 @@ catch
     [errmsg, errcode]=lasterr;
     warning(['error callig PI_gensys_singularC: ' errmsg ],'errcode');
     error('errcode',['error callig PI_gensys_singularC: ' errmsg ]);
-end
-
-return;
-
+end
\ No newline at end of file
diff --git a/matlab/partial_information/add_auxiliary_variables_to_steadystate.m b/matlab/partial_information/add_auxiliary_variables_to_steadystate.m
index d99e36ebb245448ffbd725067974bbda8159d87e..f90e7f6b0e37fea8bca185414fa5c685110786eb 100644
--- a/matlab/partial_information/add_auxiliary_variables_to_steadystate.m
+++ b/matlab/partial_information/add_auxiliary_variables_to_steadystate.m
@@ -2,7 +2,7 @@ function ys1 = add_auxiliary_variables_to_steadystate(ys,aux_vars,fname, ...
                                                   exo_steady_state, exo_det_steady_state,params, byte_code)
 % Add auxiliary variables to the steady state vector
 
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -21,7 +21,7 @@ function ys1 = add_auxiliary_variables_to_steadystate(ys,aux_vars,fname, ...
 n = length(aux_vars);
 ys1 = [ys;zeros(n,1)];
 
-for i=1:n+1;
+for i=1:n+1
     if byte_code
         [info, res] = bytecode('static','evaluate',ys1,...
                                [exo_steady_state; ...
@@ -30,7 +30,7 @@ for i=1:n+1;
         res = feval([fname '_static'],ys1,...
                     [exo_steady_state; ...
                      exo_det_steady_state],params);
-    end;
+    end
     for j=1:n
         el = aux_vars(j).endo_index;
         ys1(el) = ys1(el)-res(el);
diff --git a/matlab/partial_information/disc_riccati_fast.m b/matlab/partial_information/disc_riccati_fast.m
index 4a0bd0401838a17796c692fca2b617b996278d5e..c97da7a12603e43a53b3915f4ac52ebc94bee830 100644
--- a/matlab/partial_information/disc_riccati_fast.m
+++ b/matlab/partial_information/disc_riccati_fast.m
@@ -1,17 +1,17 @@
 function Z=disc_riccati_fast(F,D,R,H,ch)
 % function Z=disc_riccati_fast(F,D,R,H,ch)
-% 
-% Solves discrete Riccati Equation: 
+%
+% Solves discrete Riccati Equation:
 % Z=FZF' - FZD'inv(DZD'+R)DZF' + H
-% Using the Doubling Algorithm 
+% Using the Doubling Algorithm
 %
-% George Perendia: based on the doubling algorithm for Riccati   
-% and the disclyap_fast function provided by Prof. Joe Pearlman 
+% George Perendia: based on the doubling algorithm for Riccati
+% and the disclyap_fast function provided by Prof. Joe Pearlman
 % V.1 19/5/2006
 % V.2 22/10/06
 % =================================================================
 
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -28,16 +28,16 @@ function Z=disc_riccati_fast(F,D,R,H,ch)
 % 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 || isempty( ch ) == 1 
-    flag_ch = 0; 
-else 
-    flag_ch = 1; 
-end 
+if nargin == 4 || isempty( ch ) == 1
+    flag_ch = 0;
+else
+    flag_ch = 1;
+end
 
 
 % intialisation
 tol = 1e-10; % iteration convergence threshold
-P0=H; 
+P0=H;
 X0=F;
 if ~any(R) % i.e. ==0
     warning('Dangerously evading inversion of zero matrix!');
@@ -50,21 +50,21 @@ I=eye(size(POYO));
 clear POYO;
 
 % iterate Riccati equation solution
-matd=1; 
+matd=1;
 count=0;
 while matd > tol && count < 100
     INVPY=inv(I+P0*Y0);
-    P1=X0*INVPY*P0*X0'+ P0; 
-    Y1=X0'*Y0*INVPY*X0+ Y0; 
-    X1=X0*INVPY*X0; 
-    matd=sum( sum(abs( P1 - P0 ))); 
+    P1=X0*INVPY*P0*X0'+ P0;
+    Y1=X0'*Y0*INVPY*X0+ Y0;
+    X1=X0*INVPY*X0;
+    matd=sum( sum(abs( P1 - P0 )));
     %    P0=(P1+P1')/2
-    P0=P1; 
+    P0=P1;
     X0=X1;
     Y0=Y1;
     count=count+1;
     %    matd;
-end 
+end
 
 Z=(P0+P0')/2;
 %Z=P0
@@ -75,17 +75,17 @@ if count==100
     %    error.identifier='Riccati not converged!'
     %    error
 end
-%if count >5 
+%if count >5
 %    disp('Riccati count= ');
 %    count
 %end
 
-clear X0 X1 Y0 Y1 P1 I INVPY; 
+clear X0 X1 Y0 Y1 P1 I INVPY;
 
-% Check that X is positive definite 
-if flag_ch==1 
-    [C,p]=chol(Z); 
-    if p ~= 0 
+% Check that X is positive definite
+if flag_ch==1
+    [C,p]=chol(Z);
+    if p ~= 0
         error('Z is not positive definite')
-    end 
-end 
+    end
+end
diff --git a/matlab/partial_information/disclyap_fast.m b/matlab/partial_information/disclyap_fast.m
index 3e101a7a6b1b471c11b52b3992173b40ae16f107..5dfcfe4b5657ec806d4a6953fae971d7b80efb40 100644
--- a/matlab/partial_information/disclyap_fast.m
+++ b/matlab/partial_information/disclyap_fast.m
@@ -3,23 +3,23 @@ function [X,exitflag]=disclyap_fast(G,V,tol,check_flag)
 % Inputs:
 %   - G             [double]    first input matrix
 %   - V             [double]    second input matrix
-%   - tol           [scalar]    tolerance criterion 
+%   - tol           [scalar]    tolerance criterion
 %   - check_flag    empty of non-empty             if non-empty: check positive-definiteness
 % Outputs:
 %   - X             [double]    solution matrix
 %   - exitflag      [scalar]    0 if solution is found, 1 otherwise
 %
-% Solve the discrete Lyapunov Equation 
-% X=G*X*G'+V 
-% Using the Doubling Algorithm 
+% Solve the discrete Lyapunov Equation
+% X=G*X*G'+V
+% Using the Doubling Algorithm
 %
-% If check_flag is defined then the code will check if the resulting X 
-% is positive definite and generate an error message if it is not 
-% 
-% Joe Pearlman and Alejandro Justiniano 
-% 3/5/2005 
+% If check_flag is defined then the code will check if the resulting X
+% is positive definite and generate an error message if it is not
+%
+% Joe Pearlman and Alejandro Justiniano
+% 3/5/2005
 
-% Copyright (C) 2010-2016 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -36,40 +36,40 @@ function [X,exitflag]=disclyap_fast(G,V,tol,check_flag)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-if nargin <= 3 || isempty( check_flag ) == 1 
-    flag_ch = 0; 
-else 
-    flag_ch = 1; 
-end 
+if nargin <= 3 || isempty( check_flag ) == 1
+    flag_ch = 0;
+else
+    flag_ch = 1;
+end
 exitflag=0;
 
-P0=V; 
-A0=G; 
+P0=V;
+A0=G;
 
-matd=1; 
+matd=1;
 iter=1;
-while matd > tol && iter< 2000 
-    P1=P0+A0*P0*A0'; 
-    A1=A0*A0;  
-    matd=max( max( abs( P1 - P0 ) ) ); 
-    P0=P1; 
-    A0=A1; 
+while matd > tol && iter< 2000
+    P1=P0+A0*P0*A0';
+    A1=A0*A0;
+    matd=max( max( abs( P1 - P0 ) ) );
+    P0=P1;
+    A0=A1;
     iter=iter+1;
-end 
+end
 if iter==5000
     X=NaN(P0);
     exitflag=1;
     return
 end
-clear A0 A1 P1; 
+clear A0 A1 P1;
 
-X=(P0+P0')/2; 
+X=(P0+P0')/2;
 
-% Check that X is positive definite 
-if flag_ch==1 
-    [C,p]=chol(X); 
-    if p ~= 0 
+% Check that X is positive definite
+if flag_ch==1
+    [C,p]=chol(X);
+    if p ~= 0
         exitflag=1;
         error('X is not positive definite')
-    end 
-end 
\ No newline at end of file
+    end
+end
\ No newline at end of file
diff --git a/matlab/partial_information/dr1_PI.m b/matlab/partial_information/dr1_PI.m
index 0475d4befc4c44791fad2406755f315981f1bee7..04fe8d92674be5255da148e260d4627fb9ffff4c 100644
--- a/matlab/partial_information/dr1_PI.m
+++ b/matlab/partial_information/dr1_PI.m
@@ -6,7 +6,7 @@ function [dr,info,M_,options_,oo_] = dr1_PI(dr,task,M_,options_,oo_)
 % Prepares System as
 %        A0*E_t[y(t+1])+A1*y(t)=A2*y(t-1)+c+psi*eps(t)
 % with z an exogenous variable process.
-% and calls PI_Gensys.m solver 
+% and calls PI_Gensys.m solver
 % based on Pearlman et al 1986 paper and derived from
 % C.Sims' gensys linear solver.
 % to return solution in format
@@ -16,31 +16,31 @@ function [dr,info,M_,options_,oo_] = dr1_PI(dr,task,M_,options_,oo_)
 %   dr         [matlab structure] Decision rules for stochastic simulations.
 %   task       [integer]          if task = 0 then dr1 computes decision rules.
 %                                 if task = 1 then dr1 computes eigenvalues.
-%   M_         [matlab structure] Definition of the model.           
+%   M_         [matlab structure] Definition of the model.
 %   options_   [matlab structure] Global options.
-%   oo_        [matlab structure] Results 
-%    
+%   oo_        [matlab structure] Results
+%
 % OUTPUTS
 %   dr         [matlab structure] Decision rules for stochastic simulations.
 %   info       [integer]          info=1: the model doesn't define current variables uniquely
-%                                 info=2: problem in mjdgges.dll info(2) contains error code. 
+%                                 info=2: problem in mjdgges.dll info(2) contains error code.
 %                                 info=3: BK order condition not satisfied info(2) contains "distance"
 %                                         absence of stable trajectory.
 %                                 info=4: BK order condition not satisfied info(2) contains "distance"
 %                                         indeterminacy.
 %                                 info=5: BK rank condition not satisfied.
-%   M_         [matlab structure]            
+%   M_         [matlab structure]
 %   options_   [matlab structure]
 %   oo_        [matlab structure]
-%  
+%
 % ALGORITHM
 %   ...
-%    
+%
 % SPECIAL REQUIREMENTS
 %   none.
-%  
+%
 
-% Copyright (C) 1996-2012 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -66,9 +66,9 @@ xlen = M_.maximum_endo_lead + M_.maximum_endo_lag + 1;
 
 if (options_.aim_solver == 1)
     options_.aim_solver == 0;
-    warning('You can not use AIM with Part Info solver. AIM ignored'); 
+    warning('You can not use AIM with Part Info solver. AIM ignored');
 end
-if (options_.order > 1) 
+if (options_.order > 1)
     warning('You can not use order higher than 1 with Part Info solver. Order 1 assumed');
     options_.order =1;
 end
@@ -101,11 +101,11 @@ else
     iyv = iyv(:);
     iyr0 = find(iyv) ;
     it_ = M_.maximum_lag + 1 ;
-    
+
     if M_.exo_nbr == 0
         oo_.exo_steady_state = [] ;
     end
-    
+
 
     if options_.ACES_solver == 1
         sim_ruleids=[];
@@ -172,15 +172,15 @@ sdyn = M_.endo_nbr - nstatic;
 k0 = M_.lead_lag_incidence(M_.maximum_endo_lag+1,order_var);
 k1 = M_.lead_lag_incidence(find([1:klen] ~= M_.maximum_endo_lag+1),:);
 
-if (options_.aim_solver == 1) 
+if (options_.aim_solver == 1)
     error('Anderson and Moore AIM solver is not compatible with Partial Information models');
 end % end if useAIM and...
 
     % If required, try PCL86 solver, that is, if not the check being
-    % performed only and if it is 1st order 
+    % performed only and if it is 1st order
     % create sparse, extended jacobia AA:
     nendo=M_.endo_nbr; % = size(aa,1)
-    
+
 
     if(options_.ACES_solver==1)
         %if ~isfield(lq_instruments,'names')
@@ -239,8 +239,8 @@ end % end if useAIM and...
     %     E_t z(t)
     %     E_t z(t+1)
     %     E_t z(t+2)
-    %     E_t z(t+3) 
-    
+    %     E_t z(t+3)
+
     % partition jacobian:
     jlen=M_.nspred+M_.nsfwrd+M_.endo_nbr+M_.exo_nbr; % length of jacobian
     PSI=-jacobia_(:, jlen-M_.exo_nbr+1:end); % exog
@@ -253,12 +253,12 @@ end % end if useAIM and...
         AA2=AA0; % empty A2 and A3
         AA3=AA0;
         if xlen==nendo % && M_.maximum_lag <=1 && M_.maximum_lead <=1 % apply a shortcut
-            AA1=jacobia_(:,nspred+1:nspred+nendo); 
+            AA1=jacobia_(:,nspred+1:nspred+nendo);
             if M_.maximum_lead ==1
                 fnd = find(lead_lag(:,M_.maximum_lag+2));
                 AA0(:, fnd)= jacobia_(:,nonzeros(lead_lag(:,M_.maximum_lag+2))); %forwd jacobian
             end
-            if nspred>0 && M_.maximum_lag ==1  
+            if nspred>0 && M_.maximum_lag ==1
                 fnd = find(lead_lag(:,1));
                 AA2(:, fnd)= jacobia_(:,nonzeros(lead_lag(:,1))); %backward
             end
@@ -266,7 +266,7 @@ end % end if useAIM and...
         if nendo-xlen==num_inst
             PSI=[PSI;zeros(num_inst, M_.exo_nbr)];
             % AA1 contemporary
-            AA_all=jacobia_(:,nspred+1:nspred+nendo); 
+            AA_all=jacobia_(:,nspred+1:nspred+nendo);
             AA1=AA_all(:,lq_instruments.m_var); % endo without instruments
             lq_instruments.ij1=AA_all(:,lq_instruments.inst_var_indices); %  instruments only
             lq_instruments.B1=-[lq_instruments.ij1; eye(num_inst)];
@@ -281,7 +281,7 @@ end % end if useAIM and...
                 lq_instruments.B0=[lq_instruments.ij0; eye(num_inst)];
                 AA0=[AA0, zeros(xlen,num_inst); zeros(num_inst,xlen+num_inst)];
             end
-            if nspred>0 && M_.maximum_lag ==1  
+            if nspred>0 && M_.maximum_lag ==1
                 AA_all(:,:)=0.0;
                 fnd = find(lead_lag(:,1));
                 AA_all(:, fnd)= jacobia_(:,nonzeros(lead_lag(:,1))); %backward
@@ -312,7 +312,7 @@ end % end if useAIM and...
     NX=M_.exo_nbr; % no of exogenous varexo shock variables.
     NETA=nfwrd+nboth; % total no of exp. errors  set to no of forward looking equations
     FL_RANK=rank(AA0); % nfwrd+nboth; % min total no of forward looking equations and vars
-    
+
     try
         % call [G1pi,C,impact,nmat,TT1,TT2,gev,eu]=PI_gensys(a0,a1,a2,c,PSI,NX,NETA,NO_FL_EQS)
         % System given as
@@ -348,13 +348,13 @@ end % end if useAIM and...
             [G1pi,CC,impact,nmat,TT1,TT2,gev,eu, DD, E2,E5, GAMMA, FL_RANK]=PI_gensys(AA0,AA1,-AA2,AA3,cc,PSI,NX,NETA,FL_RANK, M_, options_);
         end
 
-        % reuse some of the bypassed code and tests that may be needed 
+        % reuse some of the bypassed code and tests that may be needed
         if (eu(1) ~= 1 || eu(2) ~= 1) && options_.ACES_solver==0
             info(1) = abs(eu(1)+eu(2));
             info(2) = 1.0e+8;
             %     return
         end
-        
+
         dr.PI_ghx=G1pi;
         dr.PI_ghu=impact;
         dr.PI_TT1=TT1;
@@ -369,7 +369,7 @@ end % end if useAIM and...
         dr.ghu=impact;
         dr.eigval = eig(G1pi);
         dr.rank=FL_RANK;
-        
+
         if options_.ACES_solver==1
             betap=options_.planner_discount;
             sigma_cov=M_.Sigma_e;
@@ -390,8 +390,8 @@ end % end if useAIM and...
             ACES.Q=DYN_Q;
             ACES.W=W;
             NY=nendo-num_inst;
-            
-            % save the followings in a subdirectory - BY    
+
+            % save the followings in a subdirectory - BY
             save ([ACES_DirectoryName,'/',M_.fname '_ACESLQ_Matrices'], 'ACES');
             save ([ACES_DirectoryName,'/',M_.fname '_ACESLQ_GAMMA'], 'GAMMA');
             save ([ACES_DirectoryName,'/',M_.fname '_ACESLQ_A.txt'], 'G1pi', '-ascii', '-double', '-tabs');
@@ -449,8 +449,6 @@ end % end if useAIM and...
         end
     end
 
-    % TODO: 
+    % TODO:
     % if options_.loglinear == 1
-    % if exogenous deterministic variables
-    
-    return;
+    % if exogenous deterministic variables
\ No newline at end of file
diff --git a/matlab/particles b/matlab/particles
index 285d5c171104e44e1a5d2fe30f062be08dbab8cb..84d213ea3e705f36871bc8f960d175a330fd71de 160000
--- a/matlab/particles
+++ b/matlab/particles
@@ -1 +1 @@
-Subproject commit 285d5c171104e44e1a5d2fe30f062be08dbab8cb
+Subproject commit 84d213ea3e705f36871bc8f960d175a330fd71de
diff --git a/matlab/perfect-foresight-models/det_cond_forecast.m b/matlab/perfect-foresight-models/det_cond_forecast.m
index e261de89c3657bb5674c94cb7fb4d7c9f23b911d..ee177d8306ae5e6ff8bc3f270c236e3e76f53989 100644
--- a/matlab/perfect-foresight-models/det_cond_forecast.m
+++ b/matlab/perfect-foresight-models/det_cond_forecast.m
@@ -12,7 +12,7 @@ function data_set = det_cond_forecast(varargin)
 %  dataset                [dseries]     Returns a dseries containing the forecasted endgenous variables and shocks
 %
 %
-% Copyright (C) 2013-2016 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -34,9 +34,9 @@ pp = 2;
 initial_conditions = oo_.steady_state;
 verbosity = options_.verbosity;
 if options_.periods == 0
-	options_.periods = 25;
-end;
-%We have to get an initial guess for the conditional forecast 
+    options_.periods = 25;
+end
+%We have to get an initial guess for the conditional forecast
 % and terminal conditions for the non-stationary variables, we
 % use the first order approximation of the rational expectation solution.
 if ~isfield(oo_,'dr') || (isempty(oo_.dr))
@@ -64,7 +64,7 @@ if length(varargin) > 3
     nvars = length(constrained_vars);
     for i = 1:max_periods_simulation
         constraint_index{i} = 1:nvars;
-    end;
+    end
     direct_mode = 0;
     shocks_present = 0;
     controlled_varexo = options_cond_fcst.controlled_varexo;
@@ -82,7 +82,7 @@ if length(varargin) > 3
             error(['Unknown exogenous variable ' controlled_varexo(i,:)]);
         end
     end
-        
+
 else
     % alternative way to call: plan, dset, dates_of_frcst
     plan = varargin{1};
@@ -102,32 +102,33 @@ else
                 s2 = strings(range(range.ndat));
                 error(['the dseries ' inputname(2) ' finish at time ' s1{1} ' before the last period of forecast ' s2{1}]);
             end
-            
+
             sym_dset = dset(dates(-range(1)):dates(range(range.ndat)));
             periods = options_.periods + M_.maximum_lag + M_.maximum_lead;
+            total_periods = periods + range.ndat;
             if isfield(oo_, 'exo_simul')
-                if size(oo_.exo_simul, 1) ~= max(range.ndat + 1, periods)
-                    oo_.exo_simul = repmat(oo_.exo_steady_state',max(range.ndat + 1, periods),1);
+                if size(oo_.exo_simul, 1) ~= total_periods
+                    oo_.exo_simul = repmat(oo_.exo_steady_state',total_periods,1);
                 end
             else
-                oo_.exo_simul = repmat(oo_.exo_steady_state',max(range.ndat + 1, periods),1);
+                oo_.exo_simul = repmat(oo_.exo_steady_state',total_periods,1);
             end
-            
-            oo_.endo_simul = repmat(oo_.steady_state, 1, max(range.ndat + 1, periods));
-            
+
+            oo_.endo_simul = repmat(oo_.steady_state, 1, total_periods);
+
             for i = 1:sym_dset.vobs
                 iy = find(strcmp(strtrim(sym_dset.name{i}), strtrim(plan.endo_names)));
                 if ~isempty(iy)
                     oo_.endo_simul(iy,1:sym_dset.nobs) = sym_dset.data(:, i);
                     initial_conditions(iy) = sym_dset.data(1, i);
-                 else
-                     ix = find(strcmp(strtrim(sym_dset.name{i}), strtrim(plan.exo_names)));
-                     if ~isempty(ix) 
-                         oo_.exo_simul(1, ix) = sym_dset.data(1, i)';
+                else
+                    ix = find(strcmp(strtrim(sym_dset.name{i}), strtrim(plan.exo_names)));
+                    if ~isempty(ix)
+                        oo_.exo_simul(1, ix) = sym_dset.data(1, i)';
                     else
                         %warning(['The variable ' sym_dset.name{i} ' in the dataset ' inputname(2) ' is not a endogenous neither an exogenous variable!!']);
                     end
-                 end
+                end
             end
             for i = 1:length(M_.aux_vars)
                 if M_.aux_vars(i).type == 1 %lag variable
@@ -144,8 +145,9 @@ else
             end
             %Compute the initial path using the the steady-state
             % steady-state
-            for jj = 2 : (options_.periods + 2)
-              oo_.endo_simul(:, jj) = oo_.steady_state;  
+            %for jj = 2 : (options_.periods + 2)
+            for jj = 2 : (range.ndat + 2)
+                oo_.endo_simul(:, jj) = oo_.steady_state;
             end
             missings = isnan(oo_.endo_simul(:,1));
             if any(missings)
@@ -161,9 +163,10 @@ else
                 options_.dynatol.f = 1e-7;
                 [Info, endo, exo] = bytecode('extended_path', plan, oo_.endo_simul, oo_.exo_simul, M_.params, oo_.steady_state, options_.periods);
                 options_.dynatol.f = save_options_dynatol_f;
+
                 if Info == 0
-                  oo_.endo_simul = endo;
-                  oo_.exo_simul = exo;
+                    oo_.endo_simul = endo;
+                    oo_.exo_simul = exo;
                 end
                 endo = endo';
                 endo_l = size(endo(1+M_.maximum_lag:end,:),1);
@@ -176,7 +179,7 @@ else
                     else
                         pos = find(strcmp(dset.name{i},plan.exo_names));
                         if ~isempty(pos)
-                           data_set{dset.name{i}} = dseries(exo(1+M_.maximum_lag:end,pos), plan.date(1),dset.name{i});
+                            data_set{dset.name{i}} = dseries(exo(1+M_.maximum_lag:end,pos), plan.date(1),dset.name{i});
                         end
                     end
                 end
@@ -190,30 +193,30 @@ else
                     end
                 end
                 data_set = merge(dset(dset.dates(1):(plan.date(1)-1)), data_set);
-                return;
+                return
                 union_names = union(data_set.name, dset.name);
                 dif = setdiff(union_names, data_set.name);
                 data_set_nobs = data_set.nobs;
                 for i = 1:length(dif)
                     data_set{dif{i}} = dseries(nan(data_set_nobs,1),plan.date(1), dif(i), dif(i));
-                end;
+                end
                 dif = setdiff(union_names, dset.name);
                 dset_nobs = dset.nobs;
                 for i = 1:length(dif)
                     dset{dif{i}} = dseries(nan(dset_nobs,1),dset.dates(1), dif(i), dif(i));
-                end;
+                end
                 data_set = [dset(dset.dates(1):(plan.date(1)-1)) ; data_set];
-                return;
-            end;
+                return
+            end
         else
-           error('impossible case'); 
-        end;
-            
+            error('impossible case');
+        end
+
     else
         oo_.exo_simul = repmat(oo_.exo_steady_state',options_.periods+2,1);
         oo_.endo_simul = repmat(oo_.steady_state, 1, options_.periods+2);
     end
-    
+
     direct_mode = 1;
     constrained_paths = plan.constrained_paths_;
     constrained_vars = plan.constrained_vars_;
@@ -229,16 +232,16 @@ else
     else
         shocks_present = 0;
     end
-    
+
     total_periods = plan.date;
-    
-end;
+
+end
 
 if ~isfield(options_cond_fcst,'periods') || isempty(options_cond_fcst.periods)
     options_cond_fcst.periods = 100;
 end
 
-options_.periods = 10;   
+options_.periods = 10;
 
 if direct_mode == 1
     n_periods = length(constrained_periods);
@@ -257,7 +260,7 @@ if direct_mode == 1
         else
             init_periods = period_i;
             tp_end = period_i;
-        end;
+        end
         tp0 = tp;
         while tp < init_periods
             tp = tp + 1;
@@ -268,18 +271,18 @@ if direct_mode == 1
             constrained_paths(i, tp - tp0 + 1) = constrained_paths_cell{i}(j + 1);
             tp = tp + 1;
             j = j + 1;
-        end;
-        if tp - tp0 > max_periods_simulation 
+        end
+        if tp - tp0 > max_periods_simulation
             max_periods_simulation = tp - tp0;
-        end;
+        end
     end
     n_nnz = length(sum(is_constraint,2));
     if n_nnz > 0
         constraint_index = cell(n_nnz,1);
         for i= 1:n_nnz
             constraint_index{i} = find(is_constraint(i,:));
-        end;
-    end;
+        end
+    end
     if shocks_present
         n_periods = length(shock_periods);
         shock_paths_cell = shock_paths;
@@ -296,7 +299,7 @@ if direct_mode == 1
             else
                 init_periods = period_i;
                 tp_end = period_i;
-            end;
+            end
             tp0 = tp;
             while tp < init_periods
                 tp = tp + 1;
@@ -307,17 +310,17 @@ if direct_mode == 1
                 shock_paths(i, tp - tp0 + 1) = shock_paths_cell{i}(j + 1);
                 tp = tp + 1;
                 j = j + 1;
-            end;
-            if tp - tp0 > max_periods_simulation 
+            end
+            if tp - tp0 > max_periods_simulation
                 max_periods_simulation = tp - tp0;
-            end;
-        end;
+            end
+        end
         n_nnz = length(sum(is_shock,2));
         if n_nnz > 0
             shock_index = cell(n_nnz, 1);
             for i= 1:n_nnz
                 shock_index{i} = find(is_shock(i,:));
-            end;
+            end
         end
     end
 else
@@ -333,16 +336,16 @@ ny = size(ys,1);
 xs = [oo_.exo_steady_state ; oo_.exo_det_steady_state];
 nx = size(xs,1);
 
-constrained_periods = max_periods_simulation;   
+constrained_periods = max_periods_simulation;
 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;
+    end
 else
     error('det_cond_forecast: to run a deterministic conditional forecast you have to specified the exogenous variables controlled using the option controlled_varexo in forecast command');
-end;
+end
 
 % if n_endo_constrained == 0
 %     options_.ep.use_bytecode = options_.bytecode;
@@ -374,14 +377,14 @@ if isempty(indx_endo_solve_pf)
     pf = 0;
 else
     pf = length(indx_endo_solve_pf);
-end;
+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;
+end
 
 
 eps = options_.solve_tolf;
@@ -411,7 +414,7 @@ if pf && ~surprise
     for j = 1:length(constrained_vars)
         indx_endo(col_count : col_count + constrained_periods - 1) = constrained_vars(j) + (time_index_constraint - 1) * ny;
         col_count = col_count + constrained_periods;
-    end;
+    end
     oo_=make_ex_(M_,options_,oo_);
     oo_=make_y_(M_,options_,oo_);
     it = 1;
@@ -433,9 +436,9 @@ if pf && ~surprise
                     y = oo_.endo_simul(constrained_vars(j), time_index_constraint);
                     r(col_count:col_count+constrained_periods - 1) = (y - constrained_paths(j,1:constrained_periods))';
                     col_count = col_count + constrained_periods;
-                end;
+                end
                 normr = norm(r, 1);
-            end;
+            end
             if (~oo_.deterministic_simulation.status || ~result || normr > normra) && it > 1
                 not_achieved = 1;
                 alpha = alpha / 2;
@@ -443,14 +446,14 @@ if pf && ~surprise
                 for j = controlled_varexo'
                     oo_.exo_simul(time_index_constraint,j) = (old_exo(:,j) + alpha * D_exo(col_count: (col_count + constrained_periods - 1)));
                     col_count = col_count + constrained_periods;
-                end;
+                end
                 disp(['Divergence in  Newton: reducing the path length alpha=' num2str(alpha)]);
                 oo_.endo_simul = repmat(oo_.steady_state, 1, options_cond_fcst.periods + 2);
             else
                 not_achieved = 0;
-            end;
-        end;
-        
+            end
+        end
+
         per = 30;
         z = oo_.endo_simul(:, 1 : per + 2 );
         zx = oo_.exo_simul(1: per + 2,:);
@@ -470,7 +473,7 @@ if pf && ~surprise
                 else
                     data1 = M_;
                     Size = 1;
-                end;
+                end
                 data1 = M_;
                 if (options_.bytecode)
                     [chck, zz, data1]= bytecode('dynamic','evaluate', z, zx, M_.params, oo_.steady_state, k, data1);
@@ -479,16 +482,16 @@ if pf && ~surprise
                     data1.g1_x = g1b(:,end - M_.exo_nbr + 1:end);
                     data1.g1 = g1b(:,1 : end - M_.exo_nbr);
                     chck = 0;
-                end;
+                end
                 mexErrCheck('bytecode', chck);
-            end;
-            if k == 1 
+            end
+            if k == 1
                 g1(1:M_.endo_nbr,-M_.endo_nbr + [cur_indx lead_indx]) = data1.g1(:,M_.nspred + 1:end);
             elseif k == per
                 g1(M_.endo_nbr * (k - 1) + 1 :M_.endo_nbr * k,M_.endo_nbr * (k -2) + [lag_indx cur_indx]) = data1.g1(:,1:M_.nspred + M_.endo_nbr);
             else
                 g1(M_.endo_nbr * (k - 1) + 1 :M_.endo_nbr * k, M_.endo_nbr * (k -2) + [lag_indx cur_indx lead_indx]) = data1.g1;
-            end;
+            end
             l2 = 1;
             pf_c = 1;
             if k <= constrained_periods
@@ -501,17 +504,17 @@ if pf && ~surprise
                         for ii = 2:constrained_periods
                             indx_x(l2) = length(controlled_varexo) + pf * (ii - 2) + constraint_index{k + ii - 1}(pf_c);
                             l2 = l2 + 1;
-                        end;
+                        end
                         pf_c = pf_c + 1;
                         cum_index_d_y_x = [cum_index_d_y_x; constrained_vars(l)];
                     else
                         cum_index_d_y_x = [cum_index_d_y_x; constrained_vars(l) + (k - 1) * M_.endo_nbr];
                     end
                     cum_l1 = cum_l1 + length(l1);
-                end;
-            end;
-        end;
-        
+                end
+            end
+        end
+
         d_y_x = - g1 \ g1_x;
 
         cum_l1 = 0;
@@ -530,25 +533,25 @@ if pf && ~surprise
                 cum_l1 = cum_l1 + length(l1);
             end
             cum_l1 = cum_l1 + length(constrained_vars(j1));
-        end;
-        
-        
-%         col_count = 1;
-%         for j = controlled_varexo'
-%             for time = time_index_constraint
-%                 saved = oo_.exo_simul(time,j);
-%                 oo_.exo_simul(time,j) = oo_.exo_simul(time,j) + eps1;
-%                 simul();
-%                 J1(:,col_count) = (oo_.endo_simul(indx_endo) - ys) / eps1;
-%                 oo_.exo_simul(time,j) = saved;
-%                 col_count = col_count + 1;
-%             end;
-%         end;
-%         J1
-%         sdfmlksdf;
-        
+        end
+
+
+        %         col_count = 1;
+        %         for j = controlled_varexo'
+        %             for time = time_index_constraint
+        %                 saved = oo_.exo_simul(time,j);
+        %                 oo_.exo_simul(time,j) = oo_.exo_simul(time,j) + eps1;
+        %                 simul();
+        %                 J1(:,col_count) = (oo_.endo_simul(indx_endo) - ys) / eps1;
+        %                 oo_.exo_simul(time,j) = saved;
+        %                 col_count = col_count + 1;
+        %             end
+        %         end
+        %         J1
+        %         sdfmlksdf;
+
         disp(['iteration ' int2str(it) ' error = ' num2str(normr)]);
-        
+
         if normr <= eps
             convg = 1;
             disp('convergence achieved');
@@ -561,25 +564,25 @@ if pf && ~surprise
             for j = controlled_varexo'
                 oo_.exo_simul(time_index_constraint,j) = oo_.exo_simul(time_index_constraint,j) + D_exo(col_count: (col_count + constrained_periods - 1));
                 col_count = col_count + constrained_periods - 1;
-            end;
-        end;
+            end
+        end
         it = it + 1;
         normra = normr;
-    end;
+    end
     endo = oo_.endo_simul';
     exo = oo_.exo_simul;
 else
     for t = 1:constrained_periods
-        
-        if direct_mode && ~isempty(is_constraint) 
+
+        if direct_mode && ~isempty(is_constraint)
             [pos_constrained_pf, junk] = find(constrained_perfect_foresight .* is_constraint(t, :)');
             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;
-        
+            end
+
             [pos_constrained_surprise, junk] = find((1-constrained_perfect_foresight) .* is_constraint(t, :)');
             indx_endo_solve_surprise = constrained_vars(pos_constrained_surprise);
 
@@ -587,18 +590,18 @@ else
                 surprise = 0;
             else
                 surprise = length(indx_endo_solve_surprise);
-            end;
-        end;
-        
-        if direct_mode && ~isempty(is_shock) 
+            end
+        end
+
+        if direct_mode && ~isempty(is_shock)
             [pos_shock_pf, junk] = find(shock_perfect_foresight .* is_shock(t, :)');
             indx_endo_solve_pf = shock_vars(pos_shock_pf);
             if isempty(indx_endo_solve_pf)
                 b_pf = 0;
             else
                 b_pf = length(indx_endo_solve_pf);
-            end;
-        
+            end
+
             [pos_shock_surprise, junk] = find((1-shock_perfect_foresight) .* is_shock(t, :)');
             indx_endo_solve_surprise = shock_vars(pos_shock_surprise);
 
@@ -606,9 +609,9 @@ else
                 b_surprise = 0;
             else
                 b_surprise = length(indx_endo_solve_surprise);
-            end;
-        end;
-        
+            end
+        end
+
         disp('===============================================================================================');
         disp(['t=' int2str(t) ' conditional (surprise=' int2str(surprise) ' perfect foresight=' int2str(pf) ') unconditional (surprise=' int2str(b_surprise) ' perfect foresight=' int2str(b_pf) ')']);
         disp('===============================================================================================');
@@ -620,20 +623,20 @@ else
                 exo_init = zeros(size(oo_.exo_simul));
             end
             oo_=make_y_(M_,options_,oo_);
-        end;
+        end
         %exo_init
         oo_.exo_simul = exo_init;
         oo_.endo_simul(:,1) = initial_conditions;
-        
+
         time_index_constraint = maximum_lag + 1:maximum_lag + constrained_periods - t + 1;
-        
+
         if direct_mode
             nb_shocks = length(plan.shock_vars_);
             if nb_shocks > 0
                 shock_index_t = shock_index{t};
                 shock_vars_t = shock_vars(shock_index_t);
                 for shock_indx = shock_index_t
-                    if shock_perfect_foresight(shock_indx) 
+                    if shock_perfect_foresight(shock_indx)
                         oo_.exo_simul(time_index_constraint,shock_vars_t(shock_indx)) = shock_paths(shock_indx,t:constrained_periods);
                     else
                         oo_.exo_simul(maximum_lag + 1,shock_vars_t(shock_indx)) = shock_paths(shock_indx,t);
@@ -650,11 +653,11 @@ else
         for jj = 1 : (options_.periods + 2)
             oo_.endo_simul(:,jj) = oo_.steady_state + oo_.endo_simul(:,jj);
         end
-        
+
         constraint_index_t = constraint_index{t};
         controlled_varexo_t = controlled_varexo(constraint_index_t);
         constrained_vars_t = constrained_vars(constraint_index_t);
-        
+
         second_system_size = surprise + pf * (constrained_periods - t + 1);
         indx_endo = zeros(second_system_size,1);
         col_count = 1;
@@ -665,11 +668,11 @@ else
             else
                 indx_endo(col_count) = constrained_vars(j) + maximum_lag * ny;
                 col_count = col_count + 1;
-            end;
-        end;
-        
+            end
+        end
+
         r = zeros(second_system_size,1);
-        
+
         convg = 0;
         it = 1;
         while ~convg && it <= maxit
@@ -693,20 +696,20 @@ else
                         else
                             oo_.exo_simul(maximum_lag + 1,j) = old_exo(maximum_lag + 1,j) + alpha * D_exo(col_count);
                             col_count = col_count + 1;
-                        end;
-                    end;
+                        end
+                    end
                     disp(['Divergence in  Newton: reducing the path length alpha=' num2str(alpha) ' result=' num2str(result) ' sum(sum)=' num2str(sum(sum(isfinite(oo_.endo_simul(:,time_index_constraint))))) ' ny * length(time_index_constraint)=' num2str(ny * length(time_index_constraint)) ' oo_.deterministic_simulation.status=' num2str(oo_.deterministic_simulation.status)]);
                     oo_.endo_simul = [initial_conditions repmat(oo_.steady_state, 1, options_cond_fcst.periods + 1)];
                 else
                     not_achieved = 0;
-                end;
-            end;
+                end
+            end
             if t==constrained_periods
                 ycc = oo_.endo_simul;
-            end;
+            end
             yc = oo_.endo_simul(:,maximum_lag + 1);
             ys = oo_.endo_simul(indx_endo);
-            
+
             col_count = 1;
             for j = constraint_index_t
                 if constrained_perfect_foresight(j)
@@ -717,9 +720,9 @@ else
                     y = yc(constrained_vars(j));
                     r(col_count) = y - constrained_paths(j,t);
                     col_count = col_count + 1;
-                end;
+                end
             end
-            
+
             disp('computation of derivatives w.r. to exogenous shocks');
 
             per = 30;
@@ -742,7 +745,7 @@ else
                     else
                         data1 = M_;
                         Size = 1;
-                    end;
+                    end
                     data1 = M_;
                     if (options_.bytecode)
                         [chck, zz, data1]= bytecode('dynamic','evaluate', z, zx, M_.params, oo_.steady_state, k, data1);
@@ -751,17 +754,17 @@ else
                         data1.g1_x = g1b(:,end - M_.exo_nbr + 1:end);
                         data1.g1 = g1b(:,1 : end - M_.exo_nbr);
                         chck = 0;
-                    end;
+                    end
                     mexErrCheck('bytecode', chck);
-                end;
-                if k == 1 
+                end
+                if k == 1
                     g1(1:M_.endo_nbr,-M_.endo_nbr + [cur_indx lead_indx]) = data1.g1(:,M_.nspred + 1:end);
                 elseif k == per
                     g1(M_.endo_nbr * (k - 1) + 1 :M_.endo_nbr * k,M_.endo_nbr * (k -2) + [lag_indx cur_indx]) = data1.g1(:,1:M_.nspred + M_.endo_nbr);
                 else
                     g1(M_.endo_nbr * (k - 1) + 1 :M_.endo_nbr * k, M_.endo_nbr * (k -2) + [lag_indx cur_indx lead_indx]) = data1.g1;
-                end;
-                
+                end
+
                 l2 = 1;
                 pf_c = 1;
                 if t + k - 1 <= constrained_periods
@@ -776,25 +779,25 @@ else
                                     for ii = 2:constrained_periods - t + 1
                                         indx_x(l2) = length(controlled_varexo) + pf * (ii - 2) + constraint_index{k + ii - 1}(pf_c);
                                         l2 = l2 + 1;
-                                    end;
+                                    end
                                     pf_c = pf_c + 1;
                                 else
                                     indx_x(l2) = l;
                                     l2 = l2 + 1;
-                                end;
+                                end
                                 cum_index_d_y_x = [cum_index_d_y_x; constrained_vars_t(l)];
                             else
                                 cum_index_d_y_x = [cum_index_d_y_x; constrained_vars_t(l) + (k - 1) * M_.endo_nbr];
                             end
                             cum_l1 = cum_l1 + length(l1);
-                        end;
-                    end;
-                end;
-            end;
-            
+                        end
+                    end
+                end
+            end
+
             d_y_x = - g1 \ g1_x;
 
-            
+
             cum_l1 = 0;
             count_col = 1;
             cum_index_J  = 1:length(cum_index_d_y_x(indx_x));
@@ -816,41 +819,41 @@ else
                     count_col = count_col + 1;
                 end
                 cum_l1 = cum_l1 + length(constrained_vars_t(j1));
-            end;
-
-            
-%             % Numerical computation of the derivatives in the second systme        
-%             J1 = [];
-%             col_count = 1;
-%             for j = constraint_index_t
-%                 j_pos = controlled_varexo(j);
-%                 if constrained_perfect_foresight(j)
-%                     for time = time_index_constraint
-%                         saved = oo_.exo_simul(time,j_pos);
-%                         oo_.exo_simul(time,j_pos) = oo_.exo_simul(time,j_pos) + eps1;
-%                         simul();
-%                         J1(:,col_count) = (oo_.endo_simul(indx_endo) - ys) / eps1;
-%                         oo_.exo_simul(time,j_pos) = saved;
-%                         col_count = col_count + 1;
-%                     end;
-%                 else
-%                     saved = oo_.exo_simul(maximum_lag+1,j_pos);
-%                     oo_.exo_simul(maximum_lag+1,j_pos) = oo_.exo_simul(maximum_lag+1,j_pos) + eps1;
-%                     simul();
-% %                    indx_endo
-%                     J1(:,col_count) = (oo_.endo_simul(indx_endo) - ys) / eps1;
-% %                    J(:,col_count) = (oo_.endo_simul((pp - 1) * M_.endo_nbr + 1: pp * M_.endo_nbr) - ys) / eps1;
-%                     oo_.exo_simul(maximum_lag+1,j_pos) = saved;
-%                     col_count = col_count + 1;
-%                 end;
-%             end;
-%             disp('J1');
-%             disp(full(J1));
-%             sdfmlk;
-            
+            end
+
+
+            %             % Numerical computation of the derivatives in the second systme
+            %             J1 = [];
+            %             col_count = 1;
+            %             for j = constraint_index_t
+            %                 j_pos = controlled_varexo(j);
+            %                 if constrained_perfect_foresight(j)
+            %                     for time = time_index_constraint
+            %                         saved = oo_.exo_simul(time,j_pos);
+            %                         oo_.exo_simul(time,j_pos) = oo_.exo_simul(time,j_pos) + eps1;
+            %                         simul();
+            %                         J1(:,col_count) = (oo_.endo_simul(indx_endo) - ys) / eps1;
+            %                         oo_.exo_simul(time,j_pos) = saved;
+            %                         col_count = col_count + 1;
+            %                     end
+            %                 else
+            %                     saved = oo_.exo_simul(maximum_lag+1,j_pos);
+            %                     oo_.exo_simul(maximum_lag+1,j_pos) = oo_.exo_simul(maximum_lag+1,j_pos) + eps1;
+            %                     simul();
+            % %                    indx_endo
+            %                     J1(:,col_count) = (oo_.endo_simul(indx_endo) - ys) / eps1;
+            % %                    J(:,col_count) = (oo_.endo_simul((pp - 1) * M_.endo_nbr + 1: pp * M_.endo_nbr) - ys) / eps1;
+            %                     oo_.exo_simul(maximum_lag+1,j_pos) = saved;
+            %                     col_count = col_count + 1;
+            %                 end
+            %             end
+            %             disp('J1');
+            %             disp(full(J1));
+            %             sdfmlk;
+
 
             normr = norm(r, 1);
-            
+
             disp(['iteration ' int2str(it) ' error = ' num2str(normr) ' at time ' int2str(t)]);
 
             if normr <= eps
@@ -859,7 +862,7 @@ else
             else
                 % Newton update on exogenous shocks
                 try
-                   D_exo = - J \ r;
+                    D_exo = - J \ r;
                 catch
                     [V, D] = eig(full(J));
                     ev = diag(D);
@@ -867,7 +870,7 @@ else
                     z_root = find(abs(ev) < 1e-4);
                     z_root
                     disp(V(:,z_root));
-                end;
+                end
                 old_exo = oo_.exo_simul;
                 col_count = 1;
                 for j = constraint_index_t
@@ -878,14 +881,14 @@ else
                     else
                         oo_.exo_simul(maximum_lag + 1,j_pos) = oo_.exo_simul(maximum_lag + 1,j_pos) + D_exo(col_count);
                         col_count = col_count + 1;
-                    end;
-                end;
-            end;
+                    end
+                end
+            end
             it = it + 1;
-        end;
+        end
         if ~convg
             error(['convergence not achived at time ' int2str(t) ' after ' int2str(it) ' iterations']);
-        end;
+        end
         for j = constraint_index_t
             j_pos=controlled_varexo(j);
             if constrained_perfect_foresight(j)
@@ -897,20 +900,20 @@ else
                 end
             else
                 exo(maximum_lag + t,j_pos) = oo_.exo_simul(maximum_lag + 1,j_pos);
-            end;
-        end;
+            end
+        end
         past_val = past_val + length(time_index_constraint);
         if t < constrained_periods
             endo(maximum_lag + t,:) = yc;
         else
             endo(maximum_lag + t :maximum_lag + options_cond_fcst.periods ,:) = ycc(:,maximum_lag + 1:maximum_lag + options_cond_fcst.periods - constrained_periods + 1)';
-        end;
+        end
         initial_conditions = yc;
         if maximum_lag > 0
             exo_init(1,:) = exo(maximum_lag + t,:);
-        end;
-    end;
-end;
+        end
+    end
+end
 options_.periods = save_options_periods;
 options_.dynatol.f = save_options_dynatol_f;
 options_.initval_file = save_options_initval_file;
@@ -919,4 +922,4 @@ oo_.endo_simul = endo';
 oo_.exo_simul = exo;
 if direct_mode
     data_set = dseries([endo(2:end,1:M_.orig_endo_nbr) exo(2:end,:)], total_periods(1), {plan.endo_names{:} plan.exo_names{:}}, {plan.endo_names{:} plan.exo_names{:}});
-end;
+end
diff --git a/matlab/perfect-foresight-models/linear_approximation_accuracy.m b/matlab/perfect-foresight-models/linear_approximation_accuracy.m
index e3f9eb521529941ad8c4f96e60f99dd2156c7e94..2899971761a852ece1f1f99e695f137b79f244d9 100644
--- a/matlab/perfect-foresight-models/linear_approximation_accuracy.m
+++ b/matlab/perfect-foresight-models/linear_approximation_accuracy.m
@@ -2,15 +2,15 @@ function err = linear_approximation_accuracy(options_, M_, oo_)
 % Evaluates the accuracy of the linear approximation when solving perfect foresight models, by
 % reporting the max absolute value of the dynamic residuals.
 %
-% INPUTS 
+% INPUTS
 % - options_ [struct] contains various options.
 % - M_       [struct] contains a description of the model.
 % - oo_      [struct] contains results.
 %
-% OUTPUTS 
+% OUTPUTS
 % - err      [double] n*1 vector, evaluation of the accuracy (n is the number of equations).
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/perfect-foresight-models/linear_perfect_foresight_problem.m b/matlab/perfect-foresight-models/linear_perfect_foresight_problem.m
index 306960b4c87d4046b7826cfa053cb5659d67b165..78d9fed418d182339acfa25b89e247e2346288a4 100644
--- a/matlab/perfect-foresight-models/linear_perfect_foresight_problem.m
+++ b/matlab/perfect-foresight-models/linear_perfect_foresight_problem.m
@@ -1,11 +1,11 @@
-function [residuals,JJacobian] = perfect_foresight_problem(y, dynamicjacobian, Y0, YT, ...
-                                           exo_simul, params, steady_state, ...
-                                           maximum_lag, T, ny, i_cols, ...
-                                           i_cols_J1, i_cols_1, i_cols_T, ...
-                                           i_cols_j,nnzJ,jendo,jexog)
+function [residuals,JJacobian] = linear_perfect_foresight_problem(y, dynamicjacobian, Y0, YT, ...
+                                                  exo_simul, params, steady_state, ...
+                                                  maximum_lag, T, ny, i_cols, ...
+                                                  i_cols_J1, i_cols_1, i_cols_T, ...
+                                                  i_cols_j,nnzJ,jendo,jexog)
 % function [residuals,JJacobian] = perfect_foresight_problem(x, model_dynamic, Y0, YT,exo_simul,
 % params, steady_state, maximum_lag, periods, ny, i_cols,i_cols_J1, i_cols_1,
-% i_cols_T, i_cols_j, nnzA) 
+% i_cols_T, i_cols_j, nnzA)
 % computes the residuals and th Jacobian matrix
 % for a perfect foresight problem over T periods.
 %
@@ -19,7 +19,7 @@ function [residuals,JJacobian] = perfect_foresight_problem(y, dynamicjacobian, Y
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/perfect-foresight-models/make_ex_.m b/matlab/perfect-foresight-models/make_ex_.m
index 73ab28f436093c9ebe172d10165a47295d4ab453..4f72590484e4ee29f34fb652998f8c04792476ca 100644
--- a/matlab/perfect-foresight-models/make_ex_.m
+++ b/matlab/perfect-foresight-models/make_ex_.m
@@ -5,16 +5,16 @@ function oo_=make_ex_(M_,options_,oo_)
 %   M_:           Dynare model structure
 %   options_:     Dynare options structure
 %   oo_:          Dynare results structure
-%    
+%
 % OUTPUTS
 %   oo_:          Dynare results structure
 %
 % ALGORITHM
-%   
+%
 % SPECIAL REQUIREMENTS
-%  
+%
 
-% Copyright (C) 1996-2016 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -53,7 +53,7 @@ else
     else
         error('histval and endval cannot be used simultaneously')
     end
-end    
+end
 
 % Initialize oo_.exo_det_simul
 if M_.exo_det_nbr > 0
diff --git a/matlab/perfect-foresight-models/make_y_.m b/matlab/perfect-foresight-models/make_y_.m
index f3c8f686f679c88ef60e5183acdbc0ec1861b5d1..e96333825e78ff103ec33220b825556dd1c2ca0a 100644
--- a/matlab/perfect-foresight-models/make_y_.m
+++ b/matlab/perfect-foresight-models/make_y_.m
@@ -1,22 +1,22 @@
 function oo_=make_y_(M_,options_,oo_)
 % function oo_=make_y_(M_,options_,oo_)
 % forms oo_.endo_simul as guess values for deterministic simulations
-%  
+%
 % INPUTS
 %   M_:           Dynare model structure
 %   options_:     Dynare options structure
 %   oo_:          Dynare results structure
-%    
+%
 % OUTPUTS
 %   oo_:          Dynare results structure
-% 
+%
 % ALGORITHM
 %   ...
 % SPECIAL REQUIREMENTS
 %   none
-%  
+%
 
-% Copyright (C) 1996-2016 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -33,7 +33,7 @@ function oo_=make_y_(M_,options_,oo_)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-global ys0_ 
+global ys0_
 
 if options_.steadystate_flag
     [oo_.steady_state,M_.params,check] = ...
diff --git a/matlab/perfect-foresight-models/perfect_foresight_mcp_problem.m b/matlab/perfect-foresight-models/perfect_foresight_mcp_problem.m
index d4b419308659cec1ac240f50657f66cbc3f6f9f1..eb898322df33fce3da043103b0caabfa177c971b 100644
--- a/matlab/perfect-foresight-models/perfect_foresight_mcp_problem.m
+++ b/matlab/perfect-foresight-models/perfect_foresight_mcp_problem.m
@@ -1,8 +1,8 @@
 function [residuals,JJacobian] = perfect_foresight_mcp_problem(y, dynamic_function, Y0, YT, ...
-                                           exo_simul, params, steady_state, ...
-                                           maximum_lag, T, ny, i_cols, ...
-                                           i_cols_J1, i_cols_1, i_cols_T, ...
-                                           i_cols_j,nnzJ,eq_index)
+                                                  exo_simul, params, steady_state, ...
+                                                  maximum_lag, T, ny, i_cols, ...
+                                                  i_cols_J1, i_cols_1, i_cols_T, ...
+                                                  i_cols_j,nnzJ,eq_index)
 % function [residuals,JJacobian] = perfect_foresight_mcp_problem(y, dynamic_function, Y0, YT, ...
 %                                            exo_simul, params, steady_state, ...
 %                                            maximum_lag, T, ny, i_cols, ...
@@ -17,7 +17,7 @@ function [residuals,JJacobian] = perfect_foresight_mcp_problem(y, dynamic_functi
 %   Y0                  [double] N*1 array, initial conditions for the endogenous variables
 %   YT                  [double] N*1 array, terminal conditions for the endogenous variables
 %   exo_simul           [double] nperiods*M_.exo_nbr matrix of exogenous variables (in declaration order)
-%                                for all simulation periods           
+%                                for all simulation periods
 %   params              [double] nparams*1 array, parameter values
 %   steady_state        [double] endo_nbr*1 vector of steady state values
 %   maximum_lag         [scalar] maximum lag present in the model
@@ -25,7 +25,7 @@ function [residuals,JJacobian] = perfect_foresight_mcp_problem(y, dynamic_functi
 %   ny                  [scalar] number of endogenous variables
 %   i_cols              [double] indices of variables appearing in M.lead_lag_incidence
 %                                and that need to be passed to _dynamic-file
-%   i_cols_J1           [double] indices of contemporaneous and forward looking variables 
+%   i_cols_J1           [double] indices of contemporaneous and forward looking variables
 %                                appearing in M.lead_lag_incidence
 %   i_cols_1            [double] indices of contemporaneous and forward looking variables in
 %                                M.lead_lag_incidence in dynamic Jacobian (relevant in first period)
@@ -33,8 +33,8 @@ function [residuals,JJacobian] = perfect_foresight_mcp_problem(y, dynamic_functi
 %                                variables (relevant in last period)
 %   i_cols_j            [double] indices of variables in M.lead_lag_incidence
 %                                in dynamic Jacobian (relevant in intermediate periods)
-%   nnzJ                [scalar] number of non-zero elements in Jacobian                                
-%   eq_index            [double] N*1 array, index vector describing residual mapping resulting 
+%   nnzJ                [scalar] number of non-zero elements in Jacobian
+%   eq_index            [double] N*1 array, index vector describing residual mapping resulting
 %                                from complementarity setup
 % OUTPUTS
 %   residuals           [double] (N*T)*1 array, residuals of the stacked problem
@@ -45,7 +45,7 @@ function [residuals,JJacobian] = perfect_foresight_mcp_problem(y, dynamic_functi
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 1996-2016 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -77,11 +77,11 @@ i_cols_J = i_cols;
 for it = 2:(T+1)
     if nargout == 1
         res = dynamic_function(YY(i_cols),exo_simul, params, ...
-            steady_state,it);
+                               steady_state,it);
         residuals(i_rows) = res(eq_index);
     elseif nargout == 2
         [res,jacobian] = dynamic_function(YY(i_cols),exo_simul, params, ...
-            steady_state,it);
+                                          steady_state,it);
         residuals(i_rows) = res(eq_index);
         if it == 2
             [rows,cols,vals] = find(jacobian(eq_index,i_cols_1));
@@ -96,7 +96,7 @@ for it = 2:(T+1)
         end
         offset = offset + ny;
     end
-    
+
     i_rows = i_rows + ny;
     i_cols = i_cols + ny;
 end
@@ -104,5 +104,5 @@ end
 if nargout == 2
     iJacobian = cat(1,iJacobian{:});
     JJacobian = sparse(iJacobian(:,1),iJacobian(:,2),iJacobian(:,3),T* ...
-        ny,T*ny);
+                       ny,T*ny);
 end
\ No newline at end of file
diff --git a/matlab/perfect-foresight-models/perfect_foresight_problem.m b/matlab/perfect-foresight-models/perfect_foresight_problem.m
index 95611909453fa57a6652972ecb50ed3f96bcc697..a4df03f80bf621942d27693f0efa22402d0b8d27 100644
--- a/matlab/perfect-foresight-models/perfect_foresight_problem.m
+++ b/matlab/perfect-foresight-models/perfect_foresight_problem.m
@@ -1,8 +1,8 @@
 function [residuals,JJacobian] = perfect_foresight_problem(y, dynamic_function, Y0, YT, ...
-                                           exo_simul, params, steady_state, ...
-                                           maximum_lag, T, ny, i_cols, ...
-                                           i_cols_J1, i_cols_1, i_cols_T, ...
-                                           i_cols_j,nnzJ)
+                                                  exo_simul, params, steady_state, ...
+                                                  maximum_lag, T, ny, i_cols, ...
+                                                  i_cols_J1, i_cols_1, i_cols_T, ...
+                                                  i_cols_j,nnzJ)
 % function [residuals,JJacobian] = perfect_foresight_problem(y, dynamic_function, Y0, YT, ...
 %                                            exo_simul, params, steady_state, ...
 %                                            maximum_lag, T, ny, i_cols, ...
@@ -16,7 +16,7 @@ function [residuals,JJacobian] = perfect_foresight_problem(y, dynamic_function,
 %   Y0                  [double] N*1 array, initial conditions for the endogenous variables
 %   YT                  [double] N*1 array, terminal conditions for the endogenous variables
 %   exo_simul           [double] nperiods*M_.exo_nbr matrix of exogenous variables (in declaration order)
-%                                for all simulation periods           
+%                                for all simulation periods
 %   params              [double] nparams*1 array, parameter values
 %   steady_state        [double] endo_nbr*1 vector of steady state values
 %   maximum_lag         [scalar] maximum lag present in the model
@@ -24,7 +24,7 @@ function [residuals,JJacobian] = perfect_foresight_problem(y, dynamic_function,
 %   ny                  [scalar] number of endogenous variables
 %   i_cols              [double] indices of variables appearing in M.lead_lag_incidence
 %                                and that need to be passed to _dynamic-file
-%   i_cols_J1           [double] indices of contemporaneous and forward looking variables 
+%   i_cols_J1           [double] indices of contemporaneous and forward looking variables
 %                                appearing in M.lead_lag_incidence
 %   i_cols_1            [double] indices of contemporaneous and forward looking variables in
 %                                M.lead_lag_incidence in dynamic Jacobian (relevant in first period)
@@ -32,7 +32,7 @@ function [residuals,JJacobian] = perfect_foresight_problem(y, dynamic_function,
 %                                variables (relevant in last period)
 %   i_cols_j            [double] indices of variables in M.lead_lag_incidence
 %                                in dynamic Jacobian (relevant in intermediate periods)
-%   nnzJ                [scalar] number of non-zero elements in Jacobian                                
+%   nnzJ                [scalar] number of non-zero elements in Jacobian
 % OUTPUTS
 %   residuals           [double] (N*T)*1 array, residuals of the stacked problem
 %   JJacobian           [double] (N*T)*(N*T) array, Jacobian of the stacked problem
@@ -42,7 +42,7 @@ function [residuals,JJacobian] = perfect_foresight_problem(y, dynamic_function,
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 1996-2016 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -60,44 +60,44 @@ function [residuals,JJacobian] = perfect_foresight_problem(y, dynamic_function,
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 
-    YY = [Y0; y; YT];
-    
-    residuals = zeros(T*ny,1);
-    if nargout == 2
-        iJacobian = cell(T,1);
-    end
+YY = [Y0; y; YT];
 
-    i_rows = 1:ny;
-    i_cols_J = i_cols;
-    offset = 0;
-    
-    for it = 2:(T+1)
-        if nargout == 1
-             residuals(i_rows) = dynamic_function(YY(i_cols),exo_simul, params, ...
-                                                         steady_state,it);
-        elseif nargout == 2
-            [residuals(i_rows),jacobian] = dynamic_function(YY(i_cols),exo_simul, params, ...
-                                                         steady_state,it);
-            if it == 2
-                [rows,cols,vals] = find(jacobian(:,i_cols_1));
-                iJacobian{1} = [offset+rows, i_cols_J1(cols), vals];
-            elseif it == T + 1
-                [rows,cols,vals] = find(jacobian(:,i_cols_T));
-                iJacobian{T} = [offset+rows, i_cols_J(i_cols_T(cols)), vals];
-            else
-                [rows,cols,vals] = find(jacobian(:,i_cols_j));
-                iJacobian{it-1} = [offset+rows, i_cols_J(cols), vals];
-                i_cols_J = i_cols_J + ny;
-            end
-            offset = offset + ny;
-        end
+residuals = zeros(T*ny,1);
+if nargout == 2
+    iJacobian = cell(T,1);
+end
+
+i_rows = 1:ny;
+i_cols_J = i_cols;
+offset = 0;
 
-        i_rows = i_rows + ny;
-        i_cols = i_cols + ny;
+for it = 2:(T+1)
+    if nargout == 1
+        residuals(i_rows) = dynamic_function(YY(i_cols),exo_simul, params, ...
+                                             steady_state,it);
+    elseif nargout == 2
+        [residuals(i_rows),jacobian] = dynamic_function(YY(i_cols),exo_simul, params, ...
+                                                        steady_state,it);
+        if it == 2
+            [rows,cols,vals] = find(jacobian(:,i_cols_1));
+            iJacobian{1} = [offset+rows, i_cols_J1(cols), vals];
+        elseif it == T + 1
+            [rows,cols,vals] = find(jacobian(:,i_cols_T));
+            iJacobian{T} = [offset+rows, i_cols_J(i_cols_T(cols)), vals];
+        else
+            [rows,cols,vals] = find(jacobian(:,i_cols_j));
+            iJacobian{it-1} = [offset+rows, i_cols_J(cols), vals];
+            i_cols_J = i_cols_J + ny;
+        end
+        offset = offset + ny;
     end
 
-    if nargout == 2
-        iJacobian = cat(1,iJacobian{:});
-        JJacobian = sparse(iJacobian(:,1),iJacobian(:,2),iJacobian(:,3),T* ...
-                           ny,T*ny);
-    end
\ No newline at end of file
+    i_rows = i_rows + ny;
+    i_cols = i_cols + ny;
+end
+
+if nargout == 2
+    iJacobian = cat(1,iJacobian{:});
+    JJacobian = sparse(iJacobian(:,1),iJacobian(:,2),iJacobian(:,3),T* ...
+                       ny,T*ny);
+end
\ No newline at end of file
diff --git a/matlab/perfect-foresight-models/perfect_foresight_setup.m b/matlab/perfect-foresight-models/perfect_foresight_setup.m
index 3b28254326f2642f46cfa098ec61b210e9336f8d..341d70aad67569ff9e5e48b655c538e9a3eadaf5 100644
--- a/matlab/perfect-foresight-models/perfect_foresight_setup.m
+++ b/matlab/perfect-foresight-models/perfect_foresight_setup.m
@@ -1,18 +1,18 @@
 function perfect_foresight_setup()
 % Prepares a deterministic simulation, by filling oo_.exo_simul and oo_.endo_simul
-%  
+%
 % INPUTS
 %   None
-%  
+%
 % OUTPUTS
 %   none
-%    
+%
 % ALGORITHM
-%   
+%
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 1996-2016 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -35,14 +35,14 @@ 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 : 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
+    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-models/perfect_foresight_simulation.m b/matlab/perfect-foresight-models/perfect_foresight_simulation.m
index ffef743edff31a71a08448c6025eab55086b76b3..15f1b8b7628007ddc82d458a76f39e5bd9cefec3 100644
--- a/matlab/perfect-foresight-models/perfect_foresight_simulation.m
+++ b/matlab/perfect-foresight-models/perfect_foresight_simulation.m
@@ -18,7 +18,7 @@ function info = perfect_foresight_simulation(compute_linear_solution,steady_stat
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/perfect-foresight-models/perfect_foresight_solver.m b/matlab/perfect-foresight-models/perfect_foresight_solver.m
index b5fc7e4f21402b04c7fdbbb23c7bd55838662958..8e7c3bcbc5144c64268cc9b60f74ace90b3c84a7 100644
--- a/matlab/perfect-foresight-models/perfect_foresight_solver.m
+++ b/matlab/perfect-foresight-models/perfect_foresight_solver.m
@@ -12,7 +12,7 @@ function perfect_foresight_solver()
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 1996-2016 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -184,20 +184,20 @@ if ~isreal(oo_.endo_simul(:)) %can only happen without bytecode
     [i_cols_J1,junk,i_cols_1] = find(illi(:));
     i_cols_T = nonzeros(M_.lead_lag_incidence(1:2,:)');
     residuals = perfect_foresight_problem(yy(:),str2func([M_.fname '_dynamic']), y0, yT, ...
-                                      oo_.exo_simul,M_.params,oo_.steady_state, ...
-                                      M_.maximum_lag,options_.periods,M_.endo_nbr,i_cols, ...
-                                      i_cols_J1, i_cols_1, i_cols_T, i_cols_j, ...
-                                      M_.NNZDerivatives(1));
+                                          oo_.exo_simul,M_.params,oo_.steady_state, ...
+                                          M_.maximum_lag,options_.periods,M_.endo_nbr,i_cols, ...
+                                          i_cols_J1, i_cols_1, i_cols_T, i_cols_j, ...
+                                          M_.NNZDerivatives(1));
     if max(abs(residuals))< options_.dynatol.f
         oo_.deterministic_simulation.status = 1;
         oo_.endo_simul=real(oo_.endo_simul);
     else
-        oo_.deterministic_simulation.status = 0; 
+        oo_.deterministic_simulation.status = 0;
         disp('Simulation terminated with imaginary parts in the residuals or endogenous variables.')
-    end            
+    end
 end
 
-if oo_.deterministic_simulation.status == 1 
+if oo_.deterministic_simulation.status == 1
     disp('Perfect foresight solution found.')
 else
     disp('Failed to solve perfect foresight model')
diff --git a/matlab/perfect-foresight-models/perfect_foresight_solver_core.m b/matlab/perfect-foresight-models/perfect_foresight_solver_core.m
index da267b7dae697716ccffc3b4e8537c01375d33d4..272cd38337dfed3aeebc8978feacbabeefd0111d 100644
--- a/matlab/perfect-foresight-models/perfect_foresight_solver_core.m
+++ b/matlab/perfect-foresight-models/perfect_foresight_solver_core.m
@@ -2,16 +2,16 @@ function [oo_, maxerror] = perfect_foresight_solver_core(M_, options_, oo_)
 %function [oo_, maxerror] = perfect_foresight_solver_core(M_, options_, oo_)
 % Core function calling solvers for perfect foresight model
 %
-% INPUTS 
+% INPUTS
 % - M_                  [struct] contains a description of the model.
 % - options_            [struct] contains various options.
 % - oo_                 [struct] contains results
 %
-% OUTPUTS 
+% OUTPUTS
 % - oo_                 [struct] contains results
 % - maxerror            [double] contains the maximum absolute error
 
-% Copyright (C) 2015-2016 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -81,8 +81,8 @@ else
             [oo_.endo_simul, oo_.deterministic_simulation] = ...
                 sim1_purely_backward(oo_.endo_simul, oo_.exo_simul, oo_.steady_state, M_, options_);
         elseif M_.maximum_endo_lag == 0 % Purely forward model
-            [oo_.endo_simul, oo_.deterministic_simulation] = ...
-                sim1_purely_forward(oo_.endo_simul, oo_.exo_simul, oo_.steady_state, M_, options_);
+        [oo_.endo_simul, oo_.deterministic_simulation] = ...
+            sim1_purely_forward(oo_.endo_simul, oo_.exo_simul, oo_.steady_state, M_, options_);
         else % General case
             switch options_.stack_solve_algo
               case 0
@@ -143,5 +143,3 @@ if nargout>1
         maxerror = max(max(abs(residuals)));
     end
 end
-
-
diff --git a/matlab/perfect-foresight-models/private/check_input_arguments.m b/matlab/perfect-foresight-models/private/check_input_arguments.m
index affb808e081591bf1fc84b0e1a0026af030454b2..fc50114d0cc7f89ecfa50a0ce1adb6083987fc72 100644
--- a/matlab/perfect-foresight-models/private/check_input_arguments.m
+++ b/matlab/perfect-foresight-models/private/check_input_arguments.m
@@ -3,7 +3,7 @@ function check_input_arguments(DynareOptions, DynareModel, DynareResults)
 %Conducts checks for inconsistent/missing inputs to deterministic
 %simulations
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -43,7 +43,7 @@ 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'' ?')
diff --git a/matlab/perfect-foresight-models/private/initialize_stacked_problem.m b/matlab/perfect-foresight-models/private/initialize_stacked_problem.m
index 64beba34e2734456a69da08bcee6a4ecea70b88c..014bb9acb44ac8000c679457c49c2a2c1e40c820 100644
--- a/matlab/perfect-foresight-models/private/initialize_stacked_problem.m
+++ b/matlab/perfect-foresight-models/private/initialize_stacked_problem.m
@@ -4,19 +4,19 @@ function [options, y0, yT, z, i_cols, i_cols_J1, i_cols_T, i_cols_j, i_cols_1, .
 %           dynamicmodel] = initialize_stacked_problem(endogenousvariables, options, M, steadystate_y)
 % Sets up the stacked perfect foresight problem for use with dynare_solve.m
 %
-% INPUTS 
+% INPUTS
 % - endogenousvariables [double] N*T array, paths for the endogenous variables (initial guess).
 % - options             [struct] contains various options.
 % - M                   [struct] contains a description of the model.
 % - steadystate_y       [double] N*1 array, steady state for the endogenous variables.
-% OUTPUTS 
+% OUTPUTS
 % - options             [struct] contains various options.
 % - y0                  [double] N*1 array, initial conditions for the endogenous variables
 % - yT                  [double] N*1 array, terminal conditions for the endogenous variables
 % - z                   [double] T*M array, paths for the exogenous variables.
 % - i_cols              [double] indices of variables appearing in M.lead_lag_incidence
 %                                and that need to be passed to _dynamic-file
-% - i_cols_J1           [double] indices of contemporaneous and forward looking variables 
+% - i_cols_J1           [double] indices of contemporaneous and forward looking variables
 %                                appearing in M.lead_lag_incidence
 % - i_cols_T            [double] columns of dynamic Jacobian related to
 %                                contemporaneous and backward-looking
@@ -27,7 +27,7 @@ function [options, y0, yT, z, i_cols, i_cols_J1, i_cols_T, i_cols_j, i_cols_1, .
 %                                M.lead_lag_incidence in dynamic Jacobian (relevant in first period)
 % - dynamicmodel        [handle] function handle to _dynamic-file
 
-% Copyright (C) 2015-16 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -43,7 +43,7 @@ function [options, y0, yT, z, i_cols, i_cols_J1, i_cols_T, i_cols_j, i_cols_1, .
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
-    
+
 periods = options.periods;
 if (options.solve_algo == 10)
     if ~isfield(options.lmmcp,'lb')
diff --git a/matlab/perfect-foresight-models/private/simulation_core.m b/matlab/perfect-foresight-models/private/simulation_core.m
index b52ecad172b4fc167e7dd48a00f7536532ece602..0c944c2a68a5119cbc0669076e0aad76bd6afd3a 100644
--- a/matlab/perfect-foresight-models/private/simulation_core.m
+++ b/matlab/perfect-foresight-models/private/simulation_core.m
@@ -1,7 +1,7 @@
 function [oo_, maxerror] = simulation_core(options_, M_, oo_)
 %function [oo_, maxerror] = simulation_core(options_, M_, oo_)
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -66,8 +66,8 @@ else
             [oo_.endo_simul, oo_.deterministic_simulation] = ...
                 sim1_purely_backward(oo_.endo_simul, oo_.exo_simul, oo_.steady_state, M_, options_);
         elseif M_.maximum_endo_lag == 0 % Purely forward model
-            [oo_.endo_simul, oo_.deterministic_simulation] = ...
-                sim1_purely_forward(oo_.endo_simul, oo_.exo_simul, oo_.steady_state, M_, options_);
+        [oo_.endo_simul, oo_.deterministic_simulation] = ...
+            sim1_purely_forward(oo_.endo_simul, oo_.exo_simul, oo_.steady_state, M_, options_);
         else % General case
             if options_.stack_solve_algo == 0
                 if options_.linear_approximation
diff --git a/matlab/perfect-foresight-models/sim1.m b/matlab/perfect-foresight-models/sim1.m
index 05ef5b186732ee19a565b9890b99c8c9771dd70d..b8d09a808693cb5318a4e70ca95ea619304ab087 100644
--- a/matlab/perfect-foresight-models/sim1.m
+++ b/matlab/perfect-foresight-models/sim1.m
@@ -17,7 +17,7 @@ function [endogenousvariables, info] = sim1(endogenousvariables, exogenousvariab
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 1996-2016 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -154,17 +154,22 @@ for iter = 1:options.simul.maxit
     if endogenous_terminal_period && iter>1
         dy = ZERO;
         if options.simul.robust_lin_solve
-            dy(1:i_rows(end)) = -lin_solve_robust( A(1:i_rows(end),1:i_rows(end)), res(1:i_rows(end)),verbose );            
+            dy(1:i_rows(end)) = -lin_solve_robust( A(1:i_rows(end),1:i_rows(end)), res(1:i_rows(end)),verbose );
         else
             dy(1:i_rows(end)) = -lin_solve( A(1:i_rows(end),1:i_rows(end)), res(1:i_rows(end)), verbose );
         end
     else
         if options.simul.robust_lin_solve
-            dy = -lin_solve_robust( A, res, verbose );            
+            dy = -lin_solve_robust( A, res, verbose );
         else
             dy = -lin_solve( A, res, verbose );
         end
     end
+    if any(~isreal(dy)) || any(isnan(dy)) || any(isinf(dy))
+        if verbose
+            display_critical_variables(reshape(dy,[ny periods])', M);
+        end
+    end
     Y(i_upd) = Y(i_upd) + dy;
 end
 
@@ -184,7 +189,12 @@ if stop
         if verbose
             skipline()
             disp(sprintf('Total time of simulation: %s.', num2str(etime(clock,h1))))
-            disp('Simulation terminated with NaN or Inf in the residuals or endogenous variables.')
+            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
+            display_critical_variables(reshape(dy,[ny periods])', M);
             disp('There is most likely something wrong with your model. Try model_diagnostics or another simulation method.')
             printline(105)
         end
@@ -218,82 +228,106 @@ if verbose
 end
 
 function x = lin_solve( A, b,verbose)
-    if norm( b ) < sqrt( eps ) % then x = 0 is a solution
-        x = 0;
-        return
-    end
-    
-    x = A\b;
-    x( ~isfinite( x ) ) = 0;
-    relres = norm( b - A * x ) / norm( b );
-    if relres > 1e-6 && verbose
-        fprintf( 'WARNING : Failed to find a solution to the linear system.\n' );
-    end
-    
+if norm( b ) < sqrt( eps ) % then x = 0 is a solution
+    x = 0;
+    return
+end
+
+x = A\b;
+x( ~isfinite( x ) ) = 0;
+relres = norm( b - A * x ) / norm( b );
+if relres > 1e-6 && verbose
+    fprintf( 'WARNING : Failed to find a solution to the linear system.\n' );
+end
+
 function [ x, flag, relres ] = lin_solve_robust( A, b , verbose)
-    if norm( b ) < sqrt( eps ) % then x = 0 is a solution
-        x = 0;
-        flag = 0;
-        relres = 0;
-        return
-    end
-    
-    x = A\b;
-    x( ~isfinite( x ) ) = 0;
-    [ x, flag, relres ] = bicgstab( A, b, [], [], [], [], x ); % returns immediately if x is a solution
-    if flag == 0
-        return
-    end
+if norm( b ) < sqrt( eps ) % then x = 0 is a solution
+    x = 0;
+    flag = 0;
+    relres = 0;
+    return
+end
 
-    disp( relres );
+x = A\b;
+x( ~isfinite( x ) ) = 0;
+[ x, flag, relres ] = bicgstab( A, b, [], [], [], [], x ); % returns immediately if x is a solution
+if flag == 0
+    return
+end
 
-    if verbose
-        fprintf( 'Initial bicgstab failed, trying alternative start point.\n' );
-    end
-    old_x = x;
-    old_relres = relres;
-    [ x, flag, relres ] = bicgstab( A, b );
-    if flag == 0
-        return
-    end
+disp( relres );
 
-    if verbose
-        fprintf( 'Alternative start point also failed with bicgstab, trying gmres.\n' );
-    end
-    if old_relres < relres
-        x = old_x;
-    end
-    [ x, flag, relres ] = gmres( A, b, [], [], [], [], [], x );
-    if flag == 0
-        return
-    end
+if verbose
+    fprintf( 'Initial bicgstab failed, trying alternative start point.\n' );
+end
+old_x = x;
+old_relres = relres;
+[ x, flag, relres ] = bicgstab( A, b );
+if flag == 0
+    return
+end
 
-    if verbose
-        fprintf( 'Initial gmres failed, trying alternative start point.\n' );
-    end
-    old_x = x;
-    old_relres = relres;
-    [ x, flag, relres ] = gmres( A, b );
-    if flag == 0
-        return
-    end
+if verbose
+    fprintf( 'Alternative start point also failed with bicgstab, trying gmres.\n' );
+end
+if old_relres < relres
+    x = old_x;
+end
+[ x, flag, relres ] = gmres( A, b, [], [], [], [], [], x );
+if flag == 0
+    return
+end
 
-    if verbose
-        fprintf( 'Alternative start point also failed with gmres, using the (SLOW) Moore-Penrose Pseudo-Inverse.\n' );
-    end
-    if old_relres < relres
-        x = old_x;
-        relres = old_relres;
-    end
-    old_x = x;
-    old_relres = relres;
-    x = pinv( full( A ) ) * b;
-    relres = norm( b - A * x ) / norm( b );
-    if old_relres < relres
-        x = old_x;
-        relres = old_relres;
-    end
-    flag = relres > 1e-6;
-    if flag ~= 0 && verbose
-        fprintf( 'WARNING : Failed to find a solution to the linear system\n' );
-    end
\ No newline at end of file
+if verbose
+    fprintf( 'Initial gmres failed, trying alternative start point.\n' );
+end
+old_x = x;
+old_relres = relres;
+[ x, flag, relres ] = gmres( A, b );
+if flag == 0
+    return
+end
+
+if verbose
+    fprintf( 'Alternative start point also failed with gmres, using the (SLOW) Moore-Penrose Pseudo-Inverse.\n' );
+end
+if old_relres < relres
+    x = old_x;
+    relres = old_relres;
+end
+old_x = x;
+old_relres = relres;
+x = pinv( full( A ) ) * b;
+relres = norm( b - A * x ) / norm( b );
+if old_relres < relres
+    x = old_x;
+    relres = old_relres;
+end
+flag = relres > 1e-6;
+if flag ~= 0 && verbose
+    fprintf( 'WARNING : Failed to find a solution to the linear system\n' );
+end
+
+function display_critical_variables(dyy, M)
+
+if any(isnan(dyy))
+    indx = find(any(isnan(dyy)));
+    endo_names=cellstr(M.endo_names(indx,:));
+    disp('Last iteration provided NaN for the following variables:')
+    fprintf('%s, ',endo_names{:}),
+    fprintf('\n'),
+end
+if any(isinf(dyy))
+    indx = find(any(isinf(dyy)));
+    endo_names=cellstr(M.endo_names(indx,:));
+    disp('Last iteration diverged (Inf) for the following variables:')
+    fprintf('%s, ',endo_names{:}),
+    fprintf('\n'),
+end
+if any(~isreal(dyy))
+    indx = find(any(~isreal(dyy)));
+    endo_names=cellstr(M.endo_names(indx,:));
+    disp('Last iteration provided complex number for the following variables:')
+    fprintf('%s, ',endo_names{:}),
+    fprintf('\n'),
+end
diff --git a/matlab/perfect-foresight-models/sim1_lbj.m b/matlab/perfect-foresight-models/sim1_lbj.m
index d4d8c24f2bc137fc389435383263d8ab73d1de4b..a9b585907c99db20699cbfd3248f99ea455a7749 100644
--- a/matlab/perfect-foresight-models/sim1_lbj.m
+++ b/matlab/perfect-foresight-models/sim1_lbj.m
@@ -15,7 +15,7 @@ function [endogenousvariables, info] = sim1_lbj(endogenousvariables, exogenousva
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 1996-2015 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -122,7 +122,7 @@ if ~stop
     end
     info.status = 0;% more iterations are needed.
     info.error = err;
-    info.errors = c/abs(err);    
+    info.errors = c/abs(err);
     info.iterations = options.simul.maxit;
 end
 
diff --git a/matlab/perfect-foresight-models/sim1_linear.m b/matlab/perfect-foresight-models/sim1_linear.m
index 6820c92bc2c05fa6ea6ad37aee659b1869003925..85dc384058b908a44cecc49e2113f249eb70ae08 100644
--- a/matlab/perfect-foresight-models/sim1_linear.m
+++ b/matlab/perfect-foresight-models/sim1_linear.m
@@ -2,7 +2,7 @@ function [endogenousvariables, info] = sim1_linear(endogenousvariables, exogenou
 
 % Solves a linear approximation of a perfect foresight model using sparse matrix.
 %
-% INPUTS 
+% INPUTS
 % - endogenousvariables [double] N*T array, paths for the endogenous variables (initial guess).
 % - exogenousvariables  [double] T*M array, paths for the exogenous variables.
 % - steadystate_y       [double] N*1 array, steady state for the endogenous variables.
@@ -10,16 +10,16 @@ function [endogenousvariables, info] = sim1_linear(endogenousvariables, exogenou
 % - M                   [struct] contains a description of the model.
 % - options             [struct] contains various options.
 %
-% OUTPUTS 
+% OUTPUTS
 % - endogenousvariables [double] N*T array, paths for the endogenous variables (solution of the perfect foresight model).
 % - info                [struct] contains informations about the results.
 %
-% NOTATIONS 
+% NOTATIONS
 % - N is the number of endogenous variables.
 % - M is the number of innovations.
 % - T is the number of periods (including initial and/or terminal conditions).
 %
-% REMARKS 
+% REMARKS
 % - The structure `M` describing the structure of the model, must contain the
 % following informations:
 %  + lead_lag_incidence, incidence matrix (given by the preprocessor).
@@ -38,7 +38,7 @@ function [endogenousvariables, info] = sim1_linear(endogenousvariables, exogenou
 % to center the variables around the deterministic steady state to solve the
 % perfect foresight model.
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/perfect-foresight-models/sim1_purely_backward.m b/matlab/perfect-foresight-models/sim1_purely_backward.m
index abc871a6852d76861d1f749e9c0023a8aef33970..a2ec8db13213746ce4e1784d22494ccf6571dfe8 100644
--- a/matlab/perfect-foresight-models/sim1_purely_backward.m
+++ b/matlab/perfect-foresight-models/sim1_purely_backward.m
@@ -2,7 +2,7 @@ function [endogenousvariables, info] = sim1_purely_backward(endogenousvariables,
 
 % Performs deterministic simulation of a purely backward model
 
-% Copyright (C) 2012-2015 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -28,12 +28,12 @@ else
     nyb = 0;
     iyb = [];
 end
-        
+
 
 if ny0 ~= M.endo_nbr
     error('All endogenous variables must appear at the current period!')
 end
-    
+
 dynamicmodel = str2func([M.fname,'_dynamic']);
 
 info.status = 1;
diff --git a/matlab/perfect-foresight-models/sim1_purely_forward.m b/matlab/perfect-foresight-models/sim1_purely_forward.m
index ca2b2b5b2770a88af1e9fb388902788546ceb317..31cd12b77423eb8a9fd31ec8063364f6c6d1217d 100644
--- a/matlab/perfect-foresight-models/sim1_purely_forward.m
+++ b/matlab/perfect-foresight-models/sim1_purely_forward.m
@@ -1,7 +1,7 @@
 function [endogenousvariables, info] = sim1_purely_forward(endogenousvariables, exogenousvariables, steadystate, M, options)
 % Performs deterministic simulation of a purely forward model
 
-% Copyright (C) 2012-2015 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -24,7 +24,7 @@ iyf = find(M.lead_lag_incidence(2,:)>0); % Indices of variables at next period
 if ny0 ~= M.endo_nbr
     error('All endogenous variables must appear at the current period!')
 end
-    
+
 dynamicmodel = str2func([M.fname,'_dynamic']);
 
 info.status = 1;
diff --git a/matlab/perfect-foresight-models/solve_stacked_linear_problem.m b/matlab/perfect-foresight-models/solve_stacked_linear_problem.m
index 52a2efe48c55598a37ba1cd771813167fbdabfbb..5464c9e06b2f1a1414441e6c4182a7a258d6d55c 100644
--- a/matlab/perfect-foresight-models/solve_stacked_linear_problem.m
+++ b/matlab/perfect-foresight-models/solve_stacked_linear_problem.m
@@ -1,6 +1,6 @@
 function [endogenousvariables, info] = solve_stacked_linear_problem(endogenousvariables, exogenousvariables, steadystate_y, steadystate_x, M, options)
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -42,11 +42,11 @@ z = bsxfun(@minus, z, steadystate_y);
 x = bsxfun(@minus, exogenousvariables, steadystate_x');
 
 [y, check] = dynare_solve(@linear_perfect_foresight_problem,z(:), options, ...
-                        jacobian, y0-steadystate_y, yT-steadystate_y, ...
-                        x, M.params, steadystate_y, ...
-                        M.maximum_lag, options.periods, M.endo_nbr, i_cols, ...
-                        i_cols_J1, i_cols_1, i_cols_T, i_cols_j, ...
-                        M.NNZDerivatives(1), jendo, jexog);
+                          jacobian, y0-steadystate_y, yT-steadystate_y, ...
+                          x, M.params, steadystate_y, ...
+                          M.maximum_lag, options.periods, M.endo_nbr, i_cols, ...
+                          i_cols_J1, i_cols_1, i_cols_T, i_cols_j, ...
+                          M.NNZDerivatives(1), jendo, jexog);
 
 if all(imag(y)<.1*options.dynatol.x)
     if ~isreal(y)
diff --git a/matlab/perfect-foresight-models/solve_stacked_problem.m b/matlab/perfect-foresight-models/solve_stacked_problem.m
index 7a1835ba6bc52bd0e19f9b150d4e29be86e1334a..dd3bc6363d165f018e01e4bf5a7a8b78e4c056fb 100644
--- a/matlab/perfect-foresight-models/solve_stacked_problem.m
+++ b/matlab/perfect-foresight-models/solve_stacked_problem.m
@@ -1,19 +1,19 @@
-function [endogenousvariables, info] = solve_stacked_problem(endogenousvariables, exogenousvariables, steadystate, M, options);
+function [endogenousvariables, info] = solve_stacked_problem(endogenousvariables, exogenousvariables, steadystate, M, options)
 % [endogenousvariables, info] = solve_stacked_problem(endogenousvariables, exogenousvariables, steadystate, M, options);
 % Solves the perfect foresight model using dynare_solve
 %
-% INPUTS 
+% INPUTS
 % - endogenousvariables [double] N*T array, paths for the endogenous variables (initial guess).
 % - exogenousvariables  [double] T*M array, paths for the exogenous variables.
 % - steadystate         [double] N*1 array, steady state for the endogenous variables.
 % - M                   [struct] contains a description of the model.
 % - options             [struct] contains various options.
 %
-% OUTPUTS 
+% OUTPUTS
 % - endogenousvariables [double] N*T array, paths for the endogenous variables (solution of the perfect foresight model).
 % - info                [struct] contains informations about the results.
 
-% Copyright (C) 2015-16 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -29,7 +29,7 @@ function [endogenousvariables, info] = solve_stacked_problem(endogenousvariables
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
-    
+
 [options, y0, yT, z, i_cols, i_cols_J1, i_cols_T, i_cols_j, i_cols_1, dynamicmodel] = ...
     initialize_stacked_problem(endogenousvariables, options, M, steadystate);
 
@@ -74,6 +74,6 @@ endogenousvariables = [y0 reshape(y, M.endo_nbr, options.periods) yT];
 if check
     info.status = false;
 else
-    
+
     info.status = true;
 end
\ No newline at end of file
diff --git a/matlab/plot_icforecast.m b/matlab/plot_icforecast.m
index 62d788414f0c7265e161a0e110e66725de807968..c4e3c2b2b995ba9ae5b102ff2a6a526c962e10df 100644
--- a/matlab/plot_icforecast.m
+++ b/matlab/plot_icforecast.m
@@ -1,16 +1,16 @@
 function plot_icforecast(Variables,periods,options_)
 % Build plots for the conditional forecasts.
 %
-% INPUTS 
-%  o Variables     [char]        m*x array holding the names of the endogenous variables to be plotted. 
+% INPUTS
+%  o Variables     [char]        m*x array holding the names of the endogenous variables to be plotted.
 %
 % OUTPUTS
 %  None.
-% 
+%
 % SPECIAL REQUIREMENTS
 %  This routine has to be called after imcforecast.m.
 
-% Copyright (C) 2006-2016 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -57,7 +57,7 @@ for i=1:size(Variables,1)
 end
 
 function build_figure(name,cci1,cci2,mm1,mm2,options_,graphoptions)
-hh = dyn_figure(options_,'Name',['Conditional forecast (' graphoptions.title ,'): ' name '.']);
+hh = dyn_figure(options_.nodisplay,'Name',['Conditional forecast (' graphoptions.title ,'): ' name '.']);
 H = length(mm1);
 h1 = area(1:H,cci1(2,1:H),'BaseValue',min([min(cci1(1,:)),min(cci2(1,:))]),'FaceColor',[.9 .9 .9]);
 hold on
@@ -68,4 +68,4 @@ plot(1:H,cci2(1,:),'--k','linewidth',1)
 plot(1:H,cci2(2,:),'--k','linewidth',1)
 axis tight
 hold off
-dyn_saveas(hh,[graphoptions.OutputDirectoryName '/Conditional_forecast_',strrep(deblank(graphoptions.title),' ','_'),'_',deblank(name)],options_)
\ No newline at end of file
+dyn_saveas(hh,[graphoptions.OutputDirectoryName '/Conditional_forecast_',strrep(deblank(graphoptions.title),' ','_'),'_',deblank(name)],options_.nodisplay,options_.graph_format)
\ No newline at end of file
diff --git a/matlab/plot_identification.m b/matlab/plot_identification.m
index e24695025000078d654ffcb2505d61b13df36049..12da5680486cde9938eb2997db96f3bc3bbda753 100644
--- a/matlab/plot_identification.m
+++ b/matlab/plot_identification.m
@@ -8,18 +8,18 @@ function plot_identification(params,idemoments,idehess,idemodel, idelre, advance
 %    o idemodel           [structure] identification results for the reduced form solution
 %    o idelre             [structure] identification results for the LRE model
 %    o advanced           [integer] flag for advanced identification checks
-%    o tittxt             [char] name of the results to plot 
+%    o tittxt             [char] name of the results to plot
 %    o name               [char] list of names
 %    o IdentifDirectoryName   [char] directory name
-%    o tittxt             [char] TeX-name of the results to plot 
+%    o tittxt             [char] TeX-name of the results to plot
 %    o name_tex           [char] TeX-names of the parameters
 % OUTPUTS
 %    None
-%    
+%
 % SPECIAL REQUIREMENTS
 %    None
 
-% Copyright (C) 2008-2016 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -41,8 +41,8 @@ global M_ options_
 if nargin <10 || isempty(tit_TeX)
     tit_TeX=tittxt;
 end
-    
-if nargin <11 
+
+if nargin <11
     name_TeX=name;
 end
 
@@ -58,9 +58,9 @@ siLREnorm = idelre.siLREnorm;
 % end
 tittxt1=regexprep(tittxt, ' ', '_');
 tittxt1=strrep(tittxt1, '.', '');
-if SampleSize == 1,
+if SampleSize == 1
     siJ = idemoments.siJ;
-    hh = dyn_figure(options_,'Name',[tittxt, ' - Identification using info from observables']);
+    hh = dyn_figure(options_.nodisplay,'Name',[tittxt, ' - Identification using info from observables']);
     subplot(211)
     mmm = (idehess.ide_strength_J);
     [ss, is] = sort(mmm);
@@ -72,7 +72,7 @@ if SampleSize == 1,
     set(gca,'xlim',[0 nparam+1])
     set(gca,'xticklabel','')
     dy = get(gca,'ylim');
-    for ip=1:nparam,
+    for ip=1:nparam
         text(ip,dy(1),name{is(ip)},'rotation',90,'HorizontalAlignment','right','interpreter','none')
     end
     if ~all(isnan(idehess.ide_strength_J_prior))
@@ -80,12 +80,12 @@ if SampleSize == 1,
     else
         legend('relative to param value','Location','Best')
     end
-    if  idehess.flag_score,
+    if  idehess.flag_score
         title('Identification strength with asymptotic Information matrix (log-scale)')
     else
         title('Identification strength with moments Information matrix (log-scale)')
     end
-    
+
     subplot(212)
     if ~all(isnan(idehess.deltaM_prior))
         bar(log([idehess.deltaM(is) idehess.deltaM_prior(is)]))
@@ -96,7 +96,7 @@ if SampleSize == 1,
     set(gca,'xlim',[0 nparam+1])
     set(gca,'xticklabel','')
     dy = get(gca,'ylim');
-    for ip=1:nparam,
+    for ip=1:nparam
         text(ip,dy(1),name{is(ip)},'rotation',90,'HorizontalAlignment','right','interpreter','none')
     end
     if ~all(isnan(idehess.deltaM_prior))
@@ -104,7 +104,7 @@ if SampleSize == 1,
     else
         legend('relative to param value','Location','Best')
     end
-    if  idehess.flag_score,
+    if  idehess.flag_score
         title('Sensitivity component with asymptotic Information matrix (log-scale)')
     else
         title('Sensitivity component with moments Information matrix (log-scale)')
@@ -122,17 +122,17 @@ if SampleSize == 1,
         fprintf(fidTeX,'%% End Of TeX file. \n');
         fclose(fidTeX);
     end
-    dyn_saveas(hh,[IdentifDirectoryName '/' M_.fname '_ident_strength_' tittxt1],options_);
-    
-    if advanced,
-        if ~options_.nodisplay,
+    dyn_saveas(hh,[IdentifDirectoryName '/' M_.fname '_ident_strength_' tittxt1],options_.nodisplay,options_.graph_format);
+
+    if advanced
+        if ~options_.nodisplay
             skipline()
             disp('Press ENTER to plot advanced diagnostics'), pause(5),
         end
         if all(isnan([siJnorm';siHnorm';siLREnorm']))
             fprintf('\nIDENTIFICATION: Skipping sensitivity plot, because standard deviation of parameters is NaN, possibly due to the use of ML.\n')
         else
-            hh = dyn_figure(options_,'Name',[tittxt, ' - Sensitivity plot']);
+            hh = dyn_figure(options_.nodisplay,'Name',[tittxt, ' - Sensitivity plot']);
             subplot(211)
             mmm = (siJnorm)'./max(siJnorm);
             mmm1 = (siHnorm)'./max(siHnorm);
@@ -146,12 +146,12 @@ if SampleSize == 1,
             set(gca,'xlim',[0 nparam+1])
             set(gca,'xticklabel','')
             dy = get(gca,'ylim');
-            for ip=1:nparam,
+            for ip=1:nparam
                 text(ip,dy(1),name{is(ip)},'rotation',90,'HorizontalAlignment','right','interpreter','none')
             end
             legend('Moments','Model','LRE model','Location','Best')
             title('Sensitivity bars using derivatives (log-scale)')
-            dyn_saveas(hh,[IdentifDirectoryName '/' M_.fname '_sensitivity_' tittxt1 ],options_);
+            dyn_saveas(hh,[IdentifDirectoryName '/' M_.fname '_sensitivity_' tittxt1 ],options_.nodisplay,options_.graph_format);
             if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                 fidTeX = fopen([IdentifDirectoryName '/' M_.fname '_sensitivity_' tittxt1,'.tex'],'w');
                 fprintf(fidTeX,'%% TeX eps-loader file generated by plot_identification.m (Dynare).\n');
@@ -167,29 +167,29 @@ if SampleSize == 1,
             end
         end
         % identificaton patterns
-        for  j=1:size(idemoments.cosnJ,2),
+        for  j=1:size(idemoments.cosnJ,2)
             pax=NaN(nparam,nparam);
-%             fprintf('\n')
-%             disp(['Collinearity patterns with ', int2str(j) ,' parameter(s)'])
-%             fprintf('%-15s [%-*s] %10s\n','Parameter',(15+1)*j,' Expl. params ','cosn')
-            for i=1:nparam,
+            %             fprintf('\n')
+            %             disp(['Collinearity patterns with ', int2str(j) ,' parameter(s)'])
+            %             fprintf('%-15s [%-*s] %10s\n','Parameter',(15+1)*j,' Expl. params ','cosn')
+            for i=1:nparam
                 namx='';
-                for in=1:j,
+                for in=1:j
                     dumpindx = idemoments.pars{i,j}(in);
-                    if isnan(dumpindx),
+                    if isnan(dumpindx)
                         namx=[namx ' ' sprintf('%-15s','--')];
                     else
                         namx=[namx ' ' sprintf('%-15s',name{dumpindx})];
                         pax(i,dumpindx)=idemoments.cosnJ(i,j);
                     end
                 end
-%                 fprintf('%-15s [%s] %10.3f\n',name{i},namx,idemoments.cosnJ(i,j))
+                %                 fprintf('%-15s [%s] %10.3f\n',name{i},namx,idemoments.cosnJ(i,j))
             end
-            hh = dyn_figure(options_,'Name',[tittxt,' - Collinearity patterns with ', int2str(j) ,' parameter(s)']);
+            hh = dyn_figure(options_.nodisplay,'Name',[tittxt,' - Collinearity patterns with ', int2str(j) ,' parameter(s)']);
             imagesc(pax,[0 1]);
             set(gca,'xticklabel','')
             set(gca,'yticklabel','')
-            for ip=1:nparam,
+            for ip=1:nparam
                 text(ip,(0.5),name{ip},'rotation',90,'HorizontalAlignment','left','interpreter','none')
                 text(0.5,ip,name{ip},'rotation',0,'HorizontalAlignment','right','interpreter','none')
             end
@@ -198,14 +198,14 @@ if SampleSize == 1,
             ax=colormap;
             ax(1,:)=[0.9 0.9 0.9];
             colormap(ax);
-            if nparam>10,
+            if nparam>10
                 set(gca,'xtick',(5:5:nparam))
                 set(gca,'ytick',(5:5:nparam))
             end
             set(gca,'xgrid','on')
             set(gca,'ygrid','on')
             xlabel([tittxt,' - Collinearity patterns with ', int2str(j) ,' parameter(s)'],'interpreter','none')
-            dyn_saveas(hh,[ IdentifDirectoryName '/' M_.fname '_ident_collinearity_' tittxt1 '_' int2str(j) ],options_);
+            dyn_saveas(hh,[ IdentifDirectoryName '/' M_.fname '_ident_collinearity_' tittxt1 '_' int2str(j) ],options_.nodisplay,options_.graph_format);
             if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                 fidTeX = fopen([ IdentifDirectoryName '/' M_.fname '_ident_collinearity_' tittxt1 '_' int2str(j),'.tex'],'w');
                 fprintf(fidTeX,'%% TeX eps-loader file generated by plot_identification.m (Dynare).\n');
@@ -223,54 +223,54 @@ if SampleSize == 1,
         skipline()
         [U,S,V]=svd(idehess.AHess,0);
         S=diag(S);
-        if idehess.flag_score,
-            if nparam<5,
-                f1 = dyn_figure(options_,'Name',[tittxt,' - Identification patterns (Information matrix)']);
+        if idehess.flag_score
+            if nparam<5
+                f1 = dyn_figure(options_.nodisplay,'Name',[tittxt,' - Identification patterns (Information matrix)']);
                 tex_tit_1=[tittxt,' - Identification patterns (Information matrix)'];
             else
-                f1 = dyn_figure(options_,'Name',[tittxt,' - Identification patterns (Information matrix): SMALLEST SV']);
+                f1 = dyn_figure(options_.nodisplay,'Name',[tittxt,' - Identification patterns (Information matrix): SMALLEST SV']);
                 tex_tit_1=[tittxt,' - Identification patterns (Information matrix): SMALLEST SV'];
-                f2 = dyn_figure(options_,'Name',[tittxt,' - Identification patterns (Information matrix): HIGHEST SV']);
+                f2 = dyn_figure(options_.nodisplay,'Name',[tittxt,' - Identification patterns (Information matrix): HIGHEST SV']);
                 tex_tit_2=[tittxt,' - Identification patterns (Information matrix): HIGHEST SV'];
             end
         else
-%             S = idemoments.S;
-%             V = idemoments.V;
-            if nparam<5,
-                f1 = dyn_figure(options_,'Name',[tittxt,' - Identification patterns (moments Information matrix)']);
+            %             S = idemoments.S;
+            %             V = idemoments.V;
+            if nparam<5
+                f1 = dyn_figure(options_.nodisplay,'Name',[tittxt,' - Identification patterns (moments Information matrix)']);
                 tex_tit_1=[tittxt,' - Identification patterns (moments Information matrix)'];
             else
-                f1 = dyn_figure(options_,'Name',[tittxt,' - Identification patterns (moments Information matrix): SMALLEST SV']);
+                f1 = dyn_figure(options_.nodisplay,'Name',[tittxt,' - Identification patterns (moments Information matrix): SMALLEST SV']);
                 tex_tit_1=[tittxt,' - Identification patterns (moments Information matrix): SMALLEST SV'];
-                f2 = dyn_figure(options_,'Name',[tittxt,' - Identification patterns (moments Information matrix): HIGHEST SV']);
+                f2 = dyn_figure(options_.nodisplay,'Name',[tittxt,' - Identification patterns (moments Information matrix): HIGHEST SV']);
                 tex_tit_2=[tittxt,' - Identification patterns (moments Information matrix): HIGHEST SV'];
             end
         end
-        for j=1:min(nparam,8),
-            if j<5,
+        for j=1:min(nparam,8)
+            if j<5
                 set(0,'CurrentFigure',f1),
                 jj=j;
             else
                 set(0,'CurrentFigure',f2),
                 jj=j-4;
             end
-            subplot(4,1,jj),
+            subplot(4,1,jj)
             if j<5
-                bar(abs(V(:,end-j+1))),
+                bar(abs(V(:,end-j+1)))
                 Stit = S(end-j+1);
             else
                 bar(abs(V(:,jj))),
                 Stit = S(jj);
             end
             set(gca,'xticklabel','')
-            if j==4 || j==nparam || j==8,
-                for ip=1:nparam,
+            if j==4 || j==nparam || j==8
+                for ip=1:nparam
                     text(ip,-0.02,name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
                 end
             end
             title(['Singular value ',num2str(Stit)])
         end
-        dyn_saveas(f1,[  IdentifDirectoryName '/' M_.fname '_ident_pattern_' tittxt1 '_1' ],options_);
+        dyn_saveas(f1,[  IdentifDirectoryName '/' M_.fname '_ident_pattern_' tittxt1 '_1' ],options_.nodisplay,options_.graph_format);
         if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
             fidTeX = fopen([  IdentifDirectoryName '/' M_.fname '_ident_pattern_' tittxt1 '_1','.tex'],'w');
             fprintf(fidTeX,'%% TeX eps-loader file generated by plot_identification.m (Dynare).\n');
@@ -284,8 +284,8 @@ if SampleSize == 1,
             fprintf(fidTeX,'%% End Of TeX file. \n');
             fclose(fidTeX);
         end
-        if nparam>4,
-            dyn_saveas(f2,[  IdentifDirectoryName '/' M_.fname '_ident_pattern_' tittxt1 '_2' ],options_);
+        if nparam>4
+            dyn_saveas(f2,[  IdentifDirectoryName '/' M_.fname '_ident_pattern_' tittxt1 '_2' ],options_.nodisplay,options_.graph_format);
             if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                 fidTeX = fopen([  IdentifDirectoryName '/' M_.fname '_ident_pattern_' tittxt1 '_2.tex'],'w');
                 fprintf(fidTeX,'%% TeX eps-loader file generated by plot_identification.m (Dynare).\n');
@@ -301,35 +301,35 @@ if SampleSize == 1,
             end
         end
     end
-    
+
 else
-    hh = dyn_figure(options_,'Name',['MC sensitivities']);
+    hh = dyn_figure(options_.nodisplay,'Name',['MC sensitivities']);
     subplot(211)
     mmm = (idehess.ide_strength_J);
     [ss, is] = sort(mmm);
     mmm = mean(siJnorm)';
     mmm = mmm./max(mmm);
-    if advanced,
+    if advanced
         mmm1 = mean(siHnorm)';
         mmm=[mmm mmm1./max(mmm1)];
         mmm1 = mean(siLREnorm)';
         offset=size(siHnorm,2)-size(siLREnorm,2);
         mmm1 = [NaN(offset,1); mmm1./max(mmm1)];
         mmm=[mmm mmm1];
-    end        
-        
+    end
+
     bar(mmm(is,:))
     set(gca,'xlim',[0 nparam+1])
     set(gca,'xticklabel','')
     dy = get(gca,'ylim');
-    for ip=1:nparam,
+    for ip=1:nparam
         text(ip,dy(1),name{is(ip)},'rotation',90,'HorizontalAlignment','right','interpreter','none')
     end
-    if advanced,
+    if advanced
         legend('Moments','Model','LRE model','Location','Best')
     end
     title('MC mean of sensitivity measures')
-    dyn_saveas(hh,[ IdentifDirectoryName '/' M_.fname '_MC_sensitivity' ],options_);
+    dyn_saveas(hh,[ IdentifDirectoryName '/' M_.fname '_MC_sensitivity' ],options_.nodisplay,options_.graph_format);
     if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
         fidTeX = fopen([ IdentifDirectoryName '/' M_.fname '_MC_sensitivity.tex'],'w');
         fprintf(fidTeX,'%% TeX eps-loader file generated by plot_identification.m (Dynare).\n');
@@ -343,14 +343,14 @@ else
         fprintf(fidTeX,'%% End Of TeX file. \n');
         fclose(fidTeX);
     end
-    
-    if advanced,
+
+    if advanced
         if ~options_.nodisplay,
             skipline()
             disp('Press ENTER to display advanced diagnostics'), pause(5),
         end
-%         options_.nograph=1;
-        hh = dyn_figure(options_,'Name','MC Condition Number');
+        %         options_.nograph=1;
+        hh = dyn_figure(options_.nodisplay,'Name','MC Condition Number');
         subplot(221)
         hist(log10(idemodel.cond))
         title('log10 of Condition number in the model')
@@ -360,7 +360,7 @@ else
         subplot(223)
         hist(log10(idelre.cond))
         title('log10 of Condition number in the LRE model')
-        dyn_saveas(hh,[IdentifDirectoryName '/' M_.fname '_ident_COND' ],options_);
+        dyn_saveas(hh,[IdentifDirectoryName '/' M_.fname '_ident_COND' ],options_.nodisplay,options_.graph_format);
         options_mcf.pvalue_ks = 0.1;
         options_mcf.pvalue_corr = 0.001;
         options_mcf.alpha2 = 0;
@@ -386,34 +386,34 @@ else
         options_mcf.title = 'MC Highest Condition Number Model Moments';
         [dum,is]=sort(idemoments.cond);
         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);
-% %             inonbeh=find(idemoments.Mco(j,:)>=0.9);
-% %             if ~isempty(ibeh) && ~isempty(inonbeh)
-% %                 [proba, dproba] = stab_map_1(params, ibeh, inonbeh, ['HighestMultiCollinearity_',name{j}], 1, [], IdentifDirectoryName);
-% %             end
-%             [~,is]=sort(idemoments.Mco(:,j));
-%             [proba, dproba] = stab_map_1(params, is(1:ncut), is(ncut+1:end), ['MC_HighestMultiCollinearity_',name{j}], 1, [], IdentifDirectoryName, 0.15);
-%         end
+        %         [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);
+        % %             inonbeh=find(idemoments.Mco(j,:)>=0.9);
+        % %             if ~isempty(ibeh) && ~isempty(inonbeh)
+        % %                 [proba, dproba] = stab_map_1(params, ibeh, inonbeh, ['HighestMultiCollinearity_',name{j}], 1, [], IdentifDirectoryName);
+        % %             end
+        %             [~,is]=sort(idemoments.Mco(:,j));
+        %             [proba, dproba] = stab_map_1(params, is(1:ncut), is(ncut+1:end), ['MC_HighestMultiCollinearity_',name{j}], 1, [], IdentifDirectoryName, 0.15);
+        %         end
 
-        if nparam<5,
-            f1 = dyn_figure(options_,'Name',[tittxt,' - MC Identification patterns (moments): HIGHEST SV']);
+        if nparam<5
+            f1 = dyn_figure(options_.nodisplay,'Name',[tittxt,' - MC Identification patterns (moments): HIGHEST SV']);
             tex_tit_1=[tittxt,' - MC Identification patterns (moments): HIGHEST SV'];
         else
-            f1 = dyn_figure(options_,'Name',[tittxt,' - MC Identification patterns (moments): SMALLEST SV']);
+            f1 = dyn_figure(options_.nodisplay,'Name',[tittxt,' - MC Identification patterns (moments): SMALLEST SV']);
             tex_tit_1=[tittxt,' - MC Identification patterns (moments): SMALLEST SV'];
-            f2 = dyn_figure(options_,'Name',[tittxt,' - MC Identification patterns (moments): HIGHEST SV']);
+            f2 = dyn_figure(options_.nodisplay,'Name',[tittxt,' - MC Identification patterns (moments): HIGHEST SV']);
             tex_tit_2=[tittxt,' - MC Identification patterns (moments): HIGHEST SV'];
         end
         nplots=min(nparam,8);
-        if nplots>4,
+        if nplots>4
             nsubplo=ceil(nplots/2);
         else
             nsubplo=nplots;
         end
-        for j=1:nplots,
-            if (nparam>4 && j<=ceil(nplots/2)) || nparam<5,
+        for j=1:nplots
+            if (nparam>4 && j<=ceil(nplots/2)) || nparam<5
                 set(0,'CurrentFigure',f1),
                 jj=j;
                 VVV=squeeze(abs(idemoments.V(:,:,end-j+1)));
@@ -424,8 +424,8 @@ else
                 VVV=squeeze(abs(idemoments.V(:,:,jj)));
                 SSS = idemoments.S(:,jj);
             end
-            subplot(nsubplo,1,jj),
-            for i=1:nparam,
+            subplot(nsubplo,1,jj)
+            for i=1:nparam
                 [post_mean, post_median(:,i), post_var, hpd_interval(i,:), post_deciles] = posterior_moments(VVV(:,i),0,0.9);
             end
             bar(post_median)
@@ -433,14 +433,14 @@ else
             Stit=mean(SSS);
 
             set(gca,'xticklabel','')
-            if j==4 || j==nparam || j==8,
-                for ip=1:nparam,
+            if j==4 || j==nparam || j==8
+                for ip=1:nparam
                     text(ip,-0.02,name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
                 end
             end
             title(['MEAN Singular value ',num2str(Stit)])
         end
-        dyn_saveas(f1,[IdentifDirectoryName '/' M_.fname '_MC_ident_pattern_1' ],options_);
+        dyn_saveas(f1,[IdentifDirectoryName '/' M_.fname '_MC_ident_pattern_1' ],options_.nodisplay,options_.graph_format);
         if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
             fidTeX = fopen([IdentifDirectoryName '/' M_.fname '_MC_ident_pattern_1.tex'],'w');
             fprintf(fidTeX,'%% TeX eps-loader file generated by plot_identification.m (Dynare).\n');
@@ -454,8 +454,8 @@ else
             fprintf(fidTeX,'%% End Of TeX file. \n');
             fclose(fidTeX);
         end
-        if nparam>4,
-            dyn_saveas(f2,[  IdentifDirectoryName '/' M_.fname '_MC_ident_pattern_2' ],options_);
+        if nparam>4
+            dyn_saveas(f2,[  IdentifDirectoryName '/' M_.fname '_MC_ident_pattern_2' ],options_.nodisplay,options_.graph_format);
             if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                 fidTeX = fopen([  IdentifDirectoryName '/' M_.fname '_MC_ident_pattern_2.tex'],'w');
                 fprintf(fidTeX,'%% TeX eps-loader file generated by plot_identification.m (Dynare).\n');
diff --git a/matlab/plot_priors.m b/matlab/plot_priors.m
index 15842b8e96cffd8142be9c73b6b0d861c72cb1ac..2b2fc83f6f41da02b38cf6da3b9ffe9ae939355b 100644
--- a/matlab/plot_priors.m
+++ b/matlab/plot_priors.m
@@ -13,7 +13,7 @@ function plot_priors(bayestopt_,M_,estim_params_,options_)
 % SPECIAL REQUIREMENTS
 %    None
 
-% Copyright (C) 2004-2016 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -42,8 +42,8 @@ if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
     fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
     fprintf(fidTeX,' \n');
 end
-for plt = 1:nbplt,
-    hplt = dyn_figure(options_,'Name',figurename);
+for plt = 1:nbplt
+    hplt = dyn_figure(options_.nodisplay,'Name',figurename);
     if TeX
         TeXNAMES = [];
         NAMES    = [];
@@ -70,10 +70,10 @@ for plt = 1:nbplt,
         title(nam,'Interpreter','none')
         drawnow
     end
-    dyn_saveas(hplt,[M_.fname '_Priors' int2str(plt)],options_);
+    dyn_saveas(hplt,[M_.fname '_Priors' int2str(plt)],options_.nodisplay,options_.graph_format);
     if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
         fprintf(fidTeX,'\\begin{figure}[H]\n');
-        for jj = 1:nstar0,
+        for jj = 1:nstar0
             fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:)));
         end
         fprintf(fidTeX,'\\centering\n');
diff --git a/matlab/plot_shock_decomposition.m b/matlab/plot_shock_decomposition.m
new file mode 100644
index 0000000000000000000000000000000000000000..182a0f906e6bb41471a69134b341a89d7b98d74e
--- /dev/null
+++ b/matlab/plot_shock_decomposition.m
@@ -0,0 +1,351 @@
+function [z, steady_state] = plot_shock_decomposition(M_,oo_,options_,varlist)
+% function plot_shock_decomposition(M_,oo_,options_,varlist)
+% Plots the results of shock_decomposition
+%
+% INPUTS
+%    M_:          [structure]  Definition of the model
+%    oo_:         [structure]  Storage of results
+%    options_:    [structure]  Options
+%    varlist:     [char]       List of variables
+%
+% SPECIAL REQUIREMENTS
+%    none
+
+% Copyright (C) 2016-2017 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/>.
+
+options_.nodisplay = options_.plot_shock_decomp.nodisplay;
+options_.graph_format = options_.plot_shock_decomp.graph_format;
+options_.use_shock_groups = options_.plot_shock_decomp.use_shock_groups;
+
+% indices of endogenous variables
+if size(varlist,1) == 0
+    varlist = M_.endo_names(1:M_.orig_endo_nbr,:);
+end
+
+[i_var,nvar,index_uniques] = varlist_indices(varlist,M_.endo_names);
+varlist=varlist(index_uniques,:);
+
+% number of variables
+endo_nbr = M_.endo_nbr;
+
+% number of shocks
+nshocks = M_.exo_nbr;
+% type = '';
+fig_name='';
+% detail_plot=0;
+% realtime_=0; % 0 is standard; 1 is realtime (pool/vintage); 2 is conditional (pool/vintage); 3 is forecast (pool/vintage)
+% vintage_=0; % 0 pool realtime/conditional; int: forecast/conditional shock decompositions
+% forecast_=0;
+% steadystate=0;
+% write_xls=0;
+
+if isfield(options_.plot_shock_decomp,'expand') % private trap for uimenu calls
+    expand=options_.plot_shock_decomp.expand;
+else
+    expand=0;
+end
+
+if ~isempty(options_.plot_shock_decomp.fig_name)
+    fig_name=[' ' options_.plot_shock_decomp.fig_name];
+end
+type=options_.plot_shock_decomp.type;
+detail_plot=options_.plot_shock_decomp.detail_plot;
+realtime_= options_.plot_shock_decomp.realtime;
+vintage_ = options_.plot_shock_decomp.vintage;
+forecast_ = options_.shock_decomp.forecast;
+steadystate = options_.plot_shock_decomp.steadystate;
+write_xls = options_.plot_shock_decomp.write_xls;
+
+if vintage_
+    forecast_ = min(forecast_,options_.nobs-vintage_);
+end
+
+initial_date = options_.initial_date;
+
+if isfield(options_.plot_shock_decomp,'q2a') % private trap for aoa calls
+    q2a=options_.plot_shock_decomp.q2a;
+    if isstruct(q2a) && isempty(fieldnames(q2a))
+        q2a=0;
+    end
+else
+    q2a=0;
+end
+
+switch realtime_
+
+  case 0
+    z = oo_.shock_decomposition;
+    fig_name1=fig_name;
+
+  case 1 % realtime
+    if vintage_
+        z = oo_.realtime_shock_decomposition.(['time_' int2str(vintage_)]);
+        fig_name1=[fig_name ' realtime (vintage ' char(initial_date+vintage_-1) ')'];
+    else
+        z = oo_.realtime_shock_decomposition.pool;
+        fig_name1=[fig_name ' realtime (rolling)'];
+    end
+
+  case 2 % conditional
+    if vintage_
+        z = oo_.realtime_conditional_shock_decomposition.(['time_' int2str(vintage_)]);
+        initial_date = options_.initial_date+vintage_-1;
+        fig_name1=[fig_name ' ' int2str(forecast_) '-step ahead conditional forecast (given ' char(initial_date) ')'];
+    else
+        z = oo_.conditional_shock_decomposition.pool;
+        fig_name1=[fig_name ' 1-step ahead conditional forecast (rolling)'];
+    end
+
+  case 3 % forecast
+    if vintage_
+        z = oo_.realtime_forecast_shock_decomposition.(['time_' int2str(vintage_)]);
+        initial_date = options_.initial_date+vintage_-1;
+        fig_name1=[fig_name ' ' int2str(forecast_) '-step ahead forecast (given ' char(initial_date) ')'];
+    else
+        z = oo_.realtime_forecast_shock_decomposition.pool;
+        fig_name1=[fig_name ' 1-step ahead forecast (rolling)'];
+    end
+end
+
+steady_state = oo_.steady_state;
+
+if isequal(type,'aoa') && isstruct(q2a) && realtime_
+    if isempty(initial_date)
+        t0=1;
+        initial_date = dates('1Y');
+    else
+        initial_date0 = dates([int2str(initial_date.time(1)) 'Y']);
+        if initial_date.time(2)==1
+            t0=1;
+            initial_date1=initial_date0;
+        else
+            t0=(4-initial_date.time(2)+2);
+            initial_date1=initial_date0+1;
+        end
+    end
+    t0=min(options_.plot_shock_decomp.save_realtime);
+    ini1 = initial_date+t0-1;
+    t0=t0+(4-ini1.time(2));
+    if ~isfield(q2a,'var_type') % private trap for aoa calls
+        q2a.var_type=1;
+    end
+    if ~isfield(q2a,'islog') % private trap for aoa calls
+        q2a.islog=0;
+    end
+    if ~isfield(q2a,'GYTREND0') % private trap for aoa calls
+        q2a.GYTREND0=0;
+    end
+    if ~isfield(q2a,'aux') % private trap for aoa calls
+        q2a.aux=0;
+    end
+    if ~isfield(q2a,'cumfix') % private trap for aoa calls
+        q2a.cumfix=1;
+    end
+    if ~isfield(q2a,'plot') % private trap for aoa calls
+        q2a.plot=1; % growth rate
+    end
+
+    %     if isstruct(q2a.aux) && ischar(q2a.aux.y)
+    %         opts=options_;
+    %         opts.plot_shock_decomp.type='qoq';
+    %         [y_aux, steady_state_aux] = plot_shock_decomposition(M_,oo_,opts,q2a.aux.y);
+    %         q2a.aux.y=y_aux;
+    %         q2a.aux.yss=steady_state_aux;
+    %     end
+    [za, endo_names, endo_names_tex, steady_state, i_var, oo_] = ...
+        annualized_shock_decomposition(oo_,M_, options_, i_var, t0, options_.nobs, realtime_, vintage_, steady_state,q2a);
+    %     if realtime_<2
+    %         initial_date = initial_date1;
+    %     else
+    %         initial_date = initial_date0;
+    %     end
+end
+
+
+
+if ~expand
+    fig_name = fig_name1;
+end
+gend = size(z,3);
+if options_.plot_shock_decomp.use_shock_groups
+    shock_groups = M_.shock_groups.(options_.plot_shock_decomp.use_shock_groups);
+    shock_ind = fieldnames(shock_groups);
+    ngroups = length(shock_ind);
+    fig_name=[fig_name ' group ' options_.plot_shock_decomp.use_shock_groups];
+    shock_names = shock_ind;
+    for i=1:ngroups
+        shock_names{i} = (shock_groups.(shock_ind{i}).label);
+    end
+    zz = zeros(endo_nbr,ngroups+2,gend);
+    kcum=[];
+    for i=1:ngroups
+        for j = shock_groups.(shock_ind{i}).shocks
+            k = find(strcmp(j,cellstr(M_.exo_names)));
+            zz(:,i,:) = zz(:,i,:) + z(:,k,:);
+            z(:,k,:) = 0;
+            kcum = [kcum k];
+        end
+    end
+    zothers = sum(z(:,1:nshocks,:),2);
+    shock_groups.(['group' int2str(ngroups+1)]).label =  'Others';
+    shock_groups.(['group' int2str(ngroups+1)]).shocks =  cellstr(M_.exo_names(find(~ismember([1:M_.exo_nbr],kcum)),:))';
+    M_.shock_groups.(options_.plot_shock_decomp.use_shock_groups)=shock_groups;
+    if any(any(zothers))
+        shock_names = [shock_names; {'Others + Initial Values'}];
+    end
+    zz(:,ngroups+1,:) = sum(z(:,1:nshocks+1,:),2);
+    zz(:,ngroups+2,:) = z(:,nshocks+2,:);
+    z = zz;
+else
+    shock_names = M_.exo_names;
+end
+
+func = @(x) colorspace('RGB->Lab',x);
+MAP = distinguishable_colors(size(z,2)-1,'w',func);
+%         MAP = [MAP; MAP(end,:)];
+MAP(end,:) = [0.7 0.7 0.7];
+%         MAP = [MAP; [0.7 0.7 0.7]; [0.3 0.3 0.3]];
+
+if isempty(options_.plot_shock_decomp.colormap)
+    options_.plot_shock_decomp.colormap = MAP;
+end
+
+switch type
+
+  case '' % default
+
+  case 'qoq'
+
+  case 'yoy'
+    z=z(:,:,1:end-3)+z(:,:,2:end-2)+z(:,:,3:end-1)+z(:,:,4:end);
+    if ~isempty(initial_date),
+        initial_date = initial_date+3;
+    else
+        initial_date = dates('1Q4');
+    end
+    steady_state = 4*steady_state;
+
+  case 'aoa'
+
+    if isempty(initial_date)
+        t0=4;
+        initial_date = dates('1Y');
+    else
+        initial_date0 = dates([int2str(initial_date.time(1)) 'Y']);
+        if initial_date.time(2)==1
+            t0=1;
+            initial_date1=initial_date0;
+        else
+            t0=(4-initial_date.time(2)+2);
+            initial_date1=initial_date0+1;
+        end
+    end
+    if isstruct(q2a)
+        if realtime_ == 0
+            if ~isfield(q2a,'var_type') % private trap for aoa calls
+                q2a.var_type=1;
+            end
+            if ~isfield(q2a,'islog') % private trap for aoa calls
+                q2a.islog=0;
+            end
+            if ~isfield(q2a,'GYTREND0') % private trap for aoa calls
+                q2a.GYTREND0=0;
+            end
+            if ~isfield(q2a,'aux') % private trap for aoa calls
+                q2a.aux=0;
+            end
+            if ~isfield(q2a,'cumfix') % private trap for aoa calls
+                q2a.cumfix=1;
+            end
+            if ~isfield(q2a,'plot') % private trap for aoa calls
+                q2a.plot=1; % growth rate
+            end
+
+            if isstruct(q2a.aux) && ischar(q2a.aux.y)
+                opts=options_;
+                opts.plot_shock_decomp.type='qoq';
+                [y_aux, steady_state_aux] = plot_shock_decomposition(M_,oo_,opts,q2a.aux.y);
+                q2a.aux.y=y_aux;
+                q2a.aux.yss=steady_state_aux;
+            end
+            [za, endo_names, endo_names_tex, steady_state, i_var, oo_] = ...
+                annualized_shock_decomposition(z,M_, options_, i_var, t0, options_.nobs, realtime_, vintage_, steady_state,q2a);
+        end
+        z = za;
+        M_.endo_names = endo_names;
+        M_.endo_names_tex = endo_names_tex;
+        %     endo_nbr = size(z,1);
+        if realtime_<2
+            initial_date = initial_date1;
+        else
+            initial_date = initial_date0;
+        end
+    else
+        t0=4-initial_date.time(2)+1;
+        initial_date = initial_date0;
+        z=z(:,:,t0:4:end);
+    end
+
+    if ~isempty(options_.plot_shock_decomp.plot_init_date)
+        options_.plot_shock_decomp.plot_init_date = dates([int2str(options_.plot_shock_decomp.plot_init_date.time(1)) 'Y']);
+    end
+    if ~isempty(options_.plot_shock_decomp.plot_end_date)
+        options_.plot_shock_decomp.plot_end_date = dates([int2str(options_.plot_shock_decomp.plot_end_date.time(1)) 'Y']);
+    end
+
+
+  otherwise
+
+    error('plot_shock_decomposition:: Wrong type')
+
+end
+if steadystate
+    options_.plot_shock_decomp.steady_state=steady_state;
+end
+
+if nargout
+    z=z(i_var,:,:);
+    steady_state = steady_state(i_var);
+    return
+end
+
+% here we crop data if needed
+my_initial_date = initial_date;
+a = 1;
+b = size(z,3);
+if ~isempty(options_.plot_shock_decomp.plot_init_date)
+    my_initial_date = max(initial_date,options_.plot_shock_decomp.plot_init_date);
+    a = find((initial_date:initial_date+b-1)==options_.plot_shock_decomp.plot_init_date);
+end
+if ~isempty(options_.plot_shock_decomp.plot_end_date)
+    b = find((initial_date:initial_date+b-1)==options_.plot_shock_decomp.plot_end_date);
+end
+z = z(:,:,a:b);
+% end crop data
+
+options_.plot_shock_decomp.fig_name=fig_name;
+options_.plot_shock_decomp.orig_varlist = varlist;
+if detail_plot
+    graph_decomp_detail(z,shock_names,M_.endo_names,i_var,my_initial_date,M_,options_)
+else
+    graph_decomp(z,shock_names,M_.endo_names,i_var,my_initial_date,M_,options_);
+end
+
+if write_xls
+    WriteShockDecomp2Excel(z,shock_names,M_.endo_names,i_var,initial_date,M_,options_,options_.plot_shock_decomp);
+end
diff --git a/matlab/pltorg.m b/matlab/pltorg.m
index 7f100e4b2f1f66e29bf59d80198ceae3f0abeb47..e7f6807725817baac573cde9154b86d0b2260ad7 100644
--- a/matlab/pltorg.m
+++ b/matlab/pltorg.m
@@ -1,6 +1,6 @@
 function [nbplt,nr,nc,lr,lc,nstar] = pltorg(number)
 
-% Copyright (C) 2004-2008 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -48,11 +48,11 @@ elseif number == 5
 elseif number == 6
     nbplt = 1;
     nr    = 3;
-    nc    = 2;    
+    nc    = 2;
 elseif number == 7
     nbplt = 1;
     nr    = 3;
-    nc    = 3;    
+    nc    = 3;
 elseif number == 8
     nbplt = 1;
     nr    = 3;
@@ -67,7 +67,7 @@ else
         nr    = nrstar;
         nc    = ncstar;
         lr    = nr;
-        lc    = nc; 
+        lc    = nc;
     else
         nbplt = ceil(number/nstar);
         nr    = nrstar;
@@ -90,10 +90,10 @@ else
             lc    = 2;
         elseif reste == 6
             lr    = 3;
-            lc    = 2;    
+            lc    = 2;
         elseif reste == 7
             lr    = 3;
-            lc    = 3;    
+            lc    = 3;
         elseif reste == 8
             lr    = 3;
             lc    = 3;
diff --git a/matlab/pm3.m b/matlab/pm3.m
index ae0f474d16b03363ce7ca1fd9a09168c2b6caf7c..695b641d8e47218c07ebb30dfc32ce57689ba5ed 100644
--- a/matlab/pm3.m
+++ b/matlab/pm3.m
@@ -7,7 +7,7 @@ function pm3(n1,n2,ifil,B,tit1,tit2,tit3,tit_tex,names1,names2,name3,DirectoryNa
 %  n2           [scalar] size of second dimension of moment matrix
 %  ifil         [scalar] number of moment files to load
 %  B            [scalar] number of subdraws
-%  tit1         [string] Figure title 
+%  tit1         [string] Figure title
 %  tit2         [string] not used
 %  tit3         [string] Save name for figure
 %  tit_tex      [cell array] TeX-Names for Variables
@@ -24,7 +24,7 @@ function pm3(n1,n2,ifil,B,tit1,tit2,tit3,tit_tex,names1,names2,name3,DirectoryNa
 % See also the comment in posterior_sampler.m funtion.
 
 
-% Copyright (C) 2007-2016 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -60,10 +60,10 @@ else
     end
 end
 if options_.TeX
-    if isempty(tit_tex),
+    if isempty(tit_tex)
         tit_tex=names1;
     end
-        
+
     varlist_TeX = [];
     for i=1:nvar
         if i==1
@@ -92,7 +92,7 @@ for file = 1:ifil
     stock=loaded_file.stock;
     if strcmp(var_type,'_filter_step_ahead')
         if file==1 %on first run, initialize variable for storing filter_step_ahead
-            stock1_filter_step_ahead=NaN(n1,n2,B,length(options_.filter_step_ahead)); 
+            stock1_filter_step_ahead=NaN(n1,n2,B,length(options_.filter_step_ahead));
             stock1 = zeros(n1,n2,B);
         end
         filter_step_ahead_indicator=1;
@@ -289,112 +289,111 @@ if strcmp(var_type,'_trend_coeff') || max(max(abs(Mean(:,:))))<=10^(-6) || all(a
     return %not do plots
 end
 %%
-%% 	Finally I build the plots.
+%%      Finally I build the plots.
 %%
 
 if ~options_.nograph && ~options_.no_graph.posterior
-% Block of code executed in parallel, with the exception of file
-% .tex generation always run sequentially. This portion of code is execute in parallel by
-% pm3_core1.m function.
+    % Block of code executed in parallel, with the exception of file
+    % .tex generation always run sequentially. This portion of code is execute in parallel by
+    % pm3_core1.m function.
 
-% %%%%%%%%%   PARALLEL BLOCK % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-%
-% %%% The file .TeX! are not saved in parallel.
+    % %%%%%%%%%   PARALLEL BLOCK % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+    %
+    % %%% The file .TeX! are not saved in parallel.
 
 
 
-% Store the variable mandatory for local/remote parallel computing.
+    % Store the variable mandatory for local/remote parallel computing.
 
-localVars=[];
+    localVars=[];
 
-localVars.tit1=tit1;
-localVars.nn=nn;
-localVars.n2=n2;
-localVars.Distrib=Distrib;
-localVars.varlist=varlist;
-localVars.MaxNumberOfPlotsPerFigure=MaxNumberOfPlotsPerFigure;
-localVars.name3=name3;
-localVars.tit3=tit3;
-localVars.Mean=Mean;
-% Like sequential execution!
-nvar0=nvar;
+    localVars.tit1=tit1;
+    localVars.nn=nn;
+    localVars.n2=n2;
+    localVars.Distrib=Distrib;
+    localVars.varlist=varlist;
+    localVars.MaxNumberOfPlotsPerFigure=MaxNumberOfPlotsPerFigure;
+    localVars.name3=name3;
+    localVars.tit3=tit3;
+    localVars.Mean=Mean;
+    % Like sequential execution!
+    nvar0=nvar;
 
-if ~isoctave
-    % Commenting for testing!
-    if isnumeric(options_.parallel) || ceil(size(varlist,1)/MaxNumberOfPlotsPerFigure)<4,
-        fout = pm3_core(localVars,1,nvar,0);
-        
-        % Parallel execution!
-    else
-        isRemoteOctave = 0;
-        for indPC=1:length(options_.parallel),
-            isRemoteOctave = isRemoteOctave + (findstr(options_.parallel(indPC).MatlabOctavePath, 'octave'));
-        end
-        if isRemoteOctave
+    if ~isoctave
+        % Commenting for testing!
+        if isnumeric(options_.parallel) || ceil(size(varlist,1)/MaxNumberOfPlotsPerFigure)<4
             fout = pm3_core(localVars,1,nvar,0);
+
+            % Parallel execution!
         else
-            globalVars = struct('M_',M_, ...
-                'options_', options_, ...
-                'oo_', oo_);
-            [fout, nvar0, totCPU] = masterParallel(options_.parallel, 1, nvar, [],'pm3_core', localVars,globalVars, options_.parallel_info);
+            isRemoteOctave = 0;
+            for indPC=1:length(options_.parallel)
+                isRemoteOctave = isRemoteOctave + (findstr(options_.parallel(indPC).MatlabOctavePath, 'octave'));
+            end
+            if isRemoteOctave
+                fout = pm3_core(localVars,1,nvar,0);
+            else
+                globalVars = struct('M_',M_, ...
+                                    'options_', options_, ...
+                                    'oo_', oo_);
+                [fout, nvar0, totCPU] = masterParallel(options_.parallel, 1, nvar, [],'pm3_core', localVars,globalVars, options_.parallel_info);
+            end
         end
+    else
+        % For the time being in Octave enviroment the pm3.m is executed only in
+        % serial modality, to avoid problem with the plots.
+
+        fout = pm3_core(localVars,1,nvar,0);
     end
-else
-    % For the time being in Octave enviroment the pm3.m is executed only in
-    % serial modality, to avoid problem with the plots.
-    
-    fout = pm3_core(localVars,1,nvar,0);
-end
 
-subplotnum = 0;
+    subplotnum = 0;
 
-if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
-    fidTeX = fopen([M_.dname '/Output/' M_.fname '_' name3 '.tex'],'w');
-    fprintf(fidTeX,'%% TeX eps-loader file generated by Dynare.\n');
-    fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
-    fprintf(fidTeX,' \n');
-    nvar0=cumsum(nvar0);
+    if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
+        fidTeX = fopen([M_.dname '/Output/' M_.fname '_' name3 '.tex'],'w');
+        fprintf(fidTeX,'%% TeX eps-loader file generated by Dynare.\n');
+        fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
+        fprintf(fidTeX,' \n');
+        nvar0=cumsum(nvar0);
 
-    i=0;    
-    for j=1:length(nvar0),
-    
-    NAMES = [];
-    TEXNAMES = [];
-    nvar=nvar0(j);
-    while i<nvar,
-        i=i+1;
-        if max(abs(Mean(:,i))) > 10^(-6)
-            subplotnum = subplotnum+1;
-            name = deblank(varlist(i,:));
-            texname = deblank(varlist_TeX(i,:));
-            if subplotnum==1
-                NAMES = name;
-                TEXNAMES = ['$' texname '$'];
-            else
-                NAMES = char(NAMES,name);
-                TEXNAMES = char(TEXNAMES,['$' texname '$']);
-            end
-        end
-        if subplotnum == MaxNumberOfPlotsPerFigure || i == nvar
-            fprintf(fidTeX,'\\begin{figure}[H]\n');
-            for jj = 1:size(TEXNAMES,1)
-                fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{%s}\n'],deblank(NAMES(jj,:)),deblank(TEXNAMES(jj,:)));
-            end
-            fprintf(fidTeX,'\\centering \n');
-            fprintf(fidTeX,['\\includegraphics[width=%2.2f\\textwidth]{%s/Output/%s_' name3 '_%s}\n'],options_.figures.textwidth*min(subplotnum/nn,1),M_.dname,M_.fname,deblank(tit3(i,:)));
-            fprintf(fidTeX,'\\label{Fig:%s:%s}\n',name3,deblank(tit3(i,:)));
-            fprintf(fidTeX,'\\caption{%s}\n',tit1);
-            fprintf(fidTeX,'\\end{figure}\n');
-            fprintf(fidTeX,' \n');
-            subplotnum = 0;
+        i=0;
+        for j=1:length(nvar0)
             NAMES = [];
             TEXNAMES = [];
+            nvar=nvar0(j);
+            while i<nvar
+                i=i+1;
+                if max(abs(Mean(:,i))) > 10^(-6)
+                    subplotnum = subplotnum+1;
+                    name = deblank(varlist(i,:));
+                    texname = deblank(varlist_TeX(i,:));
+                    if subplotnum==1
+                        NAMES = name;
+                        TEXNAMES = ['$' texname '$'];
+                    else
+                        NAMES = char(NAMES,name);
+                        TEXNAMES = char(TEXNAMES,['$' texname '$']);
+                    end
+                end
+                if subplotnum == MaxNumberOfPlotsPerFigure || i == nvar
+                    fprintf(fidTeX,'\\begin{figure}[H]\n');
+                    for jj = 1:size(TEXNAMES,1)
+                        fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{%s}\n'],deblank(NAMES(jj,:)),deblank(TEXNAMES(jj,:)));
+                    end
+                    fprintf(fidTeX,'\\centering \n');
+                    fprintf(fidTeX,['\\includegraphics[width=%2.2f\\textwidth]{%s/Output/%s_' name3 '_%s}\n'],options_.figures.textwidth*min(subplotnum/nn,1),M_.dname,M_.fname,deblank(tit3(i,:)));
+                    fprintf(fidTeX,'\\label{Fig:%s:%s}\n',name3,deblank(tit3(i,:)));
+                    fprintf(fidTeX,'\\caption{%s}\n',tit1);
+                    fprintf(fidTeX,'\\end{figure}\n');
+                    fprintf(fidTeX,' \n');
+                    subplotnum = 0;
+                    NAMES = [];
+                    TEXNAMES = [];
+                end
+            end
         end
+        fprintf(fidTeX,'%% End of TeX file.\n');
+        fclose(fidTeX);
     end
-    end
-    fprintf(fidTeX,'%% End of TeX file.\n');
-    fclose(fidTeX);
-end
 end
 
 fprintf(['Estimation::mcmc: ' tit1 ', done!\n']);
diff --git a/matlab/pm3_core.m b/matlab/pm3_core.m
index c2d248f760d15e83f394c68b194a37d976149477..881c4b42350e22dd657127e02cd9461319864f9e 100644
--- a/matlab/pm3_core.m
+++ b/matlab/pm3_core.m
@@ -3,7 +3,7 @@ function myoutput=pm3_core(myinputs,fpar,nvar,whoiam, ThisMatlab)
 % PARALLEL CONTEXT
 % Core functionality for pm3.m function, which can be parallelized.
 
-% INPUTS 
+% INPUTS
 % See the comment in posterior_sampler_core.m funtion.
 
 % OUTPUTS
@@ -13,7 +13,7 @@ function myoutput=pm3_core(myinputs,fpar,nvar,whoiam, ThisMatlab)
 % SPECIAL REQUIREMENTS.
 %   None.
 
-% Copyright (C) 2007-2016 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -30,7 +30,7 @@ function myoutput=pm3_core(myinputs,fpar,nvar,whoiam, ThisMatlab)
 % 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,
+if nargin<4
     whoiam=0;
 end
 
@@ -64,9 +64,9 @@ end
 
 figunumber = 0;
 subplotnum = 0;
-hh = dyn_figure(options_,'Name',[tit1 ' ' int2str(figunumber+1)]);
+hh = dyn_figure(options_.nodisplay,'Name',[tit1 ' ' int2str(figunumber+1)]);
 RemoteFlag = 0;
-if whoiam,
+if whoiam
     if Parallel(ThisMatlab).Local ==0
         RemoteFlag=1;
     end
@@ -100,35 +100,35 @@ for i=fpar:nvar
             set(gca,'yticklabel',yticklabels_new)
         end
     end
-    
-    if whoiam,
+
+    if whoiam
         if Parallel(ThisMatlab).Local==0
             DirectoryName = CheckPath('Output',M_.dname);
         end
     end
-    
+
     if subplotnum == MaxNumberOfPlotsPerFigure || i == nvar
-        dyn_saveas(hh,[M_.dname '/Output/'  M_.fname '_' name3 '_' deblank(tit3(i,:))],options_);
-        if RemoteFlag==1,
+        dyn_saveas(hh,[M_.dname '/Output/'  M_.fname '_' name3 '_' deblank(tit3(i,:))],options_.nodisplay,options_.graph_format);
+        if RemoteFlag==1
             OutputFileName = [OutputFileName; {[M_.dname, filesep, 'Output',filesep], [M_.fname '_' name3 '_' deblank(tit3(i,:)) '.*']}];
         end
         subplotnum = 0;
         figunumber = figunumber+1;
         if (i ~= nvar)
-            hh = dyn_figure(options_,'Name',[name3 ' ' int2str(figunumber+1)]);
+            hh = dyn_figure(options_.nodisplay,'Name',[name3 ' ' int2str(figunumber+1)]);
         end
     end
-    
-    if whoiam,
-%         waitbarString = [ 'Variable ' int2str(i) '/' int2str(nvar) ' done.'];
-%         fMessageStatus((i-fpar+1)/(nvar-fpar+1),whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab));
+
+    if whoiam
+        %         waitbarString = [ 'Variable ' int2str(i) '/' int2str(nvar) ' done.'];
+        %         fMessageStatus((i-fpar+1)/(nvar-fpar+1),whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab));
         dyn_waitbar((i-fpar+1)/(nvar-fpar+1),h);
     end
-    
-    
+
+
 end
 
-if whoiam,
+if whoiam
     dyn_waitbar_close(h);
 end
 myoutput.OutputFileName=OutputFileName;
diff --git a/matlab/posterior_analysis.m b/matlab/posterior_analysis.m
index faa117c03c815a94a1e05e4ac30a6178fab09d67..fa365b60775253e6554eaee9ad9cfce60e7356db 100644
--- a/matlab/posterior_analysis.m
+++ b/matlab/posterior_analysis.m
@@ -1,5 +1,5 @@
-function oo_ = posterior_analysis(type,arg1,arg2,arg3,options_,M_,oo_)  
-% Copyright (C) 2008-2012 Dynare Team
+function oo_ = posterior_analysis(type,arg1,arg2,arg3,options_,M_,oo_)
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -55,14 +55,14 @@ switch type
             dsge_simulated_theoretical_covariance(SampleSize,M_,options_,oo_,'posterior');
     end
     oo_ = covariance_mc_analysis(SampleSize,'posterior',M_.dname,M_.fname,...
-                                 vartan,nvar,arg1,arg2,options_.mh_conf_sig,oo_,options_);          
+                                 vartan,nvar,arg1,arg2,options_.mh_conf_sig,oo_,options_);
   case 'decomposition'
     if nargin==narg1
         [nvar,vartan,NumberOfFiles] = ...
             dsge_simulated_theoretical_variance_decomposition(SampleSize,M_,options_,oo_,'posterior');
     end
     oo_ = variance_decomposition_mc_analysis(SampleSize,'posterior',M_.dname,M_.fname,...
-                                             M_.exo_names,arg2,vartan,arg1,options_.mh_conf_sig,oo_,options_);    
+                                             M_.exo_names,arg2,vartan,arg1,options_.mh_conf_sig,oo_,options_);
   case 'correlation'
     if nargin==narg1
         [nvar,vartan,NumberOfFiles] = ...
@@ -76,7 +76,7 @@ switch type
             dsge_simulated_theoretical_conditional_variance_decomposition(SampleSize,arg3,M_,options_,oo_,'posterior');
     end
     oo_ = conditional_variance_decomposition_mc_analysis(SampleSize,'posterior',M_.dname,M_.fname,...
-                                                      arg3,M_.exo_names,arg2,vartan,arg1,options_.mh_conf_sig,oo_,options_);    
+                                                      arg3,M_.exo_names,arg2,vartan,arg1,options_.mh_conf_sig,oo_,options_);
   otherwise
     disp('Not yet implemented')
 end
\ No newline at end of file
diff --git a/matlab/posterior_moments.m b/matlab/posterior_moments.m
index beb1b0a41193f50db5597986752ffae21b5fb9df..915827328f5ffb8d386f93c0de33df723a3e8c15 100644
--- a/matlab/posterior_moments.m
+++ b/matlab/posterior_moments.m
@@ -11,17 +11,17 @@ function [post_mean, post_median, post_var, hpd_interval, post_deciles, density]
 %    post_mean     [double]    Scalar, posterior mean.
 %    post_median   [double]    Scalar, posterior median.
 %    post_var      [double]    Scalar, posterior variance.
-%    hpd_interval  [double]    Vector (1*2), Highest Probability Density interval 
+%    hpd_interval  [double]    Vector (1*2), Highest Probability Density interval
 %    post_deciles  [double]    Vector (9*1), deciles of the posterior distribution.
-%    density       [double]    Matrix (n*2), non parametric estimate of the posterior density. First and second 
-%                              columns are respectively abscissa and ordinate coordinates.  
-%    
+%    density       [double]    Matrix (n*2), non parametric estimate of the posterior density. First and second
+%                              columns are respectively abscissa and ordinate coordinates.
+%
 % SPECIAL REQUIREMENTS
-%    Other matlab routines distributed with Dynare: mh_optimal_bandwidth.m 
+%    Other matlab routines distributed with Dynare: mh_optimal_bandwidth.m
 %                                                   kernel_density_estimate.m.
 %
 
-% Copyright (C) 2005-2011 Dynare Team
+% Copyright (C) 2005-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -41,7 +41,7 @@ function [post_mean, post_median, post_var, hpd_interval, post_deciles, density]
 if nargin<4
     number_of_grid_points = 2^9;      % 2^9 = 512 !... Must be a power of two.
     bandwidth = 0;                    % Rule of thumb optimal bandwidth parameter.
-    kernel_function = 'gaussian';     % Gaussian kernel for Fast Fourrier Transform approximaton.  
+    kernel_function = 'gaussian';     % Gaussian kernel for Fast Fourrier Transform approximaton.
 else
     number_of_grid_points = kernel_options.gridpoints;
     bandwidth = kernel_options.bandwidth;
@@ -69,7 +69,7 @@ if hpd_draws>2
     [kmin,idx] = min(kk);
     hpd_interval = [xx(idx) xx(idx)+kmin];
 else
-    hpd_interval=NaN(1,2);    
+    hpd_interval=NaN(1,2);
 end
 if length(xx)>9
     post_deciles = xx([round(0.1*number_of_draws) ...
diff --git a/matlab/posterior_sampler.m b/matlab/posterior_sampler.m
index d7b7581858f500f2b37e36295d1e40dba8c1ac52..70f7b5de9f8786ee3edb7613803d2df8d350179b 100644
--- a/matlab/posterior_sampler.m
+++ b/matlab/posterior_sampler.m
@@ -1,8 +1,8 @@
 function posterior_sampler(TargetFun,ProposalFun,xparam1,sampler_options,mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_)
 % function posterior_sampler(TargetFun,ProposalFun,xparam1,sampler_options,mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_)
-% Random Walk Metropolis-Hastings algorithm. 
-% 
-% INPUTS 
+% 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
@@ -10,7 +10,7 @@ function posterior_sampler(TargetFun,ProposalFun,xparam1,sampler_options,mh_boun
 %   o xparam1    [double]   (p*1) vector of parameters to be estimated (initial values).
 %   o sampler_options       structure
 %            .invhess       [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 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
@@ -27,7 +27,7 @@ function posterior_sampler(TargetFun,ProposalFun,xparam1,sampler_options,mh_boun
 % 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 posterior_sampler_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.
@@ -37,7 +37,7 @@ function posterior_sampler(TargetFun,ProposalFun,xparam1,sampler_options,mh_boun
 % Then the comments write here can be used for all the other pairs of
 % parallel functions and also for management functions.
 
-% Copyright (C) 2006-2016 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -107,7 +107,7 @@ localVars =   struct('TargetFun', TargetFun, ...
                      'oo_', oo_,...
                      'varargin',[]);
 
-if strcmp(sampler_options.posterior_sampling_method,'tailored_random_block_metropolis_hastings');
+if strcmp(sampler_options.posterior_sampling_method,'tailored_random_block_metropolis_hastings')
     localVars.options_.silent_optimizer=1; %locally set optimizer to silent mode
     if ~isempty(sampler_options.optim_opt)
         localVars.options_.optim_opt=sampler_options.optim_opt; %locally set options for optimizer
@@ -117,26 +117,31 @@ end
 % User doesn't want to use parallel computing, or wants to compute a
 % single chain compute sequentially.
 
-if isnumeric(options_.parallel) || (nblck-fblck)==0,
+if isnumeric(options_.parallel) || (nblck-fblck)==0
     fout = posterior_sampler_core(localVars, fblck, nblck, 0);
     record = fout.record;
-    % Parallel in Local or remote machine.   
-else 
+    % Parallel in Local or remote machine.
+else
     % Global variables for parallel routines.
     globalVars = struct();
     % which files have to be copied to run remotely
     NamFileInput(1,:) = {'',[ModelName '_static.m']};
     NamFileInput(2,:) = {'',[ModelName '_dynamic.m']};
-    if options_.steadystate_flag,
-        NamFileInput(length(NamFileInput)+1,:)={'',[ModelName '_steadystate.m']};
+    NamFileInput(3,:) = {'',[M_.fname '_set_auxiliary_variables.m']};
+    if options_.steadystate_flag
+        if options_.steadystate_flag == 1
+            NamFileInput(length(NamFileInput)+1,:)={'',[M_.fname '_steadystate.m']};
+        else
+            NamFileInput(length(NamFileInput)+1,:)={'',[M_.fname '_steadystate2.m']};
+        end
     end
-    if (options_.load_mh_file~=0)  && any(fline>1) ,
+    if (options_.load_mh_file~=0)  && any(fline>1)
         NamFileInput(length(NamFileInput)+1,:)={[M_.dname '/metropolis/'],[ModelName '_mh' int2str(NewFile(1)) '_blck*.mat']};
     end
     % from where to get back results
     %     NamFileOutput(1,:) = {[M_.dname,'/metropolis/'],'*.*'};
     [fout, nBlockPerCPU, totCPU] = masterParallel(options_.parallel, fblck, nblck,NamFileInput,'posterior_sampler_core', localVars, globalVars, options_.parallel_info);
-    for j=1:totCPU,
+    for j=1:totCPU
         offset = sum(nBlockPerCPU(1:j-1))+fblck-1;
         record.LastLogPost(offset+1:sum(nBlockPerCPU(1:j)))=fout(j).record.LastLogPost(offset+1:sum(nBlockPerCPU(1:j)));
         record.LastParameters(offset+1:sum(nBlockPerCPU(1:j)),:)=fout(j).record.LastParameters(offset+1:sum(nBlockPerCPU(1:j)),:);
diff --git a/matlab/posterior_sampler_core.m b/matlab/posterior_sampler_core.m
index d88ae742ac633dd75ae2c12bbadc7169a2d93f08..b753391b4681cba17eaa27a19778d3023edd4cd1 100644
--- a/matlab/posterior_sampler_core.m
+++ b/matlab/posterior_sampler_core.m
@@ -31,12 +31,12 @@ function myoutput = posterior_sampler_core(myinputs,fblck,nblck,whoiam, ThisMatl
 %
 % SPECIAL REQUIREMENTS.
 %   None.
-% 
+%
 % PARALLEL CONTEXT
 % See the comments in the posterior_sampler.m funtion.
 
 
-% Copyright (C) 2006-2016 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -53,7 +53,7 @@ function myoutput = posterior_sampler_core(myinputs,fblck,nblck,whoiam, ThisMatl
 % 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,
+if nargin<4
     whoiam=0;
 end
 
@@ -108,7 +108,7 @@ end
 %
 
 sampler_options.xparam1 = xparam1;
-if ~isempty(d),
+if ~isempty(d)
     sampler_options.proposal_covariance_Cholesky_decomposition = d*diag(bayestopt_.jscale);
     %store information for load_mh_file
     record.ProposalCovariance=d;
@@ -117,7 +117,7 @@ end
 
 block_iter=0;
 
-for curr_block = fblck:nblck,
+for curr_block = fblck:nblck
     LastSeeds=[];
     block_iter=block_iter+1;
     try
@@ -132,9 +132,9 @@ for curr_block = fblck:nblck,
             set_dynare_seed(options_.DynareRandomStreams.seed+curr_block);
         end
         % Set the state of the RNG
-        set_dynare_random_generator_state(record.InitialSeeds(curr_block).Unifor, record.InitialSeeds(curr_block).Normal);            
+        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 
+        % 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(curr_block)>1) && OpenOldFile(curr_block) %load previous draws and likelihood
@@ -164,9 +164,9 @@ for curr_block = fblck:nblck,
     feval_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, logpost, accepted, neval] = posterior_sampler_iteration(TargetFun, last_draw(curr_block,:), last_posterior(curr_block), sampler_options,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_);
 
         x2(draw_index_current_file,:) = par;
@@ -192,7 +192,7 @@ for curr_block = fblck:nblck,
         end
         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
             [LastSeeds.(['file' int2str(NewFile(curr_block))]).Unifor, LastSeeds.(['file' int2str(NewFile(curr_block))]).Normal] = get_dynare_random_generator_state();
-            if save_tmp_file,
+            if save_tmp_file
                 delete([BaseName '_mh_tmp_blck' int2str(curr_block) '.mat']);
             end
             save([BaseName '_mh' int2str(NewFile(curr_block)) '_blck' int2str(curr_block) '.mat'],'x2','logpo2','LastSeeds');
diff --git a/matlab/posterior_sampler_initialization.m b/matlab/posterior_sampler_initialization.m
index f7927a173531a09c77c6749bad65344c04d0261c..b8b65e8b8dc6a11a7d63300c99014bea463c109e 100644
--- a/matlab/posterior_sampler_initialization.m
+++ b/matlab/posterior_sampler_initialization.m
@@ -3,13 +3,13 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa
 % function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npar, NumberOfBlocks, nruns, NewFile, MAX_nruns, d, bayestopt_] = ...
 %     metropolis_hastings_initialization(TargetFun, xparam1, vv, mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_)
 % Metropolis-Hastings initialization.
-% 
-% INPUTS 
+%
+% INPUTS
 %   o TargetFun  [char]     string specifying the name of the objective
 %                           function (posterior kernel).
 %   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 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
@@ -17,17 +17,17 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa
 %   o estim_params_         estimated parameters structure
 %   o bayestopt_            estimation options structure
 %   o oo_                   outputs structure
-%  
-% OUTPUTS 
+%
+% OUTPUTS
 %   o ix2                   [double]   (NumberOfBlocks*npar) vector of starting points for different chains
 %   o ilogpo2               [double]   (NumberOfBlocks*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 FirstBlock            [scalar]    number of the first MH chain to be run (not equal to 1 in case of recovery)   
-%   o FirstLine             [double]   (NumberOfBlocks*1) vector of first draw in each chain (not equal to 1 in case of recovery)   
+%   o FirstBlock            [scalar]    number of the first MH chain to be run (not equal to 1 in case of recovery)
+%   o FirstLine             [double]   (NumberOfBlocks*1) vector of first draw in each chain (not equal to 1 in case of recovery)
 %   o npar                  [scalar]    number of parameters estimated
-%   o NumberOfBlocks        [scalar]    Number of MCM chains requested   
-%   o nruns                 [double]   (NumberOfBlocks*1) number of draws in each chain 
+%   o NumberOfBlocks        [scalar]    Number of MCM chains requested
+%   o nruns                 [double]   (NumberOfBlocks*1) number of draws in each chain
 %   o NewFile               [scalar]    (NumberOfBlocks*1) vector storing the number
 %                                       of the first MH-file to created for each chain when saving additional
 %                                       draws
@@ -38,7 +38,7 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2006-2015 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -58,7 +58,7 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa
 %Initialize outputs
 ix2 = [];
 ilogpo2 = [];
-ModelName = []; 
+ModelName = [];
 MetropolisFolder = [];
 FirstBlock = [];
 FirstLine = [];
@@ -112,7 +112,7 @@ if ~options_.load_mh_file && ~options_.mh_recover
     fprintf(fidlog,['  Number of blocks...............: ' int2str(NumberOfBlocks) '\n']);
     fprintf(fidlog,['  Number of simulations per block: ' int2str(nruns(1)) '\n']);
     fprintf(fidlog,' \n');
-    if isempty(d),
+    if isempty(d)
         prior_draw(bayestopt_,options_.prior_trunc);
     end
     % Find initial values for the NumberOfBlocks chains...
@@ -127,12 +127,12 @@ if ~options_.load_mh_file && ~options_.mh_recover
             init_iter   = 0;
             trial = 1;
             while validate == 0 && trial <= 10
-                if isempty(d),
+                if isempty(d)
                     candidate = prior_draw();
                 else
                     candidate = rand_multivariate_normal( transpose(xparam1), d * options_.mh_init_scale, npar);
                 end
-                if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub) 
+                if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub)
                     ix2(j,:) = candidate;
                     ilogpo2(j) = - feval(TargetFun,ix2(j,:)',dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_);
                     if ~isfinite(ilogpo2(j)) % if returned log-density is
@@ -175,7 +175,7 @@ if ~options_.load_mh_file && ~options_.mh_recover
     else% Case 2: one chain (we start from the posterior mode)
         fprintf(fidlog,['  Initial values of the parameters:\n']);
         candidate = transpose(xparam1(:));%
-        if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub) 
+        if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub)
             ix2 = candidate;
             ilogpo2 = - feval(TargetFun,ix2',dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_);
             disp('Estimation::mcmc: Initialization at the posterior mode.')
@@ -234,7 +234,7 @@ if ~options_.load_mh_file && ~options_.mh_recover
     fprintf(fidlog,['    Expected number of files per block.......: ' int2str(AnticipatedNumberOfFiles) '.\n']);
     fprintf(fidlog,['    Expected number of lines in the last file: ' int2str(AnticipatedNumberOfLinesInTheLastFile) '.\n']);
     fprintf(fidlog,['\n']);
-    for j = 1:NumberOfBlocks,
+    for j = 1:NumberOfBlocks
         fprintf(fidlog,['    Initial state of the Gaussian random number generator for chain number ',int2str(j),':\n']);
         for i=1:length(record.InitialSeeds(j).Normal)
             fprintf(fidlog,['      ' num2str(record.InitialSeeds(j).Normal(i)') '\n']);
@@ -243,7 +243,7 @@ if ~options_.load_mh_file && ~options_.mh_recover
         for i=1:length(record.InitialSeeds(j).Unifor)
             fprintf(fidlog,['      ' num2str(record.InitialSeeds(j).Unifor(i)') '\n']);
         end
-    end,
+    end
     fprintf(fidlog,' \n');
     fclose(fidlog);
 elseif options_.load_mh_file && ~options_.mh_recover
@@ -293,7 +293,7 @@ elseif options_.load_mh_file && ~options_.mh_recover
     NumberOfDrawsWrittenInThePastLastFile = MAX_nruns - LastLineNumber;
     NumberOfDrawsToBeSaved = nruns(1) - NumberOfDrawsWrittenInThePastLastFile;
     AnticipatedNumberOfFiles = ceil(NumberOfDrawsToBeSaved/MAX_nruns);
-    AnticipatedNumberOfLinesInTheLastFile = NumberOfDrawsToBeSaved - (AnticipatedNumberOfFiles-1)*MAX_nruns;  
+    AnticipatedNumberOfLinesInTheLastFile = NumberOfDrawsToBeSaved - (AnticipatedNumberOfFiles-1)*MAX_nruns;
     record.LastFileNumber = LastFileNumber + AnticipatedNumberOfFiles;
     record.LastLineNumber = AnticipatedNumberOfLinesInTheLastFile;
     record.MhDraws(end,1) = nruns(1);
@@ -312,15 +312,15 @@ elseif options_.mh_recover
     load_last_mh_history_file(MetropolisFolder, ModelName);
     NumberOfBlocks = record.Nblck;% Number of "parallel" mcmc chains.
     options_.mh_nblck = NumberOfBlocks;
-    
+
     %% check consistency of options
     if record.MhDraws(end,1)~=options_.mh_replic
         fprintf('\nEstimation::mcmc: You cannot specify a different mh_replic than in the chain you are trying to recover\n')
         fprintf('Estimation::mcmc: I am resetting mh_replic to %u\n',record.MhDraws(end,1))
         options_.mh_replic=record.MhDraws(end,1);
         nruns = ones(NumberOfBlocks,1)*options_.mh_replic;
-    end    
-    
+    end
+
     if ~isnan(record.MAX_nruns(end,1)) %field exists
         if record.MAX_nruns(end,1)~=MAX_nruns
             fprintf('\nEstimation::mcmc: You cannot specify a different MaxNumberOfBytes than in the chain you are trying to recover\n')
@@ -347,9 +347,9 @@ elseif options_.mh_recover
     if OldMhExists
         LastLineNumberInThePreviousMh = record.MhDraws(end-1,3);% Number of lines in the last mh files of the previous session.
         LastFileNumberInThePreviousMh = sum(record.MhDraws(1:end-1,2),1);% Number of mh files in the the previous sessions.
-        %Test if the last mh files of the previous session were not full yet 
-        if LastLineNumberInThePreviousMh < MAX_nruns%not full 
-            %store starting point if whole chain needs to be redone
+                                                                         %Test if the last mh files of the previous session were not full yet
+        if LastLineNumberInThePreviousMh < MAX_nruns%not full
+                                                    %store starting point if whole chain needs to be redone
             NewFile = ones(NumberOfBlocks,1)*LastFileNumberInThePreviousMh;
             FirstLine = ones(NumberOfBlocks,1)*(LastLineNumberInThePreviousMh+1);
             LastFileFullIndicator=0;
@@ -368,7 +368,7 @@ elseif options_.mh_recover
     end
     [d,bayestopt_]=set_proposal_density_to_previous_value(record,options_,bayestopt_);
     %% Now find out what exactly needs to be redone
-    % 1. Check if really something needs to be done 
+    % 1. Check if really something needs to be done
     % How many mh files should we have ?
     ExpectedNumberOfMhFilesPerBlock = sum(record.MhDraws(:,2),1);
     ExpectedNumberOfMhFiles = ExpectedNumberOfMhFilesPerBlock*NumberOfBlocks;
@@ -378,7 +378,7 @@ elseif options_.mh_recover
     % Quit if no crashed mcmc chain can be found as there are as many files as expected
     if (TotalNumberOfMhFiles==ExpectedNumberOfMhFiles)
         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('                  You have to edit the mod file and remove the mh_recover option')
         disp('                  in the estimation command')
         error('Estimation::mcmc: mh_recover option not required!')
     end
@@ -401,15 +401,15 @@ elseif options_.mh_recover
         end
         FirstBlock = FirstBlock+1;
     end
-    
-    %% 3. Overwrite default settings for 
+
+    %% 3. Overwrite default settings for
     % How many mh-files are saved in this block?
     NumberOfSavedMhFilesInTheCrashedBlck = NumberOfMhFilesPerBlock(FirstBlock);
     ExistingDrawsInLastMCFile=0; %initialize: no MCMC draws of current MCMC are in file from last run
-    % Check whether last present file is a file included in the last MCMC run
-    if ~LastFileFullIndicator 
+                                 % Check whether last present file is a file included in the last MCMC run
+    if ~LastFileFullIndicator
         if NumberOfSavedMhFilesInTheCrashedBlck==NewFile(FirstBlock) %only that last file exists, but no files from current MCMC
-            loaded_results=load([BaseName '_mh' int2str(NewFile(FirstBlock)) '_blck' int2str(FirstBlock) '.mat']);    
+            loaded_results=load([BaseName '_mh' int2str(NewFile(FirstBlock)) '_blck' int2str(FirstBlock) '.mat']);
             %check whether that last file was filled
             if size(loaded_results.x2,1)==MAX_nruns %file is full
                 NewFile(FirstBlock)=NewFile(FirstBlock)+1; %set first file to be created to next one
@@ -419,20 +419,20 @@ elseif options_.mh_recover
                 ExistingDrawsInLastMCFile=0;
             end
         end
-    elseif LastFileFullIndicator 
+    elseif LastFileFullIndicator
         ExistingDrawsInLastMCFile=0;
         if NumberOfSavedMhFilesInTheCrashedBlck==NewFile(FirstBlock) %only the last file exists, but no files from current MCMC
             NewFile(FirstBlock)=NewFile(FirstBlock)+1; %set first file to be created to next one
         end
     end
-%     % 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 OldMhExists
-%         NumberOfSavedMhFilesInTheCrashedBlck = NumberOfSavedMhFilesInTheCrashedBlck - LastFileNumberInThePreviousMh;
-%     end
-%     NumberOfSavedMhFiles = NumberOfSavedMhFilesInTheCrashedBlck+LastFileNumberInThePreviousMh;
-    
+    %     % 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 OldMhExists
+    %         NumberOfSavedMhFilesInTheCrashedBlck = NumberOfSavedMhFilesInTheCrashedBlck - LastFileNumberInThePreviousMh;
+    %     end
+    %     NumberOfSavedMhFiles = NumberOfSavedMhFilesInTheCrashedBlck+LastFileNumberInThePreviousMh;
+
     % Correct initial conditions.
     if NumberOfSavedMhFilesInTheCrashedBlck<ExpectedNumberOfMhFilesPerBlock
         loaded_results=load([BaseName '_mh' int2str(NumberOfSavedMhFilesInTheCrashedBlck) '_blck' int2str(FirstBlock) '.mat']);
@@ -452,19 +452,19 @@ elseif options_.mh_recover
 end
 
 function [d,bayestopt_]=set_proposal_density_to_previous_value(record,options_,bayestopt_,d)
-    if isfield(record,'ProposalCovariance') && isfield(record,'ProposalCovariance')
-        if isfield(record,'MCMC_sampler')
-            if ~strcmp(record.MCMC_sampler,options_.posterior_sampler_options.posterior_sampling_method)
-                error(fprintf('Estimation::mcmc: The posterior_sampling_method differs from the one of the original chain. Please reset it to %s',record.MCMC_sampler))
-            end 
-        end
-        fprintf('Estimation::mcmc: Recovering the previous proposal density.\n')
-        d=record.ProposalCovariance;
-        bayestopt_.jscale=record.ProposalScaleVec;
-    else
-        if options_.mode_compute~=0
-            fprintf('Estimation::mcmc: No stored previous proposal density found, continuing with the one implied by mode_compute\n.');
-        elseif ~isempty(options_.mode_file)
-            fprintf('Estimation::mcmc: No stored previous proposal density found, continuing with the one implied by the mode_file\n.');
+if isfield(record,'ProposalCovariance') && isfield(record,'ProposalCovariance')
+    if isfield(record,'MCMC_sampler')
+        if ~strcmp(record.MCMC_sampler,options_.posterior_sampler_options.posterior_sampling_method)
+            error(fprintf('Estimation::mcmc: The posterior_sampling_method differs from the one of the original chain. Please reset it to %s',record.MCMC_sampler))
         end
     end
+    fprintf('Estimation::mcmc: Recovering the previous proposal density.\n')
+    d=record.ProposalCovariance;
+    bayestopt_.jscale=record.ProposalScaleVec;
+else
+    if options_.mode_compute~=0
+        fprintf('Estimation::mcmc: No stored previous proposal density found, continuing with the one implied by mode_compute\n.');
+    elseif ~isempty(options_.mode_file)
+        fprintf('Estimation::mcmc: No stored previous proposal density found, continuing with the one implied by the mode_file\n.');
+    end
+end
diff --git a/matlab/posterior_sampler_iteration.m b/matlab/posterior_sampler_iteration.m
index 09e5d8851060d425cacd040ff90e1b19232b0de9..5b54e785ef20b72de18f04adfa316f629c60f541 100644
--- a/matlab/posterior_sampler_iteration.m
+++ b/matlab/posterior_sampler_iteration.m
@@ -1,173 +1,173 @@
-function  [par, logpost, accepted, neval] = posterior_sampler_iteration(TargetFun,last_draw, last_posterior, sampler_options,varargin)
-
-% function [par, logpost, accepted, neval] = posterior_sampler_iteration(TargetFun,last_draw, last_posterior, sampler_options,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_)
-% posterior samplers
-%
-% INPUTS
-%   posterior_sampler_options:       posterior sampler options
-%   options_:       structure storing the options
-
-% OUTPUTS
-%   posterior_sampler_options:       checked posterior sampler options
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2015-16 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/>.
-
-
-posterior_sampling_method = sampler_options.posterior_sampling_method;
-mh_bounds = sampler_options.bounds;
-
-switch posterior_sampling_method
-    case 'slice'
-        
-        [par, logpost, neval] = slice_sampler(TargetFun,last_draw, [mh_bounds.lb mh_bounds.ub], sampler_options,varargin{:});
-        accepted = 1;
-    case 'random_walk_metropolis_hastings'
-        neval = 1;
-        ProposalFun = sampler_options.proposal_distribution;
-        proposal_covariance_Cholesky_decomposition = sampler_options.proposal_covariance_Cholesky_decomposition;
-        n = sampler_options.n;
-
-        par = feval(ProposalFun, last_draw, proposal_covariance_Cholesky_decomposition, n);
-        if all( par(:) > mh_bounds.lb ) && all( par(:) < mh_bounds.ub )
-            try
-                logpost = - feval(TargetFun, par(:),varargin{:});
-            catch
-                logpost = -inf;
-            end
-        else
-            logpost = -inf;
-        end
-        r = logpost-last_posterior;
-        if (logpost > -inf) && (log(rand) < r)
-            accepted = 1;
-        else
-            accepted = 0;
-            par = last_draw;
-            logpost = last_posterior;
-        end
-    case 'tailored_random_block_metropolis_hastings'
-        options_=varargin{3};
-        bayestopt_=varargin{6};
-        npar=length(last_draw);
-        %% randomize indices for blocking in this iteration
-        indices=randperm(npar)';
-        blocks=[1; (1+cumsum((rand(length(indices)-1,1)>(1-sampler_options.new_block_probability))))];
-        nblocks=blocks(end,1); %get number of blocks this iteration
-        current_draw=last_draw'; %get starting point for current draw for updating
-        blocked_draws_counter=0;
-        accepted_draws_counter=0;
-        for block_iter=1:nblocks
-            blocked_draws_counter=blocked_draws_counter+1;
-            nxopt=length(indices(blocks==block_iter,1)); %get size of current block
-            par_start_current_block=current_draw(indices(blocks==block_iter,1));
-            [xopt_current_block, fval, exitflag, hess_mat_optimizer, options_, Scale] = dynare_minimize_objective(@TaRB_optimizer_wrapper,par_start_current_block,sampler_options.mode_compute,options_,[mh_bounds.lb(indices(blocks==block_iter,1),1) mh_bounds.ub(indices(blocks==block_iter,1),1)],bayestopt_.name,bayestopt_,[],...
-                current_draw,indices(blocks==block_iter,1),TargetFun,...% inputs for wrapper
-                varargin{:}); %inputs for objective           
-            %% covariance for proposal density
-            hessian_mat = reshape(hessian('TaRB_optimizer_wrapper',xopt_current_block, ...
-                    options_.gstep,...
-                    current_draw,indices(blocks==block_iter,1),TargetFun,...% inputs for wrapper
-                    varargin{:}),nxopt,nxopt);
-            
-            if any(any(isnan(hessian_mat))) || any(any(isinf(hessian_mat)))
-                inverse_hessian_mat=eye(nxopt)*1e-4; %use diagonal
-            else
-                inverse_hessian_mat=inv(hessian_mat); %get inverse Hessian
-                if any(any((isnan(inverse_hessian_mat)))) || any(any((isinf(inverse_hessian_mat))))
-                    inverse_hessian_mat=eye(nxopt)*1e-4; %use diagonal
-                end               
-            end
-            [proposal_covariance_Cholesky_decomposition_upper,negeigenvalues]=chol(inverse_hessian_mat);            
-            %if not positive definite, use generalized Cholesky of Eskow/Schnabel
-            if negeigenvalues~=0 
-                proposal_covariance_Cholesky_decomposition_upper=chol_SE(inverse_hessian_mat,0);
-            end
-            proposal_covariance_Cholesky_decomposition_upper=proposal_covariance_Cholesky_decomposition_upper*diag(bayestopt_.jscale(indices(blocks==block_iter,1),:));
-            %get proposal draw
-            if strcmpi(sampler_options.proposal_distribution,'rand_multivariate_normal')
-                n = nxopt;
-            elseif strcmpi(sampler_options.proposal_distribution,'rand_multivariate_student')
-                n = options_.student_degrees_of_freedom;
-            end
-    
-            proposed_par = feval(sampler_options.proposal_distribution, xopt_current_block', proposal_covariance_Cholesky_decomposition_upper, n);
-            % check whether draw is valid and compute posterior
-            if all( proposed_par(:) > mh_bounds.lb(indices(blocks==block_iter,1),:) ) && all( proposed_par(:) < mh_bounds.ub(indices(blocks==block_iter,1),:) )
-                try
-                    logpost = - feval('TaRB_optimizer_wrapper', proposed_par(:),...
-                        current_draw,indices(blocks==block_iter,1),TargetFun,...% inputs for wrapper
-                        varargin{:});
-                catch
-                    logpost = -inf;
-                end
-            else
-                logpost = -inf;
-            end
-            %get ratio of proposal densities, required because proposal depends
-            %on current mode via Hessian and is thus not symmetric anymore
-            if strcmpi(sampler_options.proposal_distribution,'rand_multivariate_normal')
-                proposal_density_proposed_move_forward=multivariate_normal_pdf(proposed_par,xopt_current_block',proposal_covariance_Cholesky_decomposition_upper,n);
-                proposal_density_proposed_move_backward=multivariate_normal_pdf(par_start_current_block',xopt_current_block',proposal_covariance_Cholesky_decomposition_upper,n);
-            elseif strcmpi(sampler_options.proposal_distribution,'rand_multivariate_student')
-                proposal_density_proposed_move_forward=multivariate_student_pdf(proposed_par,xopt_current_block',proposal_covariance_Cholesky_decomposition_upper,n);
-                proposal_density_proposed_move_backward=multivariate_student_pdf(par_start_current_block',xopt_current_block',proposal_covariance_Cholesky_decomposition_upper,n);
-            end
-            accprob=logpost-last_posterior+ log(proposal_density_proposed_move_backward)-log(proposal_density_proposed_move_forward); %Formula (6), Chib/Ramamurthy
-
-            if (logpost > -inf) && (log(rand) < accprob)
-                current_draw(indices(blocks==block_iter,1))=proposed_par;
-                last_posterior=logpost;
-                accepted_draws_counter =accepted_draws_counter +1;
-            else %no updating 
-                %do nothing, keep old value
-            end
-        end
-        accepted=accepted_draws_counter/blocked_draws_counter;
-        par = current_draw;
-        neval=1;
-    case 'independent_metropolis_hastings'
-        neval = 1;
-        ProposalFun = sampler_options.proposal_distribution;
-        ProposalDensity = sampler_options.ProposalDensity;
-        proposal_covariance_Cholesky_decomposition = sampler_options.proposal_covariance_Cholesky_decomposition;
-        n = sampler_options.n;
-        xparam1 = sampler_options.xparam1';
-        par = feval(ProposalFun, xparam1, proposal_covariance_Cholesky_decomposition, n);
-        if all( par(:) > mh_bounds.lb ) && all( par(:) < mh_bounds.ub )
-            try
-                logpost = - feval(TargetFun, par(:),varargin{:});
-            catch
-                logpost = -inf;
-            end
-        else
-            logpost = -inf;
-        end
-            r = logpost - last_posterior + ...
-                log(feval(ProposalDensity, last_draw, xparam1, proposal_covariance_Cholesky_decomposition, n)) - ...
-                log(feval(ProposalDensity, par, xparam1, proposal_covariance_Cholesky_decomposition, n));
-        if (logpost > -inf) && (log(rand) < r)
-            accepted = 1;
-        else
-            accepted = 0;
-            par = last_draw;
-            logpost = last_posterior;
-        end
+function  [par, logpost, accepted, neval] = posterior_sampler_iteration(TargetFun,last_draw, last_posterior, sampler_options,varargin)
+
+% function [par, logpost, accepted, neval] = posterior_sampler_iteration(TargetFun,last_draw, last_posterior, sampler_options,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_)
+% posterior samplers
+%
+% INPUTS
+%   posterior_sampler_options:       posterior sampler options
+%   options_:       structure storing the options
+
+% OUTPUTS
+%   posterior_sampler_options:       checked posterior sampler options
+%
+% SPECIAL REQUIREMENTS
+%   none
+
+% Copyright (C) 2015-16 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/>.
+
+
+posterior_sampling_method = sampler_options.posterior_sampling_method;
+mh_bounds = sampler_options.bounds;
+
+switch posterior_sampling_method
+  case 'slice'
+
+    [par, logpost, neval] = slice_sampler(TargetFun,last_draw, [mh_bounds.lb mh_bounds.ub], sampler_options,varargin{:});
+    accepted = 1;
+  case 'random_walk_metropolis_hastings'
+    neval = 1;
+    ProposalFun = sampler_options.proposal_distribution;
+    proposal_covariance_Cholesky_decomposition = sampler_options.proposal_covariance_Cholesky_decomposition;
+    n = sampler_options.n;
+
+    par = feval(ProposalFun, last_draw, proposal_covariance_Cholesky_decomposition, n);
+    if all( par(:) > mh_bounds.lb ) && all( par(:) < mh_bounds.ub )
+        try
+            logpost = - feval(TargetFun, par(:),varargin{:});
+        catch
+            logpost = -inf;
+        end
+    else
+        logpost = -inf;
+    end
+    r = logpost-last_posterior;
+    if (logpost > -inf) && (log(rand) < r)
+        accepted = 1;
+    else
+        accepted = 0;
+        par = last_draw;
+        logpost = last_posterior;
+    end
+  case 'tailored_random_block_metropolis_hastings'
+    options_=varargin{3};
+    bayestopt_=varargin{6};
+    npar=length(last_draw);
+    %% randomize indices for blocking in this iteration
+    indices=randperm(npar)';
+    blocks=[1; (1+cumsum((rand(length(indices)-1,1)>(1-sampler_options.new_block_probability))))];
+    nblocks=blocks(end,1); %get number of blocks this iteration
+    current_draw=last_draw'; %get starting point for current draw for updating
+    blocked_draws_counter=0;
+    accepted_draws_counter=0;
+    for block_iter=1:nblocks
+        blocked_draws_counter=blocked_draws_counter+1;
+        nxopt=length(indices(blocks==block_iter,1)); %get size of current block
+        par_start_current_block=current_draw(indices(blocks==block_iter,1));
+        [xopt_current_block, fval, exitflag, hess_mat_optimizer, options_, Scale] = dynare_minimize_objective(@TaRB_optimizer_wrapper,par_start_current_block,sampler_options.mode_compute,options_,[mh_bounds.lb(indices(blocks==block_iter,1),1) mh_bounds.ub(indices(blocks==block_iter,1),1)],bayestopt_.name,bayestopt_,[],...
+                                                          current_draw,indices(blocks==block_iter,1),TargetFun,...% inputs for wrapper
+                                                          varargin{:}); %inputs for objective
+        %% covariance for proposal density
+        hessian_mat = reshape(hessian('TaRB_optimizer_wrapper',xopt_current_block, ...
+                                      options_.gstep,...
+                                      current_draw,indices(blocks==block_iter,1),TargetFun,...% inputs for wrapper
+                                      varargin{:}),nxopt,nxopt);
+
+        if any(any(isnan(hessian_mat))) || any(any(isinf(hessian_mat)))
+            inverse_hessian_mat=eye(nxopt)*1e-4; %use diagonal
+        else
+            inverse_hessian_mat=inv(hessian_mat); %get inverse Hessian
+            if any(any((isnan(inverse_hessian_mat)))) || any(any((isinf(inverse_hessian_mat))))
+                inverse_hessian_mat=eye(nxopt)*1e-4; %use diagonal
+            end
+        end
+        [proposal_covariance_Cholesky_decomposition_upper,negeigenvalues]=chol(inverse_hessian_mat);
+        %if not positive definite, use generalized Cholesky of Eskow/Schnabel
+        if negeigenvalues~=0
+            proposal_covariance_Cholesky_decomposition_upper=chol_SE(inverse_hessian_mat,0);
+        end
+        proposal_covariance_Cholesky_decomposition_upper=proposal_covariance_Cholesky_decomposition_upper*diag(bayestopt_.jscale(indices(blocks==block_iter,1),:));
+        %get proposal draw
+        if strcmpi(sampler_options.proposal_distribution,'rand_multivariate_normal')
+            n = nxopt;
+        elseif strcmpi(sampler_options.proposal_distribution,'rand_multivariate_student')
+            n = options_.student_degrees_of_freedom;
+        end
+
+        proposed_par = feval(sampler_options.proposal_distribution, xopt_current_block', proposal_covariance_Cholesky_decomposition_upper, n);
+        % check whether draw is valid and compute posterior
+        if all( proposed_par(:) > mh_bounds.lb(indices(blocks==block_iter,1),:) ) && all( proposed_par(:) < mh_bounds.ub(indices(blocks==block_iter,1),:) )
+            try
+                logpost = - feval('TaRB_optimizer_wrapper', proposed_par(:),...
+                                  current_draw,indices(blocks==block_iter,1),TargetFun,...% inputs for wrapper
+                                  varargin{:});
+            catch
+                logpost = -inf;
+            end
+        else
+            logpost = -inf;
+        end
+        %get ratio of proposal densities, required because proposal depends
+        %on current mode via Hessian and is thus not symmetric anymore
+        if strcmpi(sampler_options.proposal_distribution,'rand_multivariate_normal')
+            proposal_density_proposed_move_forward=multivariate_normal_pdf(proposed_par,xopt_current_block',proposal_covariance_Cholesky_decomposition_upper,n);
+            proposal_density_proposed_move_backward=multivariate_normal_pdf(par_start_current_block',xopt_current_block',proposal_covariance_Cholesky_decomposition_upper,n);
+        elseif strcmpi(sampler_options.proposal_distribution,'rand_multivariate_student')
+            proposal_density_proposed_move_forward=multivariate_student_pdf(proposed_par,xopt_current_block',proposal_covariance_Cholesky_decomposition_upper,n);
+            proposal_density_proposed_move_backward=multivariate_student_pdf(par_start_current_block',xopt_current_block',proposal_covariance_Cholesky_decomposition_upper,n);
+        end
+        accprob=logpost-last_posterior+ log(proposal_density_proposed_move_backward)-log(proposal_density_proposed_move_forward); %Formula (6), Chib/Ramamurthy
+
+        if (logpost > -inf) && (log(rand) < accprob)
+            current_draw(indices(blocks==block_iter,1))=proposed_par;
+            last_posterior=logpost;
+            accepted_draws_counter =accepted_draws_counter +1;
+        else %no updating
+             %do nothing, keep old value
+        end
+    end
+    accepted=accepted_draws_counter/blocked_draws_counter;
+    par = current_draw;
+    neval=1;
+  case 'independent_metropolis_hastings'
+    neval = 1;
+    ProposalFun = sampler_options.proposal_distribution;
+    ProposalDensity = sampler_options.ProposalDensity;
+    proposal_covariance_Cholesky_decomposition = sampler_options.proposal_covariance_Cholesky_decomposition;
+    n = sampler_options.n;
+    xparam1 = sampler_options.xparam1';
+    par = feval(ProposalFun, xparam1, proposal_covariance_Cholesky_decomposition, n);
+    if all( par(:) > mh_bounds.lb ) && all( par(:) < mh_bounds.ub )
+        try
+            logpost = - feval(TargetFun, par(:),varargin{:});
+        catch
+            logpost = -inf;
+        end
+    else
+        logpost = -inf;
+    end
+    r = logpost - last_posterior + ...
+        log(feval(ProposalDensity, last_draw, xparam1, proposal_covariance_Cholesky_decomposition, n)) - ...
+        log(feval(ProposalDensity, par, xparam1, proposal_covariance_Cholesky_decomposition, n));
+    if (logpost > -inf) && (log(rand) < r)
+        accepted = 1;
+    else
+        accepted = 0;
+        par = last_draw;
+        logpost = last_posterior;
+    end
 end
\ No newline at end of file
diff --git a/matlab/print_bytecode_dynamic_model.m b/matlab/print_bytecode_dynamic_model.m
index f4e381ed1514e5036179085d5153cf69e8837fed..af5eb011546ead3cb920b74b90e9fd979a32a876 100644
--- a/matlab/print_bytecode_dynamic_model.m
+++ b/matlab/print_bytecode_dynamic_model.m
@@ -1,17 +1,17 @@
 function print_bytecode_dynamic_model()
 % function print_bytecode_dynamic_model()
 % print the model and jacobian from the bytecode format for the dynamic model
-%  
+%
 % INPUTS
 %   none
-%  
+%
 % OUTPUTS
 %   none
 %
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2001-2011 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/print_bytecode_static_model.m b/matlab/print_bytecode_static_model.m
index bc216c70dad270c2a664febe8b88004871f2f8d6..ece12428b5237bd5ceb9a7293b2d727423b78a2a 100644
--- a/matlab/print_bytecode_static_model.m
+++ b/matlab/print_bytecode_static_model.m
@@ -1,17 +1,17 @@
 function print_bytecode_static_model()
 % function print_bytecode_static_model()
 % print the model and jacobian from the bytecode format for the static model
-%  
+%
 % INPUTS
 %   none
-%  
+%
 % OUTPUTS
 %   none
 %
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2001-2011 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/print_info.m b/matlab/print_info.m
index af5b40fc8d6a21948b5c080ac8c9ee4fe6afa375..76ec1d115fdea5b20c39d81ab5c65676f8c6ff2b 100644
--- a/matlab/print_info.m
+++ b/matlab/print_info.m
@@ -2,7 +2,7 @@ function print_info(info, noprint, DynareOptions)
 % Prints error messages
 %
 % INPUTS
-%   info              [double]     vector returned by resol.m 
+%   info              [double]     vector returned by resol.m
 %   noprint           [integer]    equal to 0 if the error message has to be printed.
 %   DynareOptions     [structure]  --> options_
 % OUTPUTS
@@ -11,7 +11,7 @@ function print_info(info, noprint, DynareOptions)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2005-2013 Dynare Team
+% Copyright (C) 2005-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -54,15 +54,15 @@ if ~noprint
         error('One of the eigenvalues is close to 0/0 (the absolute value of numerator and denominator is smaller than %s!\n If you believe that the model has a unique solution you can try to reduce the value of qz_zero_threshold.',num2str(DynareOptions.qz_zero_threshold))
       case 8
         if size(info,2)>=2
-          global M_;
+            global M_;
             disp_string=deblank(M_.param_names(info(2),:));
-          for ii=1:length(info)-2
-            disp_string=[disp_string,', ',deblank(M_.param_names(info(2+ii),:))];
-          end
-          error(['The Jacobian contains NaNs because the following parameters are NaN: '...
-              disp_string])
+            for ii=1:length(info)-2
+                disp_string=[disp_string,', ',deblank(M_.param_names(info(2+ii),:))];
+            end
+            error(['The Jacobian contains NaNs because the following parameters are NaN: '...
+                   disp_string])
         else
-          error(['The Jacobian contains NaNs. For more information, use options_.debug.'])
+            error(['The Jacobian contains NaNs. For more information, use options_.debug.'])
         end
       case 9
         error(['k_order_pert was unable to compute the solution'])
@@ -78,7 +78,7 @@ if ~noprint
         if DynareOptions.linear
             error(['Impossible to find the steady state. Either the model' ...
                    ' doesn''t have a steady state or there are an infinity of steady states.' ...
-                   ' Check whether your model is truly linear or whether there is a mistake in linearization.'])        
+                   ' Check whether your model is truly linear or whether there is a mistake in linearization.'])
         else
             error(['Impossible to find the steady state. Either the model' ...
                    ' doesn''t have a steady state, there are an infinity of steady states,' ...
@@ -117,12 +117,14 @@ if ~noprint
       case 49
         error('The model violates one (many) endogenous prior restriction(s)')
       case 50
-        error('Likelihood is Inf')        
+        error('Likelihood is Inf')
       case 51
         fprintf('\n The dsge_prior_weight is dsge_var=%5.4f, but must be at least %5.4f for the prior to be proper.\n',info(2),info(3));
         error('You are estimating a DSGE-VAR model, but the value of the dsge prior weight is too low!')
       case 52 %dsge_var_likelihood
-        error('You are estimating a DSGE-VAR model, but the implied covariance matrix of the VAR''s innovations is not positive definite!');
+        error('You are estimating a DSGE-VAR model, but the implied covariance matrix of the VAR''s innovations, based on artificial and actual sample is not positive definite!');
+      case 53 %dsge_var_likelihood
+        error('You are estimating a DSGE-VAR model, but the implied covariance matrix of the VAR''s innovations, based on the artificial sample, is not positive definite!');
       case 55
         error('Fast Kalman filter only works with stationary models [lik_init=1] or stationary observables for non-stationary models [lik_init=3]')
       case 61 %Discretionary policy
diff --git a/matlab/print_moments_implied_prior.m b/matlab/print_moments_implied_prior.m
index 496e3bf865a4d15c99c4a38f42d27bb65c97f43b..94d14cb02275df51a45ddda29a89daa90939f551 100644
--- a/matlab/print_moments_implied_prior.m
+++ b/matlab/print_moments_implied_prior.m
@@ -1,9 +1,9 @@
 function print_moments_implied_prior(ModelInfo, mm, vm, mv, vv)
 
 % This routine prints in the command window some descriptive statistics
-% about the endogenous variables implied prior moments. 
+% about the endogenous variables implied prior moments.
 
-% Copyright (C) 2016 Dynare Team
+% Copyright (C) 2016-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/print_table_prior.m b/matlab/print_table_prior.m
index 605adfabf7ff8aad771e4b829711a7a998b63b61..e4c7894a863f95de4ea3bd4be3ddbb40a60152e4 100644
--- a/matlab/print_table_prior.m
+++ b/matlab/print_table_prior.m
@@ -1,8 +1,8 @@
 function print_table_prior(lb, ub, DynareOptions, ModelInfo, BayesInfo, EstimationInfo)
 
-% This routine prints in the command window some descriptive statistics about the prior distribution. 
+% This routine prints in the command window some descriptive statistics about the prior distribution.
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -25,6 +25,8 @@ PriorNames = strvcat(PriorNames,'Gaussian');
 PriorNames = strvcat(PriorNames,'Inverted Gamma');
 PriorNames = strvcat(PriorNames,'Uniform');
 PriorNames = strvcat(PriorNames,'Inverted Gamma -- 2');
+PriorNames = strvcat(PriorNames,'Dirichlet');
+PriorNames = strvcat(PriorNames,'Weibull');
 
 n = size(BayesInfo.name,1); % Numbe rof estimated parameters.
 
@@ -71,7 +73,7 @@ for i=1:size(BayesInfo.name,1)
         if ~isinf(ub(i))
             UpperBound=min(UpperBound,ub(i));
         end
-      case { 2 , 4 , 6 }
+      case { 2 , 4 , 6 , 8}
         LowerBound = BayesInfo.p3(i);
         if ~isinf(lb(i))
             LowerBound=max(LowerBound,lb(i));
@@ -111,7 +113,7 @@ for i=1:size(BayesInfo.name,1)
                   UpperBound, ...
                   PriorIntervals.lb(i), ...
                   PriorIntervals.ub(i) );
-    T2 = strvcat(T2, str);    
+    T2 = strvcat(T2, str);
 end
 
 T1 = strvcat(T1, l1);
@@ -134,25 +136,25 @@ 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
+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/printline.m b/matlab/printline.m
index c60d0906a90133b7b7574ac05439d163e48b1233..29d4ec1c306266cdef8df9fb684d156627102fc2 100644
--- a/matlab/printline.m
+++ b/matlab/printline.m
@@ -1,16 +1,16 @@
 function varargout = printline(n, s, fid)
 % This function print a line formed by replicating a symbol s.
 %
-% INPUTS 
+% INPUTS
 %
 %   n  [integer]    Length of the printed line
 %   s  [char]       Symbol used to draw the line (+, -, =, ...)
 %   f  [integer]    file id returned by fopen
-%    
-% OUTPUTS 
+%
+% OUTPUTS
 %   None
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -25,7 +25,7 @@ function varargout = printline(n, s, fid)
 % 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/>.
 
 if nargin<3
     f = 1;
diff --git a/matlab/prior_analysis.m b/matlab/prior_analysis.m
index fd79414e5985274a435c2d59d937d0fe6a70db65..5820f69c3cfadd8a53b00403c2b92a743077b112 100644
--- a/matlab/prior_analysis.m
+++ b/matlab/prior_analysis.m
@@ -1,5 +1,5 @@
 function oo_ = prior_analysis(type,arg1,arg2,arg3,options_,M_,oo_,estim_params_)
-% Copyright (C) 2009-2012 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -56,7 +56,7 @@ switch type
             dsge_simulated_theoretical_covariance(SampleSize,M_,options_,oo_,'prior');
     end
     oo_ = covariance_mc_analysis(SampleSize,'prior',M_.dname,M_.fname,...
-                                 vartan,nvar,arg1,arg2,options_.mh_conf_sig,oo_,options_);          
+                                 vartan,nvar,arg1,arg2,options_.mh_conf_sig,oo_,options_);
   case 'decomposition'
     if nargin==narg1
         [nvar,vartan,NumberOfFiles] = ...
diff --git a/matlab/prior_bounds.m b/matlab/prior_bounds.m
index 2bf1173eda765d2aa5e052b8e9d332d1ac301b43..56ef1eb32ea8266deaec9139b03dcd065da385bb 100644
--- a/matlab/prior_bounds.m
+++ b/matlab/prior_bounds.m
@@ -40,14 +40,14 @@ function bounds = prior_bounds(bayestopt, prior_trunc)
 %
 % INPUTS
 %    bayestopt  [structure]  characterizing priors (shape, mean, p1..p4)
-%    
+%
 % OUTPUTS
 %    bounds     [double]      structure specifying prior bounds (lb and ub fields)
-%    
+%
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2012 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/prior_draw.m b/matlab/prior_draw.m
index 4eb628df907df2168b82b341fbb9e801581d02c3..c97eaeefd4dab1d320eafac1450af06cb6bfd8fb 100644
--- a/matlab/prior_draw.m
+++ b/matlab/prior_draw.m
@@ -2,10 +2,10 @@ function pdraw = prior_draw(BayesInfo, prior_trunc, uniform) % --*-- Unitary tes
 
 % This function generate one draw from the joint prior distribution and
 % allows sampling uniformly from the prior support (uniform==1 when called with init==1)
-% 
-% INPUTS 
-%   o init             [integer]    scalar equal to: 
-%                                       1: first call to set up persistent variables 
+%
+% INPUTS
+%   o init             [integer]    scalar equal to:
+%                                       1: first call to set up persistent variables
 %                                             describing the prior
 %                                       0: subsequent call to get prior
 %                                               draw
@@ -13,8 +13,8 @@ function pdraw = prior_draw(BayesInfo, prior_trunc, uniform) % --*-- Unitary tes
 %                                       1: sample uniformly from prior
 %                                           support (overwrites prior shape used for sampling within this function)
 %                                       0: sample from joint prior distribution
-%    
-% OUTPUTS 
+%
+% OUTPUTS
 %   o pdraw            [double]     1*npar vector, draws from the joint prior density.
 %
 %
@@ -25,8 +25,8 @@ function pdraw = prior_draw(BayesInfo, prior_trunc, uniform) % --*-- Unitary tes
 % NOTE 2. A given draw from the joint prior distribution does not satisfy BK conditions a priori.
 % NOTE 3. This code relies on bayestopt_ as created in the base workspace
 %           by the preprocessor (or as updated in subsequent pieces of code and handed to the base workspace)
-% 
-% Copyright (C) 2006-2016 Dynare Team
+%
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -108,9 +108,9 @@ if nargin>0
 end
 
 if uniform_draws
-    pdraw(uniform_index) = rand(length(uniform_index),1).*(p4(uniform_index)-p3(uniform_index)) + p3(uniform_index);  
+    pdraw(uniform_index) = rand(length(uniform_index),1).*(p4(uniform_index)-p3(uniform_index)) + p3(uniform_index);
     out_of_bound = find( (pdraw(uniform_index)'>ub(uniform_index)) | (pdraw(uniform_index)'<lb(uniform_index)));
-    while ~isempty(out_of_bound),
+    while ~isempty(out_of_bound)
         pdraw(uniform_index) = rand(length(uniform_index),1).*(p4(uniform_index)-p3(uniform_index)) + p3(uniform_index);
         out_of_bound = find( (pdraw(uniform_index)'>ub(uniform_index)) | (pdraw(uniform_index)'<lb(uniform_index)));
     end
@@ -119,7 +119,7 @@ end
 if gaussian_draws
     pdraw(gaussian_index) = randn(length(gaussian_index),1).*p7(gaussian_index) + p6(gaussian_index);
     out_of_bound = find( (pdraw(gaussian_index)'>ub(gaussian_index)) | (pdraw(gaussian_index)'<lb(gaussian_index)));
-    while ~isempty(out_of_bound),
+    while ~isempty(out_of_bound)
         pdraw(gaussian_index(out_of_bound)) = randn(length(gaussian_index(out_of_bound)),1).*p7(gaussian_index(out_of_bound)) + p6(gaussian_index(out_of_bound));
         out_of_bound = find( (pdraw(gaussian_index)'>ub(gaussian_index)) | (pdraw(gaussian_index)'<lb(gaussian_index)));
     end
@@ -128,7 +128,7 @@ end
 if gamma_draws
     pdraw(gamma_index) = gamrnd(p6(gamma_index),p7(gamma_index))+p3(gamma_index);
     out_of_bound = find( (pdraw(gamma_index)'>ub(gamma_index)) | (pdraw(gamma_index)'<lb(gamma_index)));
-    while ~isempty(out_of_bound),
+    while ~isempty(out_of_bound)
         pdraw(gamma_index(out_of_bound)) = gamrnd(p6(gamma_index(out_of_bound)),p7(gamma_index(out_of_bound)))+p3(gamma_index(out_of_bound));
         out_of_bound = find( (pdraw(gamma_index)'>ub(gamma_index)) | (pdraw(gamma_index)'<lb(gamma_index)));
     end
@@ -137,7 +137,7 @@ end
 if beta_draws
     pdraw(beta_index) = (p4(beta_index)-p3(beta_index)).*betarnd(p6(beta_index),p7(beta_index))+p3(beta_index);
     out_of_bound = find( (pdraw(beta_index)'>ub(beta_index)) | (pdraw(beta_index)'<lb(beta_index)));
-    while ~isempty(out_of_bound),
+    while ~isempty(out_of_bound)
         pdraw(beta_index(out_of_bound)) = (p4(beta_index(out_of_bound))-p3(beta_index(out_of_bound))).*betarnd(p6(beta_index(out_of_bound)),p7(beta_index(out_of_bound)))+p3(beta_index(out_of_bound));
         out_of_bound = find( (pdraw(beta_index)'>ub(beta_index)) | (pdraw(beta_index)'<lb(beta_index)));
     end
@@ -147,7 +147,7 @@ if inverse_gamma_1_draws
     pdraw(inverse_gamma_1_index) = ...
         sqrt(1./gamrnd(p7(inverse_gamma_1_index)/2,2./p6(inverse_gamma_1_index)))+p3(inverse_gamma_1_index);
     out_of_bound = find( (pdraw(inverse_gamma_1_index)'>ub(inverse_gamma_1_index)) | (pdraw(inverse_gamma_1_index)'<lb(inverse_gamma_1_index)));
-    while ~isempty(out_of_bound),
+    while ~isempty(out_of_bound)
         pdraw(inverse_gamma_1_index(out_of_bound)) = ...
             sqrt(1./gamrnd(p7(inverse_gamma_1_index(out_of_bound))/2,2./p6(inverse_gamma_1_index(out_of_bound))))+p3(inverse_gamma_1_index(out_of_bound));
         out_of_bound = find( (pdraw(inverse_gamma_1_index)'>ub(inverse_gamma_1_index)) | (pdraw(inverse_gamma_1_index)'<lb(inverse_gamma_1_index)));
@@ -158,7 +158,7 @@ if inverse_gamma_2_draws
     pdraw(inverse_gamma_2_index) = ...
         1./gamrnd(p7(inverse_gamma_2_index)/2,2./p6(inverse_gamma_2_index))+p3(inverse_gamma_2_index);
     out_of_bound = find( (pdraw(inverse_gamma_2_index)'>ub(inverse_gamma_2_index)) | (pdraw(inverse_gamma_2_index)'<lb(inverse_gamma_2_index)));
-    while ~isempty(out_of_bound),
+    while ~isempty(out_of_bound)
         pdraw(inverse_gamma_2_index(out_of_bound)) = ...
             1./gamrnd(p7(inverse_gamma_2_index(out_of_bound))/2,2./p6(inverse_gamma_2_index(out_of_bound)))+p3(inverse_gamma_2_index(out_of_bound));
         out_of_bound = find( (pdraw(inverse_gamma_2_index)'>ub(inverse_gamma_2_index)) | (pdraw(inverse_gamma_2_index)'<lb(inverse_gamma_2_index)));
@@ -168,7 +168,7 @@ end
 if weibull_draws
     pdraw(weibull_index) = wblrnd(p7(weibull_index), p6(weibull_index)) + p3(weibull_index);
     out_of_bound = find( (pdraw(weibull_index)'>ub(weibull_index)) | (pdraw(weibull_index)'<lb(weibull_index)));
-    while ~isempty(out_of_bound),
+    while ~isempty(out_of_bound)
         pdraw(weibull_index(out_of_bound)) = wblrnd(p7(weibull_index(out_of_bound)),p6(weibull_index(out_of_bound)))+p3(weibull_index(out_of_bound));
         out_of_bound = find( (pdraw(weibull_index)'>ub(weibull_index)) | (pdraw(weibull_index)'<lb(weibull_index)));
     end
diff --git a/matlab/prior_posterior_statistics.m b/matlab/prior_posterior_statistics.m
index 039bd79b3e6ed6ed1aeecf0f0c2c48beecefd7c4..064e7874ae0dac8c38be2bc7cb8b4a79c7c9d0ca 100644
--- a/matlab/prior_posterior_statistics.m
+++ b/matlab/prior_posterior_statistics.m
@@ -14,12 +14,12 @@ function prior_posterior_statistics(type,dataset,dataset_info)
 %
 % SPECIAL REQUIREMENTS
 %    none
-% 
+%
 % PARALLEL CONTEXT
 % See the comments in the posterior_sampler.m funtion.
-% 
-% 
-% Copyright (C) 2005-2016 Dynare Team
+%
+%
+% Copyright (C) 2005-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -79,7 +79,7 @@ elseif strcmpi(type,'gsa')
         DirectoryName = CheckPath(['gsa',filesep,'mc'],M_.dname);
         load([ RootDirectoryName filesep  M_.fname '_mc.mat'],'lpmat0','lpmat','istable')
     end
-    if ~isempty(lpmat0),
+    if ~isempty(lpmat0)
         x=[lpmat0(istable,:) lpmat(istable,:)];
     else
         x=lpmat(istable,:);
@@ -117,13 +117,13 @@ if options_.filter_covariance
     MAX_filter_covariance = min(B,ceil(MaxNumberOfBytes/(endo_nbr^2*(gend+1))/8));
 end
 
-if options_.smoothed_state_uncertainty 
+if options_.smoothed_state_uncertainty
     MAX_n_smoothed_state_uncertainty = min(B,ceil(MaxNumberOfBytes/((endo_nbr*endo_nbr)*gend)/8));
 end
 
 varlist = options_.varlist;
 if isempty(varlist)
-    varlist = M_.endo_names(1:M_.orig_endo_nbr, :);
+    varlist = char(sort(cellstr(M_.endo_names(1:M_.orig_endo_nbr,:))));
 end
 nvar = size(varlist,1);
 SelecVariables = [];
@@ -141,6 +141,11 @@ ifil = zeros(n_variables_to_fill,1);
 run_smoother = 0;
 if options_.smoother || options_.forecast || options_.filter_step_ahead || options_.smoothed_state_uncertainty
     run_smoother = 1;
+    if options_.loglinear
+        oo_.Smoother.loglinear = true;
+    else
+        oo_.Smoother.loglinear = false;
+    end
 end
 
 filter_covariance=0;
@@ -191,7 +196,7 @@ end
 if options_.filter_covariance
     localVars.MAX_filter_covariance = MAX_filter_covariance;
 end
-if options_.smoothed_state_uncertainty 
+if options_.smoothed_state_uncertainty
     localVars.MAX_n_smoothed_state_uncertainty = MAX_n_smoothed_state_uncertainty ;
 end
 localVars.MAX_n_smoothed_constant=MAX_n_smoothed_constant;
@@ -202,28 +207,43 @@ localVars.MAX_momentsno = MAX_momentsno;
 localVars.ifil=ifil;
 localVars.DirectoryName = DirectoryName;
 
-if strcmpi(type,'posterior'),
-    b=0;
-    logpost=NaN(B,1);
-    while b<=B
-        b = b + 1;
-        [x(b,:), logpost(b,1)] = GetOneDraw(type);
+if strcmpi(type,'posterior')
+    BaseName = [DirectoryName filesep M_.fname];
+    load_last_mh_history_file(DirectoryName, M_.fname);
+    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);
+    mh_nblck = options_.mh_nblck;
+    if B==NumberOfDraws*mh_nblck
+        % we load all retained MH runs !
+        logpost=GetAllPosteriorDraws(0, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws);
+        for column=1:npar
+            x(:,column) = GetAllPosteriorDraws(column, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws);
+        end
+    else
+        logpost=NaN(B,1);
+        for b=1:B
+            [x(b,:), logpost(b)] = GetOneDraw(type);
+        end
     end
     localVars.logpost=logpost;
 end
 
-if ~strcmpi(type,'prior'),
+if ~strcmpi(type,'prior')
     localVars.x=x;
 end
 
 % Like sequential execution!
-if isnumeric(options_.parallel),
+if isnumeric(options_.parallel)
     [fout] = prior_posterior_statistics_core(localVars,1,B,0);
     % Parallel execution!
 else
     [nCPU, totCPU, nBlockPerCPU] = distributeJobs(options_.parallel, 1, B);
     ifil=zeros(n_variables_to_fill,totCPU);
-    for j=1:totCPU-1,
+    for j=1:totCPU-1
         if run_smoother
             nfiles = ceil(nBlockPerCPU(j)/MAX_nsmoo);
             ifil(1,j+1) =ifil(1,j)+nfiles;
@@ -254,14 +274,14 @@ else
         end
         if run_smoother
             nfiles = ceil(nBlockPerCPU(j)/MAX_n_trend_coeff);
-            ifil(9,j+1) =ifil(9,j)+nfiles;  
+            ifil(9,j+1) =ifil(9,j)+nfiles;
             nfiles = ceil(nBlockPerCPU(j)/MAX_n_smoothed_constant);
-            ifil(10,j+1) =ifil(10,j)+nfiles;  
+            ifil(10,j+1) =ifil(10,j)+nfiles;
             nfiles = ceil(nBlockPerCPU(j)/MAX_n_smoothed_trend);
-            ifil(11,j+1) =ifil(11,j)+nfiles;  
+            ifil(11,j+1) =ifil(11,j)+nfiles;
             if smoothed_state_uncertainty
                 nfiles = ceil(nBlockPerCPU(j)/MAX_n_smoothed_state_uncertainty);
-                ifil(13,j+1) =ifil(13,j)+nfiles;           
+                ifil(13,j+1) =ifil(13,j)+nfiles;
             end
         end
     end
@@ -274,8 +294,13 @@ else
     % which files have to be copied to run remotely
     NamFileInput(1,:) = {'',[M_.fname '_static.m']};
     NamFileInput(2,:) = {'',[M_.fname '_dynamic.m']};
-    if options_.steadystate_flag,
-        NamFileInput(length(NamFileInput)+1,:)={'',[M_.fname '_steadystate.m']};
+    NamFileInput(3,:) = {'',[M_.fname '_set_auxiliary_variables.m']};
+    if options_.steadystate_flag
+        if options_.steadystate_flag == 1
+            NamFileInput(length(NamFileInput)+1,:)={'',[M_.fname '_steadystate.m']};
+        else
+            NamFileInput(length(NamFileInput)+1,:)={'',[M_.fname '_steadystate2.m']};
+        end
     end
     [fout] = masterParallel(options_.parallel, 1, B,NamFileInput,'prior_posterior_statistics_core', localVars,globalVars, options_.parallel_info);
 
@@ -300,19 +325,19 @@ end
 
 if options_.smoother
     pm3(endo_nbr,gend,ifil(1),B,'Smoothed variables',...
-        '',M_.endo_names(1:M_.orig_endo_nbr, :),M_.endo_names_tex,M_.endo_names,...
+        '',varlist,M_.endo_names_tex,M_.endo_names,...
         varlist,'SmoothedVariables',DirectoryName,'_smooth');
     pm3(exo_nbr,gend,ifil(2),B,'Smoothed shocks',...
         '',M_.exo_names,M_.exo_names_tex,M_.exo_names,...
         M_.exo_names,'SmoothedShocks',DirectoryName,'_inno');
     pm3(endo_nbr,1,ifil(9),B,'Trend_coefficients',...
-    '',M_.endo_names(1:M_.orig_endo_nbr,:),M_.endo_names_tex,M_.endo_names,...
+        '',varlist,M_.endo_names_tex,M_.endo_names,...
         varlist,'TrendCoeff',DirectoryName,'_trend_coeff');
     pm3(endo_nbr,gend,ifil(10),B,'Smoothed constant',...
-        '',M_.endo_names(1:M_.orig_endo_nbr, :),M_.endo_names_tex,M_.endo_names,...
+        '',varlist,M_.endo_names_tex,M_.endo_names,...
         varlist,'Constant',DirectoryName,'_smoothed_constant');
     pm3(endo_nbr,gend,ifil(11),B,'Smoothed trend',...
-        '',M_.endo_names(1:M_.orig_endo_nbr, :),M_.endo_names_tex,M_.endo_names,...
+        '',varlist,M_.endo_names_tex,M_.endo_names,...
         varlist,'Trend',DirectoryName,'_smoothed_trend');
     pm3(endo_nbr,gend,ifil(1),B,'Updated Variables',...
         '',varlist,M_.endo_names_tex,M_.endo_names,...
@@ -323,17 +348,17 @@ if options_.smoother
             '',varlist,M_.endo_names_tex,M_.endo_names,...
             varlist,'StateUncertainty',DirectoryName,'_state_uncert');
     end
-    
+
     if nvn
-        for obs_iter=1:length(options_.varobs)        
+        for obs_iter=1:length(options_.varobs)
             meas_error_names{obs_iter,1}=['SE_EOBS_' M_.endo_names(strmatch(options_.varobs{obs_iter},M_.endo_names,'exact'),:)];
             texnames{obs_iter,1}=['SE_EOBS_' M_.endo_names_tex(strmatch(options_.varobs{obs_iter},M_.endo_names,'exact'),:)];
         end
         meas_error_names=char(meas_error_names);
         texnames=char(texnames);
         pm3(meas_err_nbr,gend,ifil(3),B,'Smoothed measurement errors',...
-           '',meas_error_names,texnames,meas_error_names,...
-           meas_error_names,'SmoothedMeasurementErrors',DirectoryName,'_error')
+            '',meas_error_names,texnames,meas_error_names,...
+            meas_error_names,'SmoothedMeasurementErrors',DirectoryName,'_error')
     end
 end
 
@@ -352,7 +377,7 @@ if options_.forecast
         varlist,'PointForecast',DirectoryName,'_forc_point');
     if ~isequal(M_.H,0) && ~isempty(intersect(options_.varobs,varlist))
         texnames=[];
-        for obs_iter=1:length(options_.varobs)        
+        for obs_iter=1:length(options_.varobs)
             obs_names{obs_iter,1}=M_.endo_names(strmatch(options_.varobs{obs_iter},M_.endo_names,'exact'),:);
             texnames{obs_iter,1}=M_.endo_names_tex(strmatch(options_.varobs{obs_iter},M_.endo_names,'exact'),:);
         end
@@ -360,8 +385,8 @@ if options_.forecast
         texnames=char(texnames);
         varlist_forecast_ME=intersect(options_.varobs,varlist);
         pm3(meas_err_nbr,horizon,ifil(12),B,'Forecasted variables (point) with ME',...
-           '',char(varlist_forecast_ME),texnames,obs_names,...
-           char(varlist_forecast_ME),'PointForecastME',DirectoryName,'_forc_point_ME')    
+            '',char(varlist_forecast_ME),texnames,obs_names,...
+            char(varlist_forecast_ME),'PointForecastME',DirectoryName,'_forc_point_ME')
     end
 end
 
@@ -372,9 +397,9 @@ if options_.filter_covariance
 end
 
 
-if ~isnumeric(options_.parallel),
+if ~isnumeric(options_.parallel)
     options_.parallel_info.leaveSlaveOpen = leaveSlaveOpen;
-    if leaveSlaveOpen == 0,
+    if leaveSlaveOpen == 0
         closeSlave(options_.parallel,options_.parallel_info.RemoteTmpFolder),
     end
 end
\ No newline at end of file
diff --git a/matlab/prior_posterior_statistics_core.m b/matlab/prior_posterior_statistics_core.m
index 3e8e314366d51a15e8694867a1d0a83bad947aaf..03cc43a3e0c17d4d9ae0adcc816befb73e95e696 100644
--- a/matlab/prior_posterior_statistics_core.m
+++ b/matlab/prior_posterior_statistics_core.m
@@ -30,7 +30,7 @@ function myoutput=prior_posterior_statistics_core(myinputs,fpar,B,whoiam, ThisMa
 % SPECIAL REQUIREMENTS.
 %   None.
 
-% Copyright (C) 2005-2016 Dynare Team
+% Copyright (C) 2005-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -49,7 +49,7 @@ function myoutput=prior_posterior_statistics_core(myinputs,fpar,B,whoiam, ThisMa
 
 global options_ oo_ M_ bayestopt_ estim_params_
 
-if nargin<4,
+if nargin<4
     whoiam=0;
 end
 
@@ -103,9 +103,9 @@ MAX_nruns=myinputs.MAX_nruns;
 MAX_momentsno = myinputs.MAX_momentsno;
 ifil=myinputs.ifil;
 
-if ~strcmpi(type,'prior'),
+if ~strcmpi(type,'prior')
     x=myinputs.x;
-    if strcmpi(type,'posterior'),
+    if strcmpi(type,'posterior')
         logpost=myinputs.logpost;
     end
 end
@@ -128,7 +128,7 @@ end
 
 RemoteFlag = 0;
 if whoiam
-    if Parallel(ThisMatlab).Local==0,
+    if Parallel(ThisMatlab).Local==0
         RemoteFlag =1;
     end
     ifil=ifil(:,whoiam);
@@ -138,7 +138,7 @@ else
 end
 h = dyn_waitbar(prct0,['Taking ',type,' subdraws...']);
 
-if RemoteFlag==1,
+if RemoteFlag==1
     OutputFileName_smooth = {};
     OutputFileName_update = {};
     OutputFileName_inno = {};
@@ -157,22 +157,22 @@ end
 
 %initialize arrays
 if run_smoother
-  stock_smooth=NaN(endo_nbr,gend,MAX_nsmoo);
-  stock_update=NaN(endo_nbr,gend,MAX_nsmoo);
-  stock_innov=NaN(M_.exo_nbr,gend,MAX_ninno);
-  stock_smoothed_constant=NaN(endo_nbr,gend,MAX_n_smoothed_constant);
-  stock_smoothed_trend=NaN(endo_nbr,gend,MAX_n_smoothed_trend);
-  stock_trend_coeff = zeros(endo_nbr,MAX_n_trend_coeff);
-  if horizon
-      stock_forcst_mean= NaN(endo_nbr,horizon,MAX_nforc1);
-      stock_forcst_point = NaN(endo_nbr,horizon,MAX_nforc2);
-      if ~isequal(M_.H,0)
-          stock_forcst_point_ME = NaN(length(varobs),horizon,MAX_nforc_ME);
-      end
-  end
+    stock_smooth=NaN(endo_nbr,gend,MAX_nsmoo);
+    stock_update=NaN(endo_nbr,gend,MAX_nsmoo);
+    stock_innov=NaN(M_.exo_nbr,gend,MAX_ninno);
+    stock_smoothed_constant=NaN(endo_nbr,gend,MAX_n_smoothed_constant);
+    stock_smoothed_trend=NaN(endo_nbr,gend,MAX_n_smoothed_trend);
+    stock_trend_coeff = zeros(endo_nbr,MAX_n_trend_coeff);
+    if horizon
+        stock_forcst_mean= NaN(endo_nbr,horizon,MAX_nforc1);
+        stock_forcst_point = NaN(endo_nbr,horizon,MAX_nforc2);
+        if ~isequal(M_.H,0)
+            stock_forcst_point_ME = NaN(length(varobs),horizon,MAX_nforc_ME);
+        end
+    end
 end
 if nvn
-  stock_error = NaN(length(varobs),gend,MAX_nerro);
+    stock_error = NaN(length(varobs),gend,MAX_nerro);
 end
 if naK
     stock_filter_step_ahead =NaN(length(options_.filter_step_ahead),endo_nbr,gend+max(options_.filter_step_ahead),MAX_naK);
@@ -206,7 +206,7 @@ for b=fpar:B
         [dr,info,M_,options_,oo_] = resol(0,M_,options_,oo_);
         [alphahat,etahat,epsilonhat,alphatilde,SteadyState,trend_coeff,aK,junk1,junk2,P,junk4,junk5,trend_addition,state_uncertainty,M_,oo_,options_,bayestopt_] = ...
             DsgeSmoother(deep,gend,Y,data_index,missing_value,M_,oo_,options_,bayestopt_,estim_params_);
-        
+
         stock_trend_coeff(options_.varobs_id,irun(9))=trend_coeff;
         stock_smoothed_trend(IdObs,:,irun(11))=trend_addition;
         if options_.loglinear %reads values from smoother results, which are in dr-order and put them into declaration order
@@ -221,7 +221,7 @@ for b=fpar:B
                 constant_part;
             stock_update(dr.order_var,:,irun(1)) = alphatilde(1:endo_nbr,:)+ ...
                 constant_part;
-        end       
+        end
         stock_smoothed_constant(dr.order_var,:,irun(10))=constant_part;
         %% Compute constant for observables
         if options_.prefilter == 1 %as mean is taken after log transformation, no distinction is needed here
@@ -243,10 +243,10 @@ for b=fpar:B
             %smoothed variables are E_T(y_t) so no trend shift is required
             stock_smooth(IdObs,:,irun(1))=stock_smooth(IdObs,:,irun(1))+trend_addition+mean_correction;
             %updated variables are E_t(y_t) so no trend shift is required
-            stock_update(IdObs,:,irun(1))=stock_update(IdObs,:,irun(1))+trend_addition+mean_correction;         
+            stock_update(IdObs,:,irun(1))=stock_update(IdObs,:,irun(1))+trend_addition+mean_correction;
         else
             stock_smooth(IdObs,:,irun(1))=stock_smooth(IdObs,:,irun(1))+trend_addition;
-            stock_update(IdObs,:,irun(1))=stock_update(IdObs,:,irun(1))+trend_addition; 
+            stock_update(IdObs,:,irun(1))=stock_update(IdObs,:,irun(1))+trend_addition;
         end
         stock_innov(:,:,irun(2))  = etahat;
         if nvn
@@ -259,11 +259,11 @@ for b=fpar:B
                 constant_part=repmat(log(SteadyState(dr.order_var))',[length(options_.filter_step_ahead),1,gend+max(options_.filter_step_ahead)]);
             else
                 constant_part=repmat(SteadyState(dr.order_var)',[length(options_.filter_step_ahead),1,gend+max(options_.filter_step_ahead)]);
-            end       
+            end
 
             stock_filter_step_ahead(:,dr.order_var,:,irun(4)) = aK(options_.filter_step_ahead,1:endo_nbr,:) + ...
                 constant_part;
-            
+
             %now add trend to observables
             for ii=1:length(options_.filter_step_ahead)
                 if options_.prefilter
@@ -280,16 +280,16 @@ for b=fpar:B
         if horizon
             yyyy = alphahat(iendo,i_last_obs);
             yf = forcst2a(yyyy,dr,zeros(horizon,exo_nbr));
-            if options_.prefilter 
+            if options_.prefilter
                 % add mean
                 yf(:,IdObs) = yf(:,IdObs)+repmat(mean_varobs, ...
                                                  horizon+maxlag,1);
                 % add trend, taking into account that last point of sample is still included in forecasts and only cut off later
                 yf(:,IdObs) = yf(:,IdObs)+((options_.first_obs-1)+gend+[1-maxlag:horizon]')*trend_coeff'-...
-                             repmat(mean(trend_coeff*[options_.first_obs:options_.first_obs+gend-1],2)',length(1-maxlag:horizon),1); %center trend
+                    repmat(mean(trend_coeff*[options_.first_obs:options_.first_obs+gend-1],2)',length(1-maxlag:horizon),1); %center trend
             else
                 % add trend, taking into account that last point of sample is still included in forecasts and only cut off later
-                    yf(:,IdObs) = yf(:,IdObs)+((options_.first_obs-1)+gend+[1-maxlag:horizon]')*trend_coeff';                
+                yf(:,IdObs) = yf(:,IdObs)+((options_.first_obs-1)+gend+[1-maxlag:horizon]')*trend_coeff';
             end
             if options_.loglinear
                 yf = yf+repmat(log(SteadyState'),horizon+maxlag,1);
@@ -303,10 +303,10 @@ for b=fpar:B
                     repmat(mean_varobs,[horizon+maxlag,1,1]);
                 % add trend, taking into account that last point of sample is still included in forecasts and only cut off later
                 yf1(:,IdObs) = yf1(:,IdObs)+((options_.first_obs-1)+gend+[1-maxlag:horizon]')*trend_coeff'-...
-                             repmat(mean(trend_coeff*[options_.first_obs:options_.first_obs+gend-1],2)',length(1-maxlag:horizon),1); %center trend
+                    repmat(mean(trend_coeff*[options_.first_obs:options_.first_obs+gend-1],2)',length(1-maxlag:horizon),1); %center trend
             else
-               % add trend, taking into account that last point of sample is still included in forecasts and only cut off later
-               yf1(:,IdObs,:) = yf1(:,IdObs,:)+repmat(((options_.first_obs-1)+gend+[1-maxlag:horizon]')* ...
+                % add trend, taking into account that last point of sample is still included in forecasts and only cut off later
+                yf1(:,IdObs,:) = yf1(:,IdObs,:)+repmat(((options_.first_obs-1)+gend+[1-maxlag:horizon]')* ...
                                                        trend_coeff',[1,1,1]);
             end
             if options_.loglinear
@@ -345,14 +345,14 @@ for b=fpar:B
     irun = irun +  ones(13,1);
 
 
-    if run_smoother && (irun(1) > MAX_nsmoo || b == B),
+    if run_smoother && (irun(1) > MAX_nsmoo || b == B)
         stock = stock_smooth(:,:,1:irun(1)-1);
         ifil(1) = ifil(1) + 1;
         save([DirectoryName '/' M_.fname '_smooth' int2str(ifil(1)) '.mat'],'stock');
 
         stock = stock_update(:,:,1:irun(1)-1);
         save([DirectoryName '/' M_.fname '_update' int2str(ifil(1)) '.mat'],'stock');
-        if RemoteFlag==1,
+        if RemoteFlag==1
             OutputFileName_smooth = [OutputFileName_smooth; {[DirectoryName filesep], [M_.fname '_smooth' int2str(ifil(1)) '.mat']}];
             OutputFileName_update = [OutputFileName_update; {[DirectoryName filesep], [M_.fname '_update' int2str(ifil(1)) '.mat']}];
         end
@@ -363,7 +363,7 @@ for b=fpar:B
         stock = stock_innov(:,:,1:irun(2)-1);
         ifil(2) = ifil(2) + 1;
         save([DirectoryName '/' M_.fname '_inno' int2str(ifil(2)) '.mat'],'stock');
-        if RemoteFlag==1,
+        if RemoteFlag==1
             OutputFileName_inno = [OutputFileName_inno; {[DirectoryName filesep], [M_.fname '_inno' int2str(ifil(2)) '.mat']}];
         end
         irun(2) = 1;
@@ -373,7 +373,7 @@ for b=fpar:B
         stock = stock_error(:,:,1:irun(3)-1);
         ifil(3) = ifil(3) + 1;
         save([DirectoryName '/' M_.fname '_error' int2str(ifil(3)) '.mat'],'stock');
-        if RemoteFlag==1,
+        if RemoteFlag==1
             OutputFileName_error = [OutputFileName_error; {[DirectoryName filesep], [M_.fname '_error' int2str(ifil(3)) '.mat']}];
         end
         irun(3) = 1;
@@ -383,7 +383,7 @@ for b=fpar:B
         stock = stock_filter_step_ahead(:,:,:,1:irun(4)-1);
         ifil(4) = ifil(4) + 1;
         save([DirectoryName '/' M_.fname '_filter_step_ahead' int2str(ifil(4)) '.mat'],'stock');
-        if RemoteFlag==1,
+        if RemoteFlag==1
             OutputFileName_filter_step_ahead = [OutputFileName_filter_step_ahead; {[DirectoryName filesep], [M_.fname '_filter_step_ahead' int2str(ifil(4)) '.mat']}];
         end
         irun(4) = 1;
@@ -395,7 +395,7 @@ for b=fpar:B
         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,
+        if RemoteFlag==1
             OutputFileName_param = [OutputFileName_param; {[DirectoryName filesep], [M_.fname '_param' int2str(ifil(5)) '.mat']}];
         end
         irun(5) = 1;
@@ -405,7 +405,7 @@ for b=fpar:B
         stock = stock_forcst_mean(:,:,1:irun(6)-1);
         ifil(6) = ifil(6) + 1;
         save([DirectoryName '/' M_.fname '_forc_mean' int2str(ifil(6)) '.mat'],'stock');
-        if RemoteFlag==1,
+        if RemoteFlag==1
             OutputFileName_forc_mean = [OutputFileName_forc_mean; {[DirectoryName filesep], [M_.fname '_forc_mean' int2str(ifil(6)) '.mat']}];
         end
         irun(6) = 1;
@@ -415,39 +415,39 @@ for b=fpar:B
         stock = stock_forcst_point(:,:,1:irun(7)-1);
         ifil(7) = ifil(7) + 1;
         save([DirectoryName '/' M_.fname '_forc_point' int2str(ifil(7)) '.mat'],'stock');
-        if RemoteFlag==1,
+        if RemoteFlag==1
             OutputFileName_forc_point = [OutputFileName_forc_point; {[DirectoryName filesep], [M_.fname '_forc_point' int2str(ifil(7)) '.mat']}];
         end
         irun(7) = 1;
     end
-    
+
     if run_smoother && filter_covariance && (irun(8) > MAX_filter_covariance || b == B)
         stock = stock_filter_covariance(:,:,:,1:irun(8)-1);
         ifil(8) = ifil(8) + 1;
         save([DirectoryName '/' M_.fname '_filter_covar' int2str(ifil(8)) '.mat'],'stock');
-        if RemoteFlag==1,
+        if RemoteFlag==1
             OutputFileName_filter_covar = [OutputFileName_filter_covar; {[DirectoryName filesep], [M_.fname '_filter_covar' int2str(ifil(8)) '.mat']}];
         end
         irun(8) = 1;
     end
-    
+
     irun_index=9;
     if run_smoother && (irun(irun_index) > MAX_n_trend_coeff || b == B)
         stock = stock_trend_coeff(:,1:irun(irun_index)-1);
         ifil(irun_index) = ifil(irun_index) + 1;
         save([DirectoryName '/' M_.fname '_trend_coeff' int2str(ifil(irun_index)) '.mat'],'stock');
-        if RemoteFlag==1,
+        if RemoteFlag==1
             OutputFileName_trend_coeff = [OutputFileName_trend_coeff; {[DirectoryName filesep], [M_.fname '_trend_coeff' int2str(ifil(irun_index)) '.mat']}];
         end
         irun(irun_index) = 1;
     end
-    
+
     irun_index=10;
     if run_smoother && (irun(irun_index) > MAX_n_smoothed_constant || b == B)
         stock = stock_smoothed_constant(:,:,1:irun(irun_index)-1);
         ifil(irun_index) = ifil(irun_index) + 1;
         save([DirectoryName '/' M_.fname '_smoothed_constant' int2str(ifil(irun_index)) '.mat'],'stock');
-        if RemoteFlag==1,
+        if RemoteFlag==1
             OutputFileName_smoothed_constant = [OutputFileName_smoothed_constant; {[DirectoryName filesep], [M_.fname '_smoothed_constant' int2str(ifil(irun_index)) '.mat']}];
         end
         irun(irun_index) = 1;
@@ -458,29 +458,29 @@ for b=fpar:B
         stock = stock_smoothed_trend(:,:,1:irun(irun_index)-1);
         ifil(irun_index) = ifil(irun_index) + 1;
         save([DirectoryName '/' M_.fname '_smoothed_trend' int2str(ifil(irun_index)) '.mat'],'stock');
-        if RemoteFlag==1,
+        if RemoteFlag==1
             OutputFileName_smoothed_trend = [OutputFileName_smoothed_trend; {[DirectoryName filesep], [M_.fname '_smoothed_trend' int2str(ifil(irun_index)) '.mat']}];
         end
         irun(irun_index) = 1;
     end
-    
+
     irun_index=12;
     if run_smoother && horizon && ~isequal(M_.H,0) && (irun(irun_index) > MAX_nforc_ME ||  b == B)
         stock = stock_forcst_point_ME(:,:,1:irun(irun_index)-1);
         ifil(irun_index) = ifil(irun_index) + 1;
         save([DirectoryName '/' M_.fname '_forc_point_ME' int2str(ifil(irun_index)) '.mat'],'stock');
-        if RemoteFlag==1,
+        if RemoteFlag==1
             OutputFileName_forc_point_ME = [OutputFileName_forc_point_ME; {[DirectoryName filesep], [M_.fname '_forc_point_ME' int2str(ifil(irun_index)) '.mat']}];
         end
         irun(irun_index) = 1;
     end
-    
+
     irun_index=13;
     if run_smoother && smoothed_state_uncertainty && (irun(irun_index) > MAX_n_smoothed_state_uncertainty || b == B)
         stock = stock_smoothed_uncert(:,:,:,1:irun(irun_index)-1);
         ifil(irun_index) = ifil(irun_index) + 1;
         save([DirectoryName '/' M_.fname '_state_uncert' int2str(ifil(irun_index)) '.mat'],'stock');
-        if RemoteFlag==1,
+        if RemoteFlag==1
             OutputFileName_state_uncert = [OutputFileName_state_uncert; {[DirectoryName filesep], [M_.fname '_state_uncert' int2str(ifil(irun_index)) '.mat']}];
         end
         irun(irun_index) = 1;
@@ -490,7 +490,7 @@ for b=fpar:B
 end
 
 myoutput.ifil=ifil;
-if RemoteFlag==1,
+if RemoteFlag==1
     myoutput.OutputFileName = [OutputFileName_smooth;
                         OutputFileName_update;
                         OutputFileName_inno;
@@ -508,4 +508,3 @@ if RemoteFlag==1,
 end
 
 dyn_waitbar_close(h);
-
diff --git a/matlab/prior_sampler.m b/matlab/prior_sampler.m
index 267563d8e87c7fe248535f96214ce870f58282b2..e846cd02113c1d74e0c47bfd2c9af6f8acbe661e 100644
--- a/matlab/prior_sampler.m
+++ b/matlab/prior_sampler.m
@@ -13,7 +13,7 @@ function results = prior_sampler(drsave,M_,bayestopt_,options_,oo_,estim_params_
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2009-2012 Dynare Team
+% Copyright (C) 2009-2016 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -49,6 +49,7 @@ count_complex_steadystate = 0;
 count_nan_steadystate = 0;
 count_nan_params = 0;
 count_complex_params = 0;
+count_nonpositive_steadystate = 0;
 count_unknown_problem = 0;
 NumberOfSimulations = options_.prior_mc;
 NumberOfParameters = length(bayestopt_.p1);
@@ -135,6 +136,8 @@ while iteration < NumberOfSimulations
         count_complex_params = count_complex_params + 1 ;
       case 24
         count_nan_params = count_nan_params + 1 ;
+      case 26
+        count_nonpositive_steadystate = count_nonpositive_steadystate + 1;
       otherwise
         count_unknown_problem = count_unknown_problem + 1 ;
     end
@@ -162,6 +165,7 @@ results.dll.problem_share = count_dll_problem/loop_indx;
 results.ss.problem_share = count_no_steadystate/loop_indx;
 results.ss.complex_share = count_complex_steadystate/loop_indx;
 results.ass.problem_share = count_steadystate_file_exit/loop_indx;
+results.ss.nonpositive_share = count_nonpositive_steadystate/loop_indx;
 results.jacobian.problem_share = count_complex_jacobian/loop_indx;
 results.garbage_share = ...
     results.bk.indeterminacy_share + ...
@@ -170,6 +174,8 @@ results.garbage_share = ...
     results.dll.problem_share + ...
     results.ss.problem_share + ...
     results.ass.problem_share + ...
+    results.ss.complex_share + ...
+    results.ss.nonpositive_share + ...
     results.jacobian.problem_share + ...
     count_unknown_problem/loop_indx ;
 results.prior.mean = sampled_prior_expectation;
diff --git a/matlab/priordens.m b/matlab/priordens.m
index f760680cf0718f8318afe652b102a879c55f3534..b988e7ea1a4d123d7c453a7ad63610c2302ee2f0 100644
--- a/matlab/priordens.m
+++ b/matlab/priordens.m
@@ -1,7 +1,7 @@
 function [logged_prior_density, dlprior, d2lprior, info] = priordens(x, pshape, p6, p7, p3, p4, initialization) % --*-- Unitary tests --*--
 % Computes a prior density for the structural parameters of DSGE models
 %
-% INPUTS 
+% INPUTS
 %    x              [double]      vector with n elements.
 %    pshape         [integer]     vector with n elements (bayestopt_.pshape).
 %    p6:            [double]      vector with n elements, first  parameter of the prior distribution (bayestopt_.p6).
@@ -9,13 +9,13 @@ function [logged_prior_density, dlprior, d2lprior, info] = priordens(x, pshape,
 %    p3:            [double]      vector with n elements, lower bounds of the untruncated standard or generalized distribution
 %    p4:            [double]      vector with n elements, upper bound of the untruncated standard or generalized distribution
 %    initialization [integer]     if 1: initialize persistent variables
-%    
-% OUTPUTS 
+%
+% 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-2015 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -89,12 +89,12 @@ 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 
+        if nargout ==4
             info=id1(isinf(lpdfgbeta(x(id1),p6(id1),p7(id1),p3(id1),p4(id1))));
         end
         return
     end
-    if nargout == 2,
+    if nargout == 2
         [tmp, dlprior(id1)]=lpdfgbeta(x(id1),p6(id1),p7(id1),p3(id1),p4(id1));
     elseif nargout == 3
         [tmp, dlprior(id1), d2lprior(id1)]=lpdfgbeta(x(id1),p6(id1),p7(id1),p3(id1),p4(id1));
@@ -104,12 +104,12 @@ 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 
+        if nargout ==4
             info=id2(isinf(lpdfgam(x(id2)-p3(id2),p6(id2),p7(id2))));
         end
         return
     end
-    if nargout == 2,
+    if nargout == 2
         [tmp, dlprior(id2)]=lpdfgam(x(id2)-p3(id2),p6(id2),p7(id2));
     elseif nargout == 3
         [tmp, dlprior(id2), d2lprior(id2)]=lpdfgam(x(id2)-p3(id2),p6(id2),p7(id2));
@@ -118,7 +118,7 @@ end
 
 if tt3
     logged_prior_density = logged_prior_density + sum(lpdfnorm(x(id3),p6(id3),p7(id3))) ;
-    if nargout == 2,
+    if nargout == 2
         [tmp, dlprior(id3)]=lpdfnorm(x(id3),p6(id3),p7(id3));
     elseif nargout == 3
         [tmp, dlprior(id3), d2lprior(id3)]=lpdfnorm(x(id3),p6(id3),p7(id3));
@@ -128,12 +128,12 @@ 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 
+        if nargout ==4
             info=id4(isinf(lpdfig1(x(id4)-p3(id4),p6(id4),p7(id4))));
         end
         return
     end
-    if nargout == 2,
+    if nargout == 2
         [tmp, dlprior(id4)]=lpdfig1(x(id4)-p3(id4),p6(id4),p7(id4));
     elseif nargout == 3
         [tmp, dlprior(id4), d2lprior(id4)]=lpdfig1(x(id4)-p3(id4),p6(id4),p7(id4));
@@ -143,13 +143,13 @@ end
 if tt5
     if any(x(id5)-p3(id5)<0) || any(x(id5)-p4(id5)>0)
         logged_prior_density = -Inf ;
-        if nargout ==4 
+        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)))) ;
-    if nargout >1,
+    if nargout >1
         dlprior(id5)=zeros(length(id5),1);
     end
     if nargout == 3
@@ -160,12 +160,12 @@ 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 
+        if nargout ==4
             info=id6(isinf(lpdfig2(x(id6)-p3(id6),p6(id6),p7(id6))));
         end
         return
     end
-    if nargout == 2,
+    if nargout == 2
         [tmp, dlprior(id6)]=lpdfig2(x(id6)-p3(id6),p6(id6),p7(id6));
     elseif nargout == 3
         [tmp, dlprior(id6), d2lprior(id6)]=lpdfig2(x(id6)-p3(id6),p6(id6),p7(id6));
@@ -175,7 +175,7 @@ end
 if tt8
     logged_prior_density = logged_prior_density + sum(lpdfgweibull(x(id8),p6(id8),p7(id8)));
     if isinf(logged_prior_density)
-        if nargout ==4 
+        if nargout ==4
             info=id8(isinf(log(lpdfgweibull(x(id8),p6(id8),p7(id8)))));
         end
         return
@@ -187,7 +187,7 @@ if tt8
     end
 end
 
-if nargout==3,
+if nargout==3
     d2lprior = diag(d2lprior);
 end
 
diff --git a/matlab/qr2.m b/matlab/qr2.m
index 3c84db9960e5a9fbf830622a042dfb00516db2b2..bdd1c0dea0d78997d8bed3f23d41dae42f8b2fcd 100644
--- a/matlab/qr2.m
+++ b/matlab/qr2.m
@@ -1,23 +1,23 @@
 function [Q,R] = qr2(varargin)
 % This routine performs a qr decomposition of matrix X such that the
-% diagonal scalars of the upper-triangular matrix R are positive. If X 
+% diagonal scalars of the upper-triangular matrix R are positive. If X
 % is a full (column) rank matrix, then R is also the cholesky
-% factorization of X'X. This property is needed for the Del Negro 
+% factorization of X'X. This property is needed for the Del Negro
 % & Schorfheides's identification scheme.
-% 
-% INPUTS 
+%
+% INPUTS
 %   See matlab's documentation for QR decomposition.
-%     
-% OUTPUTS 
+%
+% OUTPUTS
 %   See matlab's documentation for QR decomposition.
 %
 % ALGORITHM
-%   None.       
+%   None.
 %
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2006-2012 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/quadratic_matrix_equation_solver.m b/matlab/quadratic_matrix_equation_solver.m
index f222df843f9aa5cf76bf61ef401d269f23a9ec31..40342085e9f779a0c20e5748f3df387a50e2e1f3 100644
--- a/matlab/quadratic_matrix_equation_solver.m
+++ b/matlab/quadratic_matrix_equation_solver.m
@@ -47,7 +47,7 @@ function [X,info] = quadratic_matrix_equation_solver(A,B,C,tol,maxit,line_search
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -106,34 +106,34 @@ end
 
 
 function f = eval_quadratic_matrix_equation(A,B,C,X)
-    f = C + (B + A*X)*X;
+f = C + (B + A*X)*X;
 
 function [p0,p1] = merit_polynomial(A,H,F)
-    AHH = A*H*H;
-    gamma = norm(AHH,'fro')^2;
-    alpha = norm(F,'fro')^2;
-    beta  = trace(F*AHH*AHH*F);
-    p0 = [gamma, -beta, alpha+beta, -2*alpha, alpha];
-    p1 = [4*gamma, -3*beta, 2*(alpha+beta), -2*alpha];
+AHH = A*H*H;
+gamma = norm(AHH,'fro')^2;
+alpha = norm(F,'fro')^2;
+beta  = trace(F*AHH*AHH*F);
+p0 = [gamma, -beta, alpha+beta, -2*alpha, alpha];
+p1 = [4*gamma, -3*beta, 2*(alpha+beta), -2*alpha];
 
 function t = line_search(A,H,F)
-    [p0,p1] = merit_polynomial(A,H,F);
-    if any(isnan(p0)) || any(isinf(p0))
-        t = 1.0;
-        return
-    end
-    r = roots(p1);
-    s = [Inf(3,1),r];
-    for i = 1:3
-        if isreal(r(i))
-            s(i,1) = p0(1)*r(i)^4 + p0(2)*r(i)^3 + p0(3)*r(i)^2 + p0(4)*r(i) + p0(5);
-        end
-    end
-    s = sortrows(s,1);
-    t = s(1,2);
-    if t<=1e-12 || t>=2
-        t = 1;
+[p0,p1] = merit_polynomial(A,H,F);
+if any(isnan(p0)) || any(isinf(p0))
+    t = 1.0;
+    return
+end
+r = roots(p1);
+s = [Inf(3,1),r];
+for i = 1:3
+    if isreal(r(i))
+        s(i,1) = p0(1)*r(i)^4 + p0(2)*r(i)^3 + p0(3)*r(i)^2 + p0(4)*r(i) + p0(5);
     end
+end
+s = sortrows(s,1);
+t = s(1,2);
+if t<=1e-12 || t>=2
+    t = 1;
+end
 
 %@test:1
 %$ addpath ../matlab
diff --git a/matlab/qz/mjdgges.m b/matlab/qz/mjdgges.m
index 2225e257b0cea14bb272d1382e40535f80c376af..12c91d8016a826b431ace4ec15a02b536389bbb0 100644
--- a/matlab/qz/mjdgges.m
+++ b/matlab/qz/mjdgges.m
@@ -6,23 +6,23 @@ function [err,ss,tt,w,sdim,eigval,info] = mjdgges(e,d,qz_criterium, fake)
 %   e            [double] real square (n*n) matrix.
 %   d            [double] real square (n*n) matrix.
 %   qz_criterium [double] scalar (1+epsilon).
-%    
+%
 % OUTPUTS
 %   err          [double]  scalar: 1 indicates failure, 0 indicates success
 %   ss           [complex] (n*n) matrix.
 %   tt           [complex] (n*n) matrix.
 %   w            [complex] (n*n) matrix.
-%   sdim         [integer] scalar.    
-%   eigval       [complex] (n*1) vector. 
+%   sdim         [integer] scalar.
+%   eigval       [complex] (n*1) vector.
 %   info         [integer] scalar.
-%    
+%
 % ALGORITHM
 %   Sims's qzdiv routine is used.
 %
 % SPECIAL REQUIREMENTS
 %   none.
 
-% Copyright (C) 1996-2010 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -43,6 +43,7 @@ function [err,ss,tt,w,sdim,eigval,info] = mjdgges(e,d,qz_criterium, fake)
 if nargin>4 || nargin<2 || nargout>7 || nargout==0
     error('MJDGGES: takes 2 or 3 input arguments and between 1 and 7 output arguments.')
 end
+
 % Check the first two inputs.
 [me,ne] = size(e);
 [md,nd] = size(d);
@@ -53,40 +54,34 @@ end
 
 % Set default value of qz_criterium.
 if nargin <3
-    qz_criterium = 1 + 1e-6; 
+    qz_criterium = 1 + 1e-6;
 end
 
 info = 0;
 
-% qz() function doesn't behave the same way under Octave and MATLAB:
-% - under MATLAB, complex decomposition by default, real is also available
-%   as an option
-% - under Octave, only real decomposition available, but grouping of
-%   eigenvalues <= 1 is implemented as an option (criterium can't be changed)
-if isoctave
-    [ss,tt,w,eigval] = qz(e,d,'S');
-    sdim = sum(abs(eigval) <= 1.0);
-    if any(abs(eigval) > 1.0 & abs(eigval) <= qz_criterium)
-        warning('Some eigenvalues are > 1.0 but <= qz_criterium in modulus. They have nevertheless been considered as explosive, because of a limitation of Octave. To solve this, you should compile the MEX files for Octave.')
-    end
-else
-    % Initialization of the output arguments.
-    ss = zeros(ne,ne);
-    tt = zeros(ne,ne);
-    w  = zeros(ne,ne);
-    sdim   = 0;
-    eigval = zeros(ne,1);
-    % Computational part.
-    try
-        [ss,tt,qq,w] = qz(e,d);
-        [tt,ss,qq,w] = qzdiv(qz_criterium,tt,ss,qq,w);
-        warning_old_state = warning;
-        warning off;
-        eigval = diag(ss)./diag(tt);
-        warning(warning_old_state);
-        sdim = sum(abs(eigval) < qz_criterium);
-    catch
-        info = 1;% Not as precise as lapack's info!
+% Initialization of the output arguments.
+ss = zeros(ne,ne);
+tt = zeros(ne,ne);
+w  = zeros(ne,ne);
+sdim   = 0;
+eigval = zeros(ne,1);
+
+% Computational part.
+try
+    if isoctave()
+        % Force complex QZ factorization.
+        e = complex(e);
+        d = complex(d);
     end
+    [ss,tt,qq,w,a,b,c] = qz(e, d);
+    warning_old_state = warning;
+    warning off;
+    [tt,ss,qq,w] = qzdiv(qz_criterium, tt, ss, qq, w);
+    eigval = diag(ss)./diag(tt);
+    warning(warning_old_state);
+    sdim = sum(abs(eigval) < qz_criterium);
+catch
+    info = 1;% Not as precise as lapack's info!
 end
+
 err = 0;
\ No newline at end of file
diff --git a/matlab/qzdiv.m b/matlab/qzdiv.m
index 2c88184f1599dbee88e34098e6147e00592d6945..ba5206efabe623624f8155494f1d82600e88d6ce 100644
--- a/matlab/qzdiv.m
+++ b/matlab/qzdiv.m
@@ -2,7 +2,7 @@ function [A,B,Q,Z] = qzdiv(stake,A,B,Q,Z)
 %function [A,B,Q,Z] = qzdiv(stake,A,B,Q,Z)
 %
 % Takes U.T. matrices A, B, orthonormal matrices Q,Z, rearranges them
-% so that all cases of abs(B(i,i)/A(i,i))>stake are in lower right 
+% so that all cases of abs(B(i,i)/A(i,i))>stake are in lower right
 % corner, while preserving U.T. and orthonormal properties and Q'AZ' and
 % Q'BZ'.
 
@@ -10,7 +10,7 @@ function [A,B,Q,Z] = qzdiv(stake,A,B,Q,Z)
 % http://sims.princeton.edu/yftp/gensys/mfiles/qzdiv.m
 
 % Copyright (C) 1993-2007 Christopher Sims
-% Copyright (C) 2008-2011 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -27,25 +27,25 @@ function [A,B,Q,Z] = qzdiv(stake,A,B,Q,Z)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-[n jnk] = size(A);
+[n, jnk] = size(A);
 root = abs([diag(A) diag(B)]);
 root(:,1) = root(:,1)-(root(:,1)<1.e-13).*(root(:,1)+root(:,2));
 root(:,2) = root(:,2)./root(:,1);
 for i = n:-1:1
     m=0;
     for j=i:-1:1
-        if (root(j,2) > stake || root(j,2) < -.1) 
+        if (root(j,2) > stake || root(j,2) < -.1)
             m=j;
             break
         end
     end
-    if (m==0) 
-        return 
+    if (m==0)
+        return
     end
     for k=m:1:i-1
-        [A B Q Z] = qzswitch(k,A,B,Q,Z);
+        [A, B, Q, Z] = qzswitch(k,A,B,Q,Z);
         tmp = root(k,2);
         root(k,2) = root(k+1,2);
         root(k+1,2) = tmp;
     end
-end         
+end
diff --git a/matlab/ramsey_policy.m b/matlab/ramsey_policy.m
index 7f932ab2eb7a2c1069be595150e7037682729a67..2ca9079fe4286739c826655b0b593518820c4d67 100644
--- a/matlab/ramsey_policy.m
+++ b/matlab/ramsey_policy.m
@@ -1,6 +1,6 @@
 function info = ramsey_policy(var_list)
 
-% Copyright (C) 2007-2012 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -33,8 +33,12 @@ if inst_nbr~=0
     elseif inst_nbr<implied_inst_nbr
         error('You have specified fewer instruments than there are omitted equations')
     end
+else
+    if options_.steadystate_flag
+        error('You have specified a steady state file, but not provided an instrument. Either delete the steady state file or provide an instrument')
+    end
 end
-        
+
 info = stoch_simul(var_list);
 
 oo_.steady_state = oo_.dr.ys;
diff --git a/matlab/read_data_.m b/matlab/read_data_.m
index 7ad6b4228ac58b873d0e4988ff3a99c0265e3e8c..d7de0843d826e9664e15f8f2109143f668672599 100644
--- a/matlab/read_data_.m
+++ b/matlab/read_data_.m
@@ -1,6 +1,6 @@
 function read_data_()
 % function read_data_
-% reads endogenous and exogenous variables from a text file 
+% reads endogenous and exogenous variables from a text file
 % Used by datafile option in simulate
 %
 % INPUT
@@ -12,7 +12,7 @@ function read_data_()
 % SPECIAL REQUIREMENT
 %   none
 
-% Copyright (C) 2007-2012 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/read_key_value_string.m b/matlab/read_key_value_string.m
index d6b7124ed639144f02b234b61a18cea1d8deca4e..446afd2f54b1b007e275f52c14da310fc0b7b972 100644
--- a/matlab/read_key_value_string.m
+++ b/matlab/read_key_value_string.m
@@ -4,7 +4,7 @@ function c = read_key_value_string(s)
 % estimation command) into a cell (first column for the option name ans second column for the
 % option value).
 
-% Copyright (C) 2011-2016 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -40,7 +40,7 @@ iComma = strfind(s,',');
 
 %delete commata in sublists from further checks
 for sublist_iter=length(i_begin_sublist):-1:1
-   iComma(iComma>=i_begin_sublist(sublist_iter) & iComma<=i_end_sublist(sublist_iter))=[];
+    iComma(iComma>=i_begin_sublist(sublist_iter) & iComma<=i_end_sublist(sublist_iter))=[];
 end
 
 nComma = length(iComma);
@@ -85,10 +85,10 @@ end
 
 
 function j = comma2opt(i)
-    if isodd(i)
-        % The comma is a separator between a Key and a Value (returned j is minus the option number).
-        j = - (i+1)/2;
-    else
-        % The comma is a separator between two options (returned j is the option number).
-        j = i/2;
-    end
\ No newline at end of file
+if isodd(i)
+    % The comma is a separator between a Key and a Value (returned j is minus the option number).
+    j = - (i+1)/2;
+else
+    % The comma is a separator between two options (returned j is the option number).
+    j = i/2;
+end
\ No newline at end of file
diff --git a/matlab/read_variables.m b/matlab/read_variables.m
index 6859a679574c2c557934ac7ab37c7f42e58db9a0..a505012523a2c29ab99fafafe60e7cc1cc73a127 100644
--- a/matlab/read_variables.m
+++ b/matlab/read_variables.m
@@ -6,7 +6,7 @@ function dyn_data_01=read_variables(file_name_01,var_names_01,dyn_data_01,xls_sh
 % INPUTS
 %    file_name_01:    file name
 %    var_names_01:    variables name
-%    dyn_data_01:     
+%    dyn_data_01:
 %    xls_sheet:       Excel sheet name
 %    xls_range:       Excel range specification
 %
@@ -17,7 +17,7 @@ function dyn_data_01=read_variables(file_name_01,var_names_01,dyn_data_01,xls_sh
 % all local variables have complicated names in order to avoid name
 % conflicts with possible user variable names
 
-% Copyright (C) 2005-2013 Dynare Team
+% Copyright (C) 2005-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -65,64 +65,64 @@ fullname = [basename extension];
 
 if ~exist(fullname)
     error(['Can''t find datafile: ' fullname ]);
-end 
+end
 
 switch (extension)
-    case '.m'
-        eval(basename);
-        for dyn_i_01=1:var_size_01
-            dyn_tmp_01 = eval(var_names_01{dyn_i_01});
+  case '.m'
+    eval(basename);
+    for dyn_i_01=1:var_size_01
+        dyn_tmp_01 = eval(var_names_01{dyn_i_01});
+        if length(dyn_tmp_01) > dyn_size_01 && dyn_size_01 > 0
+            cd(old_pwd)
+            error('data size is too large')
+        end
+        dyn_data_01(:,dyn_i_01) = dyn_tmp_01;
+    end
+  case '.mat'
+    s = load(basename);
+    for dyn_i_01=1:var_size_01
+        dyn_tmp_01 = s.(var_names_01{dyn_i_01});
+        if length(dyn_tmp_01) > dyn_size_01 && dyn_size_01 > 0
+            cd(old_pwd)
+            error('data size is too large')
+        end
+        dyn_data_01(:,dyn_i_01) = dyn_tmp_01;
+    end
+  case { '.xls', '.xlsx' }
+    [freq,init,data,varlist] = load_xls_file_data(fullname,xls_sheet,xls_range);
+    for dyn_i_01=1:var_size_01
+        iv = strmatch(strtrim(var_names_01(dyn_i_01,:)),varlist,'exact');
+        if ~isempty(iv)
+            dyn_tmp_01 = [data(:,iv)]';
             if length(dyn_tmp_01) > dyn_size_01 && dyn_size_01 > 0
                 cd(old_pwd)
                 error('data size is too large')
             end
             dyn_data_01(:,dyn_i_01) = dyn_tmp_01;
+        else
+            cd(old_pwd)
+            error([strtrim(var_names_01(dyn_i_01,:)) ' not found in ' fullname])
         end
-    case '.mat'
-        s = load(basename);
-        for dyn_i_01=1:var_size_01
-            dyn_tmp_01 = s.(var_names_01{dyn_i_01});
+    end
+  case '.csv'
+    [freq,init,data,varlist] = load_csv_file_data(fullname);
+    for dyn_i_01=1:var_size_01
+        iv = strmatch(var_names_01{dyn_i_01},varlist,'exact');
+        if ~isempty(iv)
+            dyn_tmp_01 = [data(:,iv)]';
             if length(dyn_tmp_01) > dyn_size_01 && dyn_size_01 > 0
                 cd(old_pwd)
                 error('data size is too large')
             end
             dyn_data_01(:,dyn_i_01) = dyn_tmp_01;
+        else
+            cd(old_pwd)
+            error([var_names_01{dyn_i_01} ' not found in ' fullname])
         end
-    case { '.xls', '.xlsx' }
-        [freq,init,data,varlist] = load_xls_file_data(fullname,xls_sheet,xls_range);
-        for dyn_i_01=1:var_size_01
-            iv = strmatch(strtrim(var_names_01(dyn_i_01,:)),varlist,'exact');
-            if ~isempty(iv)
-                dyn_tmp_01 = [data(:,iv)]';
-                if length(dyn_tmp_01) > dyn_size_01 && dyn_size_01 > 0
-                    cd(old_pwd)
-                    error('data size is too large')
-                end
-                dyn_data_01(:,dyn_i_01) = dyn_tmp_01;
-            else
-                cd(old_pwd)
-                error([strtrim(var_names_01(dyn_i_01,:)) ' not found in ' fullname])
-            end
-        end
-    case '.csv'
-        [freq,init,data,varlist] = load_csv_file_data(fullname);
-        for dyn_i_01=1:var_size_01
-            iv = strmatch(var_names_01{dyn_i_01},varlist,'exact');
-            if ~isempty(iv)
-                dyn_tmp_01 = [data(:,iv)]';
-                if length(dyn_tmp_01) > dyn_size_01 && dyn_size_01 > 0
-                    cd(old_pwd)
-                    error('data size is too large')
-                end
-                dyn_data_01(:,dyn_i_01) = dyn_tmp_01;
-            else
-                cd(old_pwd)
-                error([var_names_01{dyn_i_01} ' not found in ' fullname])
-            end
-        end
-    otherwise
-        cd(old_pwd)
-        error(['Unsupported extension for datafile: ' extension])
+    end
+  otherwise
+    cd(old_pwd)
+    error(['Unsupported extension for datafile: ' extension])
 end
 
 cd(old_pwd)
diff --git a/matlab/realtime_shock_decomposition.m b/matlab/realtime_shock_decomposition.m
new file mode 100644
index 0000000000000000000000000000000000000000..64bf96c6f7480eea70340e8cf887be41adef62cb
--- /dev/null
+++ b/matlab/realtime_shock_decomposition.m
@@ -0,0 +1,262 @@
+function oo_ = realtime_shock_decomposition(M_,oo_,options_,varlist,bayestopt_,estim_params_)
+% function oo_ = realtime_shock_decomposition(M_,oo_,options_,varlist,bayestopt_,estim_params_)
+% Computes shocks contribution to a simulated trajectory. The fields set are
+% oo_.realtime_shock_decomposition, oo_.conditional_shock_decomposition and oo_.realtime_forecast_shock_decomposition.
+% Subfields are arrays n_var by nshock+2 by nperiods. The
+% first nshock columns store the respective shock contributions, column n+1
+% stores the role of the initial conditions, while column n+2 stores the
+% value of the smoothed variables.  Both the variables and shocks are stored
+% in the order of declaration, i.e. M_.endo_names and M_.exo_names, respectively.
+%
+% INPUTS
+%    M_:          [structure]  Definition of the model
+%    oo_:         [structure]  Storage of results
+%    options_:    [structure]  Options
+%    varlist:     [char]       List of variables
+%    bayestopt_:  [structure]  describing the priors
+%    estim_params_: [structure] characterizing parameters to be estimated
+%
+% OUTPUTS
+%    oo_:         [structure]  Storage of results
+%
+% SPECIAL REQUIREMENTS
+%    none
+
+% Copyright (C) 2009-2017 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/>.
+
+% indices of endogenous variables
+if size(varlist,1) == 0
+    varlist = M_.endo_names(1:M_.orig_endo_nbr,:);
+end
+
+[i_var,nvar,index_uniques] = varlist_indices(varlist,M_.endo_names);
+varlist=varlist(index_uniques,:);
+
+% number of variables
+endo_nbr = M_.endo_nbr;
+
+% number of shocks
+nshocks = M_.exo_nbr;
+
+% parameter set
+parameter_set = options_.parameter_set;
+if isempty(parameter_set)
+    if isfield(oo_,'posterior_mean')
+        parameter_set = 'posterior_mean';
+    elseif isfield(oo_,'mle_mode')
+        parameter_set = 'mle_mode';
+    elseif isfield(oo_,'posterior')
+        parameter_set = 'posterior_mode';
+    else
+        error(['realtime_shock_decomposition: option parameter_set is not specified ' ...
+               'and posterior mode is not available'])
+    end
+end
+
+presample = max(1,options_.presample);
+if isfield(options_.shock_decomp,'presample')
+    presample = max(presample,options_.shock_decomp.presample);
+end
+% forecast_=0;
+forecast_ = options_.shock_decomp.forecast;
+forecast_params=0;
+if forecast_ && isfield(options_.shock_decomp,'forecast_params')
+    forecast_params = options_.shock_decomp.forecast_params;
+end
+
+% save_realtime=0;
+save_realtime = options_.shock_decomp.save_realtime;
+% array of time points in the range options_.presample+1:options_.nobs
+
+zreal = zeros(endo_nbr,nshocks+2,options_.nobs+forecast_);
+zcond = zeros(endo_nbr,nshocks+2,options_.nobs);
+skipline()
+skipline()
+running_text = 'Realtime shock decomposition ';
+newString=sprintf(running_text);
+fprintf(['\b%s'],newString);
+
+options_.selected_variables_only = 0; %make sure all variables are stored
+options_.plot_priors=0;
+init=1;
+nobs = options_.nobs;
+
+if forecast_ && any(forecast_params)
+    M1=M_;
+    M1.params = forecast_params;
+    [junk1,junk2,junk3,junk4,junk5,junk6,oo1] = dynare_resolve(M1,options_,oo_);
+    clear junk1 junk2 junk3 junk4 junk5 junk6
+end
+
+for j=presample+1:nobs
+    %    evalin('base',['options_.nobs=' int2str(j) ';'])
+    options_.nobs=j;
+    [oo, M_, junk2, junk3, Smoothed_Variables_deviation_from_mean] = evaluate_smoother(parameter_set,varlist,M_,oo_,options_,bayestopt_,estim_params_);
+
+    % reduced form
+    dr = oo.dr;
+
+    % data reordering
+    order_var = dr.order_var;
+    inv_order_var = dr.inv_order_var;
+
+
+    % coefficients
+    A = dr.ghx;
+    B = dr.ghu;
+
+    if forecast_
+        if any(forecast_params)
+            Af = oo1.dr.ghx;
+            Bf = oo1.dr.ghu;
+        else
+            Af = A;
+            Bf = B;
+        end
+    end
+
+    % initialization
+    gend = size(oo.SmoothedShocks.(deblank(M_.exo_names(1,:))),1);
+    epsilon=NaN(nshocks,gend);
+    for i=1:nshocks
+        epsilon(i,:) = oo.SmoothedShocks.(deblank(M_.exo_names(i,:)));
+    end
+    epsilon=[epsilon zeros(nshocks,forecast_)];
+
+    z = zeros(endo_nbr,nshocks+2,gend+forecast_);
+
+    z(:,end,1:gend) = Smoothed_Variables_deviation_from_mean;
+
+    maximum_lag = M_.maximum_lag;
+
+    k2 = dr.kstate(find(dr.kstate(:,2) <= maximum_lag+1),[1 2]);
+    i_state = order_var(k2(:,1))+(min(i,maximum_lag)+1-k2(:,2))*M_.endo_nbr;
+    for i=1:gend+forecast_
+        if i > 1 && i <= maximum_lag+1
+            lags = min(i-1,maximum_lag):-1:1;
+        end
+
+        if i > 1
+            tempx = permute(z(:,1:nshocks,lags),[1 3 2]);
+            m = min(i-1,maximum_lag);
+            tempx = [reshape(tempx,endo_nbr*m,nshocks); zeros(endo_nbr*(maximum_lag-i+1),nshocks)];
+            if i > gend
+                z(:,nshocks+2,i) = Af(inv_order_var,:)*z(i_state,nshocks+2,lags);
+                %             z(:,nshocks+2,i) = A(inv_order_var,:)*permute(z(i_state,nshocks+2,lags),[1 3 2]);
+                z(:,1:nshocks,i) = Af(inv_order_var,:)*tempx(i_state,:);
+            else
+                z(:,1:nshocks,i) = A(inv_order_var,:)*tempx(i_state,:);
+            end
+            lags = lags+1;
+            z(:,1:nshocks,i) = z(:,1:nshocks,i) + B(inv_order_var,:).*repmat(epsilon(:,i)',endo_nbr,1);
+        end
+
+        %         z(:,1:nshocks,i) = z(:,1:nshocks,i) + B(inv_order_var,:).*repmat(epsilon(:,i)',endo_nbr,1);
+        z(:,nshocks+1,i) = z(:,nshocks+2,i) - sum(z(:,1:nshocks,i),2);
+    end
+
+    %% conditional shock decomp 1 step ahead
+    z1 = zeros(endo_nbr,nshocks+2);
+    z1(:,end) = Smoothed_Variables_deviation_from_mean(:,gend);
+    for i=gend
+
+        z1(:,1:nshocks) = z1(:,1:nshocks) + B(inv_order_var,:).*repmat(epsilon(:,i)',endo_nbr,1);
+        z1(:,nshocks+1) = z1(:,nshocks+2) - sum(z1(:,1:nshocks),2);
+    end
+    %%
+
+    %% conditional shock decomp k step ahead
+    if forecast_ && forecast_<j
+        zn = zeros(endo_nbr,nshocks+2,forecast_+1);
+        zn(:,end,1:forecast_+1) = Smoothed_Variables_deviation_from_mean(:,gend-forecast_:gend);
+        for i=1:forecast_+1
+            if i > 1 && i <= maximum_lag+1
+                lags = min(i-1,maximum_lag):-1:1;
+            end
+
+            if i > 1
+                tempx = permute(zn(:,1:nshocks,lags),[1 3 2]);
+                m = min(i-1,maximum_lag);
+                tempx = [reshape(tempx,endo_nbr*m,nshocks); zeros(endo_nbr*(maximum_lag-i+1-1),nshocks)];
+                zn(:,1:nshocks,i) = A(inv_order_var,:)*tempx(i_state,:);
+                lags = lags+1;
+                zn(:,1:nshocks,i) = zn(:,1:nshocks,i) + B(inv_order_var,:).*repmat(epsilon(:,i+gend-forecast_-1)',endo_nbr,1);
+            end
+
+            %             zn(:,1:nshocks,i) = zn(:,1:nshocks,i) + B(inv_order_var,:).*repmat(epsilon(:,i+gend-forecast_-1)',endo_nbr,1);
+            zn(:,nshocks+1,i) = zn(:,nshocks+2,i) - sum(zn(:,1:nshocks,i),2);
+        end
+        oo_.conditional_shock_decomposition.(['time_' int2str(j-forecast_)])=zn;
+    end
+    %%
+
+    if init
+        zreal(:,:,1:j) = z(:,:,1:j);
+    else
+        zreal(:,:,j) = z(:,:,gend);
+    end
+    zcond(:,:,j) = z1;
+    if ismember(j,save_realtime)
+        oo_.realtime_shock_decomposition.(['time_' int2str(j)])=z;
+    end
+
+    if forecast_
+        zfrcst(:,:,j+1) = z(:,:,gend+1);
+        oo_.realtime_forecast_shock_decomposition.(['time_' int2str(j)])=z(:,:,gend:end);
+        if j>forecast_+presample
+            %% realtime conditional shock decomp k step ahead
+            oo_.realtime_conditional_shock_decomposition.(['time_' int2str(j-forecast_)]) = ...
+                zreal(:,:,j-forecast_:j) - ...
+                oo_.realtime_forecast_shock_decomposition.(['time_' int2str(j-forecast_)]);
+            oo_.realtime_conditional_shock_decomposition.(['time_' int2str(j-forecast_)])(:,end-1,:) = ...
+                oo_.realtime_forecast_shock_decomposition.(['time_' int2str(j-forecast_)])(:,end,:);
+            oo_.realtime_conditional_shock_decomposition.(['time_' int2str(j-forecast_)])(:,end,:) = ...
+                zreal(:,end,j-forecast_:j);
+
+            if j==nobs
+                for my_forecast_=(forecast_-1):-1:1
+                    oo_.realtime_conditional_shock_decomposition.(['time_' int2str(j-my_forecast_)]) = ...
+                        zreal(:,:,j-my_forecast_:j) - ...
+                        oo_.realtime_forecast_shock_decomposition.(['time_' int2str(j-my_forecast_)])(:,:,1:my_forecast_+1);
+                    oo_.realtime_conditional_shock_decomposition.(['time_' int2str(j-my_forecast_)])(:,end-1,:) = ...
+                        oo_.realtime_forecast_shock_decomposition.(['time_' int2str(j-my_forecast_)])(:,end,1:my_forecast_+1);
+                    oo_.realtime_conditional_shock_decomposition.(['time_' int2str(j-my_forecast_)])(:,end,:) = ...
+                        zreal(:,end,j-my_forecast_:j);
+                end
+            end
+
+        end
+    end
+
+    prctdone=(j-presample)/(nobs-presample);
+    if isoctave
+        printf([running_text,' %3.f%% done\r'], prctdone*100);
+    else
+        s0=repmat('\b',1,length(newString));
+        newString=sprintf([running_text,' %3.1f%% done'], prctdone*100);
+        fprintf([s0,'%s'],newString);
+    end
+    init=0;
+end
+oo_.realtime_shock_decomposition.pool = zreal;
+oo_.conditional_shock_decomposition.pool = zcond;
+if forecast_
+    oo_.realtime_forecast_shock_decomposition.pool = zfrcst;
+end
+
+skipline()
diff --git a/matlab/recursive_moments.m b/matlab/recursive_moments.m
index 712a4b5978f2cfd10a6e35478e6d6dfae28b3a5a..4d38d9b1bf366a29274c625decebc536380d802c 100644
--- a/matlab/recursive_moments.m
+++ b/matlab/recursive_moments.m
@@ -1,25 +1,25 @@
 function [mu,sigma,offset] = recursive_moments(m0,s0,data,offset)
 % Recursive estimation of order one and two moments (expectation and
-% covariance matrix). 
-% 
-% INPUTS 
+% covariance matrix).
+%
+% INPUTS
 %   o m0         [double]    (n*1) vector, the prior expectation.
 %   o s0         [double]    (n*n) matrix, the prior covariance matrix.
-%   o data       [double]    (T*n) matrix.  
+%   o data       [double]    (T*n) matrix.
 %   o offset     [integer]   scalar, number of observation previously
 %                            used to compute m0 and s0.
-% OUTPUTS 
-%   o mu         [double]    (n*1) vector, the posterior expectation. 
+% OUTPUTS
+%   o mu         [double]    (n*1) vector, the posterior expectation.
 %   o sigma      [double]    (n*n) matrix, the posterior covariance matrix.
 %   o offset     [integer]   = offset + T.
 %
-% ALGORITHM 
-%   None.       
+% ALGORITHM
+%   None.
 %
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2006-2009 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -47,6 +47,6 @@ for t = 1:T
     s0 = s1;
 end
 
-mu = m1; 
+mu = m1;
 sigma = s1;
 offset = offset+T;
\ No newline at end of file
diff --git a/matlab/reduced_form_models/local_state_space_iteration_2/local_state_space_iteration_2.m b/matlab/reduced_form_models/local_state_space_iteration_2/local_state_space_iteration_2.m
index 0c6a52d071a74c84dfcd2c69cd16cce9233084b5..5224567289988d3c29e6b21a42e3aee5b647f324 100644
--- a/matlab/reduced_form_models/local_state_space_iteration_2/local_state_space_iteration_2.m
+++ b/matlab/reduced_form_models/local_state_space_iteration_2/local_state_space_iteration_2.m
@@ -58,7 +58,7 @@ function [y,y_] = local_state_space_iteration_2(yhat,epsilon,ghx,ghu,constant,gh
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2014 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/reduced_rank_cholesky.m b/matlab/reduced_rank_cholesky.m
index 1af9ec6090e2838d9f9131275d22b90975885032..fe9edbacef6c5f44f1e1c84a917cd891a0168edb 100644
--- a/matlab/reduced_rank_cholesky.m
+++ b/matlab/reduced_rank_cholesky.m
@@ -36,7 +36,7 @@ function T = reduced_rank_cholesky(X)
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -51,8 +51,8 @@ function T = reduced_rank_cholesky(X)
 % 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/>.
+
 [T,X_is_not_positive_definite] = chol(X);
 
 if X_is_not_positive_definite
@@ -87,7 +87,7 @@ end
 %$ catch
 %$    t(1) = 0;
 %$    T = all(t);
-%$    return;
+%$    return
 %$ end
 %$
 %$
diff --git a/matlab/resid.m b/matlab/resid.m
index 7383c1944359fa29fd282bbac546b1bf845a50a2..f124409c167f4f415de6cc0ea03402acf2b13f47 100644
--- a/matlab/resid.m
+++ b/matlab/resid.m
@@ -2,17 +2,17 @@ function z = resid(junk)
 % function z = resid(junk)
 %
 % Computes static residuals associated with the guess values.
-% 
+%
 % INPUTS
 %    junk:   dummy value for backward compatibility
-%    
+%
 % OUTPUTS
 %    z:      residuals
-%        
+%
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2001-2012 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -58,9 +58,9 @@ if any(imag(oo_.steady_state))
         for iter=1:length(imagrow)
             fprintf('%s\n',M_.endo_names(imagrow(iter),:));
         end
-    end   
+    end
 end
-    
+
 if options_.steadystate_flag
     [oo_.steady_state,M_.params,info] = ...
         evaluate_steady_state(oo_.steady_state,M_,options_,oo_,0);
diff --git a/matlab/resol.m b/matlab/resol.m
index 31ce81edeb6f74b83d770bf6d7a58d0afa97a94a..ba3d0e6479a3ad981437ac8ebfcd982303e7d606 100644
--- a/matlab/resol.m
+++ b/matlab/resol.m
@@ -76,7 +76,7 @@ function [dr,info,M,options,oo] = resol(check_flag,M,options,oo)
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2001-2016 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -93,7 +93,7 @@ function [dr,info,M,options,oo] = resol(check_flag,M,options,oo)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-if isfield(oo,'dr');
+if isfield(oo,'dr')
     dr = oo.dr;
 end
 
@@ -101,7 +101,7 @@ if M.exo_nbr == 0
     oo.exo_steady_state = [] ;
 end
 
-[dr.ys,M.params,info] = evaluate_steady_state(oo.steady_state,M,options,oo,0);
+[dr.ys,M.params,info] = evaluate_steady_state(oo.steady_state,M,options,oo,~options.steadystate.nocheck);
 
 if info(1)
     oo.dr = dr;
@@ -122,7 +122,7 @@ if options.loglinear
             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()
+            if isinestimationobjective()
                 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')
diff --git a/matlab/rotated_slice_sampler.m b/matlab/rotated_slice_sampler.m
index 66908d77d44264a54693061b5a7cb738bb64231a..6dbfded0f461b2492fc4e64e5ecb32bee4f3014e 100644
--- a/matlab/rotated_slice_sampler.m
+++ b/matlab/rotated_slice_sampler.m
@@ -1,184 +1,183 @@
-function [theta, fxsim, neval] = rotated_slice_sampler(objective_function,theta,thetaprior,sampler_options,varargin)
-% ----------------------------------------------------------
-% ROTATED SLICE SAMPLER - with stepping out (Neal, 2003)
-% extension of the orthogonal univarite sampler (slice_sampler.m)
-% copyright M. Ratto (European Commission)
-%
-% objective_function(theta,varargin): -log of any unnormalized pdf 
-% with varargin (optional) a vector of auxiliaty parameters
-% to be passed to f( ).
-% ----------------------------------------------------------
-%
-% INPUTS
-%   objective_function:       objective function (expressed as minus the log of a density)
-%   theta:                    last value of theta
-%   thetaprior:               bounds of the theta space
-%   sampler_options:          posterior sampler options
-%   varargin:                 optional input arguments to objective function
-%
-% OUTPUTS
-%   theta:       new theta sample
-%   fxsim:       value of the objective function for the new sample
-%   neval:       number of function evaluations
-%
-% 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/>.
-
-theta=theta(:);
-npar = length(theta);
-neval = zeros(npar,1);
-W1=[];
-if isfield(sampler_options,'WR'),
-    W1 = sampler_options.WR;
-end
-if ~isempty(sampler_options.mode),
-    mm = sampler_options.mode;
-    n = length(mm);
-    for j=1:n,
-        distance(j)=sqrt(sum((theta-mm(j).m).^2));
-    end
-    [m, im] = min(distance);
-    
-    r=im;
-    V1 = mm(r).m;
-    jj=0;
-    for j=1:n,
-        if j~=r,
-            jj=jj+1;
-            tmp=mm(j).m-mm(r).m;
-            %tmp=mm(j).m-theta;
-            V1(:,jj)=tmp/norm(tmp);
-        end
-    end
-    resul=randperm(n-1,n-1);
-    V1 = V1(:,resul);
-
-    %V1 = V1(:, randperm(n-1));
-%     %d = chol(mm(r).invhess);
-%     %V1 = transpose(feval(sampler_options.proposal_distribution, transpose(mm(r).m), d, npar));
-% 
-%     V1=eye(npar);
-%     V1=V1(:,randperm(npar));
-%     for j=1:2,
-%         V1(:,j)=mm(r(j)).m-theta;
-%         V1(:,j)=V1(:,j)/norm(V1(:,j));
-%     end
-%     % Gram-Schmidt
-%     for j=2:npar,
-%         for k=1:j-1,
-%             V1(:,j)=V1(:,j)-V1(:,k)'*V1(:,j)*V1(:,k);
-%         end
-%         V1(:,j)=V1(:,j)/norm(V1(:,j));
-%     end    
-%     for j=1:n,
-%         distance(j)=sqrt(sum((theta-mm(j).m).^2));
-%     end
-%     [m, im] = min(distance);
-%     if im==r, 
-%         fxsim=[];
-%         return,
-%     else
-%         theta1=theta;
-%     end
-else
-    V1 = sampler_options.V1;    
-end
-npar=size(V1,2);
-    
-for it=1:npar,
-    theta0 = theta;
-    neval(it) = 0;
-    xold  = 0;
-   % XLB   = thetaprior(3);
-   % XUB   = thetaprior(4);
-    tb=sort([(thetaprior(:,1)-theta)./V1(:,it) (thetaprior(:,2)-theta)./V1(:,it)],2);
-    XLB=max(tb(:,1));
-    XUB=min(tb(:,2));  
-    if isempty(W1),
-        W = (XUB-XLB); %*0.8; 
-    else
-        W = W1(it);
-    end
-        
-    % -------------------------------------------------------
-    % 1. DRAW Z = ln[f(X0)] - EXP(1) where EXP(1)=-ln(U(0,1))
-    %    THIS DEFINES THE SLICE S={x: z < ln(f(x))}
-    % -------------------------------------------------------
-    
-    fxold = -feval(objective_function,theta,varargin{:});
-    %I have to be sure that the rotation is for L,R or for Fxold, theta(it)
-    neval(it) = neval(it) + 1;
-    Z = fxold + log(rand(1,1));
-    % -------------------------------------------------------------
-    % 2. FIND I=(L,R) AROUND X0 THAT CONTAINS S AS MUCH AS POSSIBLE
-    %    STEPPING-OUT PROCEDURE
-    % -------------------------------------------------------------
-    u = rand(1,1);
-    L = max(XLB,xold-W*u);
-    R = min(XUB,L+W);
-    
-    %[L R]=slice_rotation(L, R, alpha);
-    while(L > XLB)
-        xsim = L;
-        theta = theta0+xsim*V1(:,it);
-        fxl = -feval(objective_function,theta,varargin{:});
-        neval(it) = neval(it) + 1;
-        if (fxl <= Z)
-            break;
-        end
-        L = max(XLB,L-W);
-    end
-    while(R < XUB)
-        xsim = R;
-        theta = theta0+xsim*V1(:,it);
-        fxr = -feval(objective_function,theta,varargin{:});
-        neval(it) = neval(it) + 1;
-        if (fxr <= Z)
-            break;
-        end
-        R = min(XUB,R+W);
-    end
-    % ------------------------------------------------------
-    % 3. SAMPLING FROM THE SET A = (I INTERSECT S) = (LA,RA)
-    % ------------------------------------------------------
-    fxsim = Z-1;
-    while (fxsim < Z)
-        u = rand(1,1);
-        xsim = L + u*(R - L);
-        theta = theta0+xsim*V1(:,it);
-        fxsim = -feval(objective_function,theta,varargin{:});
-        neval(it) = neval(it) + 1;
-        if (xsim > xold)
-            R = xsim;
-        else
-            L = xsim;
-        end
-    end
-end
-
-% if ~isempty(sampler_options.mode),
-%     dist1=sqrt(sum((theta-mm(r).m).^2));
-%     if dist1>distance(r),
-%         theta=theta1;
-%         fxsim=[];
-%     end
-% end
-end
-
+function [theta, fxsim, neval] = rotated_slice_sampler(objective_function,theta,thetaprior,sampler_options,varargin)
+% ----------------------------------------------------------
+% ROTATED SLICE SAMPLER - with stepping out (Neal, 2003)
+% extension of the orthogonal univarite sampler (slice_sampler.m)
+% copyright M. Ratto (European Commission)
+%
+% objective_function(theta,varargin): -log of any unnormalized pdf
+% with varargin (optional) a vector of auxiliaty parameters
+% to be passed to f( ).
+% ----------------------------------------------------------
+%
+% INPUTS
+%   objective_function:       objective function (expressed as minus the log of a density)
+%   theta:                    last value of theta
+%   thetaprior:               bounds of the theta space
+%   sampler_options:          posterior sampler options
+%   varargin:                 optional input arguments to objective function
+%
+% OUTPUTS
+%   theta:       new theta sample
+%   fxsim:       value of the objective function for the new sample
+%   neval:       number of function evaluations
+%
+% SPECIAL REQUIREMENTS
+%   none
+
+% Copyright (C) 2015-2017 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/>.
+
+theta=theta(:);
+npar = length(theta);
+neval = zeros(npar,1);
+W1=[];
+if isfield(sampler_options,'WR')
+    W1 = sampler_options.WR;
+end
+if ~isempty(sampler_options.mode)
+    mm = sampler_options.mode;
+    n = length(mm);
+    for j=1:n
+        distance(j)=sqrt(sum((theta-mm(j).m).^2));
+    end
+    [m, im] = min(distance);
+
+    r=im;
+    V1 = mm(r).m;
+    jj=0;
+    for j=1:n
+        if j~=r
+            jj=jj+1;
+            tmp=mm(j).m-mm(r).m;
+            %tmp=mm(j).m-theta;
+            V1(:,jj)=tmp/norm(tmp);
+        end
+    end
+    resul=randperm(n-1,n-1);
+    V1 = V1(:,resul);
+
+    %V1 = V1(:, randperm(n-1));
+    %     %d = chol(mm(r).invhess);
+    %     %V1 = transpose(feval(sampler_options.proposal_distribution, transpose(mm(r).m), d, npar));
+    %
+    %     V1=eye(npar);
+    %     V1=V1(:,randperm(npar));
+    %     for j=1:2,
+    %         V1(:,j)=mm(r(j)).m-theta;
+    %         V1(:,j)=V1(:,j)/norm(V1(:,j));
+    %     end
+    %     % Gram-Schmidt
+    %     for j=2:npar,
+    %         for k=1:j-1,
+    %             V1(:,j)=V1(:,j)-V1(:,k)'*V1(:,j)*V1(:,k);
+    %         end
+    %         V1(:,j)=V1(:,j)/norm(V1(:,j));
+    %     end
+    %     for j=1:n,
+    %         distance(j)=sqrt(sum((theta-mm(j).m).^2));
+    %     end
+    %     [m, im] = min(distance);
+    %     if im==r,
+    %         fxsim=[];
+    %         return,
+    %     else
+    %         theta1=theta;
+    %     end
+else
+    V1 = sampler_options.V1;
+end
+npar=size(V1,2);
+
+for it=1:npar
+    theta0 = theta;
+    neval(it) = 0;
+    xold  = 0;
+    % XLB   = thetaprior(3);
+    % XUB   = thetaprior(4);
+    tb=sort([(thetaprior(:,1)-theta)./V1(:,it) (thetaprior(:,2)-theta)./V1(:,it)],2);
+    XLB=max(tb(:,1));
+    XUB=min(tb(:,2));
+    if isempty(W1)
+        W = (XUB-XLB); %*0.8;
+    else
+        W = W1(it);
+    end
+
+    % -------------------------------------------------------
+    % 1. DRAW Z = ln[f(X0)] - EXP(1) where EXP(1)=-ln(U(0,1))
+    %    THIS DEFINES THE SLICE S={x: z < ln(f(x))}
+    % -------------------------------------------------------
+
+    fxold = -feval(objective_function,theta,varargin{:});
+    %I have to be sure that the rotation is for L,R or for Fxold, theta(it)
+    neval(it) = neval(it) + 1;
+    Z = fxold + log(rand(1,1));
+    % -------------------------------------------------------------
+    % 2. FIND I=(L,R) AROUND X0 THAT CONTAINS S AS MUCH AS POSSIBLE
+    %    STEPPING-OUT PROCEDURE
+    % -------------------------------------------------------------
+    u = rand(1,1);
+    L = max(XLB,xold-W*u);
+    R = min(XUB,L+W);
+
+    %[L R]=slice_rotation(L, R, alpha);
+    while(L > XLB)
+        xsim = L;
+        theta = theta0+xsim*V1(:,it);
+        fxl = -feval(objective_function,theta,varargin{:});
+        neval(it) = neval(it) + 1;
+        if (fxl <= Z)
+            break
+        end
+        L = max(XLB,L-W);
+    end
+    while(R < XUB)
+        xsim = R;
+        theta = theta0+xsim*V1(:,it);
+        fxr = -feval(objective_function,theta,varargin{:});
+        neval(it) = neval(it) + 1;
+        if (fxr <= Z)
+            break
+        end
+        R = min(XUB,R+W);
+    end
+    % ------------------------------------------------------
+    % 3. SAMPLING FROM THE SET A = (I INTERSECT S) = (LA,RA)
+    % ------------------------------------------------------
+    fxsim = Z-1;
+    while (fxsim < Z)
+        u = rand(1,1);
+        xsim = L + u*(R - L);
+        theta = theta0+xsim*V1(:,it);
+        fxsim = -feval(objective_function,theta,varargin{:});
+        neval(it) = neval(it) + 1;
+        if (xsim > xold)
+            R = xsim;
+        else
+            L = xsim;
+        end
+    end
+end
+
+% if ~isempty(sampler_options.mode),
+%     dist1=sqrt(sum((theta-mm(r).m).^2));
+%     if dist1>distance(r),
+%         theta=theta1;
+%         fxsim=[];
+%     end
+% end
+end
diff --git a/matlab/row_header_width.m b/matlab/row_header_width.m
index c3132e261be6f7941acb498709c73d7cbc70e6ff..e3a99550250f4da93f660c187364282464e8319d 100644
--- a/matlab/row_header_width.m
+++ b/matlab/row_header_width.m
@@ -1,19 +1,19 @@
 function w=row_header_width(M_,estim_params_,bayestopt_)
 % This function computes the width of the row headers for
 % the estimation results
-% 
-% INPUTS 
-%   estim_params_    [structure] 
+%
+% INPUTS
+%   estim_params_    [structure]
 %   M_               [structure]
 %   bayestopt_       [structure]
-%  
-% OUTPUTS 
+%
+% OUTPUTS
 %   w                integer
 %
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2006-2013 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -44,13 +44,13 @@ if np
 end
 if nvx
     for i=1:nvx
-        k = estim_params_.var_exo(i,1); 
+        k = estim_params_.var_exo(i,1);
         w = max(w,length(deblank(M_.exo_names(k,:))));
     end
 end
 if nvn
     for i=1:nvn
-        k = estim_params_.var_endo(i,1); 
+        k = estim_params_.var_endo(i,1);
         w = max(w,length(deblank(M_.endo_names(k,:))));
     end
 end
@@ -72,4 +72,3 @@ if ncn
 
     end
 end
-
diff --git a/matlab/rplot.m b/matlab/rplot.m
index 5705abdc1b74d8971cca14d05c540d3eb113a225..cc7f30515cfc48c5033ddd9d8a4d0d10a7d3082e 100644
--- a/matlab/rplot.m
+++ b/matlab/rplot.m
@@ -14,7 +14,7 @@ function rplot(s1)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2001-2016 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -52,11 +52,11 @@ ix = [1 - M_.maximum_lag:size(oo_.endo_simul,2)-M_.maximum_lag]' ;
 
 y = [];
 for k=1:size(s1,1)
-    if isempty(strmatch(deblank(s1(k,:)),M_.endo_names,'exact')) 
-        if isempty(strmatch(deblank(s1(k,:)),M_.exo_names,'exact')) 
+    if isempty(strmatch(deblank(s1(k,:)),M_.endo_names,'exact'))
+        if isempty(strmatch(deblank(s1(k,:)),M_.exo_names,'exact'))
             error (['rplot: One of the variables specified does not exist']) ;
         else
-            y = [y; oo_.exo_simul(:,strmatch(deblank(s1(k,:)),M_.exo_names,'exact'))'] ;        
+            y = [y; oo_.exo_simul(:,strmatch(deblank(s1(k,:)),M_.exo_names,'exact'))'] ;
         end
     else
         y = [y; oo_.endo_simul(strmatch(deblank(s1(k,:)),M_.endo_names,'exact'),:)] ;
@@ -81,7 +81,7 @@ if rplottype == 0
     for j = 1:size(y,1)
         t = [t s1(j,:) ' '] ;
     end
-    hh=dyn_figure(options_,'Name',['Simulated Trajectory']);
+    hh=dyn_figure(options_.nodisplay,'Name',['Simulated Trajectory']);
     plot(ix(i),y(:,i)) ;
     title (t,'Interpreter','none') ;
     xlabel('Periods') ;
@@ -94,24 +94,24 @@ if rplottype == 0
             set(h, 'Interpreter', 'none');
         end
     end
-    dyn_saveas(hh,[M_.fname, filesep, 'graphs', filesep, 'SimulatedTrajectory_' deblank(s1(1,:))],options_)
+    dyn_saveas(hh,[M_.fname, filesep, 'graphs', filesep, 'SimulatedTrajectory_' deblank(s1(1,:))],options_.nodisplay,options_.graph_format)
     if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
         create_TeX_loader(fidTeX,options_,[M_.fname, '/graphs/', 'SimulatedTrajectory_' deblank(s1(1,:))],'Simulated trajectories','SimulatedTrajectory_',deblank(s1(1,:)),1)
     end
 elseif rplottype == 1
     for j = 1:size(y,1)
-        hh=dyn_figure(options_,'Name',['Simulated Trajectory']);
+        hh=dyn_figure(options_.nodisplay,'Name',['Simulated Trajectory']);
         plot(ix(i),y(j,i)) ;
         xlim([min(ix(i)) max(ix(i))])
         title(['Plot of ' s1(j,:)],'Interpreter','none') ;
         xlabel('Periods') ;
-        dyn_saveas(hh,[M_.fname, filesep, 'graphs', filesep, 'SimulatedTrajectory_' deblank(s1(j,:))],options_)
+        dyn_saveas(hh,[M_.fname, filesep, 'graphs', filesep, 'SimulatedTrajectory_' deblank(s1(j,:))],options_.nodisplay,options_.graph_format)
         if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
             create_TeX_loader(fidTeX,options_,[M_.fname, '/graphs/', 'SimulatedTrajectory_' deblank(s1(j,:))],'Simulated trajectories','SimulatedTrajectory_',deblank(s1(j,:)),1);
         end
     end
 elseif rplottype == 2
-    hh=dyn_figure(options_,'Name',['Simulated Trajectory']);
+    hh=dyn_figure(options_.nodisplay,'Name',['Simulated Trajectory']);
     nl = max(1,fix(size(y,1)/4)) ;
     nc = ceil(size(y,1)/nl) ;
     for j = 1:size(y,1)
@@ -128,7 +128,7 @@ elseif rplottype == 2
         title(['Plot of ' s1(j,:)],'Interpreter','none') ;
         axis tight;
     end
-    dyn_saveas(hh,[M_.fname, filesep, 'graphs', filesep, 'SimulatedTrajectory_' deblank(s1(1,:))],options_)
+    dyn_saveas(hh,[M_.fname, filesep, 'graphs', filesep, 'SimulatedTrajectory_' deblank(s1(1,:))],options_.nodisplay,options_.graph_format)
     if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
         create_TeX_loader(fidTeX,options_,[M_.fname, '/graphs/', 'SimulatedTrajectory_' deblank(s1(1,:))],'Simulated trajectories','SimulatedTrajectory_',deblank(s1(1,:)),min(j/nc,1));
     end
@@ -140,16 +140,16 @@ if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
 end
 
 function []=create_TeX_loader(fidTeX,options,figpath,caption,label_name,label_type,scale_factor)
-    if nargin<6
-        scale_factor=1;
-    end
-    fprintf(fidTeX,' \n'); 
-    fprintf(fidTeX,'\\begin{figure}[H]\n');
-    fprintf(fidTeX,'\\centering \n');
-    fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s}\n',0.8*scale_factor,strrep(figpath,'\','/'));
-    fprintf(fidTeX,'\\caption{%s.}',caption);
-    fprintf(fidTeX,'\\label{Fig:%s:%s}\n',label_name,label_type);
-    fprintf(fidTeX,'\\end{figure}\n\n');
+if nargin<6
+    scale_factor=1;
+end
+fprintf(fidTeX,' \n');
+fprintf(fidTeX,'\\begin{figure}[H]\n');
+fprintf(fidTeX,'\\centering \n');
+fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s}\n',0.8*scale_factor,strrep(figpath,'\','/'));
+fprintf(fidTeX,'\\caption{%s.}',caption);
+fprintf(fidTeX,'\\label{Fig:%s:%s}\n',label_name,label_type);
+fprintf(fidTeX,'\\end{figure}\n\n');
 
 % 02/28/01 MJ replaced bseastr by MATLAB's strmatch
 % 06/19/01 MJ added 'exact' to strmatch calls
diff --git a/matlab/sample_autocovariance.m b/matlab/sample_autocovariance.m
index 12bd34e86f2a8621c5f0bd36f1d3d242056f3d13..3ae17e1a0e0588018c38b686c0709ec9cc73aa30 100644
--- a/matlab/sample_autocovariance.m
+++ b/matlab/sample_autocovariance.m
@@ -1,19 +1,19 @@
 function [autocov,autocor] = sample_autocovariance(data,q)
 % Computes the autocovariance function associated to a time series.
-% 
 %
-% INPUTS 
+%
+% INPUTS
 %
 %   data            [double]       T*1 vector of data.
-%   q               [integer]      Order of the autocovariance function. 
-%    
-% OUTPUTS 
-%   autocov         [double]       (q+1)*1 vector, autocovariance function (first scalar is the variance).  
+%   q               [integer]      Order of the autocovariance function.
+%
+% OUTPUTS
+%   autocov         [double]       (q+1)*1 vector, autocovariance function (first scalar is the variance).
 %   autocor         [double]       (q+1)*1 vector, autocorrelation function (first scalar is equal to one).
 %
 % SPECIAL REQUIREMENTS
 
-% Copyright (C) 2003-2008 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/sample_hp_filter.m b/matlab/sample_hp_filter.m
index a7b3592cfde263e57aaff6f77895126e9fa3bf77..381086b3deaca2487ec41676e02703a49b6ba98e 100644
--- a/matlab/sample_hp_filter.m
+++ b/matlab/sample_hp_filter.m
@@ -1,18 +1,18 @@
 function [hptrend,hpcycle] = sample_hp_filter(y,s)
 % HP filters a collection of time series.
-% 
-% INPUTS 
+%
+% INPUTS
 %   y                        [double]   T*n matrix of data (n is the number of variables)
 %   s                        [double]   scalar, smoothing parameter.
-% 
-% OUTPUTS 
+%
+% OUTPUTS
 %   hptrend                  [double]   T*n matrix, trend component of y.
-%   hpcycle                  [double]   T*n matrix, cycle component of y.  
-%               
+%   hpcycle                  [double]   T*n matrix, cycle component of y.
+%
 % SPECIAL REQUIREMENTS
-%    
+%
 
-% Copyright (C) 2010-2011 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/save_params_and_steady_state.m b/matlab/save_params_and_steady_state.m
index 0f8dbfe1a4435190812a3103701d64049484b23a..273800fce11a9df739a43a04713116d95677a00e 100644
--- a/matlab/save_params_and_steady_state.m
+++ b/matlab/save_params_and_steady_state.m
@@ -12,17 +12,17 @@ function save_params_and_steady_state(filename)
 % Note that no variable type is stored in the file, so that the values
 % can be reloaded (with load_params_and_steady_state) in a setup where
 % the variable types are different.
-%  
+%
 % INPUTS
 %   filename:   where to store the saved values
-%  
+%
 % OUTPUTS
 %   none
 %
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2008-2009 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/score.m b/matlab/score.m
index 273ca639537cc49807369e58f71156023eac6afe..06c01cc0d7dcd36ad525def1d6cff869a7792832 100644
--- a/matlab/score.m
+++ b/matlab/score.m
@@ -8,7 +8,7 @@ function [DLIK] = score(T,R,Q,H,P,Y,DT,DYss,DOm,DH,DP,start,mf,kalman_tol,riccat
 % NOTE: the derivative matrices (DT,DR ...) are 3-dim. arrays with last
 % dimension equal to the number of structural parameters
 
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -25,95 +25,95 @@ function [DLIK] = score(T,R,Q,H,P,Y,DT,DYss,DOm,DH,DP,start,mf,kalman_tol,riccat
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licen
 
-    k = size(DT,3);                                 % number of structural parameters
-    smpl = size(Y,2);                               % Sample size.
-    mm   = size(T,2);                               % Number of state variables.
-    a    = zeros(mm,1);                             % State vector.
-    Om   = R*Q*transpose(R);                        % Variance of R times the vector of structural innovations.
-    t    = 0;                                       % Initialization of the time index.
-    oldK = 0;
-    notsteady   = 1;                                % Steady state flag.
-    F_singular  = 1;
-
-    DLIK  = zeros(k,1);                             % Initialization of the score.
-    Da    = zeros(mm,k);                            % State vector.
-    Dv    = zeros(length(mf),k);                    % observation vector.
-    
+k = size(DT,3);                                 % number of structural parameters
+smpl = size(Y,2);                               % Sample size.
+mm   = size(T,2);                               % Number of state variables.
+a    = zeros(mm,1);                             % State vector.
+Om   = R*Q*transpose(R);                        % Variance of R times the vector of structural innovations.
+t    = 0;                                       % Initialization of the time index.
+oldK = 0;
+notsteady   = 1;                                % Steady state flag.
+F_singular  = 1;
+
+DLIK  = zeros(k,1);                             % Initialization of the score.
+Da    = zeros(mm,k);                            % State vector.
+Dv    = zeros(length(mf),k);                    % observation vector.
+
 %     for ii = 1:k
-%         DOm = DR(:,:,ii)*Q*transpose(R) + R*DQ(:,:,ii)*transpose(R) + R*Q*transpose(DR(:,:,ii)); 
+%         DOm = DR(:,:,ii)*Q*transpose(R) + R*DQ(:,:,ii)*transpose(R) + R*Q*transpose(DR(:,:,ii));
 %     end
-    
-    while notsteady & t<smpl
-        t  = t+1;
-        v  = Y(:,t)-a(mf);
-        F  = P(mf,mf) + H;
-        if rcond(F) < kalman_tol
-            if ~all(abs(F(:))<kalman_tol)
-                return
-            else
-                a = T*a;
-                P = T*P*transpose(T)+Om;
-            end
+
+while notsteady & t<smpl
+    t  = t+1;
+    v  = Y(:,t)-a(mf);
+    F  = P(mf,mf) + H;
+    if rcond(F) < kalman_tol
+        if ~all(abs(F(:))<kalman_tol)
+            return
         else
-            F_singular = 0;
-            iF     = inv(F);
-            K      = P(:,mf)*iF;
-
-            [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K);
-            for ii = 1:k
-                Dv(:,ii)   = -Da(mf,ii)-DYss(mf,ii);
-                Da(:,ii)   = DT(:,:,ii)*(a+K*v) + T*(Da(:,ii)+DK(:,:,ii)*v + K*Dv(:,ii));
-                if t>=start
-                   DLIK(ii,1)  = DLIK(ii,1) + trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v;
-                end
+            a = T*a;
+            P = T*P*transpose(T)+Om;
+        end
+    else
+        F_singular = 0;
+        iF     = inv(F);
+        K      = P(:,mf)*iF;
+
+        [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K);
+        for ii = 1:k
+            Dv(:,ii)   = -Da(mf,ii)-DYss(mf,ii);
+            Da(:,ii)   = DT(:,:,ii)*(a+K*v) + T*(Da(:,ii)+DK(:,:,ii)*v + K*Dv(:,ii));
+            if t>=start
+                DLIK(ii,1)  = DLIK(ii,1) + trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v;
             end
-            a      = T*(a+K*v);                   
-            P      = T*(P-K*P(mf,:))*transpose(T)+Om;
-            DP     = DP1;
         end
-        notsteady = max(max(abs(K-oldK))) > riccati_tol;
-        oldK = K;
+        a      = T*(a+K*v);
+        P      = T*(P-K*P(mf,:))*transpose(T)+Om;
+        DP     = DP1;
     end
+    notsteady = max(max(abs(K-oldK))) > riccati_tol;
+    oldK = K;
+end
 
-    if F_singular
-        error('The variance of the forecast error remains singular until the end of the sample')
-    end
+if F_singular
+    error('The variance of the forecast error remains singular until the end of the sample')
+end
 
-    for ii = 1:k
-        tmp0(:,:,ii) = iF*DF(:,:,ii)*iF;
-    end
-    
-    if t < smpl
-        t0 = t+1;
-        while t < smpl
-            t = t+1;
-            v = Y(:,t)-a(mf);
-            for ii = 1:k
-                Dv(:,ii)   = -Da(mf,ii)-DYss(mf,ii);
-                Da(:,ii)   = DT(:,:,ii)*(a+K*v) + T*(Da(:,ii)+DK(:,:,ii)*v + K*Dv(:,ii));
-                if t>=start
-                   DLIK(ii,1)  = DLIK(ii,1) + trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v;
-                end
-            end
-            a = T*(a+K*v);
-        end
+for ii = 1:k
+    tmp0(:,:,ii) = iF*DF(:,:,ii)*iF;
+end
+
+if t < smpl
+    t0 = t+1;
+    while t < smpl
+        t = t+1;
+        v = Y(:,t)-a(mf);
         for ii = 1:k
-%             DLIK(ii,1)  = DLIK(ii,1) + (smpl-t0+1)*trace( iF*DF(:,:,ii) );
+            Dv(:,ii)   = -Da(mf,ii)-DYss(mf,ii);
+            Da(:,ii)   = DT(:,:,ii)*(a+K*v) + T*(Da(:,ii)+DK(:,:,ii)*v + K*Dv(:,ii));
+            if t>=start
+                DLIK(ii,1)  = DLIK(ii,1) + trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v;
+            end
         end
-        
-    end    
-    
-    DLIK = DLIK/2;
-    
-% end of main function    
-    
+        a = T*(a+K*v);
+    end
+    for ii = 1:k
+        %             DLIK(ii,1)  = DLIK(ii,1) + (smpl-t0+1)*trace( iF*DF(:,:,ii) );
+    end
+
+end
+
+DLIK = DLIK/2;
+
+% end of main function
+
 function [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K)
 
-            k      = size(DT,3);
-            tmp    = P-K*P(mf,:);
+k      = size(DT,3);
+tmp    = P-K*P(mf,:);
 
 for ii = 1:k
-    DF(:,:,ii)  = DP(mf,mf,ii) + DH(:,:,ii); 
+    DF(:,:,ii)  = DP(mf,mf,ii) + DH(:,:,ii);
     DiF(:,:,ii) = -iF*DF(:,:,ii)*iF;
     DK(:,:,ii)  = DP(:,mf,ii)*iF + P(:,mf)*DiF(:,:,ii);
     Dtmp        = DP(:,:,ii) - DK(:,:,ii)*P(mf,:) - K*DP(mf,:,ii);
@@ -121,6 +121,3 @@ for ii = 1:k
 end
 
 % end of computeDKalman
-
-
-            
\ No newline at end of file
diff --git a/matlab/selec_posterior_draws.m b/matlab/selec_posterior_draws.m
index d89baf6cf21cf7da9b73185611047357225882d9..95407609e82c059c886ac41b3544f6e18979ba61 100644
--- a/matlab/selec_posterior_draws.m
+++ b/matlab/selec_posterior_draws.m
@@ -20,7 +20,7 @@ function SampleAddress = selec_posterior_draws(SampleSize,drsize)
 %   None.
 %
 
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -100,6 +100,8 @@ SampleAddress = sortrows(SampleAddress,[3 2]);
 % Selected draws in the posterior distribution, and if drsize>0
 % reduced form solutions, are saved on disk.
 if info
+    %delete old stale files before creating new ones
+    delete_stale_file([BaseName '_posterior_draws*.mat'])
     if  SampleSize*drawsize <= MAX_mega_bytes% The posterior draws are saved in one file.
         pdraws = cell(SampleSize,info);
         old_mhfile = 0;
diff --git a/matlab/select_from_table.m b/matlab/select_from_table.m
index cc657e9347b547c6df900c5abab22716f95e54f0..1584cb9500c21d534bb7905186fb05efda8a7933 100644
--- a/matlab/select_from_table.m
+++ b/matlab/select_from_table.m
@@ -1,5 +1,5 @@
 function [indices] = select_from_table(table,key,value)
-% Copyright (C) 2010-2011 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -18,7 +18,7 @@ function [indices] = select_from_table(table,key,value)
 candidates = table(strmatch(key,table(:,2),'exact'),:);
 if nargin == 2
     indices = cell2mat( candidates(:,1) );
-    return;
+    return
 end
 indices = candidates(strmatch(value, candidates(:,3), 'exact'),1);
 indices = cell2mat(indices);
diff --git a/matlab/select_qz_criterium_value.m b/matlab/select_qz_criterium_value.m
index 09282747ea32c93cb7d3777d3ea7b7c5b8eb2ac8..574b022b271374eb26eaf4b70223b229faa5fb48 100644
--- a/matlab/select_qz_criterium_value.m
+++ b/matlab/select_qz_criterium_value.m
@@ -11,7 +11,7 @@ function options_=select_qz_criterium_value(options_)
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2016 Dynare Team
+% Copyright (C) 2016-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -36,21 +36,40 @@ function options_=select_qz_criterium_value(options_)
 %     set by default options_.qz_criterium to 1+1e-6
 stack = dbstack;
 
-if isequal(options_.lik_init,1)
-    if isempty(options_.qz_criterium)
-        options_.qz_criterium = 1-1e-6;
-    elseif options_.qz_criterium > 1-eps
-        error([stack(2).file ': option qz_criterium is too large for estimating/smoothing ' ...
-               'a stationary model. If your model contains unit roots, use ' ...
-               'option diffuse_filter'])
+if options_.particle.status
+    % Non linear filter
+    if isequal(options_.particle.initialization, 3)
+        if isempty(options_.qz_criterium)
+            options_.qz_criterium = 1+1e-6;
+        else
+            if options_.qz_criterium <= 1
+                fprintf('\n%s:: You set nonlinear_filter_initialization equal to 3, it is assumed that you try to estimate a non stationary model. Resetting it to 1+1e-6.\n', stack(2).file)
+                options_.qz_criterium = 1+1e-6;
+            end
+        end
+    else
+        if isempty(options_.qz_criterium)
+            options_.qz_criterium = 1-1e-6;
+        end
     end
 else
-    if isempty(options_.qz_criterium)
-        options_.qz_criterium = 1+1e-6;
+    % Linear filter
+    if isequal(options_.lik_init,1)
+        if isempty(options_.qz_criterium)
+            options_.qz_criterium = 1-1e-6;
+        elseif options_.qz_criterium > 1-eps
+            error([stack(2).file ': option qz_criterium is too large for estimating/smoothing ' ...
+                   'a stationary model. If your model contains unit roots, use ' ...
+                   'option diffuse_filter'])
+        end
     else
-        if options_.qz_criterium <= 1
-            fprintf('\n%s:: diffuse filter is incompatible with a qz_criterium<=1. Resetting it to 1+1e-6.\n',stack(2).file)
+        if isempty(options_.qz_criterium)
             options_.qz_criterium = 1+1e-6;
+        else
+            if options_.qz_criterium <= 1
+                fprintf('\n%s:: diffuse filter is incompatible with a qz_criterium<=1. Resetting it to 1+1e-6.\n',stack(2).file)
+                options_.qz_criterium = 1+1e-6;
+            end
         end
     end
-end
+end
\ No newline at end of file
diff --git a/matlab/selif.m b/matlab/selif.m
index 752143aa5c85015339a142723696b9160f734a0c..6a79f486c5e77707a035b9f01713413e4264f163 100644
--- a/matlab/selif.m
+++ b/matlab/selif.m
@@ -1,6 +1,6 @@
 function x = selif(a,b)
 
-% Copyright (C) 2001-2009 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -18,10 +18,9 @@ function x = selif(a,b)
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 if size(b,2) ~= 1
-    error ('The second argument in SELIF must be � column vector') ;
+    error ('The second argument in SELIF must be à column vector') ;
 end
 
 x = a(find(b == 1),:) ;
 
 return ;
-
diff --git a/matlab/set_all_parameters.m b/matlab/set_all_parameters.m
index e4daafc37e014040f9abb372773dbec8fe1b41b2..2f4fcc28e65e53bff1423721194ee7e99e2fc425 100644
--- a/matlab/set_all_parameters.m
+++ b/matlab/set_all_parameters.m
@@ -33,7 +33,7 @@ function M = set_all_parameters(xparam1,estim_params,M)
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2003-2016 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -95,7 +95,7 @@ if ncx
 end
 %build covariance matrix from correlation matrix and variances already on
 %diagonal
-Sigma_e = diag(sqrt(diag(Sigma_e)))*Correlation_matrix*diag(sqrt(diag(Sigma_e))); 
+Sigma_e = diag(sqrt(diag(Sigma_e)))*Correlation_matrix*diag(sqrt(diag(Sigma_e)));
 %if calibrated covariances, set them now to their stored value
 if isfield(estim_params,'calibrated_covariances')
     Sigma_e(estim_params.calibrated_covariances.position)=estim_params.calibrated_covariances.cov_value;
@@ -136,5 +136,5 @@ if nvx || ncx
 end
 if nvn || ncn
     M.H = H;
-    M.Correlation_matrix_ME=Correlation_matrix_ME;    
+    M.Correlation_matrix_ME=Correlation_matrix_ME;
 end
\ No newline at end of file
diff --git a/matlab/set_default_initial_condition_decomposition_options.m b/matlab/set_default_initial_condition_decomposition_options.m
new file mode 100644
index 0000000000000000000000000000000000000000..07c84d3e6b16bb0af8b67bf48743ffa8bea603b4
--- /dev/null
+++ b/matlab/set_default_initial_condition_decomposition_options.m
@@ -0,0 +1,37 @@
+function options = set_default_initial_condition_decomposition_options(options)
+%function options = set_default_initial_condition_decomposition_options(options)
+% sets the default options for prior_shock_decomposition
+%
+% INPUTS
+%    options
+%
+% OUTPUTS
+%    options
+%
+% SPECIAL REQUIREMENTS
+%    none
+
+% Copyright (C) 2017 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/>.
+
+options.initial_condition_decomp.detail_plot = 0;
+options.initial_condition_decomp.steadystate = 0;
+options.initial_condition_decomp.write_xls = 0;
+options.initial_condition_decomp.type = '';
+options.initial_condition_decomp.plot_init_date = [];
+options.initial_condition_decomp.plot_end_date = [];
+end
diff --git a/matlab/set_default_option.m b/matlab/set_default_option.m
index 760d74fa86f8ed428a064fc57998033a43e064c8..44976a15a1d2e286b7bc70a8a0cf26d3366bf346 100644
--- a/matlab/set_default_option.m
+++ b/matlab/set_default_option.m
@@ -1,20 +1,20 @@
 function options=set_default_option(options,field,default)
 
 % function options=set_default_option(options,field,default)
-% Sets the option value 
-% 
+% Sets the option value
+%
 % INPUTS
 %    options
 %    field:   option name
 %    default: assigns a value
-%    
+%
 % OUTPUTS
 %    options
-%        
+%
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2009 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/set_default_plot_shock_decomposition_options.m b/matlab/set_default_plot_shock_decomposition_options.m
new file mode 100644
index 0000000000000000000000000000000000000000..327c047cb9f04c6b94b3dc2f06201e7fc83d21f2
--- /dev/null
+++ b/matlab/set_default_plot_shock_decomposition_options.m
@@ -0,0 +1,51 @@
+function options = set_default_plot_shock_decomposition_options(options)
+%function options = set_default_plot_shock_decomposition_options(options)
+% sets the default options for prior_shock_decomposition
+%
+% INPUTS
+%    options
+%
+% OUTPUTS
+%    options
+%
+% SPECIAL REQUIREMENTS
+%    none
+
+% Copyright (C) 2017 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/>.
+
+options.plot_shock_decomp.use_shock_groups = '';
+options.plot_shock_decomp.colormap = '';
+options.plot_shock_decomp.nodisplay = 0;
+options.plot_shock_decomp.graph_format = 'eps';
+options.plot_shock_decomp.detail_plot = 0;
+options.plot_shock_decomp.interactive = 0;
+options.plot_shock_decomp.screen_shocks = 0;
+options.plot_shock_decomp.steadystate = 0;
+options.plot_shock_decomp.type = '';
+options.plot_shock_decomp.fig_name = '';
+options.plot_shock_decomp.write_xls = 0;
+options.plot_shock_decomp.realtime = 0; % 0 is standard; 1 is realtime
+                                        % (pool/vintage); 2 is conditional
+                                        % (pool/vintage); 3 is forecast
+                                        % (pool/vintage)
+options.plot_shock_decomp.vintage = 0; % 0 pool realtime/conditional; int:
+                                       % forecast/conditional shock
+                                       % decompositions
+options.plot_shock_decomp.plot_init_date = [];
+options.plot_shock_decomp.plot_end_date = [];
+end
diff --git a/matlab/set_dynare_random_generator_state.m b/matlab/set_dynare_random_generator_state.m
index f16ce13aed7eb52402aa00a635add310bca09326..a06fdff5d4568e80c66b055af23aa18c9fbbe82d 100644
--- a/matlab/set_dynare_random_generator_state.m
+++ b/matlab/set_dynare_random_generator_state.m
@@ -1,12 +1,12 @@
 function [state_u,state_n] = set_dynare_random_generator_state(state_u,state_n)
 % Wet state of Matlab/Octave random generator depending on matlab
-% (octave) version. 
+% (octave) version.
 % In older versions, Matlab kept one generator for uniformly distributed numbers and
-% one for normally distributed numbers. 
+% one for normally distributed numbers.
 % For backward compatibility, we return two vectors, but, in recent
 % versions of Matlab and in Octave, we return two identical vectors.
-%    
-% Copyright (C) 2010-2012 Dynare Team
+%
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -23,37 +23,37 @@ function [state_u,state_n] = set_dynare_random_generator_state(state_u,state_n)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-    matlab_random_streams = ~(isoctave || matlab_ver_less_than('7.7'));
+matlab_random_streams = ~(isoctave || matlab_ver_less_than('7.7'));
 
-    if matlab_random_streams% Use new matlab interface.
+if matlab_random_streams% Use new matlab interface.
+    if matlab_ver_less_than('7.12')
+        s = RandStream.getDefaultStream();
+    else
+        s = RandStream.getGlobalStream();
+    end
+    if isequal(s.Type,'legacy')
+        rand('state',state_u);
+        randn('state',state_n);
+    else
+        if ~isequal(state_u,state_n)
+            error(['You are using the new Matlab RandStream mechanism ' ...
+                   'with a single random generator, but the values ' ...
+                   'of the state of the uniformly ' ...
+                   'distributed numbers and of the state of the ' ...
+                   'normally distributed numbers are different. Something must be ' ...
+                   'wrong, such as reloading old Metropolis runs, ' ...
+                   'computed on a different version of Matlab. If you ' ...
+                   'don''t understand the origin of the problem, ' ...
+                   'please, contact Dynare''s development team.'])
+        end
+        s.State = state_u;
         if matlab_ver_less_than('7.12')
-            s = RandStream.getDefaultStream();
+            RandStream.setDefaultStream(s);
         else
-            s = RandStream.getGlobalStream();
+            RandStream.setGlobalStream(s);
         end
-        if isequal(s.Type,'legacy')
-            rand('state',state_u);
-            randn('state',state_n);
-        else            
-            if ~isequal(state_u,state_n)
-                error(['You are using the new Matlab RandStream mechanism ' ...
-                       'with a single random generator, but the values ' ...
-                       'of the state of the uniformly ' ...
-                       'distributed numbers and of the state of the ' ...
-                       'normally distributed numbers are different. Something must be ' ...
-                       'wrong, such as reloading old Metropolis runs, ' ...
-                       'computed on a different version of Matlab. If you ' ...
-                       'don''t understand the origin of the problem, ' ...
-                       'please, contact Dynare''s development team.'])
-            end
-            s.State = state_u;
-            if matlab_ver_less_than('7.12')
-                RandStream.setDefaultStream(s);
-            else
-                RandStream.setGlobalStream(s);
-            end
-        end
-    else% Use old matlab interface.
-        rand('state',state_u);
-        randn('state',state_n);
-    end
\ No newline at end of file
+    end
+else% Use old matlab interface.
+    rand('state',state_u);
+    randn('state',state_n);
+end
\ No newline at end of file
diff --git a/matlab/set_dynare_seed.m b/matlab/set_dynare_seed.m
index 3a71d7236c03ff64feeaff862cdd5b0bbac681e7..65c5e05877bd716de0c0d83150d26ece6df026e5 100644
--- a/matlab/set_dynare_seed.m
+++ b/matlab/set_dynare_seed.m
@@ -1,8 +1,8 @@
 function set_dynare_seed(a,b)
-% Set seeds depending on matlab (octave) version. This routine is called in dynare_config and can be called by the 
+% Set seeds depending on matlab (octave) version. This routine is called in dynare_config and can be called by the
 % user in the mod file.
-%    
-% Copyright (C) 2010-2014 Dynare Team
+%
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/set_historical_values.m b/matlab/set_historical_values.m
new file mode 100644
index 0000000000000000000000000000000000000000..d57662f3528adb7af775ebbfd2f7027e7facfae9
--- /dev/null
+++ b/matlab/set_historical_values.m
@@ -0,0 +1,85 @@
+function set_historical_values(ds, initialperiod)
+
+% Builds endo_histval and exo_hsitval from the content of a dseries object.
+%
+% INPUTS
+% - ds                [dseries]    Dataset.
+% - initialperiod     [dates]      Initial period of the simulation.
+%
+% OUTPUTS
+% - none
+% Copyright (C) 2017 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_
+
+if ischar(ds)
+    ds = evalin('caller', ds);
+end
+
+if ischar(initialperiod)
+    initialperiod = eval(initialperiod);
+end
+
+% Initialize endo_histval.
+M_.endo_histval = zeros(M_.endo_nbr, M_.maximum_endo_lag);
+
+% Fill endo_histval.
+k = 1;
+for i = 1:M_.endo_nbr
+    if i <= M_.orig_endo_nbr
+        if M_.lead_lag_incidence(1,i) > 0
+            if any(strcmp(deblank(M_.endo_names(i,:)),ds.name))
+                M_.endo_histval(i,M_.maximum_endo_lag) = ...
+                    ds{deblank(M_.endo_names(i,:))}(initialperiod-1).data;
+            else
+                error(sprintf('Can''t find %s in dseries', deblank(M_.endo_names(i,:))))
+            end
+        end
+    else
+        a = M_.aux_vars(k);
+        if a.type == 1
+            if any(strcmp(deblank(M_.endo_names(a.orig_index,:)), ds.name))
+                M_.endo_histval(i,M_.maximum_endo_lag) = ...
+                    ds{deblank(M_.endo_names(a.orig_index,:))}(initialperiod-1+a.orig_lead_lag).data;
+            else
+                error(sprintf('Can''t find %s in dseries', deblank(M_.endo_names(a.orig_index,:))))
+            end
+        end
+        k = k + 1;
+    end
+end
+
+% If model has lags on exogenous variables, initialize and fill exo_histval
+if M_.maximum_exo_lag
+    M_.exo_histval = zeros(M_.maximum_exo_lag, M_.exo_nbr);
+    exo_list = cellstr(M_.exo_names);
+    available_exo_variables = ismember(exo_list, ds.name);
+    if any(~available_exo_variables)
+        skipline()
+        disp('Some exogenous variables are not available in the dseries object.')
+        disp('Default value for lagged exogenous variables is zero.')
+        skipline()
+    end
+    for t = 1:M_.maximum_exo_lag
+        for i=1:M_.exo_nbr
+            if available_exo_variables(i)
+                exo_histval(M_.maximum_exo_lag+1-t,i) = ds{exo_list{i}}(initialperiod-t).data;
+            end
+        end
+    end
+end
\ No newline at end of file
diff --git a/matlab/@dynTimeIndex/subsasgn.m b/matlab/set_local_param_value.m
similarity index 74%
rename from matlab/@dynTimeIndex/subsasgn.m
rename to matlab/set_local_param_value.m
index 1014680622ce5bab3410c8b8ba0a31f032eb6fc5..52e88341dc99c3174ad2331d493f02ca5ac4f4b1 100644
--- a/matlab/@dynTimeIndex/subsasgn.m
+++ b/matlab/set_local_param_value.m
@@ -1,6 +1,6 @@
-function val = subsasgn(val, idx, rhs)
+function M = set_local_param_value(pname,value,M)
 
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -17,4 +17,11 @@ function val = subsasgn(val, idx, rhs)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-error('dynTimeIndex::subsasgn: Members of dynTimeIndex class are private!')
\ No newline at end of file
+
+i = strmatch(pname,M.param_names,'exact');
+
+if isempty(i)
+    error(['Parameter name ' pname ' doesn''t exist'])
+end
+
+M.params(i) = value;
diff --git a/matlab/set_parameters.m b/matlab/set_parameters.m
index c183bb3d311bdf7d9247df18a75fb63721e85d36..15f4175ed1112c968364093db1ea39c2cf0423fe 100644
--- a/matlab/set_parameters.m
+++ b/matlab/set_parameters.m
@@ -4,17 +4,17 @@ function set_parameters(xparam1)
 % Sets parameters value (except measurement errors)
 % This is called for computations such as IRF and forecast
 % when measurement errors aren't taken into account
-% 
+%
 % INPUTS
 %    xparam1:   vector of parameters to be estimated (initial values)
-%    
+%
 % OUTPUTS
 %    none
-%        
+%
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2013 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -66,7 +66,7 @@ if ncx
 end
 %build covariance matrix from correlation matrix and variances already on
 %diagonal
-Sigma_e = diag(sqrt(diag(Sigma_e)))*Correlation_matrix*diag(sqrt(diag(Sigma_e))); 
+Sigma_e = diag(sqrt(diag(Sigma_e)))*Correlation_matrix*diag(sqrt(diag(Sigma_e)));
 if isfield(estim_params_,'calibrated_covariances')
     Sigma_e(estim_params_.calibrated_covariances.position)=estim_params_.calibrated_covariances.cov_value;
 end
diff --git a/matlab/set_prior.m b/matlab/set_prior.m
index c6898b41386b2c7cc66231a75ea4797276c499e3..dc7922916e722b79332e6cf9f3c12f992f5cc0a5 100644
--- a/matlab/set_prior.m
+++ b/matlab/set_prior.m
@@ -4,21 +4,21 @@ function [xparam1, estim_params_, bayestopt_, lb, ub, M_]=set_prior(estim_params
 %
 % INPUTS
 %    o estim_params_    [structure] characterizing parameters to be estimated.
-%    o M_               [structure] characterizing the model. 
-%    o options_         [structure] 
-%    
+%    o M_               [structure] characterizing the model.
+%    o options_         [structure]
+%
 % OUTPUTS
 %    o xparam1          [double]    vector of parameters to be estimated (initial values)
 %    o estim_params_    [structure] characterizing parameters to be estimated
 %    o bayestopt_       [structure] characterizing priors
-%    o lb               [double]    vector of lower bounds for the estimated parameters. 
+%    o lb               [double]    vector of lower bounds for the estimated parameters.
 %    o ub               [double]    vector of upper bounds for the estimated parameters.
 %    o M_               [structure] characterizing the model.
-%    
+%
 % SPECIAL REQUIREMENTS
 %    None
 
-% Copyright (C) 2003-2013 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -64,7 +64,7 @@ bayestopt_.name = {};
 if nvx
     xparam1 = estim_params_.var_exo(:,2);
     ub = estim_params_.var_exo(:,4);
-    lb = estim_params_.var_exo(:,3); 
+    lb = estim_params_.var_exo(:,3);
     bayestopt_.pshape =  estim_params_.var_exo(:,5);
     bayestopt_.p1 =  estim_params_.var_exo(:,6);
     bayestopt_.p2 =  estim_params_.var_exo(:,7);
@@ -88,8 +88,8 @@ if nvn
         estim_params_.nvn_observable_correspondence(i,1)=obsi_;
     end
     xparam1 = [xparam1; estim_params_.var_endo(:,2)];
-    ub = [ub; estim_params_.var_endo(:,4)]; 
-    lb = [lb; estim_params_.var_endo(:,3)]; 
+    ub = [ub; estim_params_.var_endo(:,4)];
+    lb = [lb; estim_params_.var_endo(:,3)];
     bayestopt_.pshape = [ bayestopt_.pshape; estim_params_.var_endo(:,5)];
     bayestopt_.p1 = [ bayestopt_.p1; estim_params_.var_endo(:,6)];
     bayestopt_.p2 = [ bayestopt_.p2; estim_params_.var_endo(:,7)];
@@ -158,7 +158,7 @@ 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}))
+                   ' or fix the parameter completely.'], bayestopt_.name{bayestopt_.p2 ==0}))
 end
 
 % generalized location parameters by default for beta distribution
@@ -169,12 +169,15 @@ k1 = find(isnan(bayestopt_.p4(k)));
 bayestopt_.p4(k(k1)) = ones(length(k1),1);
 for i=1:length(k)
     [bayestopt_.p6(k(i)), bayestopt_.p7(k(i))] = beta_specification(bayestopt_.p1(k(i)), bayestopt_.p2(k(i))^2, bayestopt_.p3(k(i)), bayestopt_.p4(k(i)), bayestopt_.name{k(i)});
+    if bayestopt_.p6(k(i))<1 || bayestopt_.p7(k(i))<1
+        fprintf('Prior distribution for parameter %s has unbounded density!\n',bayestopt_.name{k(i)})
+    end
     m = compute_prior_mode([ bayestopt_.p6(k(i)) , bayestopt_.p7(k(i)) , bayestopt_.p3(k(i)) , bayestopt_.p4(k(i)) ],1);
     if length(m)==1
         bayestopt_.p5(k(i)) = m;
     else
         disp(['Prior distribution for parameter ' bayestopt_.name{k(i)}  ' has two modes!'])
-        bayestopt_.p5(k(i)) = m(1); 
+        bayestopt_.p5(k(i)) = m(1);
     end
 end
 
@@ -186,6 +189,9 @@ bayestopt_.p3(k(k1)) = zeros(length(k1),1);
 bayestopt_.p4(k(k2)) = Inf(length(k2),1);
 for i=1:length(k)
     [bayestopt_.p6(k(i)), bayestopt_.p7(k(i))] = gamma_specification(bayestopt_.p1(k(i)), bayestopt_.p2(k(i))^2, bayestopt_.p3(k(i)), bayestopt_.name{k(i)});
+    if bayestopt_.p6(k(i))<1
+        fprintf('Prior distribution for parameter %s has unbounded density!\n',bayestopt_.name{k(i)})
+    end
     bayestopt_.p5(k(i)) = compute_prior_mode([ bayestopt_.p6(k(i)) , bayestopt_.p7(k(i)) , bayestopt_.p3(k(i)) ], 2) ;
 end
 
diff --git a/matlab/set_state_space.m b/matlab/set_state_space.m
index a7d108165f212d0190cfc6e749bfa5e223cc4121..de8108f3273ad7898d44133777f2b1fb4ad94679 100644
--- a/matlab/set_state_space.m
+++ b/matlab/set_state_space.m
@@ -34,7 +34,7 @@ function dr=set_state_space(dr,DynareModel,DynareOptions)
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 1996-2013 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -73,7 +73,7 @@ if DynareOptions.block == 1
     order_var = DynareModel.block_structure.variable_reordered;
 else
     order_var = [ stat_var(:); pred_var(:); both_var(:); fwrd_var(:)];
-end;
+end
 inv_order_var(order_var) = (1:endo_nbr);
 
 % building kmask for z state vector in t+1
diff --git a/matlab/shock_decomposition.m b/matlab/shock_decomposition.m
index f3c264edcaf3018b17c8c5f27bf63af93147e156..1785e8c0895936679d01a676aafcafddbc3abfe3 100644
--- a/matlab/shock_decomposition.m
+++ b/matlab/shock_decomposition.m
@@ -1,10 +1,10 @@
-function oo_ = shock_decomposition(M_,oo_,options_,varlist,bayestopt_,estim_params_)
+function [oo_,M_] = shock_decomposition(M_,oo_,options_,varlist,bayestopt_,estim_params_)
 % function z = shock_decomposition(M_,oo_,options_,varlist)
 % Computes shocks contribution to a simulated trajectory. The field set is
 % oo_.shock_decomposition. It is a n_var by nshock+2 by nperiods array. The
 % first nshock columns store the respective shock contributions, column n+1
 % stores the role of the initial conditions, while column n+2 stores the
-% value of the smoothed variables.  Both the variables and shocks are stored 
+% value of the smoothed variables.  Both the variables and shocks are stored
 % in the order of declaration, i.e. M_.endo_names and M_.exo_names, respectively.
 %
 % INPUTS
@@ -17,11 +17,13 @@ function oo_ = shock_decomposition(M_,oo_,options_,varlist,bayestopt_,estim_para
 %
 % OUTPUTS
 %    oo_:         [structure]  Storage of results
+%    M_:          [structure]  Definition of the model; makes sure that
+%                               M_.params is correctly updated
 %
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2009-2016 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -43,7 +45,8 @@ if size(varlist,1) == 0
     varlist = M_.endo_names(1:M_.orig_endo_nbr,:);
 end
 
-[i_var,nvar] = varlist_indices(varlist,M_.endo_names);
+[i_var,nvar,index_uniques] = varlist_indices(varlist,M_.endo_names);
+varlist=varlist(index_uniques,:);
 
 % number of variables
 endo_nbr = M_.endo_nbr;
@@ -56,9 +59,9 @@ parameter_set = options_.parameter_set;
 if isempty(parameter_set)
     if isfield(oo_,'posterior_mean')
         parameter_set = 'posterior_mean';
-    elseif isfield(oo_,'mle_mode') 
+    elseif isfield(oo_,'mle_mode')
         parameter_set = 'mle_mode';
-    elseif isfield(oo_,'posterior') 
+    elseif isfield(oo_,'posterior')
         parameter_set = 'posterior_mode';
     else
         error(['shock_decomposition: option parameter_set is not specified ' ...
@@ -68,10 +71,11 @@ end
 
 
 options_.selected_variables_only = 0; %make sure all variables are stored
-[oo,junk1,junk2,Smoothed_Variables_deviation_from_mean] = evaluate_smoother(parameter_set,varlist,M_,oo_,options_,bayestopt_,estim_params_);
+options_.plot_priors=0;
+[oo_, M_, junk1, junk2, Smoothed_Variables_deviation_from_mean] = evaluate_smoother(parameter_set, varlist, M_, oo_, options_, bayestopt_, estim_params_);
 
 % reduced form
-dr = oo.dr;
+dr = oo_.dr;
 
 % data reordering
 order_var = dr.order_var;
@@ -83,10 +87,10 @@ A = dr.ghx;
 B = dr.ghu;
 
 % initialization
-gend = size(oo.SmoothedShocks.(deblank(M_.exo_names(1,:))),1);
+gend = size(oo_.SmoothedShocks.(deblank(M_.exo_names(1,:))),1);
 epsilon=NaN(nshocks,gend);
 for i=1:nshocks
-    epsilon(i,:) = oo.SmoothedShocks.(deblank(M_.exo_names(i,:)));
+    epsilon(i,:) = oo_.SmoothedShocks.(deblank(M_.exo_names(i,:)));
 end
 
 z = zeros(endo_nbr,nshocks+2,gend);
@@ -94,7 +98,6 @@ z = zeros(endo_nbr,nshocks+2,gend);
 z(:,end,:) = Smoothed_Variables_deviation_from_mean;
 
 maximum_lag = M_.maximum_lag;
-lead_lag_incidence = M_.lead_lag_incidence;
 
 k2 = dr.kstate(find(dr.kstate(:,2) <= maximum_lag+1),[1 2]);
 i_state = order_var(k2(:,1))+(min(i,maximum_lag)+1-k2(:,2))*M_.endo_nbr;
@@ -102,7 +105,7 @@ for i=1:gend
     if i > 1 && i <= maximum_lag+1
         lags = min(i-1,maximum_lag):-1:1;
     end
-    
+
     if i > 1
         tempx = permute(z(:,1:nshocks,lags),[1 3 2]);
         m = min(i-1,maximum_lag);
@@ -111,34 +114,14 @@ for i=1:gend
         lags = lags+1;
     end
 
-    z(:,1:nshocks,i) = z(:,1:nshocks,i) + B(inv_order_var,:).*repmat(epsilon(:,i)',endo_nbr,1);
+    if i > options_.shock_decomp.init_state
+        z(:,1:nshocks,i) = z(:,1:nshocks,i) + B(inv_order_var,:).*repmat(epsilon(:,i)',endo_nbr,1);
+    end
     z(:,nshocks+1,i) = z(:,nshocks+2,i) - sum(z(:,1:nshocks,i),2);
 end
 
-
 oo_.shock_decomposition = z;
 
-if options_.use_shock_groups
-    shock_groups = M_.shock_groups.(options_.use_shock_groups);
-    shock_ind = fieldnames(shock_groups);
-    ngroups = length(shock_ind);
-    shock_names = shock_ind;
-    for i=1:ngroups,
-       shock_names{i} = (shock_groups.(shock_ind{i}).label);
-    end
-    zz = zeros(endo_nbr,ngroups+2,gend);
-    for i=1:ngroups
-        for j = shock_groups.(shock_ind{i}).shocks
-            k = find(strcmp(j,cellstr(M_.exo_names)));
-            zz(:,i,:) = zz(:,i,:) + z(:,k,:);
-        end
-    end
-    zz(:,ngroups+(1:2),:) = z(:,nshocks+(1:2),:);
-    z = zz;
-else
-    shock_names = M_.exo_names;
-end
-        
 if ~options_.no_graph.shock_decomposition
-    graph_decomp(z,shock_names,M_.endo_names,i_var,options_.initial_date,M_,options_)
+    plot_shock_decomposition(M_,oo_,options_,varlist);
 end
\ No newline at end of file
diff --git a/matlab/simulated_moment_uncertainty.m b/matlab/simulated_moment_uncertainty.m
index ad9860fcee303160bb5f1a3c3575dd5fde026c47..14ca704296b24ff0924a64075ae37fc9f459b7c2 100644
--- a/matlab/simulated_moment_uncertainty.m
+++ b/matlab/simulated_moment_uncertainty.m
@@ -11,8 +11,8 @@ function [cmm, mm] = simulated_moment_uncertainty(indx, periods, replic,options_
 % Outputs:
 %   - cmm:      [n_moments by n_moments] covariance matrix of simulated moments
 %   - mm:       [n_moments by replic] matrix of moments
-%  
-% Copyright (C) 2009-2016 Dynare Team
+%
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -67,7 +67,7 @@ if options_.logged_steady_state %if steady state was previously logged, undo thi
     options_.logged_steady_state=0;
     logged_steady_state_indicator=1;
     evalin('base','options_.logged_steady_state=0;')
-else 
+else
     logged_steady_state_indicator=0;
 end
 
@@ -80,23 +80,31 @@ end
 
 %set starting point of simulations
 if isempty(M_.endo_histval)
-    y0 = oo_.dr.ys;
+    if options_.loglinear
+        y0 = log(oo_.dr.ys);
+    else
+        y0 = oo_.dr.ys;
+    end
 else
-    y0 = M_.endo_histval;
+    if options_.loglinear
+        y0 = log_variable(1:M_.endo_nbr,M_.endo_histval,M_);
+    else
+        y0 = M_.endo_histval;
+    end
 end
 
 
-for j=1:replic;
+for j=1:replic
     [ys, oo_] = simult(y0,oo_.dr,M_,options_,oo_);%do simulation
     oo_=disp_moments(ys,char(options_.varobs),M_,options_,oo_); %get moments
     dum=[oo_.mean; dyn_vech(oo_.var)];
     sd = sqrt(diag(oo_.var));
-    for i=1:options_.ar;
+    for i=1:options_.ar
         dum=[dum; vec(oo_.autocorr{i}.*(sd*sd'))];
     end
     mm(:,j)=dum(indx);
     dyn_waitbar(j/replic,h,['Simulated moment uncertainty. Replic  ',int2str(j),'/',int2str(replic)])
-end;
+end
 dyn_waitbar_close(h);
 
 if logged_steady_state_indicator
diff --git a/matlab/simulated_moments_estimation.m b/matlab/simulated_moments_estimation.m
index 314122d835c145c75adb8d236dbf6469c130c40e..b01e5e9d3ad739e2b50056b8d6ed97150db359e1 100644
--- a/matlab/simulated_moments_estimation.m
+++ b/matlab/simulated_moments_estimation.m
@@ -2,19 +2,19 @@ function [param,sigma] = simulated_moments_estimation(dataset,options,parallel)
 % Performs estimation by Simulated Moments Method.
 %
 % INPUTS:
-%  xparam          [double]  p*1 vector of initial values for the estimated parameters. 
+%  xparam          [double]  p*1 vector of initial values for the estimated parameters.
 %  dataset         [      ]  Structure describing the data set.
 %  options         [      ]  Structure defining options for SMM.
-%  parallel        [      ]  Structure defining the parallel mode settings (optional). 
+%  parallel        [      ]  Structure defining the parallel mode settings (optional).
 %
-% OUTPUTS: 
+% OUTPUTS:
 %  param           [double]  p*1 vector of point estimates for the parameters.
 %  sigma           [double]  p*p covariance matrix of the SMM estimates.
 %
 % SPECIAL REQUIREMENTS
 %  The user has to provide a file where the moment conditions are defined.
 
-% Copyright (C) 2010-2012 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -87,7 +87,7 @@ options.estimated_parameters.upper_bound = [options.estimated_parameters.upper_b
 
 options.number_of_simulated_sample = 0;
 for i=1:length(parallel)
-    options.number_of_simulated_sample = options.number_of_simulated_sample + parallel(i).number_of_jobs*parallel(i).number_of_simulations; 
+    options.number_of_simulated_sample = options.number_of_simulated_sample + parallel(i).number_of_jobs*parallel(i).number_of_simulations;
 end
 
 options.observed_variables_idx = dataset.observed_variables_idx;
@@ -97,7 +97,7 @@ if nargin>2
     if ~isunix
         error('The parallel version of SMM estimation is not implemented for non unix platforms!')
     end
-    [junk,hostname] = unix('hostname --fqdn');    
+    [junk,hostname] = unix('hostname --fqdn');
     hostname = deblank(hostname);
     master_is_running_a_job = 0;
     for i=1:length(parallel)
@@ -204,7 +204,7 @@ end
 skipline()
 
 if options.optimization_routine==1
-    % Set options for csminwel. 
+    % Set options for csminwel.
     H0 = 1e-4*eye(options.estimated_parameters.nb);
     ct = 1e-4;
     it = 1000;
@@ -212,7 +212,7 @@ if options.optimization_routine==1
     % Minimization of the objective function.
     if nargin==2
         [fval,param,grad,hessian_csminwel,itct,fcount,retcodehat] = ...
-            csminwel1('smm_objective',xparam,H0,[],ct,it,2,options_.gradient_epsilon,sample_moments,weighting_matrix,options);    
+            csminwel1('smm_objective',xparam,H0,[],ct,it,2,options_.gradient_epsilon,sample_moments,weighting_matrix,options);
     elseif nargin>2
         [fval,param,grad,hessian_csminwel,itct,fcount,retcodehat] = ...
             csminwel1('smm_objective',xparam,H0,[],ct,it,2,options_.gradient_epsilon,sample_moments,weighting_matrix,options,parallel);
@@ -236,7 +236,7 @@ elseif options.optimization_routine==0% Compute the variance of the SMM estimato
     V = (1+1/options.number_of_simulated_sample)*G'*long_run_covariance*G;
     [param,diag(V)]
 elseif options.optimization_routine<0
-    T = -options.optimization_routine;% length of the simulated time series.            
+    T = -options.optimization_routine;% length of the simulated time series.
     time_series = extended_path(oo_.steady_state,T,1);
     save time_series.mat;
 end
@@ -248,7 +248,7 @@ fid = fopen(['job' int2str(slave_number) '.m'],'w');
 
 fprintf(fid,['% Generated by ' hostname '.\n\n']);
 
-if ( strcmpi(hostname,remotename) && (job_number>1) )  || ~strcmpi(hostname,remotename) 
+if ( strcmpi(hostname,remotename) && (job_number>1) )  || ~strcmpi(hostname,remotename)
     fprintf(fid,'load(''master_variables'');\n');
     fprintf(fid,'assignin(''base'',''M_'',M_);\n');
     fprintf(fid,'assignin(''base'',''oo_'',oo_);\n');
@@ -270,9 +270,9 @@ fprintf(fid,'M_.Sigma_e = diag(tmp);')
 
 fprintf(fid,['stream=RandStream(''mt19937ar'',''Seed'',' int2str(slave_number) ');\n']);
 if matlab_ver_less_than('7.12')
-      fprintf(fid,['RandStream.setDefaultStream(stream);\n\n']);
+    fprintf(fid,['RandStream.setDefaultStream(stream);\n\n']);
 else
-      fprintf(fid,['RandStream.setGlobalStream(stream);\n\n']);
+    fprintf(fid,['RandStream.setGlobalStream(stream);\n\n']);
 end
 
 fprintf(fid,['maxNumCompThreads(' int2str(threads_per_job) ');\n\n']);
@@ -282,7 +282,7 @@ fprintf(fid,['    time_series = extended_path([],' int2str(sample_size) ',1);\n'
 fprintf(fid,['    data = time_series([' int2str(observed_variables_idx) '],' int2str(burn_in_periods) '+1:' int2str(sample_size) ');\n']);
 fprintf(fid,['    eval(''tmp = ' moments_file_name '(data);'');\n']);
 fprintf(fid,['    simulated_moments = simulated_moments + tmp;\n']);
-fprintf(fid,['end;\n\n']);
+fprintf(fid,['end\n\n']);
 
 fprintf(fid,['simulated_moments = simulated_moments/' int2str(number_of_simulations) ';\n']);
 fprintf(fid,['save(''simulated_moments_slave_' int2str(slave_number) '.dat'',''simulated_moments'',''-ascii'');\n']);
@@ -295,7 +295,7 @@ else
     fprintf(fid,['unix(''rm simulated_moments_slave_' int2str(slave_number) '.dat'');\n']);
 end
 
-if ((job_number>1) && strcmpi(hostname,remotename)) || ~strcmpi(hostname,remotename) 
+if ((job_number>1) && strcmpi(hostname,remotename)) || ~strcmpi(hostname,remotename)
     fprintf(fid,'exit');
 end
 
diff --git a/matlab/simult_.m b/matlab/simult_.m
index 31daa3a6ccebe33068ead81daf6916721b87395b..381bfaf1be5b00737fcad22521bae9347cdc45c3 100644
--- a/matlab/simult_.m
+++ b/matlab/simult_.m
@@ -3,7 +3,7 @@ function y_=simult_(y0,dr,ex_,iorder)
 % decision rules.
 %
 % INPUTS
-%    y0       [double]   n*1 vector, initial value (n is the number of declared endogenous variables plus the number 
+%    y0       [double]   n*1 vector, initial value (n is the number of declared endogenous variables plus the number
 %                        of auxilliary variables for lags and leads); must be in declaration order, i.e. as in M_.endo_names
 %    dr       [struct]   matlab's structure where the reduced form solution of the model is stored.
 %    ex_      [double]   T*q matrix of innovations.
@@ -15,7 +15,7 @@ function y_=simult_(y0,dr,ex_,iorder)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2001-2015 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -77,15 +77,15 @@ else
             k2 = dr.state_var;
         else
             k2 = [];
-        end;
+        end
         order_var = 1:endo_nbr;
         dr.order_var = order_var;
     else
         k2 = dr.kstate(find(dr.kstate(:,2) <= M_.maximum_lag+1),[1 2]);
         k2 = k2(:,1)+(M_.maximum_lag+1-k2(:,2))*endo_nbr;
         order_var = dr.order_var;
-    end;
-    
+    end
+
     switch iorder
       case 1
         if isempty(dr.ghu)% For (linearized) deterministic models.
@@ -134,7 +134,7 @@ else
                 y_(dr.order_var,i) = constant + dr.ghx*yhat + dr.ghu*epsilon ...
                     + abcOut1 + abcOut2 + abcOut3;
             end
-         end
+        end
       case 3
         % only with pruning
         % the third moments of the shocks are assumed null. We don't have
@@ -176,7 +176,7 @@ else
             mexErrCheck('A_times_B_kronecker_C', err);
             [gy2u, err] = A_times_B_kronecker_C(ghxu,yhat2,u,threads);
             mexErrCheck('A_times_B_kronecker_C', err);
-            %construct terms of order 3, all based on first order component yhat1              
+            %construct terms of order 3, all based on first order component yhat1
             y2a = kron(yhat1,yhat1);
             [gyyy, err] = A_times_B_kronecker_C(ghxxx,y2a,yhat1,threads);
             mexErrCheck('A_times_B_kronecker_C', err);
@@ -199,6 +199,6 @@ else
             yhat1 = yhat1(ipred);
             yhat2 = yhat2(ipred);
             yhat3 = yhat3(ipred);
-        end   
+        end
     end
 end
diff --git a/matlab/simultxdet.m b/matlab/simultxdet.m
index 032f20588ceb4b2c0ee25af6716ff6ace802db74..21f0421e4535ba5b29f91cb50da80f45eae20106 100644
--- a/matlab/simultxdet.m
+++ b/matlab/simultxdet.m
@@ -22,7 +22,7 @@ function [y_,int_width,int_width_ME]=simultxdet(y0,ex,ex_det, iorder,var_list,M_
 % The condition size(ex,1)+M_.maximum_lag=size(ex_det,1) must be verified
 %  for consistency.
 
-% Copyright (C) 2008-2016 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -88,7 +88,7 @@ if iorder == 1
         for j=1:min(ykmin+M_.exo_det_length+1-i,M_.exo_det_length)
             y_(dr.order_var,i) = y_(dr.order_var,i) + dr.ghud{j}*(ex_det(i+j-1,:)'-exo_det_steady_state);
         end
-        
+
         k1 = k1+1;
     end
 elseif iorder == 2
@@ -153,7 +153,7 @@ end
 int_width = zeros(iter,nvar);
 for i=1:nvar
     int_width(:,i) = fact*sqrt(var_yf(:,i));
-        if nargout==3
+    if nargout==3
         int_width_ME(:,i) = -fact*sqrt(var_yf_ME(:,i));
-        end
+    end
 end
diff --git a/matlab/skipline.m b/matlab/skipline.m
index 5b311ab937d912f690dc50ede578e3855e6dda4b..f148997b8be74c08fbc8e1fb908ba68e356cd158 100644
--- a/matlab/skipline.m
+++ b/matlab/skipline.m
@@ -1,16 +1,16 @@
 function skipline(n, fid)
 % This function prints n newlines to fid
 %
-% INPUTS 
+% INPUTS
 %
 %   n        [integer]    Number of newlines to print
 %   fid      [integer]    file id returned by fopen
-%    
-% OUTPUTS 
+%
+% OUTPUTS
 %   None
 %
 
-% Copyright (C) 2013-2014 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -25,7 +25,7 @@ function skipline(n, fid)
 % 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/>.
 
 if nargin < 2
     fid = 1;
diff --git a/matlab/slice_sampler.m b/matlab/slice_sampler.m
index e454d59365da8030f5b871d5d8ee780c9e7628b4..8aa18fb1d4bf727d6bcd80d3b9e118ae6bbffb6d 100644
--- a/matlab/slice_sampler.m
+++ b/matlab/slice_sampler.m
@@ -1,123 +1,123 @@
-function [theta, fxsim, neval] = slice_sampler(objective_function,theta,thetaprior,sampler_options,varargin)
-% function [theta, fxsim, neval] = slice_sampler(objective_function,theta,thetaprior,sampler_options,varargin)
-% ----------------------------------------------------------
-% UNIVARIATE SLICE SAMPLER - stepping out (Neal, 2003)
-% W: optimal value in the range (3,10)*std(x)
-%    - see C.Planas and A.Rossi (2014)
-% objective_function(theta,varargin): -log of any unnormalized pdf 
-% with varargin (optional) a vector of auxiliaty parameters
-% to be passed to f( ).
-% ----------------------------------------------------------
-%
-% INPUTS
-%   objective_function:       objective function (expressed as minus the log of a density)
-%   theta:                    last value of theta
-%   thetaprior:               bounds of the theta space
-%   sampler_options:          posterior sampler options
-%   varargin:                 optional input arguments to objective function
-%
-% OUTPUTS
-%   theta:       new theta sample
-%   fxsim:       value of the objective function for the new sample
-%   neval:       number of function evaluations
-%
-% 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 sampler_options.rotated %&& ~isempty(sampler_options.V1),
-    [theta, fxsim, neval] = rotated_slice_sampler(objective_function,theta,thetaprior,sampler_options,varargin{:});
-    if isempty(sampler_options.mode), % jumping 
-       return,
-    else
-        nevalR=sum(neval);
-    end    
-end
-    
-theta=theta(:);
-npar = length(theta);
-W1 = sampler_options.W1;
-neval = zeros(npar,1);
-
-for it=1:npar,
-    neval(it) = 0;
-    W = W1(it); 
-    xold  = theta(it);
-   % XLB   = thetaprior(3);
-   % XUB   = thetaprior(4);
-    XLB   = thetaprior(it,1);
-    XUB   = thetaprior(it,2);
-   
-    
-    % -------------------------------------------------------
-    % 1. DRAW Z = ln[f(X0)] - EXP(1) where EXP(1)=-ln(U(0,1))
-    %    THIS DEFINES THE SLICE S={x: z < ln(f(x))}
-    % -------------------------------------------------------
-    fxold = -feval(objective_function,theta,varargin{:});
-    neval(it) = neval(it) + 1;
-    Z = fxold + log(rand(1,1));
-    % -------------------------------------------------------------
-    % 2. FIND I=(L,R) AROUND X0 THAT CONTAINS S AS MUCH AS POSSIBLE
-    %    STEPPING-OUT PROCEDURE
-    % -------------------------------------------------------------
-    u = rand(1,1);
-    L = max(XLB,xold-W*u);
-    R = min(XUB,L+W);
-    while(L > XLB)
-        xsim = L;
-        theta(it) = xsim;
-        fxl = -feval(objective_function,theta,varargin{:});
-        neval(it) = neval(it) + 1;
-        if (fxl <= Z)
-            break;
-        end
-        L = max(XLB,L-W);
-    end
-    while(R < XUB)
-        xsim = R;
-        theta(it) = xsim;
-        fxr = -feval(objective_function,theta,varargin{:});
-        neval(it) = neval(it) + 1;
-        if (fxr <= Z)
-            break;
-        end
-        R = min(XUB,R+W);
-    end
-    % ------------------------------------------------------
-    % 3. SAMPLING FROM THE SET A = (I INTERSECT S) = (LA,RA)
-    % ------------------------------------------------------
-    fxsim = Z-1;
-    while (fxsim < Z)
-        u = rand(1,1);
-        xsim = L + u*(R - L);
-        theta(it) = xsim;
-        fxsim = -feval(objective_function,theta,varargin{:});
-        neval(it) = neval(it) + 1;
-        if (xsim > xold)
-            R = xsim;
-        else
-            L = xsim;
-        end
-    end
-    
-end
-
-if sampler_options.rotated && ~isempty(sampler_options.mode), % jumping
-    neval=sum(neval)+nevalR;
-end
+function [theta, fxsim, neval] = slice_sampler(objective_function,theta,thetaprior,sampler_options,varargin)
+% function [theta, fxsim, neval] = slice_sampler(objective_function,theta,thetaprior,sampler_options,varargin)
+% ----------------------------------------------------------
+% UNIVARIATE SLICE SAMPLER - stepping out (Neal, 2003)
+% W: optimal value in the range (3,10)*std(x)
+%    - see C.Planas and A.Rossi (2014)
+% objective_function(theta,varargin): -log of any unnormalized pdf
+% with varargin (optional) a vector of auxiliaty parameters
+% to be passed to f( ).
+% ----------------------------------------------------------
+%
+% INPUTS
+%   objective_function:       objective function (expressed as minus the log of a density)
+%   theta:                    last value of theta
+%   thetaprior:               bounds of the theta space
+%   sampler_options:          posterior sampler options
+%   varargin:                 optional input arguments to objective function
+%
+% OUTPUTS
+%   theta:       new theta sample
+%   fxsim:       value of the objective function for the new sample
+%   neval:       number of function evaluations
+%
+% SPECIAL REQUIREMENTS
+%   none
+
+% Copyright (C) 2015-2017 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 sampler_options.rotated %&& ~isempty(sampler_options.V1),
+    [theta, fxsim, neval] = rotated_slice_sampler(objective_function,theta,thetaprior,sampler_options,varargin{:});
+    if isempty(sampler_options.mode) % jumping
+        return
+    else
+        nevalR=sum(neval);
+    end
+end
+
+theta=theta(:);
+npar = length(theta);
+W1 = sampler_options.W1;
+neval = zeros(npar,1);
+
+for it=1:npar
+    neval(it) = 0;
+    W = W1(it);
+    xold  = theta(it);
+    % XLB   = thetaprior(3);
+    % XUB   = thetaprior(4);
+    XLB   = thetaprior(it,1);
+    XUB   = thetaprior(it,2);
+
+
+    % -------------------------------------------------------
+    % 1. DRAW Z = ln[f(X0)] - EXP(1) where EXP(1)=-ln(U(0,1))
+    %    THIS DEFINES THE SLICE S={x: z < ln(f(x))}
+    % -------------------------------------------------------
+    fxold = -feval(objective_function,theta,varargin{:});
+    neval(it) = neval(it) + 1;
+    Z = fxold + log(rand(1,1));
+    % -------------------------------------------------------------
+    % 2. FIND I=(L,R) AROUND X0 THAT CONTAINS S AS MUCH AS POSSIBLE
+    %    STEPPING-OUT PROCEDURE
+    % -------------------------------------------------------------
+    u = rand(1,1);
+    L = max(XLB,xold-W*u);
+    R = min(XUB,L+W);
+    while(L > XLB)
+        xsim = L;
+        theta(it) = xsim;
+        fxl = -feval(objective_function,theta,varargin{:});
+        neval(it) = neval(it) + 1;
+        if (fxl <= Z)
+            break
+        end
+        L = max(XLB,L-W);
+    end
+    while(R < XUB)
+        xsim = R;
+        theta(it) = xsim;
+        fxr = -feval(objective_function,theta,varargin{:});
+        neval(it) = neval(it) + 1;
+        if (fxr <= Z)
+            break
+        end
+        R = min(XUB,R+W);
+    end
+    % ------------------------------------------------------
+    % 3. SAMPLING FROM THE SET A = (I INTERSECT S) = (LA,RA)
+    % ------------------------------------------------------
+    fxsim = Z-1;
+    while (fxsim < Z)
+        u = rand(1,1);
+        xsim = L + u*(R - L);
+        theta(it) = xsim;
+        fxsim = -feval(objective_function,theta,varargin{:});
+        neval(it) = neval(it) + 1;
+        if (xsim > xold)
+            R = xsim;
+        else
+            L = xsim;
+        end
+    end
+
+end
+
+if sampler_options.rotated && ~isempty(sampler_options.mode) % jumping
+    neval=sum(neval)+nevalR;
+end
diff --git a/matlab/smm_objective.m b/matlab/smm_objective.m
index 030cb98d9ee47f035d3a5431f79dbfe28994de90..fc6358205c484e169e557c6fd74e597e70e2015e 100644
--- a/matlab/smm_objective.m
+++ b/matlab/smm_objective.m
@@ -2,20 +2,20 @@ function [r,flag] = smm_objective(xparams,sample_moments,weighting_matrix,option
 % Evaluates the objective of the Simulated Moments Method.
 %
 % INPUTS:
-%  xparams          [double]  p*1 vector of estimated parameters. 
+%  xparams          [double]  p*1 vector of estimated parameters.
 %  sample_moments   [double]  n*1 vector of sample moments (n>=p).
 %  weighting_matrix [double]  n*n symetric, positive definite matrix.
 %  options          [      ]  Structure defining options for SMM.
 %  parallel         [      ]  Structure defining the parallel mode settings (optional).
 %
-% OUTPUTS: 
+% OUTPUTS:
 %  r                [double]  scalar, the value of the objective function.
 %  junk             [      ]  empty matrix.
 %
 % SPECIAL REQUIREMENTS
 %  The user has to provide a file where the moment conditions are defined.
 
-% Copyright (C) 2010-2013 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -30,7 +30,7 @@ function [r,flag] = smm_objective(xparams,sample_moments,weighting_matrix,option
 % 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/>.
 
 global M_ options_ oo_
 persistent mainStream mainState
@@ -67,8 +67,8 @@ end
 
 if penalty>0
     flag = 0;
-    r = priorObjectiveValue + penalty; 
-    return;
+    r = priorObjectiveValue + penalty;
+    return
 end
 
 save('estimated_parameters.mat','xparams');
@@ -114,7 +114,7 @@ else% parallel mode.
             end
         end
         for j=1:parallel(i).number_of_jobs
-            if (strcmpi(hostname,machine) && j>1) || ~strcmpi(hostname,machine)  
+            if (strcmpi(hostname,machine) && j>1) || ~strcmpi(hostname,machine)
                 job_number = job_number + 1;
                 unix(['ssh -A ' parallel(i).login '@' machine ' ./call_matlab_session.sh job' int2str(job_number) '.m &']);
             end
@@ -125,7 +125,7 @@ else% parallel mode.
     eval('job1;')
     tElapsedMasterJob = etime(clock, tStartMasterJob);
     TimeLimit = tElapsedMasterJob*1.2;
-    % Master waits for the  slaves' output... 
+    % Master waits for the  slaves' output...
     tStart = clock;
     tElapsed = 0;
     while tElapsed<TimeLimit
@@ -140,7 +140,7 @@ else% parallel mode.
             simulated_moments = load(['./intermediary_results_from_master_and_slaves/simulated_moments_slave_' int2str(i) '.dat'],'-ascii');
             tmp = tmp + simulated_moments;
         end
-        simulated_moments = tmp / job_number;        
+        simulated_moments = tmp / job_number;
     catch
         r = priorObjectiveValue*1.1;
         flag = 0;
diff --git a/matlab/smoother2histval.m b/matlab/smoother2histval.m
index 99b91a9bcb80d7193c252aaaeb4d4967889c5199..5d6a67f1df05a036e8b6ed27c283478d6c40f2e9 100644
--- a/matlab/smoother2histval.m
+++ b/matlab/smoother2histval.m
@@ -1,10 +1,10 @@
 function smoother2histval(opts)
 % This function takes values from oo_.SmoothedVariables (and possibly
 % oo_.SmoothedShocks) and copies them into M_.histval.
-% 
+%
 % Optional fields in 'opts' structure:
 %    infile:      An optional *_results MAT file created by Dynare.
-%                 If present, oo_.Smoothed{Variables,Shocks} are read from 
+%                 If present, oo_.Smoothed{Variables,Shocks} are read from
 %                 there. Otherwise, they are read from the global workspace.
 %    invars:      An optional char or cell array listing variables to read in
 %                 oo_.SmoothedVariables. If absent, all the endogenous
@@ -24,7 +24,7 @@ function smoother2histval(opts)
 %
 % The function also uses the value of option_.parameter_set
 
-% Copyright (C) 2014 Dynare Team
+% Copyright (C) 2014-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -64,10 +64,26 @@ end
 tmp = fieldnames(smoothedvars);
 if isstruct(getfield(smoothedvars, tmp{1}))
     post_metropolis = 1;
+    if ~ isstruct(getfield(smoothedvars, tmp{end}))
+        % point and metropolis results are simultaneously present
+        post_metropolis = 2;
+    end
+
+elseif isstruct(getfield(smoothedvars, tmp{end}))
+    % point and metropolis results are simultaneously present
+    post_metropolis = 2;
 else
     post_metropolis = 0;
 end
 
+if post_metropolis
+    tmp = fieldnames(smoothedvars.Mean);
+    tmpexo = fieldnames(smoothedshocks.Mean);
+else
+    tmp = fieldnames(smoothedvars);
+    tmpexo = fieldnames(smoothedshocks);
+end
+
 % If post-Metropolis, select the parameter set
 if isempty(options_.parameter_set)
     if post_metropolis
@@ -78,11 +94,11 @@ if isempty(options_.parameter_set)
 else
     switch options_.parameter_set
       case 'calibration'
-        if post_metropolis
+        if post_metropolis == 1
             error('Option parameter_set=calibration is not consistent with computed smoothed values.')
         end
       case 'posterior_mode'
-        if post_metropolis
+        if post_metropolis == 1
             error('Option parameter_set=posterior_mode is not consistent with computed smoothed values.')
         end
       case 'posterior_mean'
@@ -105,7 +121,6 @@ else
 end
 
 % Determine number of periods
-tmp = fieldnames(smoothedvars);
 n = size(getfield(smoothedvars, tmp{1}));
 
 if n < M_.maximum_endo_lag
@@ -118,7 +133,7 @@ if isfield(opts, 'invars')
         invars = cellstr(invars);
     end
 else
-    invars = [fieldnames(smoothedvars); fieldnames(smoothedshocks)];
+    invars = [tmp; tmpexo];
 end
 
 if isfield(opts, 'period')
diff --git a/matlab/solve1.m b/matlab/solve1.m
index 5d5241fced037bcf26ab6f9e6897432cac441ec7..5ea2651bfd869f154486f4edcf0dfcc3f0d91123 100644
--- a/matlab/solve1.m
+++ b/matlab/solve1.m
@@ -15,7 +15,7 @@ function [x,check] = solve1(func,x,j1,j2,jacobian_flag,gstep,tolf,tolx,maxit,deb
 %    maxit            maximum number of iterations
 %    debug            debug flag
 %    varargin:        list of extra arguments to the function
-%    
+%
 % OUTPUTS
 %    x:               results
 %    check=1:         the model can not be solved
@@ -23,7 +23,7 @@ function [x,check] = solve1(func,x,j1,j2,jacobian_flag,gstep,tolf,tolx,maxit,deb
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2001-2016 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -59,7 +59,7 @@ if ~isempty(i)
           'equation(s) resulted in a non-finite number:'])
     disp(j1(i)')
     check = 1;
-    return;
+    return
 end
 
 f = 0.5*(fvec'*fvec) ;
@@ -80,7 +80,7 @@ for its = 1:maxit
         fjac = fjac(j1,j2);
     else
         dh = max(abs(x(j2)),gstep(1)*ones(nn,1))*eps^(1/3);
-        
+
         for j = 1:nn
             xdh = x ;
             xdh(j2(j)) = xdh(j2(j))+dh(j) ;
@@ -114,7 +114,7 @@ for its = 1:maxit
         disp([its f])
         disp([xold x])
     end
-    
+
     if check > 0
         den = max([f;0.5*nn]) ;
         if max(abs(g).*max([abs(x(j2)') ones(1,nn)])')/den < tolmin
@@ -147,13 +147,3 @@ disp('SOLVE: maxit has been reached')
 % 04/13/01 MJ added test  f < tolf !!
 % 05/11/01 MJ changed tests for 'check' so as to remove 'continue' which is
 %             an instruction which appears only in version 6
-
-
-
-
-
-
-
-
-
-
diff --git a/matlab/solve_one_boundary.m b/matlab/solve_one_boundary.m
index 2ce90c7bc50367d4ffbb5cde6ad0821179602f17..a579ea67e2a03c826bf2cd777983d06522edb7d0 100644
--- a/matlab/solve_one_boundary.m
+++ b/matlab/solve_one_boundary.m
@@ -1,7 +1,7 @@
 function [y, info] = solve_one_boundary(fname, y, x, params, steady_state, ...
                                         y_index_eq, nze, periods, is_linear, Block_Num, y_kmin, maxit_, solve_tolf, lambda, cutoff, stack_solve_algo, forward_backward, is_dynamic, verbose, M, options, oo)
 % Computes the deterministic simulation of a block of equation containing
-% lead or lag variables 
+% lead or lag variables
 %
 % INPUTS
 %   fname               [string]        name of the file containing the block
@@ -26,7 +26,7 @@ function [y, info] = solve_one_boundary(fname, y, x, params, steady_state, ...
 %   cutoff              [double]        cutoff to correct the direction in Newton in case
 %                                       of singular jacobian matrix
 %   stack_solve_algo    [integer]       linear solver method used in the
-%                                       Newton algorithm : 
+%                                       Newton algorithm :
 %                                            - 1 sparse LU
 %                                            - 2 GMRES
 %                                            - 3 BicGStab
@@ -43,19 +43,19 @@ function [y, info] = solve_one_boundary(fname, y, x, params, steady_state, ...
 %   indirect_call      [integer]        (0) direct call to the fname
 %                                       (1) indirect call via the
 %                                       local_fname wrapper
-% OUTPUTS                                    
-%   y                  [matrix]         All endogenous variables of the model      
+% OUTPUTS
+%   y                  [matrix]         All endogenous variables of the model
 %   info               [integer]        >=0 no error
 %                                       <0 error
-%  
+%
 % ALGORITHM
 %   Newton with LU or GMRES or BicGstab for dynamic block
-%    
+%
 % SPECIAL REQUIREMENTS
 %   none.
-%  
+%
 
-% Copyright (C) 1996-2016 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -387,7 +387,7 @@ for it_=start:incr:finish
             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
diff --git a/matlab/solve_perfect_foresight_model.m b/matlab/solve_perfect_foresight_model.m
index 5de112ad8a6dd3d65ca8da7c93f94816aebef796..cedf3e0604f0419d58e95514ebd1085c5a2e93b1 100644
--- a/matlab/solve_perfect_foresight_model.m
+++ b/matlab/solve_perfect_foresight_model.m
@@ -1,6 +1,6 @@
 function [flag,endo_simul,err] = solve_perfect_foresight_model(endo_simul,exo_simul,pfm)
 
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -17,107 +17,107 @@ function [flag,endo_simul,err] = solve_perfect_foresight_model(endo_simul,exo_si
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-    flag = 0;
-    err = 0;
-    stop = 0;
-    nan_flag = 0;
+flag = 0;
+err = 0;
+stop = 0;
+nan_flag = 0;
 
-    model_dynamic = pfm.dynamic_model;
+model_dynamic = pfm.dynamic_model;
 
-    Y = endo_simul(:);
+Y = endo_simul(:);
 
-    if pfm.verbose
-        disp (['-----------------------------------------------------']) ;
-        disp (['MODEL SIMULATION :']) ;
-        fprintf('\n') ;
-    end
+if pfm.verbose
+    disp (['-----------------------------------------------------']) ;
+    disp (['MODEL SIMULATION :']) ;
+    fprintf('\n') ;
+end
 
-    if pfm.use_bytecode
-        [flag, endo_simul]=bytecode(Y, exo_simul, pfm.params);
-        return;
-    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);
+z = Y(find(pfm.lead_lag_incidence'));
+[d1,jacobian] = model_dynamic(z,exo_simul,pfm.params,pfm.steady_state,2);
 
-    % Initialization of the jacobian of the stacked model.
-    A = sparse([],[],[],pfm.periods*pfm.ny,pfm.periods*pfm.ny,pfm.periods*nnz(jacobian));
+% Initialization of the jacobian of the stacked model.
+A = sparse([],[],[],pfm.periods*pfm.ny,pfm.periods*pfm.ny,pfm.periods*nnz(jacobian));
 
-    % Initialization of the Newton residuals.
-    res = zeros(pfm.periods*pfm.ny,1);
+% Initialization of the Newton residuals.
+res = zeros(pfm.periods*pfm.ny,1);
 
-    h1 = clock;
-    
-    % Newton loop.
-    for iter = 1:pfm.maxit_
-        h2 = clock;
-        i_rows = 1:pfm.ny;
-        i_cols = find(pfm.lead_lag_incidence');
-        i_cols_A = i_cols;
-        % Fill the jacobian of the stacked model.
-        for it = 2:(pfm.periods+1)
-            [d1,jacobian] = model_dynamic(Y(i_cols),exo_simul,pfm.params,pfm.steady_state,it);
-            if it == 2
-                A(i_rows,pfm.i_cols_A1) = jacobian(:,pfm.i_cols_1);
-            elseif it == pfm.periods+1
-                A(i_rows,i_cols_A(pfm.i_cols_T)) = jacobian(:,pfm.i_cols_T);
-            else
-                A(i_rows,i_cols_A) = jacobian(:,pfm.i_cols_j);
-            end
-            res(i_rows) = d1;
-            i_rows = i_rows + pfm.ny;
-            i_cols = i_cols + pfm.ny;
-            if it > 2
-                i_cols_A = i_cols_A + pfm.ny;
-            end
-        end
-        % Stop if Newton residuals are zero.
-        err = max(abs(res)); 
-        if err < pfm.tolerance
-            stop = 1 ;
-            if pfm.verbose
-                fprintf('\n') ;
-                disp([' Total time of simulation        :' num2str(etime(clock,h1))]) ;
-                fprintf('\n') ;
-                disp([' Convergency obtained.']) ;
-                fprintf('\n') ;
-            end
-            flag = 0;% Convergency obtained.
-            endo_simul = reshape(Y,pfm.ny,pfm.periods+2);
-            break
+h1 = clock;
+
+% Newton loop.
+for iter = 1:pfm.maxit_
+    h2 = clock;
+    i_rows = 1:pfm.ny;
+    i_cols = find(pfm.lead_lag_incidence');
+    i_cols_A = i_cols;
+    % Fill the jacobian of the stacked model.
+    for it = 2:(pfm.periods+1)
+        [d1,jacobian] = model_dynamic(Y(i_cols),exo_simul,pfm.params,pfm.steady_state,it);
+        if it == 2
+            A(i_rows,pfm.i_cols_A1) = jacobian(:,pfm.i_cols_1);
+        elseif it == pfm.periods+1
+            A(i_rows,i_cols_A(pfm.i_cols_T)) = jacobian(:,pfm.i_cols_T);
+        else
+            A(i_rows,i_cols_A) = jacobian(:,pfm.i_cols_j);
         end
-        % Compute the Newton step. 
-        dy = -A\res;
-        if any(isnan(dy))
-            nan_flag = 1;
-            break
+        res(i_rows) = d1;
+        i_rows = i_rows + pfm.ny;
+        i_cols = i_cols + pfm.ny;
+        if it > 2
+            i_cols_A = i_cols_A + pfm.ny;
         end
-        % Update the endogenous variables paths.
-        Y(pfm.i_upd) =   Y(pfm.i_upd) + dy;
     end
-
-    if ~stop
+    % Stop if Newton residuals are zero.
+    err = max(abs(res));
+    if err < pfm.tolerance
+        stop = 1 ;
         if pfm.verbose
             fprintf('\n') ;
-            disp(['     Total time of simulation        :' num2str(etime(clock,h1))]) ;
+            disp([' Total time of simulation        :' num2str(etime(clock,h1))]) ;
             fprintf('\n') ;
-            disp(['WARNING : maximum number of iterations is reached (modify options_.simul.maxit).']) ;
+            disp([' Convergency obtained.']) ;
             fprintf('\n') ;
         end
-        flag = 1;% more iterations are needed.
-        endo_simul = 1;
+        flag = 0;% Convergency obtained.
+        endo_simul = reshape(Y,pfm.ny,pfm.periods+2);
+        break
     end
-    if nan_flag
-        if pfm.verbose
-            fprintf('\n') ;
-            disp(['     Total time of simulation        :' num2str(etime(clock,h1))]) ;
-            fprintf('\n') ;
-            disp(['WARNING : NaNs!']) ;
-            fprintf('\n') ;
-        end
-        flag = 1;
-        endo_simul = 1;
+    % Compute the Newton step.
+    dy = -A\res;
+    if any(isnan(dy))
+        nan_flag = 1;
+        break
     end
+    % Update the endogenous variables paths.
+    Y(pfm.i_upd) =   Y(pfm.i_upd) + dy;
+end
+
+if ~stop
     if pfm.verbose
-        disp (['-----------------------------------------------------']) ;
-    end
\ No newline at end of file
+        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') ;
+    end
+    flag = 1;% more iterations are needed.
+    endo_simul = 1;
+end
+if nan_flag
+    if pfm.verbose
+        fprintf('\n') ;
+        disp(['     Total time of simulation        :' num2str(etime(clock,h1))]) ;
+        fprintf('\n') ;
+        disp(['WARNING : NaNs!']) ;
+        fprintf('\n') ;
+    end
+    flag = 1;
+    endo_simul = 1;
+end
+if pfm.verbose
+    disp (['-----------------------------------------------------']) ;
+end
\ No newline at end of file
diff --git a/matlab/solve_two_boundaries.m b/matlab/solve_two_boundaries.m
index 136d3e1acba8dc6b0205c44eb7152bb53751a481..4b5904946556a6dc71915bf2cb6b3e6b2ad07875 100644
--- a/matlab/solve_two_boundaries.m
+++ b/matlab/solve_two_boundaries.m
@@ -1,6 +1,6 @@
 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 
+% both lead and lag variables using relaxation methods
 %
 % INPUTS
 %   fname               [string]        name of the file containing the block
@@ -27,7 +27,7 @@ function [y, oo]= solve_two_boundaries(fname, y, x, params, steady_state, y_inde
 %   cutoff              [double]        cutoff to correct the direction in Newton in case
 %                                       of singular jacobian matrix
 %   stack_solve_algo    [integer]       linear solver method used in the
-%                                       Newton algorithm : 
+%                                       Newton algorithm :
 %                                            - 1 sprse LU
 %                                            - 2 GMRES
 %                                            - 3 BicGStab
@@ -36,17 +36,17 @@ function [y, oo]= solve_two_boundaries(fname, y, x, params, steady_state, y_inde
 %   oo                  [structure]     Results
 %
 % OUTPUTS
-%   y                   [matrix]        All endogenous variables of the model      
+%   y                   [matrix]        All endogenous variables of the model
 %   oo                  [structure]     Results
 %
 % ALGORITHM
 %   Newton with LU or GMRES or BicGstab
-%    
+%
 % SPECIAL REQUIREMENTS
 %   none.
-%  
+%
 
-% Copyright (C) 1996-2016 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -92,7 +92,7 @@ while ~(cvg==1 || iter>maxit_)
     [max_res, max_indx]=max(max(abs(r')));
     if ~isreal(r)
         max_res = (-max_res^2)^0.5;
-    end;
+    end
     if ~isreal(max_res) || isnan(max_res)
         cvg = 0;
     elseif(is_linear && iter>0)
@@ -123,7 +123,7 @@ while ~(cvg==1 || iter>maxit_)
                             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;
+                            continue
                         else
                             disp('The singularity of the jacobian matrix could not be corrected');
                             return
@@ -178,7 +178,7 @@ while ~(cvg==1 || iter>maxit_)
                 B1_inv = inv(g1a(Elem, Elem));
                 if (t < periods)
                     S1 = B1_inv * g1a(Elem, Elem_1);
-                end;
+                end
                 g1a(Elem, Elem_1) = S1;
                 b(Elem) = B1_inv * b(Elem);
                 g1a(Elem, Elem) = ones(Blck_size, Blck_size);
diff --git a/matlab/steady.m b/matlab/steady.m
index 760fb1d3f5f9aee4d51f3efcbcbf02a1ed9ede52..3e0ec0095aa0fab1df03b431de9b4e5d97aff08c 100644
--- a/matlab/steady.m
+++ b/matlab/steady.m
@@ -1,17 +1,17 @@
 function steady()
 % function steady()
 % computes and prints the steady state calculations
-%  
+%
 % INPUTS
 %   none
-%  
+%
 % OUTPUTS
 %   none
 %
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2001-2012 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -28,7 +28,7 @@ function steady()
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-global M_ oo_ options_ ys0_ 
+global M_ oo_ options_ ys0_
 
 test_for_deep_parameters_calibration(M_);
 
@@ -70,14 +70,14 @@ if info(1)
         disp(sprintf('%12s %12.6f',M_.exo_det_names(hv(ixd(i),2),:), ...
                      oo_.exo_det_steady_state(hv(ixd(i),2))))
     end
-    
+
     if options_.homotopy_force_continue
         disp('Option homotopy_continue is set, so I continue ...')
     else
         error('Homotopy step failed')
     end
 end
-    
+
 [steady_state,M_.params,info] = steady_(M_,options_,oo_);
 oo_.steady_state = steady_state;
 
@@ -99,7 +99,7 @@ else
         fprintf('\nThe steady state computation failed. It terminated with the following values:\n')
         for i=1:M_.orig_endo_nbr
             fprintf('%s \t\t %g\n',M_.endo_names(i,:),steady_state(i));
-        end        
+        end
     end
     print_info(info,options_.noprint, options_);
 end
diff --git a/matlab/steady_.m b/matlab/steady_.m
index 02c7c69ed8e7464cc2c7aa2f2e5d98168f45a9b6..46c0e34114ba3c444d9524efdb4d7c5ddab6a7ee 100644
--- a/matlab/steady_.m
+++ b/matlab/steady_.m
@@ -1,12 +1,12 @@
 function [steady_state,params,info] = steady_(M_,options_,oo_)
 % function [steady_state,params,info] = steady_(M_,options_,oo_)
-% Computes the steady state 
-%  
+% Computes the steady state
+%
 % INPUTS
 %   M                         struct           model structure
 %   options                   struct           options
 %   oo                        struct           output results
-%  
+%
 % OUTPUTS
 %   steady_state              vector           steady state
 %   params                    vector           parameters (may have been
@@ -18,7 +18,7 @@ function [steady_state,params,info] = steady_(M_,options_,oo_)
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2001-2016 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/step_length_correction.m b/matlab/step_length_correction.m
index 8950bc7649d387190c47bddc703e1ebc76f09e18..89710637be0dd3e1e44168650c297edfe2e52482 100644
--- a/matlab/step_length_correction.m
+++ b/matlab/step_length_correction.m
@@ -1,6 +1,6 @@
 function c = step_length_correction(x,scale,i)
 
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -17,8 +17,8 @@ function c = step_length_correction(x,scale,i)
 % 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(scale)
-        c = 10^round(log10(abs(x)));
-    else
-        c = scale(i);
-    end
+if isempty(scale)
+    c = 10^round(log10(abs(x)));
+else
+    c = scale(i);
+end
diff --git a/matlab/stoch_simul.m b/matlab/stoch_simul.m
index d08887ab855b2c8932ef0640b3de933d72723bc3..81f8b886aef2107666ac46453ae6ef61e1516b86 100644
--- a/matlab/stoch_simul.m
+++ b/matlab/stoch_simul.m
@@ -1,6 +1,6 @@
 function info=stoch_simul(var_list)
 
-% Copyright (C) 2001-2016 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -56,7 +56,8 @@ if size(var_list,1) == 0
     var_list = M_.endo_names(1:M_.orig_endo_nbr, :);
 end
 
-[i_var,nvar] = varlist_indices(var_list,M_.endo_names);
+[i_var,nvar,index_uniques] = varlist_indices(var_list,M_.endo_names);
+var_list=var_list(index_uniques,:);
 
 iter_ = max(options_.periods,1);
 if M_.exo_nbr > 0
@@ -83,7 +84,7 @@ else
     [oo_.dr,info,M_,options_,oo_] = resol(0,M_,options_,oo_);
 end
 
-if options_.loglinear && isfield(oo_.dr,'ys') && options_.logged_steady_state==0 %log steady state for correct display of decision rule    
+if options_.loglinear && isfield(oo_.dr,'ys') && options_.logged_steady_state==0 %log steady state for correct display of decision rule
     oo_.dr.ys=log_variable(1:M_.endo_nbr,oo_.dr.ys,M_);
     oo_.steady_state=log_variable(1:M_.endo_nbr,oo_.steady_state,M_);
     options_old.logged_steady_state = 1; %make sure option is preserved outside of stoch_simul
@@ -150,12 +151,16 @@ if options_.periods > 0 && ~PI_PCL_solver
     if isempty(M_.endo_histval)
         y0 = oo_.dr.ys;
     else
-        y0 = M_.endo_histval;
+        if options_.loglinear
+            y0 = log_variable(1:M_.endo_nbr,M_.endo_histval,M_);
+        else
+            y0 = M_.endo_histval;
+        end
     end
     [ys, oo_] = simult(y0,oo_.dr,M_,options_,oo_);
     oo_.endo_simul = ys;
     if ~options_.minimal_workspace
-      dyn2vec;
+        dyn2vec;
     end
 end
 
@@ -196,7 +201,7 @@ if options_.irf
             else
                 if options_.order>1 && options_.relative_irf % normalize shock to 0.01 before IRF generation for GIRFs; multiply with 100 later
                     y=irf(oo_.dr,cs(M_.exo_names_orig_ord,i)./cs(i,i)/100, options_.irf, options_.drop, ...
-                          options_.replic, options_.order);                
+                          options_.replic, options_.order);
                 else %for linear model, rescaling is done later
                     y=irf(oo_.dr,cs(M_.exo_names_orig_ord,i), options_.irf, options_.drop, ...
                           options_.replic, options_.order);
@@ -249,10 +254,10 @@ if options_.irf
                 if nbplt == 0
                 elseif nbplt == 1
                     if options_.relative_irf
-                        hh = dyn_figure(options_,'Name',['Relative response to' ...
+                        hh = dyn_figure(options_.nodisplay,'Name',['Relative response to' ...
                                             ' orthogonalized shock to ' tit(i,:)]);
                     else
-                        hh = dyn_figure(options_,'Name',['Orthogonalized shock to' ...
+                        hh = dyn_figure(options_.nodisplay,'Name',['Orthogonalized shock to' ...
                                             ' ' tit(i,:)]);
                     end
                     for j = 1:number_of_plots_to_draw
@@ -265,7 +270,7 @@ if options_.irf
                         remove_fractional_xticks;
                         title(deblank(mylist(j,:)),'Interpreter','none');
                     end
-                    dyn_saveas(hh,[M_.fname '_IRF_' deblank(tit(i,:))],options_);
+                    dyn_saveas(hh,[M_.fname '_IRF_' deblank(tit(i,:))],options_.nodisplay,options_.graph_format);
                     if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                         fprintf(fidTeX,'\\begin{figure}[H]\n');
                         for j = 1:number_of_plots_to_draw
@@ -281,10 +286,10 @@ if options_.irf
                 else
                     for fig = 1:nbplt-1
                         if options_.relative_irf
-                            hh = dyn_figure(options_,'Name',['Relative response to orthogonalized shock' ...
+                            hh = dyn_figure(options_.nodisplay,'Name',['Relative response to orthogonalized shock' ...
                                                 ' to ' tit(i,:) ' figure ' int2str(fig)]);
                         else
-                            hh = dyn_figure(options_,'Name',['Orthogonalized shock to ' tit(i,:) ...
+                            hh = dyn_figure(options_.nodisplay,'Name',['Orthogonalized shock to ' tit(i,:) ...
                                                 ' figure ' int2str(fig)]);
                         end
                         for plt = 1:nstar
@@ -297,7 +302,7 @@ if options_.irf
                             remove_fractional_xticks
                             title(deblank(mylist((fig-1)*nstar+plt,:)),'Interpreter','none');
                         end
-                        dyn_saveas(hh,[ M_.fname '_IRF_' deblank(tit(i,:)) int2str(fig)],options_);
+                        dyn_saveas(hh,[ M_.fname '_IRF_' deblank(tit(i,:)) int2str(fig)],options_.nodisplay,options_.graph_format);
                         if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                             fprintf(fidTeX,'\\begin{figure}[H]\n');
                             for j = 1:nstar
@@ -317,9 +322,9 @@ if options_.irf
                             fprintf(fidTeX,' \n');
                         end
                     end
-                    hh = dyn_figure(options_,'Name',['Orthogonalized shock to ' tit(i,:) ' figure ' int2str(nbplt) '.']);
+                    hh = dyn_figure(options_.nodisplay,'Name',['Orthogonalized shock to ' tit(i,:) ' figure ' int2str(nbplt) '.']);
                     m = 0;
-                    for plt = 1:number_of_plots_to_draw-(nbplt-1)*nstar;
+                    for plt = 1:number_of_plots_to_draw-(nbplt-1)*nstar
                         m = m+1;
                         subplot(lr,lc,m);
                         plot(1:options_.irf,transpose(irfs((nbplt-1)*nstar+plt,:)),'-k','linewidth',1);
@@ -330,7 +335,7 @@ if options_.irf
                         remove_fractional_xticks
                         title(deblank(mylist((nbplt-1)*nstar+plt,:)),'Interpreter','none');
                     end
-                    dyn_saveas(hh,[ M_.fname '_IRF_' deblank(tit(i,:)) int2str(nbplt) ],options_);
+                    dyn_saveas(hh,[ M_.fname '_IRF_' deblank(tit(i,:)) int2str(nbplt) ],options_.nodisplay,options_.graph_format);
                     if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                         fprintf(fidTeX,'\\begin{figure}[H]\n');
                         for j = 1:m
diff --git a/matlab/stochastic_solvers.m b/matlab/stochastic_solvers.m
index 2772001431a50c4d80355e68d64d28d47ecfd573..a51648a43914d1fb6870858dff9011393254c239 100644
--- a/matlab/stochastic_solvers.m
+++ b/matlab/stochastic_solvers.m
@@ -1,35 +1,35 @@
 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 expectations model (first, second or third 
-% 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.
 %   task       [integer]          if task = 0 then dr1 computes decision rules.
 %                                 if task = 1 then dr1 computes eigenvalues.
-%   M_         [matlab structure] Definition of the model.           
+%   M_         [matlab structure] Definition of the model.
 %   options_   [matlab structure] Global options.
-%   oo_        [matlab structure] Results 
-%    
+%   oo_        [matlab structure] Results
+%
 % OUTPUTS
 %   dr         [matlab structure] Decision rules for stochastic simulations.
 %   info       [integer]          info=1: the model doesn't define current variables uniquely
-%                                 info=2: problem in mjdgges.dll info(2) contains error code. 
+%                                 info=2: problem in mjdgges.dll info(2) contains error code.
 %                                 info=3: BK order condition not satisfied info(2) contains "distance"
 %                                         absence of stable trajectory.
 %                                 info=4: BK order condition not satisfied info(2) contains "distance"
 %                                         indeterminacy.
 %                                 info=5: BK rank condition not satisfied.
-%                                 info=6: The jacobian matrix evaluated at the steady state is complex.        
-%                                 info=9: k_order_pert was unable to compute the solution    
+%                                 info=6: The jacobian matrix evaluated at the steady state is complex.
+%                                 info=9: k_order_pert was unable to compute the solution
 % ALGORITHM
 %   ...
-%    
+%
 % SPECIAL REQUIREMENTS
 %   none.
-%  
+%
 
-% Copyright (C) 1996-2016 Dynare Team
+% Copyright (C) 1996-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -52,17 +52,23 @@ if options_.linear
     options_.order = 1;
 end
 
-if (options_.aim_solver == 1) && (options_.order > 1)
-        error('Option "aim_solver" is incompatible with order >= 2')
+local_order = options_.order;
+if M_.hessian_eq_zero && local_order~=1
+    local_order = 1;
+    warning('stochastic_solvers: using order = 1 because Hessian is equal to zero');
 end
 
-if M_.maximum_endo_lag == 0 
-    if options_.order >= 2
-    fprintf('\nSTOCHASTIC_SOLVER: Dynare does not solve purely forward models at higher order.\n')
-    fprintf('STOCHASTIC_SOLVER: To circumvent this restriction, you can add a backward-looking dummy equation of the form:\n')
-    fprintf('STOCHASTIC_SOLVER: junk=0.9*junk(-1);\n')
-    error(['2nd and 3rd order approximation not implemented for purely ' ...
-           'forward models'])
+if (options_.aim_solver == 1) && (local_order > 1)
+    error('Option "aim_solver" is incompatible with order >= 2')
+end
+
+if M_.maximum_endo_lag == 0
+    if local_order >= 2
+        fprintf('\nSTOCHASTIC_SOLVER: Dynare does not solve purely forward models at higher order.\n')
+        fprintf('STOCHASTIC_SOLVER: To circumvent this restriction, you can add a backward-looking dummy equation of the form:\n')
+        fprintf('STOCHASTIC_SOLVER: junk=0.9*junk(-1);\n')
+        error(['2nd and 3rd order approximation not implemented for purely ' ...
+               'forward models'])
     end
     if M_.exo_det_nbr~=0
         fprintf('\nSTOCHASTIC_SOLVER: Dynare does not solve purely forward models with var_exo_det.\n')
@@ -79,15 +85,18 @@ if M_.maximum_endo_lead==0 && M_.exo_det_nbr~=0
     error(['var_exo_det not implemented for purely backwards models'])
 end
 
-if options_.k_order_solver;
+if options_.k_order_solver
     if options_.risky_steadystate
         [dr,info] = dyn_risky_steadystate_solver(oo_.steady_state,M_,dr, ...
-                                             options_,oo_);
+                                                 options_,oo_);
     else
+        orig_order = options_.order;
+        options_.order = local_order;
         dr = set_state_space(dr,M_,options_);
         [dr,info] = k_order_pert(dr,M_,options_);
+        options_.order = orig_order;
     end
-    return;
+    return
 end
 
 klen = M_.maximum_lag + M_.maximum_lead + 1;
@@ -103,25 +112,25 @@ end
 
 it_ = M_.maximum_lag + 1;
 z = repmat(dr.ys,1,klen);
-if options_.order == 1
+if local_order == 1
     if (options_.bytecode)
         [chck, junk, loc_dr] = bytecode('dynamic','evaluate', z,exo_simul, ...
                                         M_.params, dr.ys, 1);
         jacobia_ = [loc_dr.g1 loc_dr.g1_x loc_dr.g1_xd];
     else
         [junk,jacobia_] = feval([M_.fname '_dynamic'],z(iyr0),exo_simul, ...
-                            M_.params, dr.ys, it_);
-    end;
-elseif options_.order == 2
+                                M_.params, dr.ys, it_);
+    end
+elseif local_order == 2
     if (options_.bytecode)
         [chck, junk, loc_dr] = bytecode('dynamic','evaluate', z,exo_simul, ...
-                            M_.params, dr.ys, 1);
+                                        M_.params, dr.ys, 1);
         jacobia_ = [loc_dr.g1 loc_dr.g1_x];
     else
         [junk,jacobia_,hessian1] = feval([M_.fname '_dynamic'],z(iyr0),...
                                          exo_simul, ...
                                          M_.params, dr.ys, it_);
-    end;
+    end
     if options_.use_dll
         % In USE_DLL mode, the hessian is in the 3-column sparse representation
         hessian1 = sparse(hessian1(:,1), hessian1(:,2), hessian1(:,3), ...
@@ -129,10 +138,10 @@ elseif options_.order == 2
     end
     [infrow,infcol]=find(isinf(hessian1));
     if options_.debug
-        if ~isempty(infrow)     
-        fprintf('\nSTOCHASTIC_SOLVER: The Hessian of the dynamic model contains Inf.\n')
-        fprintf('STOCHASTIC_SOLVER: Try running model_diagnostics to find the source of the problem.\n')
-        save([M_.fname '_debug.mat'],'hessian1')
+        if ~isempty(infrow)
+            fprintf('\nSTOCHASTIC_SOLVER: The Hessian of the dynamic model contains Inf.\n')
+            fprintf('STOCHASTIC_SOLVER: Try running model_diagnostics to find the source of the problem.\n')
+            save([M_.fname '_debug.mat'],'hessian1')
         end
     end
     if ~isempty(infrow)
@@ -141,7 +150,7 @@ elseif options_.order == 2
     end
     [nanrow,nancol]=find(isnan(hessian1));
     if options_.debug
-        if ~isempty(nanrow)     
+        if ~isempty(nanrow)
             fprintf('\nSTOCHASTIC_SOLVER: The Hessian of the dynamic model contains NaN.\n')
             fprintf('STOCHASTIC_SOLVER: Try running model_diagnostics to find the source of the problem.\n')
             save([M_.fname '_debug.mat'],'hessian1')
@@ -150,16 +159,16 @@ elseif options_.order == 2
     if ~isempty(nanrow)
         info(1)=12;
         return
-    end    
+    end
 end
 
 [infrow,infcol]=find(isinf(jacobia_));
-    
+
 if options_.debug
-    if ~isempty(infrow)     
-    fprintf('\nSTOCHASTIC_SOLVER: The Jacobian of the dynamic model contains Inf. The problem is associated with:\n\n')    
-    display_problematic_vars_Jacobian(infrow,infcol,M_,dr.ys,'dynamic','STOCHASTIC_SOLVER: ')
-    save([M_.fname '_debug.mat'],'jacobia_')
+    if ~isempty(infrow)
+        fprintf('\nSTOCHASTIC_SOLVER: The Jacobian of the dynamic model contains Inf. The problem is associated with:\n\n')
+        display_problematic_vars_Jacobian(infrow,infcol,M_,dr.ys,'dynamic','STOCHASTIC_SOLVER: ')
+        save([M_.fname '_debug.mat'],'jacobia_')
     end
 end
 
@@ -185,18 +194,18 @@ end
 
 [nanrow,nancol]=find(isnan(jacobia_));
 if options_.debug
-    if ~isempty(nanrow)     
-    fprintf('\nSTOCHASTIC_SOLVER: The Jacobian of the dynamic model contains NaN. The problem is associated with:\n\n')    
-    display_problematic_vars_Jacobian(nanrow,nancol,M_,dr.ys,'dynamic','STOCHASTIC_SOLVER: ')
-    save([M_.fname '_debug.mat'],'jacobia_')
+    if ~isempty(nanrow)
+        fprintf('\nSTOCHASTIC_SOLVER: The Jacobian of the dynamic model contains NaN. The problem is associated with:\n\n')
+        display_problematic_vars_Jacobian(nanrow,nancol,M_,dr.ys,'dynamic','STOCHASTIC_SOLVER: ')
+        save([M_.fname '_debug.mat'],'jacobia_')
     end
 end
 
 if ~isempty(nanrow)
-   info(1) = 8;
-   NaN_params=find(isnan(M_.params));
-   info(2:length(NaN_params)+1) =  NaN_params;
-   return
+    info(1) = 8;
+    NaN_params=find(isnan(M_.params));
+    info(2:length(NaN_params)+1) =  NaN_params;
+    return
 end
 
 kstate = dr.kstate;
@@ -218,11 +227,11 @@ b(:,cols_b) = jacobia_(:,cols_j);
 
 if M_.maximum_endo_lead == 0
     % backward models: simplified code exist only at order == 1
-    if options_.order == 1
+    if local_order == 1
         [k1,junk,k2] = find(kstate(:,4));
-        dr.ghx(:,k1) = -b\jacobia_(:,k2); 
+        dr.ghx(:,k1) = -b\jacobia_(:,k2);
         if M_.exo_nbr
-            dr.ghu =  -b\jacobia_(:,nz+1:end); 
+            dr.ghu =  -b\jacobia_(:,nz+1:end);
         end
         dr.eigval = eig(kalman_transition_matrix(dr,nstatic+(1:nspred),1:nspred,M_.exo_nbr));
         dr.full_rank = 1;
@@ -241,8 +250,11 @@ if M_.maximum_endo_lead == 0
                'backward models'])
     end
 elseif options_.risky_steadystate
+    orig_order = options_.order;
+    options_.order = local_order;
     [dr,info] = dyn_risky_steadystate_solver(oo_.steady_state,M_,dr, ...
                                              options_,oo_);
+    options_.order = orig_order;
 else
     % If required, use AIM solver if not check only
     if (options_.aim_solver == 1) && (task == 0)
@@ -251,16 +263,16 @@ else
     else  % use original Dynare solver
         [dr,info] = dyn_first_order_solver(jacobia_,M_,dr,options_,task);
         if info(1) || task
-            return;
+            return
         end
     end
 
-    if options_.order > 1
+    if local_order > 1
         % Second order
         dr = dyn_second_order_solver(jacobia_,hessian1,dr,M_,...
                                      options_.threads.kronecker.A_times_B_kronecker_C,...
                                      options_.threads.kronecker.sparse_hessian_times_B_kronecker_C);
-                                 
+
         % reordering second order derivatives, used for deterministic
         % variables below
         k1 = nonzeros(M_.lead_lag_incidence(:,order_var)');
@@ -287,14 +299,14 @@ if M_.exo_det_nbr > 0
         dr.ghud{i} = -M2*dr.ghud{i-1}(end-nsfwrd+1:end,:);
     end
 
-    if options_.order > 1
+    if local_order > 1
         lead_lag_incidence = M_.lead_lag_incidence;
         k0 = find(lead_lag_incidence(M_.maximum_endo_lag+1,order_var)');
         k1 = find(lead_lag_incidence(M_.maximum_endo_lag+2,order_var)');
         hu = dr.ghu(nstatic+[1:nspred],:);
         hud = dr.ghud{1}(nstatic+1:nstatic+nspred,:);
         zx = [eye(nspred);dr.ghx(k0,:);gx*dr.Gy;zeros(M_.exo_nbr+M_.exo_det_nbr, ...
-                                               nspred)];
+                                                      nspred)];
         zu = [zeros(nspred,M_.exo_nbr); dr.ghu(k0,:); gx*hu; zeros(M_.exo_nbr+M_.exo_det_nbr, ...
                                                           M_.exo_nbr)];
         zud=[zeros(nspred,M_.exo_det_nbr);dr.ghud{1};gx(:,1:nspred)*hud;zeros(M_.exo_nbr,M_.exo_det_nbr);eye(M_.exo_det_nbr)];
@@ -364,9 +376,8 @@ if options_.loglinear
         dr.ghx(il,iklag) = dr.ghx(il,iklag).*repmat(dr.ys(klag1)', ...
                                                     length(il),1);
     end
-    if options_.order>1
-       error('Loglinear options currently only works at order 1')
+    if local_order > 1
+        error('Loglinear options currently only works at order 1')
     end
 end
 end
-
diff --git a/matlab/store_smoother_results.m b/matlab/store_smoother_results.m
index 61af7b6a6ee83bd6f51f776d0ab16fd86261aa5e..5ef6e15099f3bd93808fc80db8f9bb3c1948ebc1 100644
--- a/matlab/store_smoother_results.m
+++ b/matlab/store_smoother_results.m
@@ -1,7 +1,7 @@
 function [oo_, yf]=store_smoother_results(M_,oo_,options_,bayestopt_,dataset_,dataset_info,atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,P,PK,decomp,Trend,state_uncertainty)
 % oo_=store_smoother_results(M_,oo_,options_,bayestopt_,dataset_,atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,P,PK,decomp,Trend)
 % Writes the smoother results into respective fields in oo_
-% 
+%
 % Inputs:
 %   M_              [structure]     storing the model information
 %   oo_             [structure]     storing the results
@@ -42,19 +42,19 @@ function [oo_, yf]=store_smoother_results(M_,oo_,options_,bayestopt_,dataset_,da
 %                   oo_.SmoothedMeasurementErrors: structure storing the smoothed measurement errors
 %                   oo_.Smoother.State_uncertainty: smoothed state uncertainty (declaration order)
 
-%   yf              [double]    (nvarobs*T) matrix storing the smoothed observed variables (order of options_.varobs)  
-% 
-% Notes: 
+%   yf              [double]    (nvarobs*T) matrix storing the smoothed observed variables (order of options_.varobs)
+%
+% Notes:
 %   m:  number of endogenous variables (M_.endo_nbr)
 %   T:  number of Time periods (options_.nobs)
 %   r:  number of strucural shocks (M_.exo_nbr)
 %   n:  number of observables (length(options_.varobs))
 %   K:  maximum forecast horizon (max(options_.nk))
-% 
+%
 %   First all smoothed variables are saved without trend and constant.
 %       Then trend and constant are added for the observed variables.
 %
-% Copyright (C) 2014-2016 Dynare Team
+% Copyright (C) 2014-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -76,6 +76,11 @@ if nargin<16
     Trend=zeros(options_.number_of_observed_variables,gend);
 end
 
+if options_.loglinear
+    oo_.Smoother.loglinear = true;
+else
+    oo_.Smoother.loglinear = false;
+end
 %% write variable steady state
 oo_.Smoother.SteadyState = ys;
 
@@ -108,7 +113,7 @@ trend_constant_observables=constant_part+Trend;
 yf = atT(bayestopt_.mf,:)+trend_constant_observables;
 
 if options_.nk > 0
-    %filtered variable E_t(y_t+k) requires to shift trend by k periods    
+    %filtered variable E_t(y_t+k) requires to shift trend by k periods
     filter_steps_required=union(1,options_.filter_step_ahead); % 1 is required for standard filtered variables
     for filter_iter=1:length(filter_steps_required)
         filter_step=filter_steps_required(filter_iter);
@@ -136,7 +141,7 @@ if ~isempty(options_.nk) && options_.nk ~= 0
     end
     % add constant
     oo_.FilteredVariablesKStepAhead = aK(options_.filter_step_ahead,i_endo_in_dr_matrices,:)+constant_all_variables;
-    if ~isempty(PK) %get K-step ahead variances
+    if ~isempty(PK) && options_.filter_covariance %get K-step ahead variances
         oo_.FilteredVariablesKStepAheadVariances = ...
             PK(options_.filter_step_ahead,i_endo_in_dr_matrices,i_endo_in_dr_matrices,:);
     end
@@ -157,18 +162,18 @@ for i_endo_in_bayestopt_smoother_varlist=bayestopt_.smoother_saved_var_list'
     end
     oo_.Smoother.Constant.(deblank(M_.endo_names(i_endo_declaration_order,:)))=constant_current_variable;
     oo_.SmoothedVariables.(deblank(M_.endo_names(i_endo_declaration_order,:)))=atT(i_endo_in_dr,:)'+constant_current_variable;
-    if ~isempty(options_.nk) && options_.nk > 0 && ~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.pshape> 0) && options_.load_mh_file))
+    if ~isempty(options_.nk) && options_.nk > 0 % && ~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.pshape> 0) && options_.load_mh_file))
         oo_.FilteredVariables.(deblank(M_.endo_names(i_endo_declaration_order,:)))=squeeze(aK(1,i_endo_in_dr,2:end-(options_.nk-1)))+constant_current_variable;
     end
     oo_.UpdatedVariables.(deblank(M_.endo_names(i_endo_declaration_order,:)))=updated_variables(i_endo_in_dr,:)'+constant_current_variable;
 end
-    
+
 %% Add trend and constant for observed variables
 for pos_iter=1:length(bayestopt_.mf)
     oo_.Smoother.Constant.(deblank(M_.endo_names(bayestopt_.mfys(pos_iter),:)))=constant_part(pos_iter,:)';
     if ismember(bayestopt_.mf(pos_iter),bayestopt_.smoother_var_list(bayestopt_.smoother_saved_var_list))
-        oo_.SmoothedVariables.(deblank(M_.endo_names(bayestopt_.mfys(pos_iter),:)))=yf(pos_iter,:)';   
-        if ~isempty(options_.nk) && options_.nk > 0 
+        oo_.SmoothedVariables.(deblank(M_.endo_names(bayestopt_.mfys(pos_iter),:)))=yf(pos_iter,:)';
+        if ~isempty(options_.nk) && options_.nk > 0
             %filtered variable E_t(y_t+1) requires to shift trend by 1 period
             oo_.FilteredVariables.(deblank(M_.endo_names(bayestopt_.mfys(pos_iter),:)))=...
                 squeeze(aK(1,bayestopt_.mf(pos_iter),2:end-(options_.nk-1)))...
@@ -177,7 +182,7 @@ for pos_iter=1:length(bayestopt_.mf)
                 filter_step=options_.filter_step_ahead(filter_iter);
                 oo_.FilteredVariablesKStepAhead(filter_iter,find(i_endo_in_dr_matrices==bayestopt_.mf(pos_iter)),1+filter_step:end-(max(options_.filter_step_ahead)-filter_step)) = ...
                     squeeze(aK(filter_step,bayestopt_.mf(pos_iter),1+filter_step:end-(max(options_.filter_step_ahead)-filter_step)))...
-                    +trend_constant_observables_filtered.(['filter_ahead_' num2str(filter_step)])(pos_iter,:)';    
+                    +trend_constant_observables_filtered.(['filter_ahead_' num2str(filter_step)])(pos_iter,:)';
             end
         end
         %updated variables are E_t(y_t) so no trend shift is required
@@ -191,7 +196,7 @@ if ~isempty(options_.nk) && options_.nk ~= 0
     positions_in_declaration_order=oo_.dr.order_var(bayestopt_.smoother_var_list(bayestopt_.smoother_saved_var_list));
     if ~(options_.selected_variables_only && ~(options_.forecast > 0)) %happens only when selected_variables_only is not used
         oo_.FilteredVariablesKStepAhead(:,positions_in_declaration_order,:)=oo_.FilteredVariablesKStepAhead;
-        if ~isempty(PK) %get K-step ahead variances
+        if ~isempty(PK) && options_.filter_covariance %get K-step ahead variances
             oo_.FilteredVariablesKStepAheadVariances(:,positions_in_declaration_order,positions_in_declaration_order,:)=oo_.FilteredVariablesKStepAheadVariances;
         end
         if ~isempty(decomp)
@@ -201,7 +206,7 @@ if ~isempty(options_.nk) && options_.nk ~= 0
         positions_in_declaration_order=oo_.dr.order_var(bayestopt_.smoother_var_list(bayestopt_.smoother_saved_var_list));
         [junk,sorted_index_declaration_order]=sort(positions_in_declaration_order);
         oo_.FilteredVariablesKStepAhead(:,sorted_index_declaration_order,:)=oo_.FilteredVariablesKStepAhead;
-        if ~isempty(PK) %get K-step ahead variances
+        if ~isempty(PK) && options_.filter_covariance %get K-step ahead variances
             oo_.FilteredVariablesKStepAheadVariances(:,sorted_index_declaration_order,sorted_index_declaration_order,:)=oo_.FilteredVariablesKStepAheadVariances;
         end
         if ~isempty(decomp)
@@ -224,8 +229,8 @@ end
 
 %%  Smoothed measurement errors
 if ~isequal(M_.H,0)
-%     measurement_error_indices=find(diag(M_.H)~=0);
+    %     measurement_error_indices=find(diag(M_.H)~=0);
     for meas_error_iter=1:length(options_.varobs)
-       oo_.SmoothedMeasurementErrors.(options_.varobs{meas_error_iter})= measurement_error(meas_error_iter,:)';
+        oo_.SmoothedMeasurementErrors.(options_.varobs{meas_error_iter})= measurement_error(meas_error_iter,:)';
     end
 end
diff --git a/matlab/subset.m b/matlab/subset.m
index dedbdbfba2ec4a5997c1b80b6b0444199ab6ce67..946ebdcc5b98f16b8d010b5f1a5dc4d078191b21 100644
--- a/matlab/subset.m
+++ b/matlab/subset.m
@@ -1,6 +1,6 @@
 function jndx = subset()
 
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -54,8 +54,8 @@ else
     for i = 1:length(ExcludedParamNames)
         tmp = strmatch(ExcludedParamNames{i},M_.exo_names);
         if ~isempty(tmp) && ( strcmpi(info,'All') || strcmpi(info,'StructuralShocks') || ...
-                             strcmpi(info,'StructuralShocksWithoutCorrelations') || ...
-                             strcmpi(info,'AllWithoutMeasurementErrors') )
+                              strcmpi(info,'StructuralShocksWithoutCorrelations') || ...
+                              strcmpi(info,'AllWithoutMeasurementErrors') )
             % The parameter the user wants to exclude is related to the size of the structural innovations.
             if ncx
                 disp(['I cannot exclude some of the structural variances if the'])
@@ -63,10 +63,10 @@ else
                 error
             end
             tt = [tt;tmp];
-        elseif isempty(tmp) && nvn 
+        elseif isempty(tmp) && nvn
             tmp = strmatch(ExcludedParamNames{i},options_.varobs);
             if ~isempty(tmp) && ( strcmpi(info,'All') || strcmpi(info,'MeasurementErrors') || ...
-                                 strcmpi(info,'MeasurementErrorsWithoutCorrelations') )
+                                  strcmpi(info,'MeasurementErrorsWithoutCorrelations') )
                 % The parameter the user wants to exclude is related to the size of the measurement errors variances.
                 tmp = nvx+tmp;
                 if ncn
diff --git a/matlab/supported_octave_version.m b/matlab/supported_octave_version.m
index 9f6f2d633d4107f6a9fb70fea5011f6e2a711919..97e2c46056c81237375e201f26a44e56bdf4c19a 100644
--- a/matlab/supported_octave_version.m
+++ b/matlab/supported_octave_version.m
@@ -17,4 +17,4 @@ function v = supported_octave_version()
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-v = '4.2.0';
\ No newline at end of file
+v = '4.2.1';
\ No newline at end of file
diff --git a/matlab/symmetric_matrix_index.m b/matlab/symmetric_matrix_index.m
index 73cf4a50b0a6025e0e3b3ccd58ab09d003d7ce7c..60b2afe700ab920795077558b28a2a4f32dc4511 100644
--- a/matlab/symmetric_matrix_index.m
+++ b/matlab/symmetric_matrix_index.m
@@ -1,9 +1,9 @@
 function k = symmetric_matrix_index(i,j,n)
 % function k = symmetric_matrix_index(i,j,n)
-% Returns index number of variable combination (i,j) in vech(A) where A is 
+% Returns index number of variable combination (i,j) in vech(A) where A is
 % an symmetric n by n matrix and vech creates row vector by stacking rows
 % of A on and above the diagonal
-% 
+%
 % Inputs:
 %   i   [scalar]    index of first variable
 %   j   [scalar]    index of second variable
@@ -11,7 +11,7 @@ function k = symmetric_matrix_index(i,j,n)
 % Outputs:
 %   k   [scalar]    index of variable combination in vech(A)
 
-% Copyright (C) 2007-2015 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/test_for_deep_parameters_calibration.m b/matlab/test_for_deep_parameters_calibration.m
index 4dbfca7cd3a85f1e8b03c4b00ca9663fd3891dae..3cdc831b9271b4eee4e7b4a820a838994ac6ebb7 100644
--- a/matlab/test_for_deep_parameters_calibration.m
+++ b/matlab/test_for_deep_parameters_calibration.m
@@ -3,17 +3,17 @@ function info=test_for_deep_parameters_calibration(M_)
 %
 % INPUTS
 %   M_    [structure]   Description of the (simulated or estimated) model.
-%  
+%
 % OUTPUTS
-%   info  [scalar]      0 if no problems detected, 1 otherwise 
-%    
+%   info  [scalar]      0 if no problems detected, 1 otherwise
+%
 % ALGORITHM
 %   none
-%    
+%
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2010-2014 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -28,7 +28,7 @@ function info=test_for_deep_parameters_calibration(M_)
 % 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/>.
 plist = list_of_parameters_calibrated_as_NaN(M_);
 if ~isempty(plist)
     info=1;
diff --git a/matlab/th_autocovariances.m b/matlab/th_autocovariances.m
index 966ece83415ef7f71a5c7a92adf231a7d5ed33f6..3cde22f314cc760519ad40a94fcf1c77261e4fc4 100644
--- a/matlab/th_autocovariances.m
+++ b/matlab/th_autocovariances.m
@@ -1,28 +1,28 @@
 function [Gamma_y,stationary_vars] = th_autocovariances(dr,ivar,M_,options_,nodecomposition)
-% Computes the theoretical auto-covariances, Gamma_y, for an AR(p) process 
+% Computes the theoretical auto-covariances, Gamma_y, for an AR(p) process
 % with coefficients dr.ghx and dr.ghu and shock variances Sigma_e
 % for a subset of variables ivar.
 % Theoretical HP-filtering and band-pass filtering is available as an option
-%    
+%
 % INPUTS
 %   dr:               [structure]    Reduced form solution of the DSGE model  (decisions rules)
 %   ivar:             [integer]      Vector of indices for a subset of variables.
 %   M_                [structure]    Global dynare's structure, description of the DSGE model.
 %   options_          [structure]    Global dynare's structure.
-%   nodecomposition   [integer]      Scalar, if different from zero the variance decomposition is not triggered.  
-%    
+%   nodecomposition   [integer]      Scalar, if different from zero the variance decomposition is not triggered.
+%
 % OUTPUTS
-%   Gamma_y           [cell]         Matlab cell of nar+3 (second order approximation) or nar+2 (first order approximation) arrays, 
+%   Gamma_y           [cell]         Matlab cell of nar+3 (second order approximation) or nar+2 (first order approximation) arrays,
 %                                    where nar is the order of the autocorrelation function.
 %                                      Gamma_y{1}       [double]  Covariance matrix.
 %                                      Gamma_y{i+1}     [double]  Autocorrelation function (for i=1,...,options_.nar).
-%                                      Gamma_y{nar+2}   [double]  Variance decomposition.  
-%                                      Gamma_y{nar+3}   [double]  Expectation of the endogenous variables associated with a second 
-%                                                                 order approximation.    
+%                                      Gamma_y{nar+2}   [double]  Variance decomposition.
+%                                      Gamma_y{nar+3}   [double]  Expectation of the endogenous variables associated with a second
+%                                                                 order approximation.
 %   stationary_vars   [integer]      Vector of indices of stationary variables (as a subset of 1:length(ivar))
 %
 % SPECIAL REQUIREMENTS
-%   
+%
 % Algorithms
 %   The means at order=2 are based on the pruned state space as
 %   in Kim, Kim, Schaumburg, Sims (2008): Calculating and using second-order accurate
@@ -34,15 +34,15 @@ function [Gamma_y,stationary_vars] = th_autocovariances(dr,ivar,M_,options_,node
 %   Taking expectations on both sides requires to compute E(x^2)=Var(x), which
 %   can be obtained up to second order from the first order solution
 %   \[
-%       \hat x_t = g_x \hat x_{t - 1} + g_u u_t   
+%       \hat x_t = g_x \hat x_{t - 1} + g_u u_t
 %   \]
-%   by solving the corresponding Lyapunov equation. 
+%   by solving the corresponding Lyapunov equation.
 %   Given Var(x), the above equation can be solved for E(x_t) as
 %   \[
 %   E(x_t) = (I - {g_x}\right)^{- 1} 0.5\left( g_{\sigma\sigma} \sigma^2 + g_{xx} Var(\hat x_t) + g_{uu} Var(u_t) \right)
 %   \]
-% 
-% Copyright (C) 2001-2014 Dynare Team
+%
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -67,6 +67,11 @@ if options_.order >= 3
     error('Theoretical moments not implemented above 2nd order')
 end
 
+local_order = options_.order;
+if M_.hessian_eq_zero && local_order~=1
+    local_order = 1;
+end
+
 endo_nbr = M_.endo_nbr;
 exo_names_orig_ord  = M_.exo_names_orig_ord;
 if isoctave
@@ -114,7 +119,7 @@ else
     trend = 1:M_.endo_nbr;
     inv_order_var = trend(M_.block_structure.variable_reordered);
     ghu1(1:length(dr.state_var),:) = ghu(dr.state_var,:);
-end;
+end
 b = ghu1*M_.Sigma_e*ghu1';
 
 
@@ -122,19 +127,19 @@ if options_.block == 0
     ipred = nstatic+(1:nspred)';
 else
     ipred = dr.state_var;
-end;
+end
 % state space representation for state variables only
 [A,B] = kalman_transition_matrix(dr,ipred,1:nx,M_.exo_nbr);
 % Compute stationary variables (before HP filtering),
 % and compute 2nd order mean correction on stationary variables (in case of
 % HP filtering, this mean correction is computed *before* filtering)
-if options_.order == 2 || options_.hp_filter == 0
+if local_order == 2 || options_.hp_filter == 0
     [vx, u] =  lyapunov_symm(A,B*M_.Sigma_e*B',options_.lyapunov_fixed_point_tol,options_.qz_criterium,options_.lyapunov_complex_threshold,[],options_.debug);
     if options_.block == 0
         iky = inv_order_var(ivar);
     else
         iky = ivar;
-    end;
+    end
     stationary_vars = (1:length(ivar))';
     if ~isempty(u)
         x = abs(ghx*u);
@@ -143,8 +148,8 @@ if options_.order == 2 || options_.hp_filter == 0
     end
     aa = ghx(iky,:);
     bb = ghu(iky,:);
-    if options_.order == 2         % mean correction for 2nd order
-        if ~isempty(ikx) 
+    if local_order == 2         % mean correction for 2nd order
+        if ~isempty(ikx)
             Ex = (dr.ghs2(ikx)+dr.ghxx(ikx,:)*vx(:)+dr.ghuu(ikx,:)*M_.Sigma_e(:))/2;
             Ex = (eye(n0)-AS(ikx,:))\Ex;
             Gamma_y{nar+3} = NaN*ones(nvar, 1);
@@ -164,7 +169,7 @@ if options_.hp_filter == 0 && ~options_.bandpass.indicator
     Gamma_y{1} = v;
     % autocorrelations
     if nar > 0
-        vxy = (A*vx*aa'+ghu1*M_.Sigma_e*bb');    
+        vxy = (A*vx*aa'+ghu1*M_.Sigma_e*bb');
         sy = sqrt(diag(Gamma_y{1}));
         sy = sy(stationary_vars);
         sy = sy *sy';
@@ -209,7 +214,7 @@ if options_.hp_filter == 0 && ~options_.bandpass.indicator
     end
 else% ==> Theoretical filters.
     % By construction, all variables are stationary when HP filtered
-    iky = inv_order_var(ivar);  
+    iky = inv_order_var(ivar);
     stationary_vars = (1:length(ivar))';
     aa = ghx(iky,:); %R in Uhlig (2001)
     bb = ghu(iky,:); %S in Uhlig (2001)
@@ -227,22 +232,22 @@ else% ==> Theoretical filters.
         filter_gain(freqs>=2*pi/lowest_periodicity & freqs<=2*pi/highest_periodicity)=1;
         filter_gain(freqs<=-2*pi/lowest_periodicity+2*pi & freqs>=-2*pi/highest_periodicity+2*pi)=1;
     else
-        filter_gain = 4*lambda*(1 - cos(freqs)).^2 ./ (1 + 4*lambda*(1 - cos(freqs)).^2);   %HP transfer function  
+        filter_gain = 4*lambda*(1 - cos(freqs)).^2 ./ (1 + 4*lambda*(1 - cos(freqs)).^2);   %HP transfer function
     end
     mathp_col = NaN(ngrid,length(ivar)^2);
     IA = eye(size(A,1));
     IE = eye(M_.exo_nbr);
     for ig = 1:ngrid
-        if filter_gain(ig)==0,
+        if filter_gain(ig)==0
             f_hp = zeros(length(ivar),length(ivar));
         else
             f_omega  =(1/(2*pi))*([(IA-A*tneg(ig))\ghu1;IE]...
-                                   *M_.Sigma_e*[ghu1'/(IA-A'*tpos(ig)) IE]); % spectral density of state variables; top formula Uhlig (2001), p. 20 with N=0
-            g_omega = [aa*tneg(ig) bb]*f_omega*[aa'*tpos(ig); bb']; % spectral density of selected variables; middle formula Uhlig (2001), p. 20; only middle block, i.e. y_t' 
+                                  *M_.Sigma_e*[ghu1'/(IA-A'*tpos(ig)) IE]); % spectral density of state variables; top formula Uhlig (2001), p. 20 with N=0
+            g_omega = [aa*tneg(ig) bb]*f_omega*[aa'*tpos(ig); bb']; % spectral density of selected variables; middle formula Uhlig (2001), p. 20; only middle block, i.e. y_t'
             f_hp = filter_gain(ig)^2*g_omega; % spectral density of selected filtered series; top formula Uhlig (2001), p. 21;
         end
         mathp_col(ig,:) = (f_hp(:))';    % store as matrix row for ifft
-    end;
+    end
     % Covariance of filtered series
     imathp_col = real(ifft(mathp_col))*(2*pi); % Inverse Fast Fourier Transformation; middle formula Uhlig (2001), p. 21;
     Gamma_y{1} = reshape(imathp_col(1,:),nvar,nvar);
@@ -269,32 +274,32 @@ else% ==> Theoretical filters.
             IA = eye(size(A,1));
             IE = eye(M_.exo_nbr);
             for ig = 1:ngrid
-                if filter_gain(ig)==0,
+                if filter_gain(ig)==0
                     f_hp = zeros(length(ivar),length(ivar));
                 else
                     f_omega  =(1/(2*pi))*( [(IA-A*tneg(ig))\b1;IE]...
                                            *SS*[b1'/(IA-A'*tpos(ig)) IE]); % spectral density of state variables; top formula Uhlig (2001), p. 20 with N=0
-                    g_omega = [aa*tneg(ig) b2]*f_omega*[aa'*tpos(ig); b2']; % spectral density of selected variables; middle formula Uhlig (2001), p. 20; only middle block, i.e. y_t' 
+                    g_omega = [aa*tneg(ig) b2]*f_omega*[aa'*tpos(ig); b2']; % spectral density of selected variables; middle formula Uhlig (2001), p. 20; only middle block, i.e. y_t'
                     f_hp = filter_gain(ig)^2*g_omega;  % spectral density of selected filtered series; top formula Uhlig (2001), p. 21;
                 end
                 mathp_col(ig,:) = (f_hp(:))';    % store as matrix row for ifft
-            end;  
+            end
             imathp_col = real(ifft(mathp_col))*(2*pi);
             vv = diag(reshape(imathp_col(1,:),nvar,nvar));
             for i=1:M_.exo_nbr
                 mathp_col = NaN(ngrid,length(ivar)^2);
                 SSi = cs(:,i)*cs(:,i)';
                 for ig = 1:ngrid
-                    if filter_gain(ig)==0,
+                    if filter_gain(ig)==0
                         f_hp = zeros(length(ivar),length(ivar));
                     else
                         f_omega  =(1/(2*pi))*( [(IA-A*tneg(ig))\b1;IE]...
                                                *SSi*[b1'/(IA-A'*tpos(ig)) IE]); % spectral density of state variables; top formula Uhlig (2001), p. 20 with N=0
-                        g_omega = [aa*tneg(ig) b2]*f_omega*[aa'*tpos(ig); b2']; % spectral density of selected variables; middle formula Uhlig (2001), p. 20; only middle block, i.e. y_t' 
+                        g_omega = [aa*tneg(ig) b2]*f_omega*[aa'*tpos(ig); b2']; % spectral density of selected variables; middle formula Uhlig (2001), p. 20; only middle block, i.e. y_t'
                         f_hp = filter_gain(ig)^2*g_omega; % spectral density of selected filtered series; top formula Uhlig (2001), p. 21;
                     end
                     mathp_col(ig,:) = (f_hp(:))';    % store as matrix row for ifft
-                end;
+                end
                 imathp_col = real(ifft(mathp_col))*(2*pi);
                 Gamma_y{nar+2}(:,i) = abs(diag(reshape(imathp_col(1,:),nvar,nvar)))./vv;
             end
diff --git a/matlab/thet2tau.m b/matlab/thet2tau.m
index 929193ca44d4b440aa5c4c0d4a4b2c5dccd03b6b..965934e3d93734f82cb5280a0b2e5aee1a36e5b4 100644
--- a/matlab/thet2tau.m
+++ b/matlab/thet2tau.m
@@ -1,7 +1,7 @@
 function tau = thet2tau(params, estim_params_, M_, oo_, indx, indexo, flagmoments,mf,nlags,useautocorr,iv)
 
 %
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -20,22 +20,22 @@ function tau = thet2tau(params, estim_params_, M_, oo_, indx, indexo, flagmoment
 
 global options_
 
-if nargin==1,
+if nargin==1
     indx = [1:M_.param_nbr];
     indexo = [];
 end
 
-if nargin<7,
+if nargin<7
     flagmoments=0;
 end
-if nargin<10 || isempty(useautocorr),
+if nargin<10 || isempty(useautocorr)
     useautocorr=0;
 end
-if nargin<11 || isempty(iv),
+if nargin<11 || isempty(iv)
     iv=[1:M_.endo_nbr];
 end
 
-if length(params)>length(indx),
+if length(params)>length(indx)
     M_ = set_all_parameters(params,estim_params_,M_);
 else
     M_.params(indx) = params;
@@ -44,21 +44,21 @@ end
 %     M_.Sigma_e(indexo,indexo) = diag(params(1:length(indexo)).^2);
 % end
 [A,B,tele,tubbies,M_,options_,oo_] = dynare_resolve(M_,options_,oo_);
-if flagmoments==0,
+if flagmoments==0
     ys=oo_.dr.ys(oo_.dr.order_var);
     tau = [ys(iv); vec(A(iv,iv)); dyn_vech(B(iv,:)*M_.Sigma_e*B(iv,:)')];
 elseif flagmoments==-1
     [I,J]=find(M_.lead_lag_incidence');
     yy0=oo_.dr.ys(I);
     [residual, g1] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', ...
-        M_.params, oo_.dr.ys, 1);
+                           M_.params, oo_.dr.ys, 1);
     tau=[oo_.dr.ys(oo_.dr.order_var); g1(:)];
 
 else
     GAM =  lyapunov_symm(A,B*M_.Sigma_e*B',options_.lyapunov_fixed_point_tol,options_.qz_criterium,options_.lyapunov_complex_threshold,[],options_.debug);
     k = find(abs(GAM) < 1e-12);
     GAM(k) = 0;
-    if useautocorr,
+    if useautocorr
         sy = sqrt(diag(GAM));
         sy = sy*sy';
         sy0 = sy-diag(diag(sy))+eye(length(sy));
@@ -69,7 +69,7 @@ else
     end
     for ii = 1:nlags
         dum = A^(ii)*GAM;
-        if useautocorr,
+        if useautocorr
             dum = dum./sy;
         end
         tau = [tau;vec(dum(mf,mf))];
diff --git a/matlab/trace_plot.m b/matlab/trace_plot.m
index 1073480d6d474b9546b8aef25bae59197648d302..9fbf383581745c1e64356ce726b991bb250a4338 100644
--- a/matlab/trace_plot.m
+++ b/matlab/trace_plot.m
@@ -18,7 +18,7 @@ function trace_plot(options_,M_,estim_params_,type,blck,name1,name2)
 %
 % SPECIAL REQUIREMENTS
 
-% Copyright (C) 2003-2016 Dynare Team
+% Copyright (C) 2003-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -95,7 +95,7 @@ if options_.mh_nblck>1
     FigureName = [ FigureName , ' (block number ' int2str(blck)  ').'];
 end
 
-hh=dyn_figure(options_,'Name',FigureName);
+hh=dyn_figure(options_.nodisplay,'Name',FigureName);
 plot(1:TotalNumberOfMhDraws,PosteriorDraws,'Color',[.7 .7 .7]);
 
 
@@ -131,11 +131,11 @@ else
 end
 plot_name=[plot_name,'_blck_',num2str(blck)];
 
-dyn_saveas(hh,[M_.fname, filesep, 'graphs', filesep, 'TracePlot_' plot_name],options_)
+dyn_saveas(hh,[M_.fname, filesep, 'graphs', filesep, 'TracePlot_' plot_name],options_.nodisplay,options_.graph_format)
 
 if options_.TeX
     fid=fopen([M_.fname,'/graphs/',M_.fname,'_TracePlot_' plot_name,'.tex'],'w+');
-    
+
     if strcmpi(type,'DeepParameter')
         tex_names=M_.param_names_tex;
         base_names=M_.param_names;
@@ -146,7 +146,7 @@ if options_.TeX
         tex_names=M_.endo_names_tex;
         base_names=M_.endo_names;
     end
-    
+
     if strcmpi(type,'PosteriorDensity')
         FigureName = ['Trace plot for ' TYPE name1];
     else
@@ -159,7 +159,7 @@ if options_.TeX
     if options_.mh_nblck>1
         FigureName = [ FigureName , ' (block number ' int2str(blck)  ').'];
     end
-    
+
     fprintf(fid,'%-s\n','\begin{figure}[H]');
     fprintf(fid,'%-s\n','\centering');
     fprintf(fid,'%-s\n',['  \includegraphics[width=0.8\textwidth]{',[M_.fname, '/graphs/TracePlot_' plot_name],'}\\']);
@@ -167,4 +167,3 @@ if options_.TeX
     fprintf(fid,'%-s\n','\end{figure}');
     fclose(fid);
 end
-
diff --git a/matlab/trust_region.m b/matlab/trust_region.m
index 02acae0c5361a8a5cadbac19518f83997961f978..13f11bd3da1cab3e6947bce3400030f359e10486 100644
--- a/matlab/trust_region.m
+++ b/matlab/trust_region.m
@@ -25,7 +25,7 @@ function [x,check,info] = trust_region(fcn,x0,j1,j2,jacobian_flag,gstep,tolf,tol
 %    none
 
 % Copyright (C) 2008-2012 VZLU Prague, a.s.
-% Copyright (C) 2014-2016 Dynare Team
+% Copyright (C) 2014-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -150,7 +150,7 @@ while (niter < maxiter && ~info)
             else
                 info = -3;
             end
-            break;
+            break
         end
     elseif (abs (1-ratio) <= 0.1)
         delta = 1.4142*sn;
@@ -229,4 +229,3 @@ if (xn > delta)
     x = alpha * x + ((1-alpha) * min (snm, delta)) * s;
 end
 end
-
diff --git a/matlab/uniform_specification.m b/matlab/uniform_specification.m
index 5af782162f3e180209ede22413f3c3463658c27d..6baceb82ff878ffba2d4a704d87d4978ae3f7323 100644
--- a/matlab/uniform_specification.m
+++ b/matlab/uniform_specification.m
@@ -3,20 +3,20 @@ function [m,s,p6,p7] = uniform_specification(m,s,p3,p4)
 %
 % INPUTS
 %    m:      mean
-%    s:      standard deviation 
-%    p3:     lower bound 
-%    p4:     upper bound 
+%    s:      standard deviation
+%    p3:     lower bound
+%    p4:     upper bound
 
 % OUTPUTS
 %    m:      mean
-%    s:      standard deviation 
-%    p1:     lower bound 
-%    p2:     upper bound 
-%        
+%    s:      standard deviation
+%    p1:     lower bound
+%    p2:     upper bound
+%
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2004-2011 Dynare Team
+% Copyright (C) 2004-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/update_last_mh_history_file.m b/matlab/update_last_mh_history_file.m
index d0c4e9ca54f1e5a3f4502e2719e6118584303366..a0e2d4a9691c74a9b7e50a2811cbc128ecc9ab02 100644
--- a/matlab/update_last_mh_history_file.m
+++ b/matlab/update_last_mh_history_file.m
@@ -5,9 +5,9 @@ function update_last_mh_history_file(MetropolisFolder, ModelName, record)
 %   MetropolisFolder    [char]      Name of the metropolis subfolder
 %   ModelName           [char]      Name of the mod-file
 %   record              [structure] structure storing the MH history
-% Outputs:  none 
+% Outputs:  none
 
-% Copyright (C) 2013-2015 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/user_has_matlab_license.m b/matlab/user_has_matlab_license.m
index 86b8c94bd688133738578f3aa18294fd8631ed42..c8c681283ce8f924ed31caec0e94868d293cf0ff 100644
--- a/matlab/user_has_matlab_license.m
+++ b/matlab/user_has_matlab_license.m
@@ -11,7 +11,7 @@ function [hasLicense] = user_has_matlab_license(toolbox)
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2012 Dynare Team
+% Copyright (C) 2012-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -31,26 +31,26 @@ function [hasLicense] = user_has_matlab_license(toolbox)
 if matlab_ver_less_than('7.12')
     hasLicense = license('test', toolbox);
 else
-    [hasLicense junk] = license('checkout',toolbox);
+    [hasLicense, junk] = license('checkout',toolbox);
 end
 if ~hasLicense
     return
 end
 switch toolbox
     %use function unique to toolbox
-    case 'statistics_toolbox'
-        n = 'gppdf';
-    case 'optimization_toolbox'
-        n='fsolve';
-    case 'GADS_Toolbox'
-        n='simulannealbnd';
-    case 'control_toolbox'
-        n='dlyap';
+  case 'statistics_toolbox'
+    n = 'gppdf';
+  case 'optimization_toolbox'
+    n='fsolve';
+  case 'GADS_Toolbox'
+    n='simulannealbnd';
+  case 'control_toolbox'
+    n='dlyap';
 end
 hasInstallation=check_toolbox_installation(n);
 if ~hasInstallation
     hasLicense=0;
-    return;
+    return
 end
 end
 
@@ -64,7 +64,7 @@ else
     a=ver(ver_string);
     if isempty(a)
         hasInstallation=0;
-    else 
+    else
         hasInstallation=1;
     end
 end
diff --git a/matlab/utilities/dataset/descriptive_statistics.m b/matlab/utilities/dataset/descriptive_statistics.m
index d2b52292d2c59a5e61ee3ca434d064ee1e86bf8f..79d3241414db6bb52caade9eff7f35ee97b6530d 100644
--- a/matlab/utilities/dataset/descriptive_statistics.m
+++ b/matlab/utilities/dataset/descriptive_statistics.m
@@ -3,7 +3,7 @@ function dataset_ = descriptive_statistics(dataset_,statistic,varagin)
 
 %@info:
 %! @deftypefn {Function File} {@var{dataset_} =} descriptive_statistics(@var{dataset_},@var{statistic})
-%! @deftypefn {Function File} {@var{dataset_} =} descriptive_statistics(@var{dataset_},@var{statistic},nlags)    
+%! @deftypefn {Function File} {@var{dataset_} =} descriptive_statistics(@var{dataset_},@var{statistic},nlags)
 %! @anchor{compute_corr}
 %! This function computes various descriptive statistics on the sample (possibly with missing observations).
 %!
@@ -14,15 +14,15 @@ function dataset_ = descriptive_statistics(dataset_,statistic,varagin)
 %! @item statistic
 %! String. The name of the statistic to be computed. Admissible values are:
 %!   @table @var
-%!   @item 'stdv'    
+%!   @item 'stdv'
 %!   Computes the standard deviation of each observed variable.
-%!   @item 'cova'    
-%!   Computes the covariance matrix of the sample.    
+%!   @item 'cova'
+%!   Computes the covariance matrix of the sample.
 %!   @item 'corr'
 %!   Computes the correlation matrix of the sample.
 %!   @item 'acov'
 %!   Computes the (multivariate) auto-covariance function of the sample. In this case a third argument (@code{nlags}) defining the
-%!   maximum number of lags is mandatory.    
+%!   maximum number of lags is mandatory.
 %!   @end table
 %! @item nlags
 %! Integer scalar. The maximum number of lags when computing the autocovariance function.
@@ -33,20 +33,20 @@ function dataset_ = descriptive_statistics(dataset_,statistic,varagin)
 %! @item dataset_
 %! Dynare structure describing the dataset, built by @ref{initialize_dataset}
 %! @end table
-%! 
-%! @strong{This function is called by:} 
+%!
+%! @strong{This function is called by:}
 %! none.
-%! 
+%!
 %! @strong{This function calls:}
 %! @ref{compute_stdv}, @ref{compute_cova}, @ref{compute_corr}, @ref{compute_acov}.
-%!    
+%!
 %! @strong{Remark 1.} On exit, a new field containing the computed statistics is appended to the structure.
-%!    
+%!
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2011-2012 Dynare Team
-%    
+% Copyright (C) 2011-2017 Dynare Team
+%
 % This file is part of Dynare.
 %
 % Dynare is free software: you can redistribute it and/or modify
diff --git a/matlab/utilities/dataset/initialize_dataset.m b/matlab/utilities/dataset/initialize_dataset.m
index 5d992a288955d728734b7b5f216fe03f371ef0fc..d7e3ed3842559ba5d85692c4d1557ccd30c9e28b 100644
--- a/matlab/utilities/dataset/initialize_dataset.m
+++ b/matlab/utilities/dataset/initialize_dataset.m
@@ -1,7 +1,7 @@
 function dataset_ = initialize_dataset(datafile,varobs,first,nobs,logged_data_flag,prefilter,xls)
 % Initializes a structure describing the dataset.
 
-% Copyright (C) 2011-2013 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -55,7 +55,7 @@ if dataset_.info.nvobs-size(rawdata,2)
 end
 
 if size(rawdata,1)~=dataset_.info.ntobs
-   fprintf('Restricting the sample to observations %d to %d. Using in total %d observations. \n',first,first+dataset_.info.ntobs-1,dataset_.info.ntobs)
+    fprintf('Restricting the sample to observations %d to %d. Using in total %d observations. \n',first,first+dataset_.info.ntobs-1,dataset_.info.ntobs)
 end
 rawdata = rawdata(first:(first+dataset_.info.ntobs-1),:);
 
diff --git a/matlab/utilities/dataset/lagged.m b/matlab/utilities/dataset/lagged.m
new file mode 100644
index 0000000000000000000000000000000000000000..4f17d7eeb302d84c536050e83bcd7570d913f75e
--- /dev/null
+++ b/matlab/utilities/dataset/lagged.m
@@ -0,0 +1,34 @@
+function xlag = lagged(x, n)
+% xlag = lagged(x, n);
+% applies n-lags backward shift operator to x
+%
+% INPUTS
+% x    = time series
+% n    = number of backward shifts [DEFAULT=1]
+%
+% OUTPUT
+% xlag = backward shifted series
+
+% Copyright (C) 2017 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==1
+    n=1;
+end
+
+x=x(:);
+xlag=[NaN(n,1); x(1:end-n)];
\ No newline at end of file
diff --git a/matlab/utilities/dataset/makedataset.m b/matlab/utilities/dataset/makedataset.m
index 7e4aedd981268978d0ea6a1ba08863b21d9b394d..85d86d8419ea2dad7cb85bfa04b4f831cc10d2b3 100644
--- a/matlab/utilities/dataset/makedataset.m
+++ b/matlab/utilities/dataset/makedataset.m
@@ -23,6 +23,24 @@ function [DynareDataset, DatasetInfo, newdatainterface] = makedataset(DynareOpti
 %
 % See also dynare_estimation_init
 
+% Copyright (C) 2014-2017 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+    
+
 if nargin<3
     gsa_flag = 0;
 end
@@ -37,7 +55,7 @@ if isempty(DynareOptions.datafile) && isempty(DynareOptions.dataset.file) && ise
     if gsa_flag
         DynareDataset = dseries();
         DatasetInfo = struct('missing', struct('state', 0, 'aindex', [], 'vindex', [], 'number_of_observations', NaN, 'no_more_missing_observations', NaN), ...
-                     'descriptive', struct('mean', [], 'covariance', [], 'correlation', [], 'autocovariance', []));
+                             'descriptive', struct('mean', [], 'covariance', [], 'correlation', [], 'autocovariance', []));
         newdatainterface=0;
         return
     else
@@ -99,11 +117,16 @@ end
 
 % Load the data in a dseries object.
 if ~isempty(datafile)
-    if ~( newdatainterface==0 && strcmp(datafile(end-1:end),'.m'))
+    if ~( newdatainterface==0 && (strcmp(datafile(end-1:end),'.m')|| strcmp(datafile(end-3:end),'.mat')))
         DynareDataset = dseries(datafile);
     else
-        % Load an m file with the old interface.
-        DynareDataset = load_m_file_data_legacy(datafile, DynareOptions.varobs);
+        if strcmp(datafile(end-1:end),'.m')
+            % Load an m file with the old interface.
+            DynareDataset = load_m_file_data_legacy(datafile, DynareOptions.varobs);
+        elseif strcmp(datafile(end-3:end),'.mat')
+            % Load a mat file with the old interface.
+            DynareDataset = load_mat_file_data_legacy(datafile, DynareOptions.varobs);
+        end
     end
 else
     DynareDataset = dseriesobjectforuserdataset;
diff --git a/matlab/utilities/dataset/nanvariance.m b/matlab/utilities/dataset/nanvariance.m
index d4894e8e9212d1a37759c464bfd8524d944c1c30..121fb2ddafdeeb7a26d5c804b2ae0c35329c45f9 100644
--- a/matlab/utilities/dataset/nanvariance.m
+++ b/matlab/utilities/dataset/nanvariance.m
@@ -1,4 +1,4 @@
-function variances = nanvariance(data) 
+function variances = nanvariance(data)
 % Compute the standard deviation for each observed variable (possibly with missing observations).
 
 %@info:
@@ -17,21 +17,21 @@ function variances = nanvariance(data)
 %! @item variances
 %! A N*1 vector of real numbers
 %! @end table
-%! 
-%! @strong{This function is called by:} 
+%!
+%! @strong{This function is called by:}
 %! @ref{descriptive_statistics}.
-%! 
+%!
 %! @strong{This function calls:}
 %! @ref{ndim}, @ref{demean}, @ref{nandemean}.
-%!    
-%! @strong{Remark 1.} On exit, a new field is appended to the structure: @code{dataset_.descriptive.stdv} is a 
+%!
+%! @strong{Remark 1.} On exit, a new field is appended to the structure: @code{dataset_.descriptive.stdv} is a
 %! @tex{n\times 1} vector (where @tex{n} is the number of observed variables as defined by @code{dataset_.info.nvobs}).
-%!    
+%!
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2011-2014 Dynare Team
-%    
+% Copyright (C) 2011-2017 Dynare Team
+%
 % This file is part of Dynare.
 %
 % Dynare is free software: you can redistribute it and/or modify
diff --git a/matlab/utilities/dataset/quarterly2annual.m b/matlab/utilities/dataset/quarterly2annual.m
new file mode 100644
index 0000000000000000000000000000000000000000..6342c4605e4c39b64b25f8454b47f13c799d9d95
--- /dev/null
+++ b/matlab/utilities/dataset/quarterly2annual.m
@@ -0,0 +1,135 @@
+function [ya, yass, gya, gyass] = quarterly2annual(y,yss,GYTREND0,type,islog,aux)
+% function [ya, yass, gya, gyass] = quarterly2annual(y,yss,GYTREND0,type,islog,aux)
+% transforms quarterly (log-)level time series to annual level and growth rate
+% it accounts for stock/flow/deflator series.
+%
+% INPUTS
+% y        quarterly time series
+% yss      steady state of y
+% GYTREND0 growth rate of y
+% type     1 sum (default)
+%          2 average
+%          3 last period (Q4)
+%          4 geometric average
+%          5 annual price as quantity weighted average
+%          6 annual quantity from average price
+%          7 annual nominal from Q real and deflator
+% islog    0 level (default)
+%          1 log-level
+%          2 growth rate Q frequency
+% aux      optional input used when type>4
+%
+%
+% OUTPUTS
+% ya       annual (log-)level
+% yass     annual steadystate (log-)level
+% gya      annual growth rate
+% gyass    annual growth rate steadystate
+
+% Copyright (C) 2017 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 ==0
+    disp('[ya, yass, gya, gyass] = quarterly2annual(y,yss,GYTREND0,type,islog);')
+    return
+end
+
+if nargin<4 || isempty(type)
+    type=1;
+end
+if nargin<5 || isempty(islog)
+    islog=0;
+end
+if isstruct(aux)
+    yaux=aux.y;
+    yauxss=aux.yss;
+    islogaux=aux.islog;
+    GYTREND0aux=aux.GYTREND0;
+    typeaux=aux.type;
+    if islogaux
+        yaux=exp(yaux+yauxss);
+        yauxss=exp(yauxss);
+        yaux=yaux-yauxss;
+    end
+elseif type > 4
+    error('TYPE>4 requires auxiliary variable!')
+end
+if islog == 2
+    % construct loglevel out of growth rate
+    y = cumsum(y);
+    yss=0;
+    islog=1;
+end
+if islog == 1
+    y=exp(y+yss);
+    yss=exp(yss);
+    y=y-yss;
+end
+switch type
+  case 1
+    yass = yss*(exp(-GYTREND0*3)+exp(-GYTREND0*2)+exp(-GYTREND0)+1);
+    tmp = lagged(y,3)*exp(-GYTREND0*3)+lagged(y,2)*exp(-GYTREND0*2)+lagged(y,1)*exp(-GYTREND0)+y; % annualized level
+    ya = tmp(4:4:end);
+  case 2
+    yass = yss*(exp(-GYTREND0*3)+exp(-GYTREND0*2)+exp(-GYTREND0)+1)/4;
+    tmp = (lagged(y,3)*exp(-GYTREND0*3)+lagged(y,2)*exp(-GYTREND0*2)+lagged(y,1)*exp(-GYTREND0)+y)/4; % annualized level
+    ya = tmp(4:4:end);
+  case 3
+    yass=yss;
+    tmp = y;
+    ya = tmp(4:4:end);
+  case 4
+    yass = yss*(exp(-GYTREND0*3/2));
+    tmp = (lagged(y+yss,3)*exp(-GYTREND0*3).*lagged(y+yss,2)*exp(-GYTREND0*2).*lagged(y+yss,1)*exp(-GYTREND0).*(y+yss)).^(1/4); % annualized level
+    tmp = tmp - yass;
+    ya = tmp(4:4:end);
+  case 5
+    % nominal series
+    yn = (y+yss).*(yaux+yauxss) - yss.*yauxss;
+    [yna, ynass] = quarterly2annual(yn,yss.*yauxss,GYTREND0+GYTREND0aux,typeaux,0,0);
+    % real series
+    [yra, yrass] = quarterly2annual(yaux,yauxss,GYTREND0aux,typeaux,0,0);
+    % deflator
+    yass = ynass/yrass;
+    ya = (yna+ynass)./(yr+yrass)-yass;
+  case 6
+    % nominal series
+    yn = (y+yss).*(yaux+yauxss) - yss.*yauxss;
+    [yna, ynass] = quarterly2annual(yn,yss.*yauxss,GYTREND0+GYTREND0aux,typeaux,0,0);
+    % deflator
+    [pa, pass] = quarterly2annual(yaux,yauxss,GYTREND0aux,2,0,0);
+    % real series
+    yass = ynass/pass;
+    ya = (yna+ynass)./(pa+pass)-yass;
+  case 7
+    % nominal series
+    yn = (y+yss).*(yaux+yauxss) - yss.*yauxss;
+    [ya, yass] = quarterly2annual(yn,yss.*yauxss,GYTREND0+GYTREND0aux,typeaux,0,0);
+    GYTREND0=GYTREND0+GYTREND0aux;
+  otherwise
+    error('Wrong type input')
+end
+
+% annual growth rate
+gyass = GYTREND0*4;
+gya = (ya+yass)./(lagged(ya,1)+yass).*exp(4*GYTREND0)-1-gyass;
+
+if islog
+    ya=log(ya+yass);
+    yass=log(yass);
+    ya=ya-yass;
+end
diff --git a/matlab/utilities/doc/dynInfo.m b/matlab/utilities/doc/dynInfo.m
index 952c5bbe16d515c8a24ef32411386babba337e40..85c9649740fbfe2b2e554921a6c570c3297b4b0f 100644
--- a/matlab/utilities/doc/dynInfo.m
+++ b/matlab/utilities/doc/dynInfo.m
@@ -31,7 +31,7 @@ function dynInfo(fun)
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2013 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/utilities/doc/get_internal_doc_block.m b/matlab/utilities/doc/get_internal_doc_block.m
index 718b2a28d94f3802a21a0a1037bc62f89fff5098..96dda6d6f1248d77d6403237b950127a6e03ef4e 100644
--- a/matlab/utilities/doc/get_internal_doc_block.m
+++ b/matlab/utilities/doc/get_internal_doc_block.m
@@ -1,8 +1,8 @@
 function block = get_internal_doc_block(fname,fpath)
 % Extract doc sections from matlab's routine.
- 
-% Copyright (C) 2011-2012 Dynare Team
-%    
+
+% Copyright (C) 2011-2017 Dynare Team
+%
 % This file is part of Dynare.
 %
 % Dynare is free software: you can redistribute it and/or modify
@@ -22,7 +22,7 @@ function block = get_internal_doc_block(fname,fpath)
 
 % Default output
 block = [];
-    
+
 % Open the matlab file.
 mid = fopen([fpath '/' fname '.m'],'r');
 
@@ -43,14 +43,14 @@ if ( isempty(b1) && isempty(b2) && isempty(b) )
     return
 else
     if ( (~isempty(b1) && isempty(b2) && isempty(b)) || ...
-            (isempty(b1) && ~isempty(b2) && isempty(b)) || ...
-            (isempty(b1) && isempty(b2) && ~isempty(b)) || ...
-            (isempty(b1) && ~isempty(b2) && ~isempty(b)) || ...
-            (~isempty(b1) && isempty(b2) && ~isempty(b)) || ...
-            (~isempty(b1) && ~isempty(b2) && isempty(b)) )
+         (isempty(b1) && ~isempty(b2) && isempty(b)) || ...
+         (isempty(b1) && isempty(b2) && ~isempty(b)) || ...
+         (isempty(b1) && ~isempty(b2) && ~isempty(b)) || ...
+         (~isempty(b1) && isempty(b2) && ~isempty(b)) || ...
+         (~isempty(b1) && ~isempty(b2) && isempty(b)) )
         error('get_internal_doc_block:: There is a problem with the internal block definition!')
     end
-    if ( b2~=b(end) || b1~=b(1) || any(b-transpose(b1:1:b2)) ) 
+    if ( b2~=b(end) || b1~=b(1) || any(b-transpose(b1:1:b2)) )
         error('get_internal_doc_block:: There is a problem with the internal block definition!')
     end
 end
diff --git a/matlab/utilities/general/clean_current_folder.m b/matlab/utilities/general/clean_current_folder.m
index e3408bec1577cf074d23ecb46e4eab4faf58f90a..6c302927e4b6e3195b04dca19e16663e410c4a11 100644
--- a/matlab/utilities/general/clean_current_folder.m
+++ b/matlab/utilities/general/clean_current_folder.m
@@ -1,6 +1,6 @@
-function clean()
+function clean_current_folder()
 
-% Copyright (C) 2014 Dynare Team
+% Copyright (C) 2014-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/utilities/general/compare_vectors.m b/matlab/utilities/general/compare_vectors.m
index 97e916c7573cee000345a042880d70d8d4acc71e..00ea0c11e24199008af1b1f04a64fac6e52a9844 100644
--- a/matlab/utilities/general/compare_vectors.m
+++ b/matlab/utilities/general/compare_vectors.m
@@ -1,5 +1,5 @@
 function C = compare_vectors(f, A, B)  % --*-- Unitary tests --*--
- 
+
 % Performs lexicographical comparison of vectors.
 %
 % INPUTS
@@ -7,13 +7,13 @@ function C = compare_vectors(f, A, B)  % --*-- Unitary tests --*--
 %  o A    vector of real numbers.
 %  o B    vector of real numbers.
 %
-% OUTPUTS 
+% OUTPUTS
 %  o C    integer scalar, 1 or 0.
 %
-% REMARKS 
+% REMARKS
 %  o It is assumed that vectors A and B have the same number of elements.
-    
-% Copyright (C) 2013 Dynare Team
+
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/utilities/general/delete_stale_file.m b/matlab/utilities/general/delete_stale_file.m
index 8ac8b799635e88eaedc4e03093a3b3201ee5dcbb..d5e9951e45dd23b3844b05a97f5f1b23d572869f 100644
--- a/matlab/utilities/general/delete_stale_file.m
+++ b/matlab/utilities/general/delete_stale_file.m
@@ -2,7 +2,7 @@ function delete_stale_file(fname)
 % function delete_old_files(fname)
 % Checks for presence of files and deletes them if necessary
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -23,4 +23,3 @@ Files_info = dir(fname);
 if length(Files_info)>0
     delete(fname)
 end
-
diff --git a/matlab/utilities/general/demean.m b/matlab/utilities/general/demean.m
index 4bf53aaa62d6ed66275093e09b442be7a597a202..741a2f10778a15e7f87de593b6cfd1e6eb6647bc 100644
--- a/matlab/utilities/general/demean.m
+++ b/matlab/utilities/general/demean.m
@@ -1,6 +1,6 @@
 function c = demean(x)
 % Removes the mean of each column of a matrix.
- 
+
 %@info:
 %! @deftypefn {Function File} {@var{c} =} demean (@var{x})
 %! @anchor{demean}
@@ -17,18 +17,18 @@ function c = demean(x)
 %! @item c
 %! Matlab matrix (T-by-N). The demeaned x matrix.
 %! @end table
-%! 
-%! @strong{This function is called by:} 
+%!
+%! @strong{This function is called by:}
 %! @ref{compute_cova}, @ref{compute_acov}, @ref{compute_std}.
-%! 
-%! @strong{This function calls:} 
+%!
+%! @strong{This function calls:}
 %! @ref{ndim},
-%!    
+%!
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2011-2012 Dynare Team
-%    
+% Copyright (C) 2011-2017 Dynare Team
+%
 % This file is part of Dynare.
 %
 % Dynare is free software: you can redistribute it and/or modify
@@ -45,7 +45,7 @@ function c = demean(x)
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 % Original author: stephane DOT adjemian AT univ DASH lemans DOT fr
-   
+
 if ndim(x)==1
     c = x-mean(x);
 elseif ndim(x)==2
diff --git a/matlab/utilities/general/disp_verbose.m b/matlab/utilities/general/disp_verbose.m
index 09c09e4d7e66ad001945c13aceadd84158f447c0..6ea4e702e55be49ffe82c0515362b8ac72a8a49b 100644
--- a/matlab/utilities/general/disp_verbose.m
+++ b/matlab/utilities/general/disp_verbose.m
@@ -1,8 +1,8 @@
 function disp_verbose(input_string,Verbose)
 % function disp_verbose(input_string,Verbose)
 % Prints input_string unless Verbose=0 is requested
-% 
-% Copyright (C) 2015 Dynare Team
+%
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/utilities/general/dyn_mex.m b/matlab/utilities/general/dyn_mex.m
index 7892ee9bed66ce2563e0f36443f820641ff895e2..ec682aebb90377373e28ddac82ac4f0d9d703ac0 100644
--- a/matlab/utilities/general/dyn_mex.m
+++ b/matlab/utilities/general/dyn_mex.m
@@ -1,21 +1,21 @@
 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 
+% if C file is fresher than mex file
 %
 % INPUTS
-%  o win_compiler  str  compiler used under Windows (unused under Linux or OSX): 
+%  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 
+%  o force         bool recompile if 1
+%
+% OUTPUTS
 %  none
 %
 
-    
-% Copyright (C) 2015-2016 Dynare Team
+
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -47,26 +47,26 @@ end
 if ~exist('OCTAVE_VERSION')
     % Some mex commands are enclosed in an eval(), because otherwise it will make Octave fail
     if ispc
-      if strcmp(win_compiler,'msvc')
-          % MATLAB/Windows + Microsoft Visual C++
-          % Add /TP flag as fix for #1227
-          eval(['mex -O LINKFLAGS="$LINKFLAGS /export:Dynamic" COMPFLAGS="/TP" ' basename '_dynamic.c ' basename '_dynamic_mex.c'])
-          eval(['mex -O LINKFLAGS="$LINKFLAGS /export:Static" COMPFLAGS="/TP" ' basename '_static.c ' basename '_static_mex.c'])
-      elseif strcmp(win_compiler,'mingw')
-          eval(['mex -O LINKFLAGS="$LINKFLAGS /export:Dynamic" ' basename '_dynamic.c ' basename '_dynamic_mex.c'])
-          eval(['mex -O LINKFLAGS="$LINKFLAGS /export:Static"  ' basename '_static.c ' basename '_static_mex.c'])
-      elseif strcmp(win_compiler,'cygwin') %legacy support for Cygwin with mexopts.bat
-          % 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'', ''mingw'' or ''msvc'' option to the ''dynare'' command'])
-      end
+        if strcmp(win_compiler,'msvc')
+            % MATLAB/Windows + Microsoft Visual C++
+            % Add /TP flag as fix for #1227
+            eval(['mex -O LINKFLAGS="$LINKFLAGS /export:Dynamic" COMPFLAGS="/TP" ' basename '_dynamic.c ' basename '_dynamic_mex.c'])
+            eval(['mex -O LINKFLAGS="$LINKFLAGS /export:Static" COMPFLAGS="/TP" ' basename '_static.c ' basename '_static_mex.c'])
+        elseif strcmp(win_compiler,'mingw')
+            eval(['mex -O LINKFLAGS="$LINKFLAGS /export:Dynamic" ' basename '_dynamic.c ' basename '_dynamic_mex.c'])
+            eval(['mex -O LINKFLAGS="$LINKFLAGS /export:Static"  ' basename '_static.c ' basename '_static_mex.c'])
+        elseif strcmp(win_compiler,'cygwin') %legacy support for Cygwin with mexopts.bat
+                                             % 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'', ''mingw'' or ''msvc'' option to the ''dynare'' command'])
+        end
     elseif isunix && ~ismac
         % MATLAB/Linux
         if matlab_ver_less_than('8.3')
diff --git a/matlab/utilities/general/get_all_variables_but_lagged_leaded_exogenous.m b/matlab/utilities/general/get_all_variables_but_lagged_leaded_exogenous.m
index 37697e723ebab5e61d2f49498ce022d358eb84e2..1e092e0ac0c58f50895ea21add5eed72a180f16a 100644
--- a/matlab/utilities/general/get_all_variables_but_lagged_leaded_exogenous.m
+++ b/matlab/utilities/general/get_all_variables_but_lagged_leaded_exogenous.m
@@ -9,8 +9,8 @@ function k = get_all_variables_but_lagged_leaded_exogenous(M)
 % k: vector of variable indices
 %
 
-% Copyright (C) 2011-2016 Dynare Team
-%    
+% Copyright (C) 2011-2017 Dynare Team
+%
 % This file is part of Dynare.
 %
 % Dynare is free software: you can redistribute it and/or modify
@@ -31,5 +31,5 @@ if isempty(M.aux_vars)
 else
     type = [M.aux_vars.type];
     k = [1:M.orig_endo_nbr, M.orig_endo_nbr ...
-         + find((type ~= 2) & (type ~= 3))]; 
+         + find((type ~= 2) & (type ~= 3))];
 end
\ No newline at end of file
diff --git a/matlab/utilities/general/indices_lagged_leaded_exogenous_variables.m b/matlab/utilities/general/indices_lagged_leaded_exogenous_variables.m
index 6b3f0b4161c39f57d7ea23ccf0cd1b64b92acf16..a199b4b0fbba51c919136a3c01c2498e13473d4b 100644
--- a/matlab/utilities/general/indices_lagged_leaded_exogenous_variables.m
+++ b/matlab/utilities/general/indices_lagged_leaded_exogenous_variables.m
@@ -12,8 +12,8 @@ function [il,l1,ik,k1] = indices_lagged_leaded_exogenous_variables(k,M)
 % ik: indices of non lagged or leaded variable in vector k
 % k1: value of non lagged or leaded variable in vector k
 
-% Copyright (C) 2011-2016 Dynare Team
-%    
+% Copyright (C) 2011-2017 Dynare Team
+%
 % This file is part of Dynare.
 %
 % Dynare is free software: you can redistribute it and/or modify
diff --git a/matlab/utilities/general/isaletter.m b/matlab/utilities/general/isaletter.m
index 054ced91dff7773ad760148452deacea6c4f64fa..f562a320ac95b410a00457344310f396cda1d8ea 100644
--- a/matlab/utilities/general/isaletter.m
+++ b/matlab/utilities/general/isaletter.m
@@ -1,7 +1,7 @@
 function info = isaletter(str)
 % Returns 1 if the string str has at least one letter, 0 otherwise.
 
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2014 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/utilities/general/isconst.m b/matlab/utilities/general/isconst.m
index 37ee235321def2cd0e4896453360ce77fd2e8920..28001ce4ec336400b3118a85ca8caf23eb0c5b88 100644
--- a/matlab/utilities/general/isconst.m
+++ b/matlab/utilities/general/isconst.m
@@ -1,6 +1,6 @@
 function aa = isconst(y)
 % Returns 1 if vector y is constant, 0 otherwise.
-%  
+%
 % INPUTS:
 %   yy        [double]    n*1 vector.
 %
@@ -10,7 +10,7 @@ function aa = isconst(y)
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2008-2009 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/utilities/general/isdiagonal.m b/matlab/utilities/general/isdiagonal.m
index f76e4379721684ead967f737d14dfeef6d12fba5..a8c1a4cf83963953974e81e0c3b019361d3d7d14 100644
--- a/matlab/utilities/general/isdiagonal.m
+++ b/matlab/utilities/general/isdiagonal.m
@@ -1,6 +1,6 @@
 function b = isdiagonal(A) % --*-- Unitary tests --*--
 
-% Copyright (C) 2014 Dynare Team
+% Copyright (C) 2014-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -60,5 +60,3 @@ end
 %$ t = isdiagonal(A);
 %$ T = all(t);
 %@eof:5
-
-
diff --git a/matlab/utilities/general/isestimation.m b/matlab/utilities/general/isestimation.m
index f86ffb32c92d04b5c1636b312a078236f2ac40c0..9e17d4b03a70a847067ba735e87f69f51df1f434 100644
--- a/matlab/utilities/general/isestimation.m
+++ b/matlab/utilities/general/isestimation.m
@@ -1,8 +1,8 @@
-function a = isestimation()
+function b = isestimation(option)
 
-% Returns 1 if we are currently estimating a model, 0 otherwise.
+% Returns true if we are currently estimating a model.
 
-% Copyright (C) 2014 Dynare Team
+% Copyright (C) 2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -19,14 +19,8 @@ function a = isestimation()
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-a = 0;
+b = false;
 
-tmp = struct2cell(dbstack);
-list_of_previously_called_routines = transpose(tmp(2,:));
-
-if ~isempty(strmatch('dsge_likelihood', list_of_previously_called_routines, 'exact')) || ...
-    ~isempty(strmatch('dsge_var_likelihood', list_of_previously_called_routines, 'exact')) || ...
-    ~isempty(strmatch('non_linear_dsge_likelihood', list_of_previously_called_routines, 'exact')) || ...
-    ~isempty(strmatch('simulated_moments_estimation', list_of_previously_called_routines, 'exact'))
-    a = 1;
+if ischar(option.mode_compute) || option.mode_compute || option.mh_replic
+    b = true;
 end
\ No newline at end of file
diff --git a/matlab/utilities/general/isinestimationobjective.m b/matlab/utilities/general/isinestimationobjective.m
new file mode 100644
index 0000000000000000000000000000000000000000..023e4cb14e77c29bffbeff747d3003ae15425651
--- /dev/null
+++ b/matlab/utilities/general/isinestimationobjective.m
@@ -0,0 +1,32 @@
+function b = isinestimationobjective()
+
+% Returns true iff the caller function is called by a routine defining the objective of an estimation algorithm.
+
+% Copyright (C) 2014-2017 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 = false;
+
+tmp = struct2cell(dbstack);
+list_of_previously_called_routines = transpose(tmp(2,:));
+
+if ~isempty(strmatch('dsge_likelihood', list_of_previously_called_routines, 'exact')) || ...
+        ~isempty(strmatch('dsge_var_likelihood', list_of_previously_called_routines, 'exact')) || ...
+        ~isempty(strmatch('non_linear_dsge_likelihood', list_of_previously_called_routines, 'exact')) || ...
+        ~isempty(strmatch('simulated_moments_estimation', list_of_previously_called_routines, 'exact'))
+    b = true;
+end
diff --git a/matlab/utilities/general/isint.m b/matlab/utilities/general/isint.m
index 9f59a5e9164494945b3d22b020039531fbb5eb80..c40ef792e6839f51b01387d0060433a0b759799a 100644
--- a/matlab/utilities/general/isint.m
+++ b/matlab/utilities/general/isint.m
@@ -1,21 +1,21 @@
 function [b,c,d] = isint(a)
 %  This function tests if the input argument is an integer.
 %
-%  INPUT 
+%  INPUT
 %    a    [double]   m*n matrix.
 %
-%  OUTPUT 
-%    b    [integer]  m*n matrix of 0 and 1. b(i,j)=1 if a(i,j) is an integer.    
+%  OUTPUT
+%    b    [integer]  m*n matrix of 0 and 1. b(i,j)=1 if a(i,j) is an integer.
 %    c    [integer]  p*1 vector of indices pointing to the integer elements of a.
 %    d    [integer]  q*1 vector of indices pointing to the non integer elements of a.
-%    
+%
 %  SPECIAL REQUIREMENTS
 %    None.
-%    
-%  NOTES 
+%
+%  NOTES
 %    p+q is equal to the product of m by n.
 
-% Copyright (C) 2009 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/utilities/general/ispd.m b/matlab/utilities/general/ispd.m
index e319a47a1f1c3a21ffb16829d8379bac880cab51..7ddd73e8af6aecad9011870916b03ebcb8d6f2f6 100644
--- a/matlab/utilities/general/ispd.m
+++ b/matlab/utilities/general/ispd.m
@@ -24,7 +24,7 @@ function [test, penalty] = ispd(A)
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2007-2009, 2013 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -44,7 +44,7 @@ function [test, penalty] = ispd(A)
 if ~isquare(A)
     error(['ispd:: Input argument ' inputname(1) ' has to be a square matrix!'])
 end
-    
+
 [cholA, info] = chol(A);
 test = ~info;
 
diff --git a/matlab/utilities/general/isquare.m b/matlab/utilities/general/isquare.m
index da47ac62e59a5b3454e0566d2b8b413daad5de32..693417c354894ab4b4b543cbdc14b29f942f7183 100644
--- a/matlab/utilities/general/isquare.m
+++ b/matlab/utilities/general/isquare.m
@@ -22,7 +22,7 @@ function info = isquare(A)
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2014 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/utilities/general/log_variable.m b/matlab/utilities/general/log_variable.m
index 74a6aa126d9f7b73e895663244280835a5f04c32..98956a77cf7793b947d890d1e818547c1a5301c9 100644
--- a/matlab/utilities/general/log_variable.m
+++ b/matlab/utilities/general/log_variable.m
@@ -12,8 +12,8 @@ function y = log_variable(ivar,x,M)
 %       for lagged/leaded exogenous variables
 %
 
-% Copyright (C) 2011-2016 Dynare Team
-%    
+% Copyright (C) 2011-2017 Dynare Team
+%
 % This file is part of Dynare.
 %
 % Dynare is free software: you can redistribute it and/or modify
diff --git a/matlab/utilities/general/ndim.m b/matlab/utilities/general/ndim.m
index 1c4d003bb823f1d61aecb84c86f2a31332d29c4d..95dda019d0c2062cc1dce21092cf3e00f0d57af2 100644
--- a/matlab/utilities/general/ndim.m
+++ b/matlab/utilities/general/ndim.m
@@ -3,7 +3,7 @@ function n = ndim(x)
 
 %@info:
 %! @deftypefn {Function File} {@var{n} =} ndim (@var{x})
-%! @anchor{ndim}    
+%! @anchor{ndim}
 %! This function reports the number of non singleton dimensions of a matlab array.
 %!
 %! @strong{Inputs}
@@ -17,18 +17,18 @@ function n = ndim(x)
 %! @item n
 %! Integer scalar. The number of non singleton dimensions of a matlab array.
 %! @end table
-%!    
-%! @strong{This function is called by:} 
+%!
+%! @strong{This function is called by:}
 %! @ref{demean}, @ref{nandemean}.
-%!    
+%!
 %! @strong{This function calls:}
 %! none.
-%!    
+%!
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2011-2012 Dynare Team
-%    
+% Copyright (C) 2011-2017 Dynare Team
+%
 % This file is part of Dynare.
 %
 % Dynare is free software: you can redistribute it and/or modify
diff --git a/matlab/utilities/general/remove_fractional_xticks.m b/matlab/utilities/general/remove_fractional_xticks.m
index 19eab7a044b873f1c512e80fd66ba2410e31b791..5cf6f33fda5252f7c0cdd01aeda3743eda4d12da 100644
--- a/matlab/utilities/general/remove_fractional_xticks.m
+++ b/matlab/utilities/general/remove_fractional_xticks.m
@@ -2,7 +2,7 @@ function remove_fractional_xticks
 % function remove_fractional_xticks
 % removes non-integer xtick-labels
 
-% Copyright (C) 2001-2016 Dynare Team
+% Copyright (C) 2001-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -17,7 +17,7 @@ function remove_fractional_xticks
 % 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/>.
 
 xticks=get(gca,'xtick');
 fractional_periods=find(rem(xticks,1)~=0);
diff --git a/matlab/utilities/graphics/colorspace.m b/matlab/utilities/graphics/colorspace.m
new file mode 100644
index 0000000000000000000000000000000000000000..a83aee2ffaffe11b44cbb90e3b9949b458ccbfae
--- /dev/null
+++ b/matlab/utilities/graphics/colorspace.m
@@ -0,0 +1,508 @@
+function varargout = colorspace(Conversion,varargin)
+%COLORSPACE  Transform a color image between color representations.
+%   B = COLORSPACE(S,A) transforms the color representation of image A
+%   where S is a string specifying the conversion.  The input array A
+%   should be a real full double array of size Mx3 or MxNx3.  The output B
+%   is the same size as A.
+%
+%   S tells the source and destination color spaces, S = 'dest<-src', or
+%   alternatively, S = 'src->dest'.  Supported color spaces are
+%
+%     'RGB'              sRGB IEC 61966-2-1
+%     'YCbCr'            Luma + Chroma ("digitized" version of Y'PbPr)
+%     'JPEG-YCbCr'       Luma + Chroma space used in JFIF JPEG
+%     'YDbDr'            SECAM Y'DbDr Luma + Chroma
+%     'YPbPr'            Luma (ITU-R BT.601) + Chroma
+%     'YUV'              NTSC PAL Y'UV Luma + Chroma
+%     'YIQ'              NTSC Y'IQ Luma + Chroma
+%     'HSV' or 'HSB'     Hue Saturation Value/Brightness
+%     'HSL' or 'HLS'     Hue Saturation Luminance
+%     'HSI'              Hue Saturation Intensity
+%     'XYZ'              CIE 1931 XYZ
+%     'Lab'              CIE 1976 L*a*b* (CIELAB)
+%     'Luv'              CIE L*u*v* (CIELUV)
+%     'LCH'              CIE L*C*H* (CIELCH)
+%     'CAT02 LMS'        CIE CAT02 LMS
+%
+%  All conversions assume 2 degree observer and D65 illuminant.
+%
+%  Color space names are case insensitive and spaces are ignored.  When
+%  sRGB is the source or destination, it can be omitted. For example
+%  'yuv<-' is short for 'yuv<-rgb'.
+%
+%  For sRGB, the values should be scaled between 0 and 1.  Beware that
+%  transformations generally do not constrain colors to be "in gamut."
+%  Particularly, transforming from another space to sRGB may obtain
+%  R'G'B' values outside of the [0,1] range.  So the result should be
+%  clamped to [0,1] before displaying:
+%     image(min(max(B,0),1));  % Clamp B to [0,1] and display
+%
+%  sRGB (Red Green Blue) is the (ITU-R BT.709 gamma-corrected) standard
+%  red-green-blue representation of colors used in digital imaging.  The
+%  components should be scaled between 0 and 1.  The space can be
+%  visualized geometrically as a cube.
+%
+%  Y'PbPr, Y'CbCr, Y'DbDr, Y'UV, and Y'IQ are related to sRGB by linear
+%  transformations.  These spaces separate a color into a grayscale
+%  luminance component Y and two chroma components.  The valid ranges of
+%  the components depends on the space.
+%
+%  HSV (Hue Saturation Value) is related to sRGB by
+%     H = hexagonal hue angle   (0 <= H < 360),
+%     S = C/V                   (0 <= S <= 1),
+%     V = max(R',G',B')         (0 <= V <= 1),
+%  where C = max(R',G',B') - min(R',G',B').  The hue angle H is computed on
+%  a hexagon.  The space is geometrically a hexagonal cone.
+%
+%  HSL (Hue Saturation Lightness) is related to sRGB by
+%     H = hexagonal hue angle                (0 <= H < 360),
+%     S = C/(1 - |2L-1|)                     (0 <= S <= 1),
+%     L = (max(R',G',B') + min(R',G',B'))/2  (0 <= L <= 1),
+%  where H and C are the same as in HSV.  Geometrically, the space is a
+%  double hexagonal cone.
+%
+%  HSI (Hue Saturation Intensity) is related to sRGB by
+%     H = polar hue angle        (0 <= H < 360),
+%     S = 1 - min(R',G',B')/I    (0 <= S <= 1),
+%     I = (R'+G'+B')/3           (0 <= I <= 1).
+%  Unlike HSV and HSL, the hue angle H is computed on a circle rather than
+%  a hexagon.
+%
+%  CIE XYZ is related to sRGB by inverse gamma correction followed by a
+%  linear transform.  Other CIE color spaces are defined relative to XYZ.
+%
+%  CIE L*a*b*, L*u*v*, and L*C*H* are nonlinear functions of XYZ.  The L*
+%  component is designed to match closely with human perception of
+%  lightness.  The other two components describe the chroma.
+%
+%  CIE CAT02 LMS is the linear transformation of XYZ using the MCAT02
+%  chromatic adaptation matrix.  The space is designed to model the
+%  response of the three types of cones in the human eye, where L, M, S,
+%  correspond respectively to red ("long"), green ("medium"), and blue
+%  ("short").
+
+% Copyright (C) 2005-2010 Pascal Getreuer
+% Copyright (C) 2017 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/>.
+
+%%% Input parsing %%%
+if nargin < 2, error('Not enough input arguments.'); end
+[SrcSpace,DestSpace] = parse(Conversion);
+
+if nargin == 2
+    Image = varargin{1};
+elseif nargin >= 3
+    Image = cat(3,varargin{:});
+else
+    error('Invalid number of input arguments.');
+end
+
+FlipDims = (size(Image,3) == 1);
+
+if FlipDims, Image = permute(Image,[1,3,2]); end
+if ~isa(Image,'double'), Image = double(Image)/255; end
+if size(Image,3) ~= 3, error('Invalid input size.'); end
+
+SrcT = gettransform(SrcSpace);
+DestT = gettransform(DestSpace);
+
+if ~ischar(SrcT) && ~ischar(DestT)
+    % Both source and destination transforms are affine, so they
+    % can be composed into one affine operation
+    T = [DestT(:,1:3)*SrcT(:,1:3),DestT(:,1:3)*SrcT(:,4)+DestT(:,4)];
+    Temp = zeros(size(Image));
+    Temp(:,:,1) = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10);
+    Temp(:,:,2) = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11);
+    Temp(:,:,3) = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3) + T(12);
+    Image = Temp;
+elseif ~ischar(DestT)
+    Image = rgb(Image,SrcSpace);
+    Temp = zeros(size(Image));
+    Temp(:,:,1) = DestT(1)*Image(:,:,1) + DestT(4)*Image(:,:,2) + DestT(7)*Image(:,:,3) + DestT(10);
+    Temp(:,:,2) = DestT(2)*Image(:,:,1) + DestT(5)*Image(:,:,2) + DestT(8)*Image(:,:,3) + DestT(11);
+    Temp(:,:,3) = DestT(3)*Image(:,:,1) + DestT(6)*Image(:,:,2) + DestT(9)*Image(:,:,3) + DestT(12);
+    Image = Temp;
+else
+    Image = feval(DestT,Image,SrcSpace);
+end
+
+%%% Output format %%%
+if nargout > 1
+    varargout = {Image(:,:,1),Image(:,:,2),Image(:,:,3)};
+else
+    if FlipDims, Image = permute(Image,[1,3,2]); end
+    varargout = {Image};
+end
+
+return
+
+
+function [SrcSpace,DestSpace] = parse(Str)
+% Parse conversion argument
+
+if ischar(Str)
+    Str = lower(strrep(strrep(Str,'-',''),'=',''));
+    k = find(Str == '>');
+
+    if length(k) == 1         % Interpret the form 'src->dest'
+        SrcSpace = Str(1:k-1);
+        DestSpace = Str(k+1:end);
+    else
+        k = find(Str == '<');
+
+        if length(k) == 1      % Interpret the form 'dest<-src'
+            DestSpace = Str(1:k-1);
+            SrcSpace = Str(k+1:end);
+        else
+            error(['Invalid conversion, ''',Str,'''.']);
+        end
+    end
+
+    SrcSpace = alias(SrcSpace);
+    DestSpace = alias(DestSpace);
+else
+    SrcSpace = 1;             % No source pre-transform
+    DestSpace = Conversion;
+    if any(size(Conversion) ~= 3), error('Transformation matrix must be 3x3.'); end
+end
+return
+
+
+function Space = alias(Space)
+Space = strrep(strrep(Space,'cie',''),' ','');
+
+if isempty(Space)
+    Space = 'rgb';
+end
+
+switch Space
+  case {'ycbcr','ycc'}
+    Space = 'ycbcr';
+  case {'hsv','hsb'}
+    Space = 'hsv';
+  case {'hsl','hsi','hls'}
+    Space = 'hsl';
+  case {'rgb','yuv','yiq','ydbdr','ycbcr','jpegycbcr','xyz','lab','luv','lch'}
+    return
+end
+return
+
+
+function T = gettransform(Space)
+% Get a colorspace transform: either a matrix describing an affine transform,
+% or a string referring to a conversion subroutine
+switch Space
+  case 'ypbpr'
+    T = [0.299,0.587,0.114,0;-0.1687367,-0.331264,0.5,0;0.5,-0.418688,-0.081312,0];
+  case 'yuv'
+    % sRGB to NTSC/PAL YUV
+    % Wikipedia: http://en.wikipedia.org/wiki/YUV
+    T = [0.299,0.587,0.114,0;-0.147,-0.289,0.436,0;0.615,-0.515,-0.100,0];
+  case 'ydbdr'
+    % sRGB to SECAM YDbDr
+    % Wikipedia: http://en.wikipedia.org/wiki/YDbDr
+    T = [0.299,0.587,0.114,0;-0.450,-0.883,1.333,0;-1.333,1.116,0.217,0];
+  case 'yiq'
+    % sRGB in [0,1] to NTSC YIQ in [0,1];[-0.595716,0.595716];[-0.522591,0.522591];
+    % Wikipedia: http://en.wikipedia.org/wiki/YIQ
+    T = [0.299,0.587,0.114,0;0.595716,-0.274453,-0.321263,0;0.211456,-0.522591,0.311135,0];
+  case 'ycbcr'
+    % sRGB (range [0,1]) to ITU-R BRT.601 (CCIR 601) Y'CbCr
+    % Wikipedia: http://en.wikipedia.org/wiki/YCbCr
+    % Poynton, Equation 3, scaling of R'G'B to Y'PbPr conversion
+    T = [65.481,128.553,24.966,16;-37.797,-74.203,112.0,128;112.0,-93.786,-18.214,128];
+  case 'jpegycbcr'
+    % Wikipedia: http://en.wikipedia.org/wiki/YCbCr
+    T = [0.299,0.587,0.114,0;-0.168736,-0.331264,0.5,0.5;0.5,-0.418688,-0.081312,0.5]*255;
+  case {'rgb','xyz','hsv','hsl','lab','luv','lch','cat02lms'}
+    T = Space;
+  otherwise
+    error(['Unknown color space, ''',Space,'''.']);
+end
+return
+
+
+function Image = rgb(Image,SrcSpace)
+% Convert to sRGB from 'SrcSpace'
+switch SrcSpace
+  case 'rgb'
+    return
+  case 'hsv'
+    % Convert HSV to sRGB
+    Image = huetorgb((1 - Image(:,:,2)).*Image(:,:,3),Image(:,:,3),Image(:,:,1));
+  case 'hsl'
+    % Convert HSL to sRGB
+    L = Image(:,:,3);
+    Delta = Image(:,:,2).*min(L,1-L);
+    Image = huetorgb(L-Delta,L+Delta,Image(:,:,1));
+  case {'xyz','lab','luv','lch','cat02lms'}
+    % Convert to CIE XYZ
+    Image = xyz(Image,SrcSpace);
+    % Convert XYZ to RGB
+    T = [3.2406, -1.5372, -0.4986; -0.9689, 1.8758, 0.0415; 0.0557, -0.2040, 1.057];
+    R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3);  % R
+    G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3);  % G
+    B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3);  % B
+                                                                    % Desaturate and rescale to constrain resulting RGB values to [0,1]
+    AddWhite = -min(min(min(R,G),B),0);
+    R = R + AddWhite;
+    G = G + AddWhite;
+    B = B + AddWhite;
+    % Apply gamma correction to convert linear RGB to sRGB
+    Image(:,:,1) = gammacorrection(R);  % R'
+    Image(:,:,2) = gammacorrection(G);  % G'
+    Image(:,:,3) = gammacorrection(B);  % B'
+  otherwise  % Conversion is through an affine transform
+    T = gettransform(SrcSpace);
+    temp = inv(T(:,1:3));
+    T = [temp,-temp*T(:,4)];
+    R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10);
+    G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11);
+    B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3) + T(12);
+    Image(:,:,1) = R;
+    Image(:,:,2) = G;
+    Image(:,:,3) = B;
+end
+
+% Clip to [0,1]
+Image = min(max(Image,0),1);
+return
+
+
+function Image = xyz(Image,SrcSpace)
+% Convert to CIE XYZ from 'SrcSpace'
+WhitePoint = [0.950456,1,1.088754];
+
+switch SrcSpace
+  case 'xyz'
+    return
+  case 'luv'
+    % Convert CIE L*uv to XYZ
+    WhitePointU = (4*WhitePoint(1))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));
+    WhitePointV = (9*WhitePoint(2))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));
+    L = Image(:,:,1);
+    Y = (L + 16)/116;
+    Y = invf(Y)*WhitePoint(2);
+    U = Image(:,:,2)./(13*L + 1e-6*(L==0)) + WhitePointU;
+    V = Image(:,:,3)./(13*L + 1e-6*(L==0)) + WhitePointV;
+    Image(:,:,1) = -(9*Y.*U)./((U-4).*V - U.*V);                  % X
+    Image(:,:,2) = Y;                                             % Y
+    Image(:,:,3) = (9*Y - (15*V.*Y) - (V.*Image(:,:,1)))./(3*V);  % Z
+  case {'lab','lch'}
+    Image = lab(Image,SrcSpace);
+    % Convert CIE L*ab to XYZ
+    fY = (Image(:,:,1) + 16)/116;
+    fX = fY + Image(:,:,2)/500;
+    fZ = fY - Image(:,:,3)/200;
+    Image(:,:,1) = WhitePoint(1)*invf(fX);  % X
+    Image(:,:,2) = WhitePoint(2)*invf(fY);  % Y
+    Image(:,:,3) = WhitePoint(3)*invf(fZ);  % Z
+  case 'cat02lms'
+    % Convert CAT02 LMS to XYZ
+    T = inv([0.7328, 0.4296, -0.1624;-0.7036, 1.6975, 0.0061; 0.0030, 0.0136, 0.9834]);
+    L = Image(:,:,1);
+    M = Image(:,:,2);
+    S = Image(:,:,3);
+    Image(:,:,1) = T(1)*L + T(4)*M + T(7)*S;  % X
+    Image(:,:,2) = T(2)*L + T(5)*M + T(8)*S;  % Y
+    Image(:,:,3) = T(3)*L + T(6)*M + T(9)*S;  % Z
+  otherwise   % Convert from some gamma-corrected space
+              % Convert to sRGB
+    Image = rgb(Image,SrcSpace);
+    % Undo gamma correction
+    R = invgammacorrection(Image(:,:,1));
+    G = invgammacorrection(Image(:,:,2));
+    B = invgammacorrection(Image(:,:,3));
+    % Convert RGB to XYZ
+    T = inv([3.2406, -1.5372, -0.4986; -0.9689, 1.8758, 0.0415; 0.0557, -0.2040, 1.057]);
+    Image(:,:,1) = T(1)*R + T(4)*G + T(7)*B;  % X
+    Image(:,:,2) = T(2)*R + T(5)*G + T(8)*B;  % Y
+    Image(:,:,3) = T(3)*R + T(6)*G + T(9)*B;  % Z
+end
+return
+
+
+function Image = hsv(Image,SrcSpace)
+% Convert to HSV
+Image = rgb(Image,SrcSpace);
+V = max(Image,[],3);
+S = (V - min(Image,[],3))./(V + (V == 0));
+Image(:,:,1) = rgbtohue(Image);
+Image(:,:,2) = S;
+Image(:,:,3) = V;
+return
+
+
+function Image = hsl(Image,SrcSpace)
+% Convert to HSL
+switch SrcSpace
+  case 'hsv'
+    % Convert HSV to HSL
+    MaxVal = Image(:,:,3);
+    MinVal = (1 - Image(:,:,2)).*MaxVal;
+    L = 0.5*(MaxVal + MinVal);
+    temp = min(L,1-L);
+    Image(:,:,2) = 0.5*(MaxVal - MinVal)./(temp + (temp == 0));
+    Image(:,:,3) = L;
+  otherwise
+    Image = rgb(Image,SrcSpace);  % Convert to sRGB
+                                  % Convert sRGB to HSL
+    MinVal = min(Image,[],3);
+    MaxVal = max(Image,[],3);
+    L = 0.5*(MaxVal + MinVal);
+    temp = min(L,1-L);
+    S = 0.5*(MaxVal - MinVal)./(temp + (temp == 0));
+    Image(:,:,1) = rgbtohue(Image);
+    Image(:,:,2) = S;
+    Image(:,:,3) = L;
+end
+return
+
+
+function Image = lab(Image,SrcSpace)
+% Convert to CIE L*a*b* (CIELAB)
+WhitePoint = [0.950456,1,1.088754];
+
+switch SrcSpace
+  case 'lab'
+    return
+  case 'lch'
+    % Convert CIE L*CH to CIE L*ab
+    C = Image(:,:,2);
+    Image(:,:,2) = cos(Image(:,:,3)*pi/180).*C;  % a*
+    Image(:,:,3) = sin(Image(:,:,3)*pi/180).*C;  % b*
+  otherwise
+    Image = xyz(Image,SrcSpace);  % Convert to XYZ
+                                  % Convert XYZ to CIE L*a*b*
+    X = Image(:,:,1)/WhitePoint(1);
+    Y = Image(:,:,2)/WhitePoint(2);
+    Z = Image(:,:,3)/WhitePoint(3);
+    fX = f(X);
+    fY = f(Y);
+    fZ = f(Z);
+    Image(:,:,1) = 116*fY - 16;    % L*
+    Image(:,:,2) = 500*(fX - fY);  % a*
+    Image(:,:,3) = 200*(fY - fZ);  % b*
+end
+return
+
+
+function Image = luv(Image,SrcSpace)
+% Convert to CIE L*u*v* (CIELUV)
+WhitePoint = [0.950456,1,1.088754];
+WhitePointU = (4*WhitePoint(1))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));
+WhitePointV = (9*WhitePoint(2))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));
+
+Image = xyz(Image,SrcSpace); % Convert to XYZ
+Denom = Image(:,:,1) + 15*Image(:,:,2) + 3*Image(:,:,3);
+U = (4*Image(:,:,1))./(Denom + (Denom == 0));
+V = (9*Image(:,:,2))./(Denom + (Denom == 0));
+Y = Image(:,:,2)/WhitePoint(2);
+L = 116*f(Y) - 16;
+Image(:,:,1) = L;                        % L*
+Image(:,:,2) = 13*L.*(U - WhitePointU);  % u*
+Image(:,:,3) = 13*L.*(V - WhitePointV);  % v*
+return
+
+
+function Image = lch(Image,SrcSpace)
+% Convert to CIE L*ch
+Image = lab(Image,SrcSpace);  % Convert to CIE L*ab
+H = atan2(Image(:,:,3),Image(:,:,2));
+H = H*180/pi + 360*(H < 0);
+Image(:,:,2) = sqrt(Image(:,:,2).^2 + Image(:,:,3).^2);  % C
+Image(:,:,3) = H;                                        % H
+return
+
+
+function Image = cat02lms(Image,SrcSpace)
+% Convert to CAT02 LMS
+Image = xyz(Image,SrcSpace);
+T = [0.7328, 0.4296, -0.1624;-0.7036, 1.6975, 0.0061; 0.0030, 0.0136, 0.9834];
+X = Image(:,:,1);
+Y = Image(:,:,2);
+Z = Image(:,:,3);
+Image(:,:,1) = T(1)*X + T(4)*Y + T(7)*Z;  % L
+Image(:,:,2) = T(2)*X + T(5)*Y + T(8)*Z;  % M
+Image(:,:,3) = T(3)*X + T(6)*Y + T(9)*Z;  % S
+return
+
+
+function Image = huetorgb(m0,m2,H)
+% Convert HSV or HSL hue to RGB
+N = size(H);
+H = min(max(H(:),0),360)/60;
+m0 = m0(:);
+m2 = m2(:);
+F = H - round(H/2)*2;
+M = [m0, m0 + (m2-m0).*abs(F), m2];
+Num = length(m0);
+j = [2 1 0;1 2 0;0 2 1;0 1 2;1 0 2;2 0 1;2 1 0]*Num;
+k = floor(H) + 1;
+Image = reshape([M(j(k,1)+(1:Num).'),M(j(k,2)+(1:Num).'),M(j(k,3)+(1:Num).')],[N,3]);
+return
+
+
+function H = rgbtohue(Image)
+% Convert RGB to HSV or HSL hue
+[M,i] = sort(Image,3);
+i = i(:,:,3);
+Delta = M(:,:,3) - M(:,:,1);
+Delta = Delta + (Delta == 0);
+R = Image(:,:,1);
+G = Image(:,:,2);
+B = Image(:,:,3);
+H = zeros(size(R));
+k = (i == 1);
+H(k) = (G(k) - B(k))./Delta(k);
+k = (i == 2);
+H(k) = 2 + (B(k) - R(k))./Delta(k);
+k = (i == 3);
+H(k) = 4 + (R(k) - G(k))./Delta(k);
+H = 60*H + 360*(H < 0);
+H(Delta == 0) = nan;
+return
+
+
+function Rp = gammacorrection(R)
+Rp = zeros(size(R));
+i = (R <= 0.0031306684425005883);
+Rp(i) = 12.92*R(i);
+Rp(~i) = real(1.055*R(~i).^0.416666666666666667 - 0.055);
+return
+
+
+function R = invgammacorrection(Rp)
+R = zeros(size(Rp));
+i = (Rp <= 0.0404482362771076);
+R(i) = Rp(i)/12.92;
+R(~i) = real(((Rp(~i) + 0.055)/1.055).^2.4);
+return
+
+
+function fY = f(Y)
+fY = real(Y.^(1/3));
+i = (Y < 0.008856);
+fY(i) = Y(i)*(841/108) + (4/29);
+return
+
+
+function Y = invf(fY)
+Y = fY.^3;
+i = (Y < 0.008856);
+Y(i) = (fY(i) - 4/29)*(108/841);
+return
diff --git a/matlab/utilities/graphics/distinguishable_colors.m b/matlab/utilities/graphics/distinguishable_colors.m
new file mode 100644
index 0000000000000000000000000000000000000000..027ad2cb6478feac11cebbb4632e5c873f881c7e
--- /dev/null
+++ b/matlab/utilities/graphics/distinguishable_colors.m
@@ -0,0 +1,168 @@
+function colors = distinguishable_colors(n_colors,bg,func)
+% DISTINGUISHABLE_COLORS: pick colors that are maximally perceptually distinct
+%
+% When plotting a set of lines, you may want to distinguish them by color.
+% By default, Matlab chooses a small set of colors and cycles among them,
+% and so if you have more than a few lines there will be confusion about
+% which line is which. To fix this problem, one would want to be able to
+% pick a much larger set of distinct colors, where the number of colors
+% equals or exceeds the number of lines you want to plot. Because our
+% ability to distinguish among colors has limits, one should choose these
+% colors to be "maximally perceptually distinguishable."
+%
+% This function generates a set of colors which are distinguishable
+% by reference to the "Lab" color space, which more closely matches
+% human color perception than RGB. Given an initial large list of possible
+% colors, it iteratively chooses the entry in the list that is farthest (in
+% Lab space) from all previously-chosen entries. While this "greedy"
+% algorithm does not yield a global maximum, it is simple and efficient.
+% Moreover, the sequence of colors is consistent no matter how many you
+% request, which facilitates the users' ability to learn the color order
+% and avoids major changes in the appearance of plots when adding or
+% removing lines.
+%
+% Syntax:
+%   colors = distinguishable_colors(n_colors)
+% Specify the number of colors you want as a scalar, n_colors. This will
+% generate an n_colors-by-3 matrix, each row representing an RGB
+% color triple. If you don't precisely know how many you will need in
+% advance, there is no harm (other than execution time) in specifying
+% slightly more than you think you will need.
+%
+%   colors = distinguishable_colors(n_colors,bg)
+% This syntax allows you to specify the background color, to make sure that
+% your colors are also distinguishable from the background. Default value
+% is white. bg may be specified as an RGB triple or as one of the standard
+% "ColorSpec" strings. You can even specify multiple colors:
+%     bg = {'w','k'}
+% or
+%     bg = [1 1 1; 0 0 0]
+% will only produce colors that are distinguishable from both white and
+% black.
+%
+%   colors = distinguishable_colors(n_colors,bg,rgb2labfunc)
+% By default, distinguishable_colors uses the image processing toolbox's
+% color conversion functions makecform and applycform. Alternatively, you
+% can supply your own color conversion function.
+%
+% Example:
+%   c = distinguishable_colors(25);
+%   figure
+%   image(reshape(c,[1 size(c)]))
+%
+% Example using the file exchange's 'colorspace':
+%   func = @(x) colorspace('RGB->Lab',x);
+%   c = distinguishable_colors(25,'w',func);
+    
+% Copyright (C) 2005-2010 2010-2011 by Timothy E. Holy
+% Copyright (C) 2017 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/>.
+
+% Parse the inputs
+if (nargin < 2)
+    bg = [1 1 1];  % default white background
+else
+    if iscell(bg)
+        % User specified a list of colors as a cell aray
+        bgc = bg;
+        for i = 1:length(bgc)
+            bgc{i} = parsecolor(bgc{i});
+        end
+        bg = cat(1,bgc{:});
+    else
+        % User specified a numeric array of colors (n-by-3)
+        bg = parsecolor(bg);
+    end
+end
+
+% Generate a sizable number of RGB triples. This represents our space of
+% possible choices. By starting in RGB space, we ensure that all of the
+% colors can be generated by the monitor.
+n_grid = 30;  % number of grid divisions along each axis in RGB space
+x = linspace(0,1,n_grid);
+[R,G,B] = ndgrid(x,x,x);
+rgb = [R(:) G(:) B(:)];
+if (n_colors > size(rgb,1)/3)
+    error('You can''t readily distinguish that many colors');
+end
+
+% Convert to Lab color space, which more closely represents human
+% perception
+if (nargin > 2)
+    lab = func(rgb);
+    bglab = func(bg);
+else
+    C = makecform('srgb2lab');
+    lab = applycform(rgb,C);
+    bglab = applycform(bg,C);
+end
+
+% If the user specified multiple background colors, compute distances
+% from the candidate colors to the background colors
+mindist2 = inf(size(rgb,1),1);
+for i = 1:size(bglab,1)-1
+    dX = bsxfun(@minus,lab,bglab(i,:)); % displacement all colors from bg
+    dist2 = sum(dX.^2,2);  % square distance
+    mindist2 = min(dist2,mindist2);  % dist2 to closest previously-chosen color
+end
+
+% Iteratively pick the color that maximizes the distance to the nearest
+% already-picked color
+colors = zeros(n_colors,3);
+lastlab = bglab(end,:);   % initialize by making the "previous" color equal to background
+for i = 1:n_colors
+    dX = bsxfun(@minus,lab,lastlab); % displacement of last from all colors on list
+    dist2 = sum(dX.^2,2);  % square distance
+    mindist2 = min(dist2,mindist2);  % dist2 to closest previously-chosen color
+    [~,index] = max(mindist2);  % find the entry farthest from all previously-chosen colors
+    colors(i,:) = rgb(index,:);  % save for output
+    lastlab = lab(index,:);  % prepare for next iteration
+end
+end
+
+function c = parsecolor(s)
+if ischar(s)
+    c = colorstr2rgb(s);
+elseif isnumeric(s) && size(s,2) == 3
+    c = s;
+else
+    error('MATLAB:InvalidColorSpec','Color specification cannot be parsed.');
+end
+end
+
+function c = colorstr2rgb(c)
+% Convert a color string to an RGB value.
+% This is cribbed from Matlab's whitebg function.
+% Why don't they make this a stand-alone function?
+rgbspec = [1 0 0;0 1 0;0 0 1;1 1 1;0 1 1;1 0 1;1 1 0;0 0 0];
+cspec = 'rgbwcmyk';
+k = find(cspec==c(1));
+if isempty(k)
+    error('MATLAB:InvalidColorString','Unknown color string.');
+end
+if k~=3 || length(c)==1
+    c = rgbspec(k,:);
+elseif length(c)>2
+    if strcmpi(c(1:3),'bla')
+        c = [0 0 0];
+    elseif strcmpi(c(1:3),'blu')
+        c = [0 0 1];
+    else
+        error('MATLAB:UnknownColorString', 'Unknown color string.');
+    end
+end
+end
diff --git a/matlab/utilities/tests b/matlab/utilities/tests
index b2a8b9c059b1e2cb119e8d5fa92b4388fd93c9dd..fe65c7727f4d1b91355b62b2cc58f5775c287afd 160000
--- a/matlab/utilities/tests
+++ b/matlab/utilities/tests
@@ -1 +1 @@
-Subproject commit b2a8b9c059b1e2cb119e8d5fa92b4388fd93c9dd
+Subproject commit fe65c7727f4d1b91355b62b2cc58f5775c287afd
diff --git a/matlab/variance_decomposition_mc_analysis.m b/matlab/variance_decomposition_mc_analysis.m
index cfaf71c9a4476df6d10d5d1a2f063e4c3f2fe1d9..4621f25d317a6dc65a0b7080120219a2cbae9005 100644
--- a/matlab/variance_decomposition_mc_analysis.m
+++ b/matlab/variance_decomposition_mc_analysis.m
@@ -25,7 +25,7 @@ function oo_ = variance_decomposition_mc_analysis(NumberOfSimulations,type,dname
 
 
 
-% Copyright (C) 2008-2013 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -94,7 +94,7 @@ if options_.estimation.moments_posterior_density.indicator
         posterior_moments(tmp,1,mh_conf_sig);
 else
     [p_mean, p_median, p_var, hpd_interval, p_deciles] = ...
-        posterior_moments(tmp,0,mh_conf_sig);        
+        posterior_moments(tmp,0,mh_conf_sig);
 end
 
 oo_.([TYPE, 'TheoreticalMoments']).dsge.VarianceDecomposition.Mean.(var).(exo) = p_mean;
diff --git a/matlab/varlist_indices.m b/matlab/varlist_indices.m
index 1299e54d57e13ea4a589a6df05085e2e77bfb777..4347f9af423ab6116269947bd611750ab9fbf5d6 100644
--- a/matlab/varlist_indices.m
+++ b/matlab/varlist_indices.m
@@ -1,10 +1,10 @@
 function [i_var,nvar,index_uniques] = varlist_indices(sublist,list)
-% function [i_var,nvar] = varlist_indices(sublist,list)
+% function [i_var,nvar,index_uniques] = varlist_indices(sublist,list)
 % returns the indices of a list of endogenous variables
 %
 % INPUT
 %   sublist:    sublist of variables
-%   list:       list of variables 
+%   list:       list of variables
 %
 % OUTPUT
 %   i_var:      variable indices in M_.endo_names
@@ -14,7 +14,7 @@ function [i_var,nvar,index_uniques] = varlist_indices(sublist,list)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2010-2014 Dynare Team
+% Copyright (C) 2010-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/ver_greater_than.m b/matlab/ver_greater_than.m
index 1fef34bf281ac1cadb90ac14ee6647f30fb671e6..7bd973f45befa4d3d0c873456b5f2f78107a07db 100644
--- a/matlab/ver_greater_than.m
+++ b/matlab/ver_greater_than.m
@@ -12,7 +12,7 @@ function tf = ver_greater_than(ver1, ver2)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -36,27 +36,27 @@ ver2 = strsplit(ver2, {'.', '-'});
 maj_ver1 = str2double(ver1{1});
 maj_ver2 = str2double(ver2{1});
 if maj_ver1 > maj_ver2
-    return;
+    return
 end
 
 min_ver1 = str2double(ver1{2});
 min_ver2 = str2double(ver2{2});
 if (maj_ver1 == maj_ver2) && (min_ver1 > min_ver2)
-    return;
+    return
 end
 
 if (length(ver1) == length(ver2) && length(ver1) == 3)
     ismaster1 = isnan(str2double(ver1{3}));
     ismaster2 = isnan(str2double(ver2{3}));
     if (maj_ver1 == maj_ver2) && (min_ver1 == min_ver2) && (ismaster1 && ~ismaster2)
-        return;
+        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;
+            return
         end
     end
 end
diff --git a/matlab/ver_less_than.m b/matlab/ver_less_than.m
index e953ed8a2901d5dc56d23f2f243eade27e0ffcf7..c71d163bee7000433fa2a8b23bc204274f7d953d 100644
--- a/matlab/ver_less_than.m
+++ b/matlab/ver_less_than.m
@@ -12,7 +12,7 @@ function tf = ver_less_than(ver1, ver2)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -36,27 +36,27 @@ ver2 = strsplit(ver2, {'.', '-'});
 maj_ver1 = str2double(ver1{1});
 maj_ver2 = str2double(ver2{1});
 if maj_ver1 < maj_ver2
-    return;
+    return
 end
 
 min_ver1 = str2double(ver1{2});
 min_ver2 = str2double(ver2{2});
 if (maj_ver1 == maj_ver2) && (min_ver1 < min_ver2)
-    return;
+    return
 end
 
 if (length(ver1) == length(ver2) && length(ver1) == 3)
     ismaster1 = isnan(str2double(ver1{3}));
     ismaster2 = isnan(str2double(ver2{3}));
     if (maj_ver1 == maj_ver2) && (min_ver1 == min_ver2) && (~ismaster1 && ismaster2)
-        return;
+        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;
+            return
         end
     end
 end
diff --git a/matlab/vnorm.m b/matlab/vnorm.m
index b6bb123d944da1b125d58402e5e90e40e767fe14..5d3cdadd66d6a46948a853b31c19b8873ed909f2 100644
--- a/matlab/vnorm.m
+++ b/matlab/vnorm.m
@@ -35,7 +35,7 @@ function y = vnorm(A,varargin)
 %       vnorm(A,[],inf)     % Correct
 %
 %
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -71,7 +71,7 @@ if isempty(dim)
     idx = find(size(A)~=1);
     dim = idx(1);
 end
-    
+
 if isempty(ntype)
     y = sqrt(sum( abs(A).^2 , dim) );
 elseif ntype==1
@@ -88,4 +88,3 @@ elseif ntype~=floor(ntype) || ntype<1
 else
     y = (sum( abs(A).^ntype , dim) ).^(1/ntype);
 end
-
diff --git a/matlab/warning_config.m b/matlab/warning_config.m
index 3b9f45d63e5fd128b91900645881a395931426b2..a7cbaab92a44bbfb143ceadd643ba2ed99918e24 100644
--- a/matlab/warning_config.m
+++ b/matlab/warning_config.m
@@ -3,14 +3,14 @@ function warning_config()
 %
 % INPUTS
 %   none
-%             
+%
 % OUTPUTS
 %   none
-%        
+%
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2008-2015 Dynare Team
+% Copyright (C) 2008-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/write_latex_definitions.m b/matlab/write_latex_definitions.m
index 2bf3acf366eb9bdcfd9cc5cb37ba6fb440d76bd0..e9345ac6ac856c4ae0cb32207babda97a4543063 100644
--- a/matlab/write_latex_definitions.m
+++ b/matlab/write_latex_definitions.m
@@ -12,7 +12,7 @@ function write_latex_definitions
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -65,9 +65,9 @@ for i=1:length(tables)
     long = eval([M_var_root{i} '_names_long']);
     for j=1:size(names,1)
         fprintf(fid, '\\texttt{%s} & $%s$ & %s\\\\\n', ...
-            regexprep(strtrim(names(j,:)), '_', '\\_'), ...
-            strtrim(tex(j,:)), ...
-            regexprep(strtrim(long(j,:)), '_', '\\_'));
+                regexprep(strtrim(names(j,:)), '_', '\\_'), ...
+                strtrim(tex(j,:)), ...
+                regexprep(strtrim(long(j,:)), '_', '\\_'));
     end
     fprintf(fid, '\\hline%%\n');
     fprintf(fid, '\\end{longtable}\n');
diff --git a/matlab/write_latex_parameter_table.m b/matlab/write_latex_parameter_table.m
index c2d7398019ed49f09dd1def5e5ac2fbb8c4a5827..92374d77c9e7ece0a920a27d3b951ca1f9d16480 100644
--- a/matlab/write_latex_parameter_table.m
+++ b/matlab/write_latex_parameter_table.m
@@ -12,7 +12,7 @@ function write_latex_parameter_table
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -29,7 +29,7 @@ function write_latex_parameter_table
 % 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_;
+global M_
 
 if ~isequal(M_.param_names,M_.param_names_long)
     Long_names_present=1;
@@ -38,7 +38,7 @@ else
 end
 fid = fopen([M_.fname '_latex_parameters.tex'], 'w');
 fprintf(fid, '\\begin{center}\n');
-if Long_names_present==1;
+if Long_names_present==1
     fprintf(fid, '\\begin{longtable}{ccc}\n');
 else
     fprintf(fid, '\\begin{longtable}{cc}\n');
@@ -48,7 +48,7 @@ fprintf(fid, ['\\caption{Parameter Values}\\\\%%\n']);
 fprintf(fid, '\\toprule%%\n');
 fprintf(fid, '\\multicolumn{1}{c}{\\textbf{Parameter}} &\n');
 fprintf(fid, '\\multicolumn{1}{c}{\\textbf{Value}} ');
-if Long_names_present==1;
+if Long_names_present==1
     fprintf(fid, '&\n \\multicolumn{1}{c}{\\textbf{Description}}\\\\%%\n');
 else
     fprintf(fid, ' \\\\%%\n');
@@ -56,7 +56,7 @@ end
 fprintf(fid, '\\midrule%%\n');
 fprintf(fid, '\\endfirsthead\n');
 
-if Long_names_present==1;
+if Long_names_present==1
     fprintf(fid, '\\multicolumn{3}{c}{{\\tablename} \\thetable{} -- Continued}\\\\%%\n');
 else
     fprintf(fid, '\\multicolumn{2}{c}{{\\tablename} \\thetable{} -- Continued}\\\\%%\n');
@@ -64,7 +64,7 @@ end
 fprintf(fid, '\\midrule%%\n');
 fprintf(fid, '\\multicolumn{1}{c}{\\textbf{Parameter}} &\n');
 fprintf(fid, '\\multicolumn{1}{c}{\\textbf{Value}} ');
-if Long_names_present==1;
+if Long_names_present==1
     fprintf(fid, '&\n  \\multicolumn{1}{c}{\\textbf{Description}}\\\\%%\n');
 else
     fprintf(fid, '\\\\%%\n');
@@ -75,20 +75,20 @@ fprintf(fid, '\\endhead\n');
 tex = M_.param_names_tex;
 long = M_.param_names_long;
 for j=1:size(tex,1)
-if Long_names_present==1;
-    % replace underscores
-    long_names_temp=regexprep(strtrim(long(j,:)), '_', '\\_');
-    % replace percent
-    long_names_temp=regexprep(long_names_temp, '%', '\\%');
-    fprintf(fid, '$%s$ \t & \t %4.3f \t & \t %s\\\\\n', ...
-        strtrim(tex(j,:)), ...
-        M_.params(j,:),...
-        long_names_temp);
-else
-    fprintf(fid, '$%s$ \t & \t %4.3f \\\\\n', ...
-        strtrim(tex(j,:)), ...
-        M_.params(j,:));
-end
+    if Long_names_present==1
+        % replace underscores
+        long_names_temp=regexprep(strtrim(long(j,:)), '_', '\\_');
+        % replace percent
+        long_names_temp=regexprep(long_names_temp, '%', '\\%');
+        fprintf(fid, '$%s$ \t & \t %4.3f \t & \t %s\\\\\n', ...
+                strtrim(tex(j,:)), ...
+                M_.params(j,:),...
+                long_names_temp);
+    else
+        fprintf(fid, '$%s$ \t & \t %4.3f \\\\\n', ...
+                strtrim(tex(j,:)), ...
+                M_.params(j,:));
+    end
 end
 fprintf(fid, '\\bottomrule%%\n');
 fprintf(fid, '\\end{longtable}\n');
diff --git a/matlab/write_latex_prior_table.m b/matlab/write_latex_prior_table.m
index 46a5e3bf5258d6f955c93fbfffb6794369869493..2fb738bd73d9895309631f2b1e541e34213eaff1 100644
--- a/matlab/write_latex_prior_table.m
+++ b/matlab/write_latex_prior_table.m
@@ -11,7 +11,7 @@ function write_latex_prior_table
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2015-16 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -37,11 +37,11 @@ end
 
 if (size(estim_params_.var_endo,1) || size(estim_params_.corrn,1))
     % Prior over measurement errors are defined...
-   if ((isfield(options_,'varobs') && isempty(options_.varobs)) || ~isfield(options_,'varobs'))
-       % ... But the list of observed variabled is not yet defined.
-       fprintf(['\nwrite_latex_prior_table:: varobs should be declared before. Skipping table creation.\n'])
-       return
-   end
+    if ((isfield(options_,'varobs') && isempty(options_.varobs)) || ~isfield(options_,'varobs'))
+        % ... But the list of observed variabled is not yet defined.
+        fprintf(['\nwrite_latex_prior_table:: varobs should be declared before. Skipping table creation.\n'])
+        return
+    end
 end
 
 % Fill or update bayestopt_ structure
@@ -115,56 +115,56 @@ for i=1:size(BayesOptions.name,1)
     PriorMode = BayesOptions.p5(i);
     PriorStandardDeviation = BayesOptions.p2(i);
     switch BayesOptions.pshape(i)
-        case { 1 , 5 }
+      case { 1 , 5 }
+        LowerBound = BayesOptions.p3(i);
+        UpperBound = BayesOptions.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, 8 }
+        LowerBound = BayesOptions.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(BayesOptions.p3(i)) && isinf(lb(i))
+            LowerBound = '$-\infty$';
+        else
             LowerBound = BayesOptions.p3(i);
-            UpperBound = BayesOptions.p4(i);
             if ~isinf(lb(i))
                 LowerBound=max(LowerBound,lb(i));
             end
+        end
+        if isinf(BayesOptions.p4(i)) && isinf(ub(i))
+            UpperBound = '$\infty$';
+        else
+            UpperBound = BayesOptions.p4(i);
             if ~isinf(ub(i))
                 UpperBound=min(UpperBound,ub(i));
             end
-        case { 2 , 4 , 6, 8 }
-            LowerBound = BayesOptions.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(BayesOptions.p3(i)) && isinf(lb(i))
-                LowerBound = '$-\infty$';
-            else
-                LowerBound = BayesOptions.p3(i);
-                if ~isinf(lb(i))
-                    LowerBound=max(LowerBound,lb(i));
-                end
-            end
-            if isinf(BayesOptions.p4(i)) && isinf(ub(i))
-                UpperBound = '$\infty$';
-            else
-                UpperBound = BayesOptions.p4(i);
-                if ~isinf(ub(i))
-                    UpperBound=min(UpperBound,ub(i));
-                end
-            end
-        otherwise
-            error('write_latex_prior_table:: Dynare bug!')
+        end
+      otherwise
+        error('write_latex_prior_table:: 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) );
+            TexName, ...
+            PriorShape, ...
+            PriorMean, ...
+            PriorMode, ...
+            PriorStandardDeviation, ...
+            LowerBound, ...
+            UpperBound, ...
+            PriorIntervals.lb(i), ...
+            PriorIntervals.ub(i) );
 end
 fprintf(fidTeX,'\\end{longtable}\n ');
 fprintf(fidTeX,'\\end{center}\n');
diff --git a/matlab/write_mh_history_file.m b/matlab/write_mh_history_file.m
index 00984c26cf38b9584b43a35e4f2b86d7dee4fe45..72ce6a22e32f819414c67a29995b36bee30ce109 100644
--- a/matlab/write_mh_history_file.m
+++ b/matlab/write_mh_history_file.m
@@ -5,10 +5,10 @@ function i = write_mh_history_file(MetropolisFolder, ModelName, record)
 %   MetropolisFolder    [char]      Name of the metropolis subfolder
 %   ModelName           [char]      Name of the mod-file
 %   record              [structure] structure storing the MH history
-% Outputs:  
+% Outputs:
 %   i                   [scalar]    number of the mh_history file
 
-% Copyright (C) 2013-2015 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/writecellofchar.m b/matlab/writecellofchar.m
index be636e6f171e0ed31daca256c1fac1031dba40af..c08f4bb508b82f169b4fb622a8fb67052c80133f 100644
--- a/matlab/writecellofchar.m
+++ b/matlab/writecellofchar.m
@@ -2,13 +2,13 @@ function str = writecellofchar(c)
 
 % Writes a two dimensional cell of char in a string.
 %
-% INPUTS 
+% INPUTS
 % - c   [cell] cell of char.
 %
-% OUTPUTS 
+% OUTPUTS
 % - str [char]
 %
-% EXAMPLES 
+% EXAMPLES
 % >> writecellofchar({'a', {'b'; 'c'}})
 %
 % ans =
@@ -19,9 +19,9 @@ function str = writecellofchar(c)
 %
 % ans =
 %
-%{'a', '['b'; 'c']', 'd'}   
+%{'a', '['b'; 'c']', 'd'}
 
-% Copyright (C) 2015 Dynare Team
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -37,27 +37,27 @@ function str = writecellofchar(c)
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
-    
+
 str = '{';
 for i=1:size(c, 1)
-    for j=1:size(c, 2)
-        if iscell(c{i,j})
-            str = sprintf('%s%s', str, writecellofchar(c{i, j}));
-        elseif ischar(c{i, j})
-            if size(c{i, j}, 1)>1
-                str = sprintf('%s''%s''', str, writematrixofchar(c{i, j}));
-            else
-                str = sprintf('%s''%s''', str, c{i, j});
-            end
-        else
-            error('Type not implemenented!')
-        end
-        if j<size(c, 2)
-            str = sprintf('%s, ', str);
-        end
-    end
-    if i<size(c, 1)
-        str = sprintf('%s; ', str);
-    end
+for j=1:size(c, 2)
+if iscell(c{i,j})
+str = sprintf('%s%s', str, writecellofchar(c{i, j}));
+elseif ischar(c{i, j})
+if size(c{i, j}, 1)>1
+str = sprintf('%s''%s''', str, writematrixofchar(c{i, j}));
+else
+str = sprintf('%s''%s''', str, c{i, j});
+end
+else
+error('Type not implemenented!')
+end
+if j<size(c, 2)
+str = sprintf('%s, ', str);
+end
+end
+if i<size(c, 1)
+str = sprintf('%s; ', str);
+end
 end
 str = sprintf('%s}', str);
\ No newline at end of file
diff --git a/matlab/writedata.m b/matlab/writedata.m
index 112d7f13065d8164097bf68b1628b912059114b3..c714728fcccdf57cb0bd3afe97fbe11e1f120740 100644
--- a/matlab/writedata.m
+++ b/matlab/writedata.m
@@ -1,6 +1,6 @@
 function writedata(fname)
 % function writedata(fname)
-% store endogenous and exogenous variables in a XLS spreadsheet file 
+% store endogenous and exogenous variables in a XLS spreadsheet file
 % INPUT
 %   fname: name of the XLS file
 % OUTPUT
@@ -10,7 +10,7 @@ function writedata(fname)
 % SPECIAL REQUIREMENT
 %   none
 
-% Copyright (C) 2007-2014 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/writedata_text.m b/matlab/writedata_text.m
index 5af543e9cb2f4313e9ab4d2f64ee7e061f53d898..0fa0f7ac2a3cba06d95786a478794ec1c0ed352d 100644
--- a/matlab/writedata_text.m
+++ b/matlab/writedata_text.m
@@ -1,6 +1,6 @@
 function writedata_text(fname)
 % function writedata(fname)
-% store endogenous and exogenous variables in a text file 
+% store endogenous and exogenous variables in a text file
 % INPUT
 %   fname: name of the text file
 % OUTPUT
@@ -10,7 +10,7 @@ function writedata_text(fname)
 % SPECIAL REQUIREMENT
 %   none
 
-% Copyright (C) 2007-2009 Dynare Team
+% Copyright (C) 2007-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -32,7 +32,7 @@ S=[fname '_endo.dat'];
 fid = fopen(S,'w');
 for i = 1:size(M_.endo_names,1)
     fprintf(fid,'%s ',M_.endo_names(i,:)');
-end;
+end
 fprintf(fid,'\n');
 for i = 1:size(oo_.endo_simul,2)
     fprintf(fid,'%15.7f ',oo_.endo_simul(:,i));
@@ -44,11 +44,10 @@ S=[fname '_exo.dat'];
 fid = fopen(S,'w');
 for i = 1:size(M_.exo_names,1)
     fprintf(fid,'%s ',M_.exo_names(i,:));
-end;
+end
 fprintf(fid,'\n');
 for i = 1:size(oo_.exo_simul,1)
     fprintf(fid,'%15.7f ',oo_.exo_simul(i,:));
     fprintf(fid,'\n');
 end
-fclose(fid);
-return;
\ No newline at end of file
+fclose(fid);
\ No newline at end of file
diff --git a/matlab/writematrixofchar.m b/matlab/writematrixofchar.m
index 6f230e554f7a7d9cf4b363da9bfc7f5c4345a630..5f3f26359a8054f2f5224abc092816363c598f5b 100644
--- a/matlab/writematrixofchar.m
+++ b/matlab/writematrixofchar.m
@@ -2,13 +2,13 @@ function str = writematrixofchar(m)
 
 % Writes a matrix of char in a string.
 %
-% INPUTS 
+% INPUTS
 % - m   [char] matrix of char.
 %
-% OUTPUTS 
+% OUTPUTS
 % - str [char]
 %
-% EXAMPLE 
+% EXAMPLE
 % >> writematrixofchar(['a'; 'b'])
 %
 % ans =
@@ -16,8 +16,8 @@ function str = writematrixofchar(m)
 % ['a'; 'b']
 %
 % where the returned argument is a string which can be evaluated or printed.
-    
-% Copyright (C) 2015 Dynare Team
+
+% Copyright (C) 2015-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/mex/build/matlab/configure.ac b/mex/build/matlab/configure.ac
index 5bc631690ad05a72708e34fc37c9a56ca8537fc7..5fd9aa04dfd3f868e31627d3dea71265ebbe0a29 100644
--- a/mex/build/matlab/configure.ac
+++ b/mex/build/matlab/configure.ac
@@ -18,7 +18,7 @@ dnl You should have received a copy of the GNU General Public License
 dnl along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 AC_PREREQ([2.62])
-AC_INIT([dynare], [4.5-unstable])
+AC_INIT([dynare], [4.6-unstable])
 AC_CONFIG_SRCDIR([configure.ac])
 AM_INIT_AUTOMAKE([-Wall -Wno-portability foreign])
 
diff --git a/mex/build/octave/configure.ac b/mex/build/octave/configure.ac
index fd563e61c35c2baf978940dc1a165a174cd815c2..54351c0030a6fd54ac2570af08e17492c9e5a56c 100755
--- a/mex/build/octave/configure.ac
+++ b/mex/build/octave/configure.ac
@@ -18,7 +18,7 @@ dnl You should have received a copy of the GNU General Public License
 dnl along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 AC_PREREQ([2.62])
-AC_INIT([dynare], [4.5-unstable])
+AC_INIT([dynare], [4.6-unstable])
 AC_CONFIG_SRCDIR([configure.ac])
 AM_INIT_AUTOMAKE([-Wall -Wno-portability foreign])
 
diff --git a/mex/sources/block_kalman_filter/block_kalman_filter.cc b/mex/sources/block_kalman_filter/block_kalman_filter.cc
index 6104feb12db2a425d5c626bc38f9e87faaccba2d..4da025ce741b0e3c17aaa56eacef4884fc0f8fce 100644
--- a/mex/sources/block_kalman_filter/block_kalman_filter.cc
+++ b/mex/sources/block_kalman_filter/block_kalman_filter.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2013 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -30,11 +30,11 @@ using namespace std;
 //#define CUBLAS
 
 #ifdef CUBLAS
-  #include <cuda_runtime.h>
-  #include <cublas_v2.h>
+# include <cuda_runtime.h>
+# include <cublas_v2.h>
 #endif
 void
-mexDisp(mxArray* P)
+mexDisp(mxArray *P)
 {
   unsigned int n = mxGetN(P);
   unsigned int m = mxGetM(P);
@@ -44,97 +44,95 @@ mexDisp(mxArray* P)
   for (unsigned int i = 0; i < m; i++)
     {
       for (unsigned int j = 0; j < n; j++)
-        mexPrintf(" %9.4f",M[i+ j * m]);
+        mexPrintf(" %9.4f", M[i+ j * m]);
       mexPrintf("\n");
     }
   mexEvalString("drawnow;");
 }
 
-
 void
-mexDisp(double* M, int m, int n)
+mexDisp(double *M, int m, int n)
 {
   mexPrintf("%d x %d\n", m, n);
   mexEvalString("drawnow;");
   for (int i = 0; i < m; i++)
     {
       for (int j = 0; j < n; j++)
-        mexPrintf(" %9.4f",M[i+ j * m]);
+        mexPrintf(" %9.4f", M[i+ j * m]);
       mexPrintf("\n");
     }
   mexEvalString("drawnow;");
 }
 /*if block
-    %nz_state_var = M_.nz_state_var;
-    while notsteady && t<smpl
-        t  = t+1;
-        v  = Y(:,t)-a(mf);
-        F  = P(mf,mf) + H;
-        if rcond(F) < kalman_tol
-            if ~all(abs(F(:))<kalman_tol)
-                return
-            else
-                a = T*a;
-                P = T*P*transpose(T)+QQ;
-            end
-        else
-            F_singular = 0;
-            dF     = det(F);
-            iF     = inv(F);
-            lik(t) = log(dF)+transpose(v)*iF*v;
-            K      = P(:,mf)*iF;
-            a      = T*(a+K*v);
-            P = block_pred_Vcov_KF(mf, P, K, T, QQ);
-            %P      = T*(P-K*P(mf,:))*transpose(T)+QQ;
-            notsteady = max(abs(K(:)-oldK)) > riccati_tol;
-            oldK = K(:);
-        end
-    end;
-else
-    while notsteady && t<smpl
-        t  = t+1;
-        v  = Y(:,t)-a(mf);
-        F  = P(mf,mf) + H;
-        if rcond(F) < kalman_tol
-            if ~all(abs(F(:))<kalman_tol)
-                return
-            else
-                a = T*a;
-                P = T*P*transpose(T)+QQ;
-            end
-        else
-            F_singular = 0;
-            dF     = det(F);
-            iF     = inv(F);
-            lik(t) = log(dF)+transpose(v)*iF*v;
-            K      = P(:,mf)*iF;
-            a      = T*(a+K*v);
-            P      = T*(P-K*P(mf,:))*transpose(T)+QQ;
-            notsteady = max(abs(K(:)-oldK)) > riccati_tol;
-            oldK = K(:);
-        
-        end
-    end
-end
+  %nz_state_var = M_.nz_state_var;
+  while notsteady && t<smpl
+  t  = t+1;
+  v  = Y(:,t)-a(mf);
+  F  = P(mf,mf) + H;
+  if rcond(F) < kalman_tol
+  if ~all(abs(F(:))<kalman_tol)
+  return
+  else
+  a = T*a;
+  P = T*P*transpose(T)+QQ;
+  end
+  else
+  F_singular = 0;
+  dF     = det(F);
+  iF     = inv(F);
+  lik(t) = log(dF)+transpose(v)*iF*v;
+  K      = P(:,mf)*iF;
+  a      = T*(a+K*v);
+  P = block_pred_Vcov_KF(mf, P, K, T, QQ);
+  %P      = T*(P-K*P(mf,:))*transpose(T)+QQ;
+  notsteady = max(abs(K(:)-oldK)) > riccati_tol;
+  oldK = K(:);
+  end
+  end;
+  else
+  while notsteady && t<smpl
+  t  = t+1;
+  v  = Y(:,t)-a(mf);
+  F  = P(mf,mf) + H;
+  if rcond(F) < kalman_tol
+  if ~all(abs(F(:))<kalman_tol)
+  return
+  else
+  a = T*a;
+  P = T*P*transpose(T)+QQ;
+  end
+  else
+  F_singular = 0;
+  dF     = det(F);
+  iF     = inv(F);
+  lik(t) = log(dF)+transpose(v)*iF*v;
+  K      = P(:,mf)*iF;
+  a      = T*(a+K*v);
+  P      = T*(P-K*P(mf,:))*transpose(T)+QQ;
+  notsteady = max(abs(K(:)-oldK)) > riccati_tol;
+  oldK = K(:);
+
+  end
+  end
+  end
 */
 
 bool
-not_all_abs_F_bellow_crit(double* F, int size, double crit)
+not_all_abs_F_bellow_crit(double *F, int size, double crit)
 {
-   int i = 0;
-   while (i < size && abs(F[i])<crit)
-     {
-       i++;
-     }
-   if (i < size)
-     return false;
-   else
-     return true;
+  int i = 0;
+  while (i < size && abs(F[i]) < crit)
+    {
+      i++;
+    }
+  if (i < size)
+    return false;
+  else
+    return true;
 }
 
-
 double
-det(double* F, int dim, lapack_int* ipiv)
+det(double *F, int dim, lapack_int *ipiv)
 {
   double det = 1.0;
   for (int i = 0; i < dim; i++)
@@ -145,27 +143,25 @@ det(double* F, int dim, lapack_int* ipiv)
   return det;
 }
 
-
-
 BlockKalmanFilter::BlockKalmanFilter(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[], double *P_mf[], double *v_pp[], double *K[], double *v_n[], double *a[], double *K_P[], double *P_t_t1[], double *tmp[], double *P[])
 {
   if (nlhs > 3)
     DYN_MEX_FUNC_ERR_MSG_TXT("block_kalman_filter provides at most 3 output argument.");
   if (nrhs != 13 && nrhs != 16)
     DYN_MEX_FUNC_ERR_MSG_TXT("block_kalman_filter requires exactly \n  13 input arguments for standard Kalman filter \nor\n  16 input arguments for missing observations Kalman filter.");
-  if (nrhs == 16) 
+  if (nrhs == 16)
     missing_observations = true;
   else
     missing_observations = false;
   if (missing_observations)
     {
-      if (! mxIsCell (prhs[0]))
+      if (!mxIsCell(prhs[0]))
         DYN_MEX_FUNC_ERR_MSG_TXT("the first input argument of block_missing_observations_kalman_filter must be a Cell Array.");
       pdata_index = prhs[0];
-      if (! mxIsDouble (prhs[1]))
+      if (!mxIsDouble(prhs[1]))
         DYN_MEX_FUNC_ERR_MSG_TXT("the second input argument of block_missing_observations_kalman_filter must be a scalar.");
       number_of_observations = ceil(mxGetScalar(prhs[1]));
-      if (! mxIsDouble (prhs[2]))
+      if (!mxIsDouble(prhs[2]))
         DYN_MEX_FUNC_ERR_MSG_TXT("the third input argument of block_missing_observations_kalman_filter must be a scalar.");
       no_more_missing_observations = ceil(mxGetScalar(prhs[2]));
       pT = mxDuplicateArray(prhs[3]);
@@ -175,10 +171,10 @@ BlockKalmanFilter::BlockKalmanFilter(int nlhs, mxArray *plhs[], int nrhs, const
       pP = mxDuplicateArray(prhs[7]);
       pY = mxDuplicateArray(prhs[8]);
       start = mxGetScalar(prhs[9]);
-      mfd = (double*)mxGetData(prhs[10]);
+      mfd = (double *) mxGetData(prhs[10]);
       kalman_tol = mxGetScalar(prhs[11]);
       riccati_tol = mxGetScalar(prhs[12]);
-      nz_state_var = (double*)mxGetData(prhs[13]);
+      nz_state_var = (double *) mxGetData(prhs[13]);
       n_diag = mxGetScalar(prhs[14]);
       pure_obs = mxGetScalar(prhs[15]);
     }
@@ -196,10 +192,10 @@ BlockKalmanFilter::BlockKalmanFilter(int nlhs, mxArray *plhs[], int nrhs, const
       n   = mxGetN(pT);           // Number of state variables.
       pp   = mxGetM(pY);          // Maximum number of observed variables.
       smpl = mxGetN(pY);          // Sample size.          ;
-      mfd = (double*)mxGetData(prhs[7]);
+      mfd = (double *) mxGetData(prhs[7]);
       kalman_tol = mxGetScalar(prhs[8]);
       riccati_tol = mxGetScalar(prhs[9]);
-      nz_state_var = (double*)mxGetData(prhs[10]);
+      nz_state_var = (double *) mxGetData(prhs[10]);
       n_diag = mxGetScalar(prhs[11]);
       pure_obs = mxGetScalar(prhs[12]);
     }
@@ -209,35 +205,32 @@ BlockKalmanFilter::BlockKalmanFilter(int nlhs, mxArray *plhs[], int nrhs, const
   H = mxGetPr(pH);
   *P = mxGetPr(pP);
   Y = mxGetPr(pY);
-  
+
   n   = mxGetN(pT);           // Number of state variables.
   pp   = mxGetM(pY);          // Maximum number of observed variables.
   smpl = mxGetN(pY);          // Sample size.          ;
   n_state = n - pure_obs;
 
-  
-  
   /*mexPrintf("T\n");
-  mexDisp(pT);*/
+    mexDisp(pT);*/
 
   H_size = mxGetN(pH) * mxGetM(pH);
-  
-  
+
   n_shocks = mxGetM(pQ);
-  
+
   if (missing_observations)
-    if (mxGetNumberOfElements(pdata_index) != (unsigned int)smpl)
+    if (mxGetNumberOfElements(pdata_index) != (unsigned int) smpl)
       DYN_MEX_FUNC_ERR_MSG_TXT("the number of element in the cell array passed to block_missing_observation_kalman_filter as first argument has to be equal to the smpl size");
-  
-  i_nz_state_var = (int*)mxMalloc(n*sizeof(int));
+
+  i_nz_state_var = (int *) mxMalloc(n*sizeof(int));
   for (int i = 0; i < n; i++)
     i_nz_state_var[i] = nz_state_var[i];
 
   pa = mxCreateDoubleMatrix(n, 1, mxREAL);         // State vector.
   *a = mxGetPr(pa);
-  tmp_a = (double*)mxMalloc(n * sizeof(double));
+  tmp_a = (double *) mxMalloc(n * sizeof(double));
   dF = 0.0;                                            // det(F).
-  
+
   p_tmp1 = mxCreateDoubleMatrix(n, n_shocks, mxREAL);
   tmp1 = mxGetPr(p_tmp1);
   t = 0;                                               // Initialization of the time index.
@@ -247,13 +240,13 @@ BlockKalmanFilter::BlockKalmanFilter(int nlhs, mxArray *plhs[], int nrhs, const
   LIK  = 0.0;                                          // Default value of the log likelihood.
   notsteady   = true;                                 // Steady state flag.
   F_singular  = true;
-  *v_pp = (double*)mxMalloc(pp * sizeof(double));
-  *v_n = (double*)mxMalloc(n * sizeof(double));
-  mf = (int*)mxMalloc(pp * sizeof(int));
+  *v_pp = (double *) mxMalloc(pp * sizeof(double));
+  *v_n = (double *) mxMalloc(n * sizeof(double));
+  mf = (int *) mxMalloc(pp * sizeof(int));
   for (int i = 0; i < pp; i++)
     mf[i] = mfd[i] - 1;
-  pi = atan2((double)0.0,(double)-1.0);
-  
+  pi = atan2((double) 0.0, (double) -1.0);
+
   /*compute QQ = R*Q*transpose(R)*/                        // Variance of R times the vector of structural innovations.;
   // tmp = R * Q;
   for (int i = 0; i < n; i++)
@@ -277,7 +270,7 @@ BlockKalmanFilter::BlockKalmanFilter(int nlhs, mxArray *plhs[], int nrhs, const
         QQ[i + j * n] = QQ[j + i * n] = res;
       }
   mxDestroyArray(p_tmp1);
-  
+
   pv = mxCreateDoubleMatrix(pp, 1, mxREAL);
   v = mxGetPr(pv);
   pF =  mxCreateDoubleMatrix(pp, pp, mxREAL);
@@ -285,9 +278,9 @@ BlockKalmanFilter::BlockKalmanFilter(int nlhs, mxArray *plhs[], int nrhs, const
   piF =  mxCreateDoubleMatrix(pp, pp, mxREAL);
   iF = mxGetPr(piF);
   lw = pp * 4;
-  w = (double*)mxMalloc(lw * sizeof(double));
-  iw = (lapack_int*)mxMalloc(pp * sizeof(lapack_int));
-  ipiv = (lapack_int*)mxMalloc(pp * sizeof(lapack_int));
+  w = (double *) mxMalloc(lw * sizeof(double));
+  iw = (lapack_int *) mxMalloc(pp * sizeof(lapack_int));
+  ipiv = (lapack_int *) mxMalloc(pp * sizeof(lapack_int));
   info = 0;
 #if defined(BLAS) || defined(CUBLAS)
   p_tmp = mxCreateDoubleMatrix(n, n, mxREAL);
@@ -298,8 +291,8 @@ BlockKalmanFilter::BlockKalmanFilter(int nlhs, mxArray *plhs[], int nrhs, const
   *K = mxGetPr(pK);
   p_K_P = mxCreateDoubleMatrix(n, n, mxREAL);
   *K_P = mxGetPr(p_K_P);
-  oldK  = (double*)mxMalloc(n * n * sizeof(double));
-  *P_mf = (double*)mxMalloc(n * n * sizeof(double));
+  oldK  = (double *) mxMalloc(n * n * sizeof(double));
+  *P_mf = (double *) mxMalloc(n * n * sizeof(double));
   for (int i = 0; i < n  * n; i++)
     oldK[i] = Inf;
 #else
@@ -311,14 +304,14 @@ BlockKalmanFilter::BlockKalmanFilter(int nlhs, mxArray *plhs[], int nrhs, const
   *K = mxGetPr(pK);
   p_K_P = mxCreateDoubleMatrix(n_state, n_state, mxREAL);
   *K_P = mxGetPr(p_K_P);
-  oldK  = (double*)mxMalloc(n * pp * sizeof(double));
-  *P_mf = (double*)mxMalloc(n * pp * sizeof(double));
+  oldK  = (double *) mxMalloc(n * pp * sizeof(double));
+  *P_mf = (double *) mxMalloc(n * pp * sizeof(double));
   for (int i = 0; i < n  * pp; i++)
     oldK[i] = Inf;
 #endif
 }
 
-void 
+void
 BlockKalmanFilter::block_kalman_filter_ss(double *P_mf, double *v_pp, double *K, double *v_n, double *a, double *K_P, double *P_t_t1, double *tmp, double *P)
 {
   if (t+1 < smpl)
@@ -328,7 +321,7 @@ BlockKalmanFilter::block_kalman_filter_ss(double *P_mf, double *v_pp, double *K,
           //v = Y(:,t)-a(mf);
           for (int i = 0; i < pp; i++)
             v[i]  = Y[i + t * pp] - a[mf[i]];
-          
+
           //a = T*(a+K*v);
           for (int i = pure_obs; i < n; i++)
             {
@@ -344,7 +337,7 @@ BlockKalmanFilter::block_kalman_filter_ss(double *P_mf, double *v_pp, double *K,
                 res += T[j  * n + i] * v_n[j];
               a[i] = res;
             }
-        
+
           //lik(t) = transpose(v)*iF*v;
           for (int i = 0; i < pp; i++)
             {
@@ -371,19 +364,19 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
 {
   while (notsteady && t < smpl)
     {
-      if(missing_observations)
+      if (missing_observations)
         {
 
           // retrieve the d_index
-          pd_index = mxGetCell( pdata_index, t);
-          dd_index = (double*)mxGetData(pd_index);
+          pd_index = mxGetCell(pdata_index, t);
+          dd_index = (double *) mxGetData(pd_index);
           size_d_index = mxGetM(pd_index);
           d_index.resize(size_d_index);
           for (int i = 0; i < size_d_index; i++)
             {
               d_index[i] = ceil(dd_index[i]) - 1;
             }
-          
+
           //v = Y(:,t) - a(mf)
           int i_i = 0;
           //#pragma omp parallel for shared(v, i_i, d_index) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
@@ -393,8 +386,7 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
               v[i_i]  = Y[*i + t * pp] - a[mf[*i]];
               i_i++;
             }
-            
-          
+
           //F  = P(mf,mf) + H;
           i_i = 0;
           if (H_size == 1)
@@ -417,16 +409,16 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
                     iF[i_i + j_j * size_d_index] = F[i_i + j_j * size_d_index] = P[mf[*i] + mf[*j] * n] + H[*i + *j * pp];
                 }
             }
-            
+
         }
       else
         {
           size_d_index = pp;
-          
+
           //v = Y(:,t) - a(mf)
           for (int i = 0; i < pp; i++)
             v[i]  = Y[i + t * pp] - a[mf[i]];
-          
+
           //F  = P(mf,mf) + H;
           if (H_size == 1)
             {
@@ -441,20 +433,21 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
                   iF[i + j * pp] = F[i + j * pp] = P[mf[i] + mf[j] * n] + H[i + j * pp];
             }
         }
-      
-     
+
       /* Computes the norm of iF */
       double anorm = dlange("1", &size_d_index, &size_d_index, iF, &size_d_index, w);
       //mexPrintf("anorm = %f\n",anorm);
 
       /* Modifies F in place with a LU decomposition */
       dgetrf(&size_d_index, &size_d_index, iF, &size_d_index, ipiv, &info);
-      if (info != 0) mexPrintf("dgetrf failure with error %d\n", (int) info);
- 
+      if (info != 0)
+        mexPrintf("dgetrf failure with error %d\n", (int) info);
+
       /* Computes the reciprocal norm */
       dgecon("1", &size_d_index, iF, &size_d_index, &anorm, &rcond, w, iw, &info);
-      if (info != 0) mexPrintf("dgecon failure with error %d\n", (int) info);
-      
+      if (info != 0)
+        mexPrintf("dgecon failure with error %d\n", (int) info);
+
       if (rcond < kalman_tol)
         if (not_all_abs_F_bellow_crit(F, size_d_index * size_d_index, kalman_tol))   //~all(abs(F(:))<kalman_tol)
           {
@@ -481,55 +474,56 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
                   res += T[i + j *n] * a[j];
                 tmp_a[i] = res;
               }
-           memcpy(a, tmp_a, n * sizeof(double));
+            memcpy(a, tmp_a, n * sizeof(double));
 
-           //P = T*P*transpose(T)+QQ;
-           memset(tmp, 0, n * n_state * sizeof(double));
+            //P = T*P*transpose(T)+QQ;
+            memset(tmp, 0, n * n_state * sizeof(double));
 
-           for (int i = 0; i < n; i++)
-            for (int j = pure_obs; j < n; j++)
-              {
-                int j1 = j - pure_obs;
-                int j1_n_state = j1 * n_state - pure_obs;
-                for (int k = pure_obs; k < i_nz_state_var[i]; k++)
-                  tmp[i + j1 * n ] += T[i + k * n] * P[k + j1_n_state];
-              }
+            for (int i = 0; i < n; i++)
+              for (int j = pure_obs; j < n; j++)
+                {
+                  int j1 = j - pure_obs;
+                  int j1_n_state = j1 * n_state - pure_obs;
+                  for (int k = pure_obs; k < i_nz_state_var[i]; k++)
+                    tmp[i + j1 * n ] += T[i + k * n] * P[k + j1_n_state];
+                }
 
-          memset(P, 0, n * n * sizeof(double));
-          int n_n_obs = n * pure_obs;
-          for (int i = 0; i < n; i++)
-            for (int j = i; j < n; j++)
+            memset(P, 0, n * n * sizeof(double));
+            int n_n_obs = n * pure_obs;
+            for (int i = 0; i < n; i++)
+              for (int j = i; j < n; j++)
+                {
+                  for (int k = pure_obs; k < i_nz_state_var[j]; k++)
+                    {
+                      int k_n = k * n;
+                      P[i * n + j] += tmp[i + k_n - n_n_obs] * T[j + k_n];
+                    }
+                }
+
+            for (int i = 0; i < n; i++)
               {
-                for (int k = pure_obs; k < i_nz_state_var[j]; k++)
-                  {
-                    int k_n = k * n;
-                    P[i * n + j] += tmp[i + k_n - n_n_obs] * T[j + k_n];
-                  }
+                for (int j = i; j < n; j++)
+                  P[j + i * n] += QQ[j + i * n];
+                for (int j = i + 1; j < n; j++)
+                  P[i + j * n] = P[j + i * n];
               }
-          
-          for ( int i = 0; i < n; i++)
-            {
-              for ( int j = i ; j < n; j++)
-                P[j + i * n] += QQ[j + i * n];
-              for ( int j = i + 1; j < n; j++)
-                P[i + j * n] = P[j + i * n];
-            }
-         }
+          }
       else
         {
           F_singular = false;
-          
+
           //dF     = det(F);
           dF     = det(iF, size_d_index, ipiv);
 
           //iF     = inv(F);
           //int lwork = 4/*2*/* pp;
           dgetri(&size_d_index, iF, &size_d_index, ipiv, w, &lw, &info);
-          if (info != 0) mexPrintf("dgetri failure with error %d\n", (int) info);
+          if (info != 0)
+            mexPrintf("dgetri failure with error %d\n", (int) info);
 
           //lik(t) = log(dF)+transpose(v)*iF*v;
 #ifdef USE_OMP
-#pragma omp parallel for shared(v_pp) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+# pragma omp parallel for shared(v_pp) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
 #endif
           for (int i = 0; i < size_d_index; i++)
             {
@@ -550,7 +544,7 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
             {
               //K      = P(:,mf)*iF;
 #ifdef USE_OMP
-#pragma omp parallel for shared(P_mf) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+# pragma omp parallel for shared(P_mf) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
 #endif
               for (int i = 0; i < n; i++)
                 {
@@ -567,9 +561,9 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
                 for (int j = 0; j < pp; j++)
                   P_mf[i + j * n] = P[i + mf[j] * n];
             }
-          
+
 #ifdef USE_OMP
-#pragma omp parallel for shared(K) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+# pragma omp parallel for shared(K) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
 #endif
           for (int i = 0; i < n; i++)
             for (int j = 0; j < size_d_index; j++)
@@ -580,10 +574,10 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
                   res += P_mf[i + k * n] * iF[j_pp + k];
                 K[i + j * n] = res;
               }
-          
+
           //a      = T*(a+K*v);
 #ifdef USE_OMP
-#pragma omp parallel for shared(v_n) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+# pragma omp parallel for shared(v_n) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
 #endif
           for (int i = pure_obs; i < n; i++)
             {
@@ -592,9 +586,9 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
                 res += K[j  * n + i] * v[j];
               v_n[i] = res + a[i];
             }
-          
+
 #ifdef USE_OMP
-#pragma omp parallel for shared(a) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+# pragma omp parallel for shared(a) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
 #endif
           for (int i = 0; i < n; i++)
             {
@@ -603,7 +597,7 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
                 res += T[j  * n + i] * v_n[j];
               a[i] = res;
             }
-          
+
           if (missing_observations)
             {
               //P      = T*(P-K*P(mf,:))*transpose(T)+QQ;
@@ -617,17 +611,17 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
             {
               //P      = T*(P-K*P(mf,:))*transpose(T)+QQ;
 #ifdef USE_OMP
-#pragma omp parallel for shared(P_mf) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+# pragma omp parallel for shared(P_mf) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
 #endif
               for (int i = 0; i < pp; i++)
                 for (int j = pure_obs; j < n; j++)
                   P_mf[i + j * pp] = P[mf[i] + j * n];
             }
-          
+
 #ifdef BLAS
-#ifdef USE_OMP
-#pragma omp parallel for shared(K_P) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
-#endif
+# ifdef USE_OMP
+#  pragma omp parallel for shared(K_P) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+# endif
           for (int i = 0; i < n; i++)
             for (int j = i; j < n; j++)
               {
@@ -649,7 +643,7 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
           memcpy(P, QQ, n * n *sizeof(double));
           blas_int n_b = n;
           /*mexPrintf("sizeof(n_b)=%d, n_b=%d, sizeof(n)=%d, n=%d\n",sizeof(n_b),n_b,sizeof(n),n);
-          mexEvalString("drawnow;");*/
+            mexEvalString("drawnow;");*/
           dsymm("R", "U", &n_b, &n_b,
                 &one, P_t_t1, &n_b,
                 T, &n_b, &zero,
@@ -659,8 +653,8 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
                 T, &n_b, &one,
                 P, &n_b);
 #else
-#ifdef CUBLAS
-         for (int i = 0; i < n; i++)
+# ifdef CUBLAS
+          for (int i = 0; i < n; i++)
             for (int j = i; j < n; j++)
               {
                 double res = 0.0;
@@ -689,29 +683,29 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
               return false;
             }
           /*int device;
-          cudaGetDevice(&device);*/
+            cudaGetDevice(&device);*/
           int n2 = n * n;
-          double* d_A = 0;
-          double* d_B = 0;
-          double* d_C = 0;
-          double* d_D = 0;
+          double *d_A = 0;
+          double *d_B = 0;
+          double *d_C = 0;
+          double *d_D = 0;
           // Allocate device memory for the matrices
-          if (cudaMalloc((void**)&d_A, n2 * sizeof(double)) != cudaSuccess)
+          if (cudaMalloc((void **) &d_A, n2 * sizeof(double)) != cudaSuccess)
             {
               mexPrintf("!!!! device memory allocation error (allocate A)\n");
               return false;
             }
-          if (cudaMalloc((void**)&d_B, n2 * sizeof(d_B[0])) != cudaSuccess)
+          if (cudaMalloc((void **) &d_B, n2 * sizeof(d_B[0])) != cudaSuccess)
             {
               mexPrintf("!!!! device memory allocation error (allocate B)\n");
               return false;
             }
-          if (cudaMalloc((void**)&d_C, n2 * sizeof(d_C[0])) != cudaSuccess)
+          if (cudaMalloc((void **) &d_C, n2 * sizeof(d_C[0])) != cudaSuccess)
             {
               mexPrintf("!!!! device memory allocation error (allocate C)\n");
               return false;
             }
-          if (cudaMalloc((void**)&d_D, n2 * sizeof(d_D[0])) != cudaSuccess)
+          if (cudaMalloc((void **) &d_D, n2 * sizeof(d_D[0])) != cudaSuccess)
             {
               mexPrintf("!!!! device memory allocation error (allocate D)\n");
               return false;
@@ -734,7 +728,7 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
             {
               mexPrintf("!!!! device access error (write C)\n");
               return false;
-           }
+            }
           mexPrintf("just before calling\n");
           mexEvalString("drawnow;");
           status = cublasSetVector(n2, sizeof(QQ[0]), QQ, 1, d_D, 1);
@@ -742,22 +736,22 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
             {
               mexPrintf("!!!! device access error (write D)\n");
               return false;
-           }
+            }
 
           // Performs operation using plain C code
 
           cublasDsymm(handle, CUBLAS_SIDE_RIGHT, CUBLAS_FILL_MODE_UPPER, n, n,
-                &one, d_A, n,
-                d_B, n, &zero,
-                d_C, n);
+                      &one, d_A, n,
+                      d_B, n, &zero,
+                      d_C, n);
           /*dgemm("N", "T", &n_b, &n_b,
-                &n_b, &one, tmp, &n_b,
-                T, &n_b, &one,
-                P, &n_b);*/
+            &n_b, &one, tmp, &n_b,
+            T, &n_b, &one,
+            P, &n_b);*/
           cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_T, n, n,
-                n, &one, d_C, n,
-                d_B, n, &one,
-                d_D, n);
+                      n, &one, d_C, n,
+                      d_B, n, &one,
+                      d_D, n);
           //double_symm(n, &one, h_A, h_B, &zero, h_C);
 
           status = cublasGetVector(n2, sizeof(P[0]), d_D, 1, P, 1);
@@ -767,14 +761,14 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
               return false;
             }
 
-#else
-#ifdef USE_OMP
-#pragma omp parallel for shared(K_P) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
-#endif
+# else
+#  ifdef USE_OMP
+#   pragma omp parallel for shared(K_P) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+#  endif
           for (int i = pure_obs; i < n; i++)
             {
               unsigned int i1 = i - pure_obs;
-              for (int j = i ; j < n; j++)
+              for (int j = i; j < n; j++)
                 {
                   unsigned int j1 = j - pure_obs;
                   double res = 0.0;
@@ -785,9 +779,9 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
                 }
             }
 
-#ifdef USE_OMP
-#pragma omp parallel for shared(P_t_t1) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
-#endif
+#  ifdef USE_OMP
+#   pragma omp parallel for shared(P_t_t1) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+#  endif
           for (int i = pure_obs; i < n; i++)
             {
               unsigned int i1 = i - pure_obs;
@@ -801,9 +795,9 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
 
           memset(tmp, 0, n * n_state * sizeof(double));
 
-#ifdef USE_OMP
-#pragma omp parallel for shared(tmp) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
-#endif
+#  ifdef USE_OMP
+#   pragma omp parallel for shared(tmp) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+#  endif
           for (int i = 0; i < n; i++)
             {
               int max_k = i_nz_state_var[i];
@@ -811,7 +805,7 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
                 {
                   int j1 = j - pure_obs;
                   int j1_n_state = j1 * n_state - pure_obs;
-                  int indx_tmp = i + j1 * n ;
+                  int indx_tmp = i + j1 * n;
                   for (int k = pure_obs; k < max_k; k++)
                     tmp[indx_tmp] += T[i + k * n] * P_t_t1[k + j1_n_state];
                 }
@@ -819,10 +813,10 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
 
           memset(P, 0, n * n * sizeof(double));
 
-          int n_n_obs = - n * pure_obs;
-#ifdef USE_OMP
-#pragma omp parallel for shared(P) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
-#endif
+          int n_n_obs = -n * pure_obs;
+#  ifdef USE_OMP
+#   pragma omp parallel for shared(P) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+#  endif
           for (int i = 0; i < n; i++)
             {
               for (int j = i; j < n; j++)
@@ -837,17 +831,17 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
                 }
             }
 
-#ifdef USE_OMP
-#pragma omp parallel for shared(P) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
-#endif
-          for ( int i = 0; i < n; i++)
+#  ifdef USE_OMP
+#   pragma omp parallel for shared(P) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+#  endif
+          for (int i = 0; i < n; i++)
             {
-              for ( int j = i ; j < n; j++)
+              for (int j = i; j < n; j++)
                 P[j + i * n] += QQ[j + i * n];
-              for ( int j = i + 1; j < n; j++)
+              for (int j = i + 1; j < n; j++)
                 P[i + j * n] = P[j + i * n];
             }
-#endif
+# endif
 #endif
           if (t >= no_more_missing_observations)
             {
@@ -861,7 +855,7 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
               notsteady = max_abs > riccati_tol;
 
               //oldK = K(:);
-             
+
               memcpy(oldK, K, n * pp * sizeof(double));
             }
         }
@@ -875,8 +869,7 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf,
   return true;
 }
 
-
-void 
+void
 BlockKalmanFilter::return_results_and_clean(int nlhs, mxArray *plhs[], double *P_mf[], double *v_pp[], double *K[], double *v_n[], double *a[], double *K_P[], double *P_t_t1[], double *tmp[], double *P[])
 {
   plhs[0] = mxCreateDoubleScalar(0);
@@ -884,7 +877,7 @@ BlockKalmanFilter::return_results_and_clean(int nlhs, mxArray *plhs[], double *P
   if (nlhs >= 2)
     {
       plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL);
-      double* pind = mxGetPr(plhs[1]);
+      double *pind = mxGetPr(plhs[1]);
       pind[0] = LIK;
     }
 
@@ -903,7 +896,7 @@ BlockKalmanFilter::return_results_and_clean(int nlhs, mxArray *plhs[], double *P
   mxFree(ipiv);
   mxFree(oldK);
   //mxFree(P_mf);
-  
+
   mxDestroyArray(pa);
   mxDestroyArray(p_tmp);
   mxDestroyArray(pQQ);
@@ -918,9 +911,8 @@ BlockKalmanFilter::return_results_and_clean(int nlhs, mxArray *plhs[], double *P
 void
 mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
 {
-  double *P_mf, * v_pp, *v_n, *a, *K, *K_P, *P_t_t1, *tmp, *P;
+  double *P_mf, *v_pp, *v_n, *a, *K, *K_P, *P_t_t1, *tmp, *P;
   BlockKalmanFilter block_kalman_filter(nlhs, plhs, nrhs, prhs, &P_mf, &v_pp, &K, &v_n, &a, &K_P, &P_t_t1, &tmp, &P);
   if (block_kalman_filter.block_kalman_filter(nlhs, plhs, P_mf, v_pp, K, K_P, a, K_P, P_t_t1, tmp, P))
     block_kalman_filter.return_results_and_clean(nlhs, plhs, &P_mf, &v_pp, &K, &K_P, &a, &K_P, &P_t_t1, &tmp, &P);
 }
-
diff --git a/mex/sources/block_kalman_filter/block_kalman_filter.h b/mex/sources/block_kalman_filter/block_kalman_filter.h
index 98803e02440f016df26be3f5631ed4675fda883f..28cb75396780dc0baa486eabacecce090ac869b9 100644
--- a/mex/sources/block_kalman_filter/block_kalman_filter.h
+++ b/mex/sources/block_kalman_filter/block_kalman_filter.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2012 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -32,30 +32,30 @@ using namespace std;
 
 class BlockKalmanFilter
 {
-  public:
-  mxArray *pT , *pR, *pQ, *pH, *pP, *pY, *pQQ, *pv, *pF, *piF, *p_P_t_t1, *pK, *p_K_P;
-  double *T , *R, *Q , *H, *Y, *mfd, *QQ, *v, *F, *iF;
+public:
+  mxArray *pT, *pR, *pQ, *pH, *pP, *pY, *pQQ, *pv, *pF, *piF, *p_P_t_t1, *pK, *p_K_P;
+  double *T, *R, *Q, *H, *Y, *mfd, *QQ, *v, *F, *iF;
   int start, pure_obs, smpl, n, n_state, n_shocks, H_size;
   double kalman_tol, riccati_tol, dF, LIK, Inf, pi;
   lapack_int pp, lw, info;
 
-  double* nz_state_var;
+  double *nz_state_var;
   int *i_nz_state_var, *mf;
   int n_diag, t;
   mxArray *M_;
-  mxArray* pa, *p_tmp, *p_tmp1, *plik;
+  mxArray *pa, *p_tmp, *p_tmp1, *plik;
   double *tmp_a, *tmp1, *lik, *v_n, *w, *oldK;
   bool notsteady, F_singular, missing_observations;
   lapack_int *iw, *ipiv;
   double anorm, rcond;
   lapack_int size_d_index;
   int no_more_missing_observations, number_of_observations;
-  const mxArray* pdata_index;
+  const mxArray *pdata_index;
   vector<int> d_index;
-  const mxArray* pd_index;
-  double* dd_index;
+  const mxArray *pd_index;
+  double *dd_index;
 
-  public:
+public:
   BlockKalmanFilter(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[], double *P_mf[], double *v_pp[], double *K[], double *v_n[], double *a[], double *K_P[], double *P_t_t1[], double *tmp[], double *P[]);
   bool block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, double *v_pp, double *K, double *v_n, double *a, double *K_P, double *P_t_t1, double *tmp, double *P);
   void block_kalman_filter_ss(double *P_mf, double *v_pp, double *K, double *v_n, double *a, double *K_P, double *P_t_t1, double *tmp, double *P);
diff --git a/mex/sources/bytecode/ErrorHandling.hh b/mex/sources/bytecode/ErrorHandling.hh
index 760d0ec7c7921d727617061b38aaa060b487a141..82d4b2c8c9a45680ae87aa488a6543c935520476 100644
--- a/mex/sources/bytecode/ErrorHandling.hh
+++ b/mex/sources/bytecode/ErrorHandling.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2015 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -24,8 +24,20 @@
 #include <iostream>
 #include <sstream>
 #include <map>
+#include <stack>
 #define BYTE_CODE
 #include "CodeInterpreter.hh"
+
+#define _USE_MATH_DEFINES
+#include <math.h>
+#ifndef M_PI
+# define M_PI (3.14159265358979323846)
+#endif
+
+#ifndef M_SQRT2
+# define M_SQRT2 1.41421356237309504880
+#endif
+
 #ifdef DEBUG_EX
 # include <math.h>
 # include "mex_interface.hh"
@@ -37,124 +49,115 @@
 # define CHAR_LENGTH 2
 #endif
 
-//Work around for: https://sourceware.org/bugzilla/show_bug.cgi?id=19439
-#ifndef __builtin_isnan
-# define isnan(x) std::isnan(x)
-#endif
-
-#ifndef __builtin_isinf
-# define isinf(x) std::isinf(x)
-#endif
-
 #ifdef _MSC_VER
-#include <limits>
-#define M_E 2.71828182845904523536
-#define M_LOG2E 1.44269504088896340736
-#define M_LOG10E 0.434294481903251827651
-#define M_LN2 0.693147180559945309417
-#define M_LN10 2.30258509299404568402
-#define M_PI 3.14159265358979323846
-#define M_PI_2 1.57079632679489661923
-#define M_PI_4 0.785398163397448309616
-#define M_1_PI 0.318309886183790671538
-#define M_2_PI 0.636619772367581343076
-#define M_1_SQRTPI 0.564189583547756286948
-#define M_2_SQRTPI 1.12837916709551257390
-#define M_SQRT2 1.41421356237309504880
-#define M_SQRT_2 0.707106781186547524401
-#define NAN numeric_limits<double>::quiet_NaN()
+# include <limits>
+# define M_E 2.71828182845904523536
+# define M_LOG2E 1.44269504088896340736
+# define M_LOG10E 0.434294481903251827651
+# define M_LN2 0.693147180559945309417
+# define M_LN10 2.30258509299404568402
+# define M_PI 3.14159265358979323846
+# define M_PI_2 1.57079632679489661923
+# define M_PI_4 0.785398163397448309616
+# define M_1_PI 0.318309886183790671538
+# define M_2_PI 0.636619772367581343076
+# define M_1_SQRTPI 0.564189583547756286948
+# define M_2_SQRTPI 1.12837916709551257390
+# define M_SQRT2 1.41421356237309504880
+# define M_SQRT_2 0.707106781186547524401
+# define NAN numeric_limits<double>::quiet_NaN()
 
-#define isnan(x) _isnan(x)
-#define isinf(x) (!_finite(x))
-#define fpu_error(x) (isinf(x) || isnan(x))
+# define isnan(x) _isnan(x)
+# define isinf(x) (!_finite(x))
+# define fpu_error(x) (isinf(x) || isnan(x))
 
-#define finite(x) _finite(x)
+# define finite(x) _finite(x)
 
 class MSVCpp_missings
 {
-  public:
+public:
   inline double
   asinh(double x) const
-    {
-      if(x==0.0)
-        return 0.0;
-      double ax = abs(x);
-      return log(x+ax*sqrt(1.+1./(ax*ax)));
-    }
+  {
+    if (x == 0.0)
+      return 0.0;
+    double ax = abs(x);
+    return log(x+ax*sqrt(1.+1./(ax*ax)));
+  }
 
   inline double
   acosh(double x) const
-    {
-      if(x==0.0)
-        return 0.0;
-      double ax = abs(x);
-      return log(x+ax*sqrt(1.-1./(ax*ax)));
-    }
+  {
+    if (x == 0.0)
+      return 0.0;
+    double ax = abs(x);
+    return log(x+ax*sqrt(1.-1./(ax*ax)));
+  }
 
   inline double
   atanh(double x) const
-    {
-      return log((1+x)/(1-x))/2;
-    }
+  {
+    return log((1+x)/(1-x))/2;
+  }
 
   inline double
   erf(double x) const
-    {
-      const double a1 = -1.26551223,   a2 = 1.00002368,
-                   a3 =  0.37409196,   a4 = 0.09678418,
-                   a5 = -0.18628806,   a6 = 0.27886807,
-                   a7 = -1.13520398,   a8 = 1.48851587,
-                   a9 = -0.82215223,  a10 = 0.17087277;
-     double v = 1;
-     double z = abs(x);
-     if (z <= 0)
-       return v;
-     double t = 1 / (1 + 0.5 * z);
-     v = t*exp((-z*z) +a1+t*(a2+t*(a3+t*(a4+t*(a5+t*(a6+t*(a7+t*(a8+t*(a9+t*a10)))))))));
-     if (x < 0)
-       v = 2 - v;
-     return 1 - v;
-    }
+  {
+    const double a1 = -1.26551223,   a2 = 1.00002368,
+      a3 =  0.37409196,   a4 = 0.09678418,
+      a5 = -0.18628806,   a6 = 0.27886807,
+      a7 = -1.13520398,   a8 = 1.48851587,
+      a9 = -0.82215223,  a10 = 0.17087277;
+    double v = 1;
+    double z = abs(x);
+    if (z <= 0)
+      return v;
+    double t = 1 / (1 + 0.5 * z);
+    v = t*exp((-z*z) +a1+t*(a2+t*(a3+t*(a4+t*(a5+t*(a6+t*(a7+t*(a8+t*(a9+t*a10)))))))));
+    if (x < 0)
+      v = 2 - v;
+    return 1 - v;
+  }
 
   inline double
   nearbyint(double x) const
-    {
-      return floor(x + 0.5);
-    }
+  {
+    return floor(x + 0.5);
+  }
 
   inline double
   fmax(double x, double y) const
-    {
-      if (x > y)
-        return x;
-      else
-        return y;
-   }
+  {
+    if (x > y)
+      return x;
+    else
+      return y;
+  }
 
   inline double
   fmin(double x, double y) const
-    {
-      if (x < y)
-        return x;
-      else
-        return y;
-    }
+  {
+    if (x < y)
+      return x;
+    else
+      return y;
+  }
 
 };
 #endif
 
 #ifdef __MINGW32__
-#define __CROSS_COMPILATION__
+# define __CROSS_COMPILATION__
 #endif
 
 #ifdef __MINGW64__
-#define __CROSS_COMPILATION__
+# define __CROSS_COMPILATION__
 #endif
 
 #ifdef __CROSS_COMPILATION__
-#define M_PI 3.14159265358979323846
-#define M_SQRT2 1.41421356237309504880
-#define finite(x) !std::isfinite(x)
+# define M_PI 3.14159265358979323846
+# define M_SQRT2 1.41421356237309504880
+# define finite(x) !std::isfinite(x)
 #endif
 
 //#define DEBUG
@@ -163,11 +166,9 @@ using namespace std;
 const int NO_ERROR_ON_EXIT = 0;
 const int ERROR_ON_EXIT = 1;
 
-
 typedef vector<pair<Tags, void * > > code_liste_type;
 typedef code_liste_type::const_iterator it_code_type;
 
-
 class GeneralExceptionHandling
 {
   string ErrorMsg;
@@ -250,7 +251,7 @@ public:
                                                                value2(value2_arg)
   {
     ostringstream tmp;
-    if (abs(value1) > 1e-10 )
+    if (fabs(value1) > 1e-10)
       tmp << " with X=" << value1 << "\n";
     else
       tmp << " with X=" << value1 << " and a=" << value2 << "\n";
@@ -289,11 +290,11 @@ struct s_plan
 };
 
 struct table_conditional_local_type
-        {
-          bool is_cond;
-          int var_exo, var_endo;
-          double constrained_value;
-        };
+{
+  bool is_cond;
+  int var_exo, var_endo;
+  double constrained_value;
+};
 typedef vector<table_conditional_local_type> vector_table_conditional_local_type;
 typedef map< int, vector_table_conditional_local_type > table_conditional_global_type;
 #ifdef MATLAB_MEX_FILE
@@ -313,7 +314,7 @@ public:
   double *y, *ya;
   int y_size;
   double *T;
-  int nb_row_xd, nb_row_x, col_x;
+  int nb_row_xd, nb_row_x, col_x, col_y;
   int y_kmin, y_kmax, periods;
   double *x, *params;
   double *u;
@@ -327,9 +328,9 @@ public:
 
   ExpressionType EQN_type;
   it_code_type it_code_expr;
-  /*unsigned int*/size_t nb_endo, nb_exo, nb_param;
+  /*unsigned int*/ size_t nb_endo, nb_exo, nb_param;
   char *P_endo_names, *P_exo_names, *P_param_names;
-  size_t/*unsigned int*/ endo_name_length, exo_name_length, param_name_length;
+  size_t /*unsigned int*/ endo_name_length, exo_name_length, param_name_length;
   unsigned int EQN_equation, EQN_block, EQN_block_number;
   unsigned int EQN_dvar1, EQN_dvar2, EQN_dvar3;
   vector<pair<string, pair<SymbolType, unsigned int> > > Variable_list;
@@ -385,7 +386,7 @@ public:
     string tmp_n(str.length(), ' ');
     string dollar, pound, tilde;
     dollar = "$";
-    pound = "�";
+    pound = "£";
     tilde = "~";
     for (unsigned int i = 0; i < str.length(); i++)
       {
@@ -394,9 +395,9 @@ public:
         else
           {
             if (dollar.compare(&str[i]) == 0)
-              pos1 = int(temp.length());
+              pos1 = int (temp.length());
             else
-              pos2 = int(temp.length());
+              pos2 = int (temp.length());
             if (pos1 >= 0 && pos2 >= 0)
               {
                 tmp_n.erase(pos1, pos2-pos1+1);
@@ -413,14 +414,14 @@ public:
   load_variable_list()
   {
     ostringstream res;
-    for (unsigned int variable_num = 0; variable_num < (unsigned int)nb_endo; variable_num++)
+    for (unsigned int variable_num = 0; variable_num < (unsigned int) nb_endo; variable_num++)
       {
         for (unsigned int i = 0; i < endo_name_length; i++)
           if (P_endo_names[CHAR_LENGTH*(variable_num+i*nb_endo)] != ' ')
             res << P_endo_names[CHAR_LENGTH*(variable_num+i*nb_endo)];
         Variable_list.push_back(make_pair(res.str(), make_pair(eEndogenous, variable_num)));
       }
-    for (unsigned int variable_num = 0; variable_num < (unsigned int)nb_exo; variable_num++)
+    for (unsigned int variable_num = 0; variable_num < (unsigned int) nb_exo; variable_num++)
       {
         for (unsigned int i = 0; i < exo_name_length; i++)
           if (P_exo_names[CHAR_LENGTH*(variable_num+i*nb_exo)] != ' ')
@@ -450,7 +451,7 @@ public:
           }
         i++;
       }
-    return(-1);
+    return (-1);
   }
 
   inline string
@@ -631,8 +632,8 @@ public:
     while (go_on)
       {
 #ifdef MATLAB_MEX_FILE
-	      if ( utIsInterruptPending() )
-		      throw UserExceptionHandling();
+        if (utIsInterruptPending())
+          throw UserExceptionHandling();
 #endif
         switch (it_code->first)
           {
@@ -698,7 +699,7 @@ public:
                 var = ((FLDV_ *) it_code->second)->get_pos();
 #ifdef DEBUG
                 mexPrintf("FLDV_ Param var=%d\n", var);
-                mexPrintf("get_variable(eParameter, var)=%s\n",get_variable(eParameter, var).c_str());
+                mexPrintf("get_variable(eParameter, var)=%s\n", get_variable(eParameter, var).c_str());
                 mexEvalString("drawnow;");
 #endif
                 Stack.push(get_variable(eParameter, var));
@@ -710,7 +711,7 @@ public:
                 lag = ((FLDV_ *) it_code->second)->get_lead_lag();
 #ifdef DEBUG
                 mexPrintf("FLDV_ endo var=%d, lag=%d\n", var, lag);
-                mexPrintf("get_variable(eEndogenous, var)=%s, compute=%d\n",get_variable(eEndogenous, var).c_str(), compute);
+                mexPrintf("get_variable(eEndogenous, var)=%s, compute=%d\n", get_variable(eEndogenous, var).c_str(), compute);
                 mexPrintf("it_=%d, lag=%d, y_size=%d, var=%d, y=%x\n", it_, lag, y_size, var, y);
                 mexEvalString("drawnow;");
 #endif
@@ -1328,7 +1329,7 @@ public:
                       tmp_out << "$";
                     tmp_out << " / ";
                     if (isinf(r))
-                      tmp_out << "�";
+                      tmp_out << "£";
                   }
                 else
                   tmp_out << " / ";
@@ -1491,7 +1492,7 @@ public:
                 if (compute)
                   {
                     if (isnan(r))
-                      tmp_out << "$ ^ " << "�";
+                      tmp_out << "$ ^ " << "£";
                     else
                       tmp_out << " ^ ";
                   }
@@ -1511,7 +1512,7 @@ public:
                   Stack.pop();
                   if (compute)
                     {
-                      int derivOrder = int(nearbyint(Stackf.top()));
+                      int derivOrder = int (nearbyint(Stackf.top()));
                       Stackf.pop();
                       if (fabs(v1f) < NEAR_ZERO && v2f > 0
                           && derivOrder > v2f
@@ -1533,7 +1534,7 @@ public:
                   if (compute)
                     {
                       if (isnan(r))
-                        tmp_out << "$ PowerDeriv " << "�";
+                        tmp_out << "$ PowerDeriv " << "£";
                       else
                         tmp_out << "PowerDeriv";
                     }
@@ -1607,7 +1608,7 @@ public:
                 if (compute)
                   {
                     if (isnan(r))
-                      tmp_out << "$log" << "�" << "(" << v1 << ")";
+                      tmp_out << "$log" << "£" << "(" << v1 << ")";
                     else
                       tmp_out << "log(" << v1 << ")";
                   }
@@ -1625,7 +1626,7 @@ public:
                 if (compute)
                   {
                     if (isnan(r))
-                      tmp_out << "$log10" << "�" << "(" << v1 << ")";
+                      tmp_out << "$log10" << "£" << "(" << v1 << ")";
                     else
                       tmp_out << "log10(" << v1 << ")";
                   }
@@ -2231,6 +2232,18 @@ public:
     it_code_ret = it_code;
     return (tmp_out.str());
   }
+  void
+
+  inline
+  test_mxMalloc(void *z, int line, string file, string func, int amount)
+  {
+    if (z == NULL && (amount > 0))
+      {
+        ostringstream tmp;
+        tmp << " mxMalloc: out of memory " << amount << " bytes required at line " << line << " in function " << func << " (file " << file;
+        throw FatalExceptionHandling(tmp.str());
+      }
+  }
 
 };
 
diff --git a/mex/sources/bytecode/Evaluate.cc b/mex/sources/bytecode/Evaluate.cc
index b0208bc0ee882f594cf6e884f7acd8782d0613e8..16b4e4d228bb21da1759bf4abb65c59b901cf931 100644
--- a/mex/sources/bytecode/Evaluate.cc
+++ b/mex/sources/bytecode/Evaluate.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Dynare Team
+ * Copyright (C) 2013-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -35,8 +35,8 @@ Evaluate::Evaluate()
   block = -1;
 }
 
-Evaluate::Evaluate(const int y_size_arg, const int y_kmin_arg, const int y_kmax_arg, const bool print_it_arg, const bool steady_state_arg, const int periods_arg, const int minimal_solving_periods_arg, const double slowc_arg):
-print_it(print_it_arg),  minimal_solving_periods(minimal_solving_periods_arg)
+Evaluate::Evaluate(const int y_size_arg, const int y_kmin_arg, const int y_kmax_arg, const bool print_it_arg, const bool steady_state_arg, const int periods_arg, const int minimal_solving_periods_arg, const double slowc_arg) :
+  print_it(print_it_arg),  minimal_solving_periods(minimal_solving_periods_arg)
 {
   symbol_table_endo_nbr = 0;
   Block_List_Max_Lag = 0;
@@ -107,7 +107,6 @@ Evaluate::log10_1(double a)
   return r;
 }
 
-
 void
 Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int block_num, const int size, const bool steady_state,*/ const bool no_derivative)
 {
@@ -137,14 +136,14 @@ Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int
         }
     }
 #ifdef MATLAB_MEX_FILE
-	if ( utIsInterruptPending() )
-		throw UserExceptionHandling();
+  if (utIsInterruptPending())
+    throw UserExceptionHandling();
 #endif
-  
+
   while (go_on)
     {
 #ifdef DEBUG
-      mexPrintf("it_code->first=%d\n",it_code->first);
+      mexPrintf("it_code->first=%d\n", it_code->first);
 #endif
       switch (it_code->first)
         {
@@ -738,7 +737,7 @@ Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int
               pos_col = ((FSTPG3_ *) it_code->second)->get_col_pos();
 #ifdef DEBUG
               mexPrintf("Endo eq=%d, pos_col=%d, size=%d, jacob=%x\n", eq, pos_col, size, jacob);
-              mexPrintf("jacob=%x\n",jacob);
+              mexPrintf("jacob=%x\n", jacob);
 #endif
               jacob[eq + size*pos_col] = rr;
               break;
@@ -843,7 +842,7 @@ Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int
             case oLess:
               Stack.push(double (v1 < v2));
 #ifdef DEBUG
-              mexPrintf("v1=%f v2=%f v1 < v2 = %f\n",v1,v2,double(v1 < v2));
+              mexPrintf("v1=%f v2=%f v1 < v2 = %f\n", v1, v2, double (v1 < v2));
 #endif
               break;
             case oGreater:
@@ -897,7 +896,7 @@ Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int
               break;
             case oPowerDeriv:
               {
-                int derivOrder = int(nearbyint(Stack.top()));
+                int derivOrder = int (nearbyint(Stack.top()));
                 Stack.pop();
                 try
                   {
@@ -1172,6 +1171,7 @@ Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int
               case ExternalFunctionWithFirstandSecondDerivative:
                 {
                   input_arguments = (mxArray **) mxMalloc(nb_input_arguments * sizeof(mxArray *));
+                  test_mxMalloc(input_arguments, __LINE__, __FILE__, __func__, nb_input_arguments * sizeof(mxArray *));
 #ifdef DEBUG
                   mexPrintf("Stack.size()=%d\n", Stack.size());
                   mexEvalString("drawnow;");
@@ -1188,7 +1188,7 @@ Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int
                       tmp << " external function: " << function_name << " not found";
                       throw FatalExceptionHandling(tmp.str());
                     }
- 
+
                   double *rr = mxGetPr(output_arguments[0]);
                   Stack.push(*rr);
                   if (function_type == ExternalFunctionWithFirstDerivative || function_type == ExternalFunctionWithFirstandSecondDerivative)
@@ -1215,6 +1215,7 @@ Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int
               case ExternalFunctionNumericalFirstDerivative:
                 {
                   input_arguments = (mxArray **) mxMalloc((nb_input_arguments+1+nb_add_input_arguments) * sizeof(mxArray *));
+                  test_mxMalloc(input_arguments, __LINE__, __FILE__, __func__, (nb_input_arguments+1+nb_add_input_arguments) * sizeof(mxArray *));
                   mxArray *vv = mxCreateString(arg_func_name.c_str());
                   input_arguments[0] = vv;
                   vv = mxCreateDoubleScalar(fc->get_row());
@@ -1254,6 +1255,7 @@ Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int
               case ExternalFunctionFirstDerivative:
                 {
                   input_arguments = (mxArray **) mxMalloc(nb_input_arguments * sizeof(mxArray *));
+                  test_mxMalloc(input_arguments, __LINE__, __FILE__, __func__, nb_input_arguments * sizeof(mxArray *));
                   for (unsigned int i = 0; i < nb_input_arguments; i++)
                     {
                       mxArray *vv = mxCreateDoubleScalar(Stack.top());
@@ -1277,6 +1279,7 @@ Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int
               case ExternalFunctionNumericalSecondDerivative:
                 {
                   input_arguments = (mxArray **) mxMalloc((nb_input_arguments+1+nb_add_input_arguments) * sizeof(mxArray *));
+                  test_mxMalloc(input_arguments, __LINE__, __FILE__, __func__, (nb_input_arguments+1+nb_add_input_arguments) * sizeof(mxArray *));
                   mxArray *vv = mxCreateString(arg_func_name.c_str());
                   input_arguments[0] = vv;
                   vv = mxCreateDoubleScalar(fc->get_row());
@@ -1315,6 +1318,7 @@ Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int
               case ExternalFunctionSecondDerivative:
                 {
                   input_arguments = (mxArray **) mxMalloc(nb_input_arguments * sizeof(mxArray *));
+                  test_mxMalloc(input_arguments, __LINE__, __FILE__, __func__, nb_input_arguments * sizeof(mxArray *));
                   for (unsigned int i = 0; i < nb_input_arguments; i++)
                     {
                       mxArray *vv = mxCreateDoubleScalar(Stack.top());
@@ -1484,7 +1488,7 @@ Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int
           throw FatalExceptionHandling(tmp.str());
         }
 #ifdef DEBUG
-      mexPrintf("it_code++=%d\n",it_code);
+      mexPrintf("it_code++=%d\n", it_code);
 #endif
       it_code++;
     }
@@ -1494,8 +1498,6 @@ Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int
 #endif
 }
 
-
-
 void
 Evaluate::evaluate_over_periods(const bool forward)
 {
@@ -1528,7 +1530,7 @@ Evaluate::solve_simple_one_periods()
 {
   bool cvg = false;
   int iter = 0;
-  double ya ;
+  double ya;
   double slowc_save = slowc;
   res1 = 0;
   while (!(cvg || (iter > maxit_)))
@@ -1537,14 +1539,14 @@ Evaluate::solve_simple_one_periods()
       Per_y_ = it_*y_size;
       ya = y[Block_Contain[0].Variable + Per_y_];
       compute_block_time(0, false, false);
-      if (!finite(res1))
+      if (!isfinite(res1))
         {
           res1 = NAN;
-          while ((isinf(res1) || isnan(res1)) && (slowc > 1e-9) )
+          while ((isinf(res1) || isnan(res1)) && (slowc > 1e-9))
             {
               it_code = start_code;
               compute_block_time(0, false, false);
-              if (!finite(res1))
+              if (!isfinite(res1))
                 {
                   slowc /= 1.5;
                   mexPrintf("Reducing the path length in Newton step slowc=%f\n", slowc);
@@ -1560,7 +1562,7 @@ Evaluate::solve_simple_one_periods()
         continue;
       try
         {
-          y[Block_Contain[0].Variable + Per_y_] += - slowc * divide(rr, g1[0]);
+          y[Block_Contain[0].Variable + Per_y_] += -slowc *divide(rr, g1[0]);
         }
       catch (FloatingPointExceptionHandling &fpeh)
         {
@@ -1578,12 +1580,13 @@ Evaluate::solve_simple_one_periods()
     }
 }
 
-
 void
 Evaluate::solve_simple_over_periods(const bool forward)
 {
   g1 = (double *) mxMalloc(sizeof(double));
+  test_mxMalloc(g1, __LINE__, __FILE__, __func__, sizeof(double));
   r = (double *) mxMalloc(sizeof(double));
+  test_mxMalloc(r, __LINE__, __FILE__, __func__, sizeof(double));
   start_code = it_code;
   if (steady_state)
     {
@@ -1605,7 +1608,7 @@ Evaluate::solve_simple_over_periods(const bool forward)
 
 void
 Evaluate::set_block(const int size_arg, const int type_arg, string file_name_arg, string bin_base_name_arg, const int block_num_arg,
-          const bool is_linear_arg, const int symbol_table_endo_nbr_arg, const int Block_List_Max_Lag_arg, const int Block_List_Max_Lead_arg, const int u_count_int_arg, const int block_arg)
+                    const bool is_linear_arg, const int symbol_table_endo_nbr_arg, const int Block_List_Max_Lag_arg, const int Block_List_Max_Lead_arg, const int u_count_int_arg, const int block_arg)
 {
   size = size_arg;
   type = type_arg;
@@ -1627,7 +1630,6 @@ Evaluate::evaluate_complete(const bool no_derivatives)
   compute_block_time(0, false, no_derivatives);
 }
 
-
 void
 Evaluate::compute_complete_2b(const bool no_derivatives, double *_res1, double *_res2, double *_max_res, int *_max_res_idx)
 {
@@ -1644,21 +1646,21 @@ Evaluate::compute_complete_2b(const bool no_derivatives, double *_res1, double *
       compute_block_time(Per_u_, false, no_derivatives);
       if (!(isnan(res1) || isinf(res1)))
         {
-            {
-              for (int i = 0; i < size; i++)
-                {
-                  double rr;
-                  rr = r[i];
-                  res[i+shift] = rr;
-                  if (max_res < fabs(rr))
-                    {
-                      *_max_res = fabs(rr);
-                      *_max_res_idx = i;
-                    }
-                  *_res2 += rr*rr;
-                  *_res1 += fabs(rr);
-                }
-            }
+          {
+            for (int i = 0; i < size; i++)
+              {
+                double rr;
+                rr = r[i];
+                res[i+shift] = rr;
+                if (max_res < fabs(rr))
+                  {
+                    *_max_res = fabs(rr);
+                    *_max_res_idx = i;
+                  }
+                *_res2 += rr*rr;
+                *_res1 += fabs(rr);
+              }
+          }
         }
       else
         return;
@@ -1666,7 +1668,6 @@ Evaluate::compute_complete_2b(const bool no_derivatives, double *_res1, double *
   return;
 }
 
-
 bool
 Evaluate::compute_complete(const bool no_derivatives, double &_res1, double &_res2, double &_max_res, int &_max_res_idx)
 {
@@ -1676,23 +1677,23 @@ Evaluate::compute_complete(const bool no_derivatives, double &_res1, double &_re
   compute_block_time(0, false, no_derivatives);
   if (!(isnan(res1) || isinf(res1)))
     {
-        {
-          _res1 = 0;
-          _res2 = 0;
-          _max_res = 0;
-          for (int i = 0; i < size; i++)
-            {
-              double rr;
-              rr = r[i];
-              if (max_res < fabs(rr))
-                {
-                  _max_res = fabs(rr);
-                  _max_res_idx = i;
-                }
-              _res2 += rr*rr;
-              _res1 += fabs(rr);
-            }
-        }
+      {
+        _res1 = 0;
+        _res2 = 0;
+        _max_res = 0;
+        for (int i = 0; i < size; i++)
+          {
+            double rr;
+            rr = r[i];
+            if (max_res < fabs(rr))
+              {
+                _max_res = fabs(rr);
+                _max_res_idx = i;
+              }
+            _res2 += rr*rr;
+            _res1 += fabs(rr);
+          }
+      }
       result = true;
     }
   else
@@ -1700,7 +1701,6 @@ Evaluate::compute_complete(const bool no_derivatives, double &_res1, double &_re
   return result;
 }
 
-
 bool
 Evaluate::compute_complete(double lambda, double *crit)
 {
@@ -1721,10 +1721,10 @@ Evaluate::compute_complete(double lambda, double *crit)
         {
           res2_ = res2;
           /*res1_ = res1;
-          if (max_res > max_res_)
+            if (max_res > max_res_)
             {
-              max_res = max_res_;
-              max_res_idx = max_res_idx_;
+            max_res = max_res_;
+            max_res_idx = max_res_idx_;
             }*/
         }
       else
@@ -1758,7 +1758,7 @@ Evaluate::compute_complete(double lambda, double *crit)
             return false;
         }
     }
-    mexPrintf("  lambda=%e, res2=%e\n", lambda, res2_);
+  mexPrintf("  lambda=%e, res2=%e\n", lambda, res2_);
   *crit = res2_/2;
   return true;
 }
diff --git a/mex/sources/bytecode/Evaluate.hh b/mex/sources/bytecode/Evaluate.hh
index 33621b7a45872e1342b636e4a147ea641077aefe..bcf62824bad7134cd9bfbbb22177fa40df641490 100644
--- a/mex/sources/bytecode/Evaluate.hh
+++ b/mex/sources/bytecode/Evaluate.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2013 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -87,7 +87,7 @@ public:
   Evaluate(const int y_size_arg, const int y_kmin_arg, const int y_kmax_arg, const bool print_it_arg, const bool steady_state_arg, const int periods_arg, const int minimal_solving_periods_arg, const double slowc);
   //typedef  void (Interpreter::*InterfpreterMemFn)(const int block_num, const int size, const bool steady_state, int it);
   void set_block(const int size_arg, const int type_arg, string file_name_arg, string bin_base_name_arg, const int block_num_arg,
-          const bool is_linear_arg, const int symbol_table_endo_nbr_arg, const int Block_List_Max_Lag_arg, const int Block_List_Max_Lead_arg, const int u_count_int_arg, const int block_arg);
+                 const bool is_linear_arg, const int symbol_table_endo_nbr_arg, const int Block_List_Max_Lag_arg, const int Block_List_Max_Lead_arg, const int u_count_int_arg, const int block_arg);
   void evaluate_complete(const bool no_derivatives);
   bool compute_complete(const bool no_derivatives, double &res1, double &res2, double &max_res, int &max_res_idx);
   void compute_complete_2b(const bool no_derivatives, double *_res1, double *_res2, double *_max_res, int *_max_res_idx);
diff --git a/mex/sources/bytecode/Interpreter.cc b/mex/sources/bytecode/Interpreter.cc
index f85c9e709a7e29c53712f4cdc416deb3e4d27ba9..1c36f5a86783bb8552fb445753e97d11263456f5 100644
--- a/mex/sources/bytecode/Interpreter.cc
+++ b/mex/sources/bytecode/Interpreter.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2013 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -35,16 +35,16 @@ Interpreter::Interpreter(double *params_arg, double *y_arg, double *ya_arg, doub
                          int maxit_arg_, double solve_tolf_arg, size_t size_of_direction_arg, double slowc_arg, int y_decal_arg, double markowitz_c_arg,
                          string &filename_arg, int minimal_solving_periods_arg, int stack_solve_algo_arg, int solve_algo_arg,
                          bool global_temporary_terms_arg, bool print_arg, bool print_error_arg, mxArray *GlobalTemporaryTerms_arg,
-                         bool steady_state_arg, bool print_it_arg, int col_x_arg
+                         bool steady_state_arg, bool print_it_arg, int col_x_arg, int col_y_arg
 #ifdef CUDA
                          , const int CUDA_device_arg, cublasHandle_t cublas_handle_arg, cusparseHandle_t cusparse_handle_arg, cusparseMatDescr_t descr_arg
 #endif
                          )
-                         : dynSparseMatrix(y_size_arg, y_kmin_arg, y_kmax_arg, print_it_arg, steady_state_arg, periods_arg, minimal_solving_periods_arg, slowc_arg
+: dynSparseMatrix(y_size_arg, y_kmin_arg, y_kmax_arg, print_it_arg, steady_state_arg, periods_arg, minimal_solving_periods_arg, slowc_arg
 #ifdef CUDA
-                                        , CUDA_device_arg, cublas_handle_arg, cusparse_handle_arg, descr_arg
+                  , CUDA_device_arg, cublas_handle_arg, cusparse_handle_arg, descr_arg
 #endif
-                                        )
+                  )
 {
   params = params_arg;
   y = y_arg;
@@ -74,6 +74,7 @@ Interpreter::Interpreter(double *params_arg, double *y_arg, double *ya_arg, doub
   global_temporary_terms = global_temporary_terms_arg;
   print = print_arg;
   col_x = col_x_arg;
+  col_y = col_y_arg;
   GlobalTemporaryTerms = GlobalTemporaryTerms_arg;
   print_error = print_error_arg;
   //steady_state = steady_state_arg;
@@ -91,7 +92,7 @@ Interpreter::evaluate_a_block(bool initialization)
     case EVALUATE_FORWARD:
       if (steady_state)
         {
-          compute_block_time(0, true, /*block_num, size, steady_state, */false);
+          compute_block_time(0, true, /*block_num, size, steady_state, */ false);
           if (block >= 0)
             for (int j = 0; j < size; j++)
               residual[j] = y[Block_Contain[j].Variable] - ya[Block_Contain[j].Variable];
@@ -106,7 +107,7 @@ Interpreter::evaluate_a_block(bool initialization)
             {
               it_code = begining;
               Per_y_ = it_*y_size;
-              compute_block_time(0, true, /*block_num, size, steady_state, */false);
+              compute_block_time(0, true, /*block_num, size, steady_state, */ false);
               if (block >= 0)
                 for (int j = 0; j < size; j++)
                   residual[it_*size+j] = y[it_*y_size+Block_Contain[j].Variable] - ya[it_*y_size+Block_Contain[j].Variable];
@@ -118,7 +119,9 @@ Interpreter::evaluate_a_block(bool initialization)
       break;
     case SOLVE_FORWARD_SIMPLE:
       g1 = (double *) mxMalloc(size*size*sizeof(double));
+      test_mxMalloc(g1, __LINE__, __FILE__, __func__, size*size*sizeof(double));
       r = (double *) mxMalloc(size*sizeof(double));
+      test_mxMalloc(r, __LINE__, __FILE__, __func__, size*sizeof(double));
       if (steady_state)
         {
           compute_block_time(0, true, /*block_num, size, steady_state,*/ false);
@@ -150,14 +153,15 @@ Interpreter::evaluate_a_block(bool initialization)
       break;
     case SOLVE_FORWARD_COMPLETE:
       if (initialization)
-         {
-           fixe_u(&u, u_count_int, u_count_int);
-           Read_SparseMatrix(bin_base_name, size, 1, 0, 0, false, stack_solve_algo, solve_algo);
-         }
+        {
+          fixe_u(&u, u_count_int, u_count_int);
+          Read_SparseMatrix(bin_base_name, size, 1, 0, 0, false, stack_solve_algo, solve_algo);
+        }
 #ifdef DEBUG
       mexPrintf("in SOLVE_FORWARD_COMPLETE r = mxMalloc(%d*sizeof(double))\n", size);
 #endif
       r = (double *) mxMalloc(size*sizeof(double));
+      test_mxMalloc(r, __LINE__, __FILE__, __func__, size*sizeof(double));
       if (steady_state)
         {
           compute_block_time(0, true, /*block_num, size, steady_state,*/ false);
@@ -216,7 +220,9 @@ Interpreter::evaluate_a_block(bool initialization)
       break;
     case SOLVE_BACKWARD_SIMPLE:
       g1 = (double *) mxMalloc(size*size*sizeof(double));
+      test_mxMalloc(g1, __LINE__, __FILE__, __func__, size*size*sizeof(double));
       r = (double *) mxMalloc(size*sizeof(double));
+      test_mxMalloc(r, __LINE__, __FILE__, __func__, size*sizeof(double));
       if (steady_state)
         {
           compute_block_time(0, true, /*block_num, size, steady_state,*/ false);
@@ -253,6 +259,7 @@ Interpreter::evaluate_a_block(bool initialization)
           Read_SparseMatrix(bin_base_name, size, 1, 0, 0, false, stack_solve_algo, solve_algo);
         }
       r = (double *) mxMalloc(size*sizeof(double));
+      test_mxMalloc(r, __LINE__, __FILE__, __func__, size*sizeof(double));
       if (steady_state)
         {
           compute_block_time(0, true, /*block_num, size, steady_state,*/ false);
@@ -270,7 +277,7 @@ Interpreter::evaluate_a_block(bool initialization)
             {
               it_code = begining;
               Per_y_ = it_*y_size;
-              compute_block_time(0, true, /*block_num, size, steady_state, */false);
+              compute_block_time(0, true, /*block_num, size, steady_state, */ false);
               if (block < 0)
                 for (int j = 0; j < size; j++)
                   residual[Per_y_+Block_Contain[j].Equation] = r[j];
@@ -290,6 +297,7 @@ Interpreter::evaluate_a_block(bool initialization)
         }
       u_count = u_count_int*(periods+y_kmax+y_kmin);
       r = (double *) mxMalloc(size*sizeof(double));
+      test_mxMalloc(r, __LINE__, __FILE__, __func__, size*sizeof(double));
       begining = it_code;
       for (it_ = y_kmin; it_ < periods+y_kmin; it_++)
         {
@@ -309,8 +317,6 @@ Interpreter::evaluate_a_block(bool initialization)
     }
 }
 
-
-
 int
 Interpreter::simulate_a_block(vector_table_conditional_local_type vector_table_conditional_local)
 {
@@ -330,14 +336,14 @@ Interpreter::simulate_a_block(vector_table_conditional_local_type vector_table_c
       mexPrintf("EVALUATE_FORWARD\n");
       mexEvalString("drawnow;");
 #endif
-        evaluate_over_periods(true);
+      evaluate_over_periods(true);
       break;
     case EVALUATE_BACKWARD:
 #ifdef DEBUG
       mexPrintf("EVALUATE_BACKWARD\n");
       mexEvalString("drawnow;");
 #endif
-        evaluate_over_periods(false);
+      evaluate_over_periods(false);
       break;
     case SOLVE_FORWARD_SIMPLE:
 #ifdef DEBUG
@@ -431,8 +437,11 @@ Interpreter::simulate_a_block(vector_table_conditional_local_type vector_table_c
         }
       u_count = u_count_int*(periods+y_kmax+y_kmin);
       r = (double *) mxMalloc(size*sizeof(double));
+      test_mxMalloc(r, __LINE__, __FILE__, __func__, size*sizeof(double));
       res = (double *) mxMalloc(size*periods*sizeof(double));
+      test_mxMalloc(res, __LINE__, __FILE__, __func__, size*periods*sizeof(double));
       y_save = (double *) mxMalloc(y_size*sizeof(double)*(periods+y_kmax+y_kmin));
+      test_mxMalloc(y_save, __LINE__, __FILE__, __func__, y_size*sizeof(double)*(periods+y_kmax+y_kmin));
       start_code = it_code;
       iter = 0;
       if (!is_linear)
@@ -450,14 +459,14 @@ Interpreter::simulate_a_block(vector_table_conditional_local_type vector_table_c
               memcpy(y_save, y, y_size*sizeof(double)*(periods+y_kmax+y_kmin));
               if (vector_table_conditional_local.size())
                 {
-                  for (vector_table_conditional_local_type::iterator it1 = vector_table_conditional_local.begin(); it1 != vector_table_conditional_local.end() ; it1++)
+                  for (vector_table_conditional_local_type::iterator it1 = vector_table_conditional_local.begin(); it1 != vector_table_conditional_local.end(); it1++)
                     {
                       if (it1->is_cond)
                         {
                           //mexPrintf("y[%d] = %f\n", it1->var_endo + y_kmin * size, y[it1->var_endo + y_kmin * size]);
                           y[it1->var_endo + y_kmin * size] = it1->constrained_value;
                         }
-                        
+
                     }
                 }
               compute_complete_2b(false, &res1, &res2, &max_res, &max_res_idx);
@@ -465,7 +474,7 @@ Interpreter::simulate_a_block(vector_table_conditional_local_type vector_table_c
               if (!(isnan(res1) || isinf(res1)))
                 cvg = (max_res < solve_tolf);
               if (isnan(res1) || isinf(res1) || (stack_solve_algo == 4 && iter > 0))
-                  memcpy(y, y_save, y_size*sizeof(double)*(periods+y_kmax+y_kmin));
+                memcpy(y, y_save, y_size*sizeof(double)*(periods+y_kmax+y_kmin));
               u_count = u_count_saved;
               int prev_iter = iter;
               Simulate_Newton_Two_Boundaries(block_num, symbol_table_endo_nbr, y_kmin, y_kmax, size, periods, cvg, minimal_solving_periods, stack_solve_algo, endo_name_length, P_endo_names, vector_table_conditional_local);
@@ -499,12 +508,18 @@ Interpreter::simulate_a_block(vector_table_conditional_local_type vector_table_c
           max_res = 0; max_res_idx = 0;
         }
       it_code = end_code;
-      mxFree(r);
-      mxFree(y_save);
-      mxFree(u);
-      mxFree(index_vara);
-      mxFree(index_equa);
-      mxFree(res);
+      if (r)
+        mxFree(r);
+      if (y_save)
+        mxFree(y_save);
+      if (u)
+        mxFree(u);
+      if (index_vara)
+        mxFree(index_vara);
+      if (index_equa)
+        mxFree(index_equa);
+      if (res)
+        mxFree(res);
       memset(direction, 0, size_of_direction);
       End_Solver();
       break;
@@ -558,14 +573,14 @@ Interpreter::print_a_block()
     }
 }
 
-void 
+void
 Interpreter::ReadCodeFile(string file_name, CodeLoad &code)
 {
   if (steady_state)
     file_name += "_static";
   else
     file_name += "_dynamic";
- 
+
   //First read and store in memory the code
   code_liste = code.get_op_code(file_name);
   EQN_block_number = code.get_block_number();
@@ -584,9 +599,8 @@ Interpreter::ReadCodeFile(string file_name, CodeLoad &code)
 
 }
 
-
 void
-Interpreter::check_for_controlled_exo_validity(FBEGINBLOCK_ *fb,vector<s_plan> sconstrained_extended_path)
+Interpreter::check_for_controlled_exo_validity(FBEGINBLOCK_ *fb, vector<s_plan> sconstrained_extended_path)
 {
   vector<unsigned int> exogenous = fb->get_exogenous();
   vector<int> endogenous = fb->get_endogenous();
@@ -615,8 +629,6 @@ Interpreter::check_for_controlled_exo_validity(FBEGINBLOCK_ *fb,vector<s_plan> s
     previous_block_exogenous.push_back(*it);
 }
 
-
-
 bool
 Interpreter::MainLoop(string bin_basename, CodeLoad code, bool evaluate, int block, bool last_call, bool constrained, vector<s_plan> sconstrained_extended_path, vector_table_conditional_local_type vector_table_conditional_local)
 {
@@ -653,9 +665,7 @@ Interpreter::MainLoop(string bin_basename, CodeLoad code, bool evaluate, int blo
             Block_Contain = fb->get_Block_Contain();
             it_code++;
             if (constrained)
-              {
-                check_for_controlled_exo_validity(fb,sconstrained_extended_path);
-              }
+              check_for_controlled_exo_validity(fb, sconstrained_extended_path);
             set_block(fb->get_size(), fb->get_type(), file_name, bin_basename, Block_Count, fb->get_is_linear(), fb->get_endo_nbr(), fb->get_Max_Lag(), fb->get_Max_Lead(), fb->get_u_count_int(), block);
             if (print)
               print_a_block();
@@ -690,7 +700,7 @@ Interpreter::MainLoop(string bin_basename, CodeLoad code, bool evaluate, int blo
 #ifdef DEBUG
                 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      
+#endif
                 bool result;
                 if (sconstrained_extended_path.size())
                   {
@@ -702,7 +712,7 @@ Interpreter::MainLoop(string bin_basename, CodeLoad code, bool evaluate, int blo
                     jacobian_other_endo_block.push_back(mxCreateDoubleMatrix(fb->get_size(), fb->get_nb_col_other_endo_jacob(), mxREAL));
                     residual = vector<double>(fb->get_size()*(periods+y_kmin));
                     result = simulate_a_block(vector_table_conditional_local);
-                    
+
                     mxDestroyArray(jacobian_block.back());
                     jacobian_block.pop_back();
                     mxDestroyArray(jacobian_exo_block.back());
@@ -713,10 +723,7 @@ Interpreter::MainLoop(string bin_basename, CodeLoad code, bool evaluate, int blo
                     jacobian_other_endo_block.pop_back();
                   }
                 else
-                  {
-                    result = simulate_a_block(vector_table_conditional_local);
-                  }
-                  
+                  result = simulate_a_block(vector_table_conditional_local);
                 //mexPrintf("OKe\n");
                 if (max_res > max_res_local)
                   {
@@ -751,6 +758,7 @@ Interpreter::MainLoop(string bin_basename, CodeLoad code, bool evaluate, int blo
           if (T)
             mxFree(T);
           T = (double *) mxMalloc(var*(periods+y_kmin+y_kmax)*sizeof(double));
+          test_mxMalloc(T, __LINE__, __FILE__, __func__, var*(periods+y_kmin+y_kmax)*sizeof(double));
           if (block >= 0)
             {
               it_code = code_liste.begin() + code.get_begin_block(block);
@@ -776,7 +784,10 @@ Interpreter::MainLoop(string bin_basename, CodeLoad code, bool evaluate, int blo
               T = mxGetPr(GlobalTemporaryTerms);
             }
           else
-            T = (double *) mxMalloc(var*sizeof(double));
+            {
+              T = (double *) mxMalloc(var*sizeof(double));
+              test_mxMalloc(T, __LINE__, __FILE__, __func__, var*sizeof(double));
+            }
 
           if (block >= 0)
             it_code = code_liste.begin() + code.get_begin_block(block);
@@ -789,7 +800,7 @@ Interpreter::MainLoop(string bin_basename, CodeLoad code, bool evaluate, int blo
           throw FatalExceptionHandling(tmp.str());
         }
     }
-  max_res = max_res_local ;
+  max_res = max_res_local;
   max_res_idx = max_res_idx_local;
   Close_SaveCode();
   return true;
@@ -808,13 +819,13 @@ Interpreter::elastic(string str, unsigned int len, bool left)
           if (left)
             {
               //mexPrintf("(1) diff=%d\n",diff);
-              str.insert(str.end(),diff-1,' ');
-              str.insert(str.begin(),1,' ');
+              str.insert(str.end(), diff-1, ' ');
+              str.insert(str.begin(), 1, ' ');
             }
           else
             {
-              str.insert(str.end(),diff/2,' ');
-              str.insert(str.begin(),diff/2,' ');
+              str.insert(str.end(), diff/2, ' ');
+              str.insert(str.begin(), diff/2, ' ');
             }
         }
       else
@@ -822,13 +833,13 @@ Interpreter::elastic(string str, unsigned int len, bool left)
           if (left)
             {
               //mexPrintf("(2) diff=%d\n",diff);
-              str.insert(str.end(),diff-1,' ');
-              str.insert(str.begin(),1,' ');
+              str.insert(str.end(), diff-1, ' ');
+              str.insert(str.begin(), 1, ' ');
             }
           else
             {
-              str.insert(str.end(),ceil(diff/2),' ');
-              str.insert(str.begin(),ceil(diff/2+1),' ');
+              str.insert(str.end(), ceil(diff/2), ' ');
+              str.insert(str.begin(), ceil(diff/2+1), ' ');
             }
         }
       return str;
@@ -839,12 +850,19 @@ bool
 Interpreter::extended_path(string file_name, string bin_basename, bool evaluate, int block, int &nb_blocks, int nb_periods, vector<s_plan> sextended_path, vector<s_plan> sconstrained_extended_path, vector<string> dates, table_conditional_global_type table_conditional_global)
 {
   CodeLoad code;
+
   ReadCodeFile(file_name, code);
   it_code = code_liste.begin();
   it_code_type Init_Code = code_liste.begin();
-  size_t size_of_direction = y_size*(periods + y_kmax + y_kmin)*sizeof(double);
+  /*size_t size_of_direction = y_size*(periods + y_kmax + y_kmin)*sizeof(double);
+    double *y_save = (double *) mxMalloc(size_of_direction);
+    double *x_save = (double *) mxMalloc((periods + y_kmax + y_kmin) * col_x *sizeof(double));*/
+  size_t size_of_direction = y_size*col_y*sizeof(double);
   double *y_save = (double *) mxMalloc(size_of_direction);
-  double *x_save = (double *) mxMalloc((periods + y_kmax + y_kmin) * col_x *sizeof(double));
+  test_mxMalloc(y_save, __LINE__, __FILE__, __func__, size_of_direction);
+  double *x_save = (double *) mxMalloc(nb_row_x * col_x *sizeof(double));
+  test_mxMalloc(x_save, __LINE__, __FILE__, __func__, nb_row_x * col_x *sizeof(double));
+
   vector_table_conditional_local_type vector_table_conditional_local;
   vector_table_conditional_local.clear();
 
@@ -855,9 +873,9 @@ Interpreter::extended_path(string file_name, string bin_basename, bool evaluate,
       x[j] = 0;
     }
   for (int j = 0; j < col_x; j++)
-    x[y_kmin + j * nb_row_x] = x_save[1 + y_kmin + j * nb_row_x];
-  for (int i = 0; i < (y_size*(periods + y_kmax + y_kmin)); i++)
-    y_save[i]  = y[i];
+    x[y_kmin + j * nb_row_x] = x_save[y_kmin + j * nb_row_x];
+  for (int i = 0; i < y_size * col_y; i++)
+    y_save[i] = y[i];
   if (endo_name_length_l < 8)
     endo_name_length_l = 8;
   bool old_print_it = print_it;
@@ -868,16 +886,16 @@ Interpreter::extended_path(string file_name, string bin_basename, bool evaluate,
   int date_length = dates[0].length();
   int table_length = 2 + date_length + 3 + endo_name_length_l + 3 + real_max_length + 3 + 3 + 2 + 6 + 2;
   string line;
-  line.insert(line.begin(),table_length,'-');
-  line.insert(line.length(),"\n");
+  line.insert(line.begin(), table_length, '-');
+  line.insert(line.length(), "\n");
   if (old_print_it)
     {
-       mexPrintf("\nExtended Path simulation:\n");
-       mexPrintf("-------------------------\n");
-       mexPrintf(line.c_str());
-       string title = "|" + elastic("date",date_length+2, false) + "|" + elastic("variable",endo_name_length_l+2, false) + "|" + elastic("max. value",real_max_length+2, false) + "| iter. |" + elastic("cvg",5, false) + "|\n";
-       mexPrintf(title.c_str());
-       mexPrintf(line.c_str());
+      mexPrintf("\nExtended Path simulation:\n");
+      mexPrintf("-------------------------\n");
+      mexPrintf(line.c_str());
+      string title = "|" + elastic("date", date_length+2, false) + "|" + elastic("variable", endo_name_length_l+2, false) + "|" + elastic("max. value", real_max_length+2, false) + "| iter. |" + elastic("cvg", 5, false) + "|\n";
+      mexPrintf(title.c_str());
+      mexPrintf(line.c_str());
     }
   for (int t = 0; t < nb_periods; t++)
     {
@@ -885,18 +903,21 @@ Interpreter::extended_path(string file_name, string bin_basename, bool evaluate,
       previous_block_exogenous.clear();
       if (old_print_it)
         {
-          mexPrintf("|%s|",elastic(dates[t], date_length+2, false).c_str());
+          mexPrintf("|%s|", elastic(dates[t], date_length+2, false).c_str());
           mexEvalString("drawnow;");
         }
       for (vector<s_plan>::const_iterator it = sextended_path.begin(); it != sextended_path.end(); it++)
-        x[y_kmin + (it->exo_num - 1) * (periods + y_kmax + y_kmin)] = it->value[t];
+        {
+          x[y_kmin + (it->exo_num - 1) * /*(nb_periods + y_kmax + y_kmin)*/ nb_row_x] = it->value[t];
+        }
+
       it_code = Init_Code;
       vector_table_conditional_local.clear();
       if (table_conditional_global.size())
         vector_table_conditional_local = table_conditional_global[t];
       if (t < nb_periods)
         MainLoop(bin_basename, code, evaluate, block, false, true, sconstrained_extended_path, vector_table_conditional_local);
-      else 
+      else
         MainLoop(bin_basename, code, evaluate, block, true, true, sconstrained_extended_path, vector_table_conditional_local);
       for (int j = 0; j < y_size; j++)
         {
@@ -907,35 +928,38 @@ Interpreter::extended_path(string file_name, string bin_basename, bool evaluate,
       for (int j = 0; j < col_x; j++)
         {
           x_save[t + y_kmin + j * nb_row_x] = x[y_kmin + j * nb_row_x];
-          x[y_kmin + j * nb_row_x] = x_save[t + 1 + y_kmin + j * nb_row_x];
+          if (t < nb_periods)
+            x[y_kmin + j * nb_row_x] = x_save[t + 1 + y_kmin + j * nb_row_x];
         }
-        
+
       if (old_print_it)
         {
           ostringstream res, res1;
           for (unsigned int i = 0; i < endo_name_length; i++)
             if (P_endo_names[CHAR_LENGTH*(max_res_idx+i*y_size)] != ' ')
               res << P_endo_names[CHAR_LENGTH*(max_res_idx+i*y_size)];
-           res1 << std::scientific << max_res;
-          mexPrintf("%s|%s| %4d  |  x  |\n",elastic(res.str(),endo_name_length_l+2, true).c_str(), elastic(res1.str(), real_max_length+2, false).c_str(), iter);
+          res1 << std::scientific << max_res;
+          mexPrintf("%s|%s| %4d  |  x  |\n", elastic(res.str(), endo_name_length_l+2, true).c_str(), elastic(res1.str(), real_max_length+2, false).c_str(), iter);
           mexPrintf(line.c_str());
           mexEvalString("drawnow;");
         }
     }
   print_it = old_print_it;
-  for (int j = 0; j < y_size; j++)
+  /*for (int j = 0; j < y_size; j++)
     {
-      for(int k = nb_periods; k < periods; k++)
-        y_save[j + (k + y_kmin) * y_size] = y[ j +  ( k - (nb_periods-1) + y_kmin) * y_size];
-    }
-  for (int i = 0; i < (y_size*(periods + y_kmax + y_kmin)); i++)
+    for(int k = nb_periods; k < periods; k++)
+    y_save[j + (k + y_kmin) * y_size] = y[ j +  ( k - (nb_periods-1) + y_kmin) * y_size];
+    }*/
+  for (int i = 0; i < y_size * col_y; i++)
     y[i]  = y_save[i];
-  for (int j = 0; j < col_x* nb_row_x; j++)
+  for (int j = 0; j < col_x * nb_row_x; j++)
     x[j] = x_save[j];
-    
-  mxFree(Init_Code->second);
-  mxFree(y_save);
-  mxFree(x_save);
+  if (Init_Code->second)
+    mxFree(Init_Code->second);
+  if (y_save)
+    mxFree(y_save);
+  if (x_save)
+    mxFree(x_save);
   nb_blocks = Block_Count+1;
   if (T && !global_temporary_terms)
     mxFree(T);
@@ -947,7 +971,7 @@ Interpreter::compute_blocks(string file_name, string bin_basename, bool evaluate
 {
   CodeLoad code;
   ReadCodeFile(file_name, code);
-  
+
   //The big loop on intructions
   it_code = code_liste.begin();
   it_code_type Init_Code = it_code;
@@ -955,8 +979,7 @@ Interpreter::compute_blocks(string file_name, string bin_basename, bool evaluate
   vector_table_conditional_local_type vector_table_conditional_local_junk;
 
   MainLoop(bin_basename, code, evaluate, block, true, false, s_plan_junk, vector_table_conditional_local_junk);
-  
-  
+
   mxFree(Init_Code->second);
   nb_blocks = Block_Count+1;
   if (T && !global_temporary_terms)
diff --git a/mex/sources/bytecode/Interpreter.hh b/mex/sources/bytecode/Interpreter.hh
index a3d9973efa9b75f16f12e2f03ae1b30089449a67..d41e0c8cdd4c75ff6ba79f5a0f0096a5c42e838b 100644
--- a/mex/sources/bytecode/Interpreter.hh
+++ b/mex/sources/bytecode/Interpreter.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2013 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -41,11 +41,10 @@
 
 using namespace std;
 
-
 class Interpreter : public dynSparseMatrix
 {
 private:
-vector<int> previous_block_exogenous;
+  vector<int> previous_block_exogenous;
 protected:
   void evaluate_a_block(bool initialization);
   int simulate_a_block(vector_table_conditional_local_type vector_table_conditional_local);
@@ -59,14 +58,14 @@ public:
               int maxit_arg_, double solve_tolf_arg, size_t size_of_direction_arg, double slowc_arg, int y_decal_arg, double markowitz_c_arg,
               string &filename_arg, int minimal_solving_periods_arg, int stack_solve_algo_arg, int solve_algo_arg,
               bool global_temporary_terms_arg, bool print_arg, bool print_error_arg, mxArray *GlobalTemporaryTerms_arg,
-              bool steady_state_arg, bool print_it_arg, int col_x_arg
+              bool steady_state_arg, bool print_it_arg, int col_x_arg, int col_y_arg
 #ifdef CUDA
               , const int CUDA_device, cublasHandle_t cublas_handle_arg, cusparseHandle_t cusparse_handle_arg, cusparseMatDescr_t descr_arg
 #endif
               );
   bool extended_path(string file_name, string bin_basename, bool evaluate, int block, int &nb_blocks, int nb_periods, vector<s_plan> sextended_path, vector<s_plan> sconstrained_extended_path, vector<string> dates, table_conditional_global_type table_conditional_global);
   bool compute_blocks(string file_name, string bin_basename, bool evaluate, int block, int &nb_blocks);
-  void check_for_controlled_exo_validity(FBEGINBLOCK_ *fb,vector<s_plan> sconstrained_extended_path);
+  void check_for_controlled_exo_validity(FBEGINBLOCK_ *fb, vector<s_plan> sconstrained_extended_path);
   bool MainLoop(string bin_basename, CodeLoad code, bool evaluate, int block, bool last_call, bool constrained, vector<s_plan> sconstrained_extended_path, vector_table_conditional_local_type vector_table_conditional_local);
   void ReadCodeFile(string file_name, CodeLoad &code);
 
diff --git a/mex/sources/bytecode/Mem_Mngr.cc b/mex/sources/bytecode/Mem_Mngr.cc
index b239b60df123b8720ead411fde1cf6f804400f2a..52a2ab905e4fc056a0367f5d1c126d178d130e50 100644
--- a/mex/sources/bytecode/Mem_Mngr.cc
+++ b/mex/sources/bytecode/Mem_Mngr.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2011 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -24,15 +24,16 @@ Mem_Mngr::Mem_Mngr()
   swp_f = false;
   swp_f_b = 0;
 }
-void
-Mem_Mngr::Print_heap()
-{
+/*void
+  Mem_Mngr::Print_heap()
+  {
   unsigned int i;
   mexPrintf("i   :");
   for (i = 0; i < CHUNK_SIZE; i++)
-    mexPrintf("%3d ", i);
+  mexPrintf("%3d ", i);
   mexPrintf("\n");
-}
+  }
+*/
 
 void
 Mem_Mngr::init_Mem()
@@ -49,7 +50,7 @@ Mem_Mngr::init_Mem()
 void
 Mem_Mngr::fixe_file_name(string filename_arg)
 {
-  filename = filename_arg;
+  filename_mem = filename_arg;
 }
 
 void
@@ -78,25 +79,25 @@ Mem_Mngr::mxMalloc_NZE()
       CHUNK_SIZE += CHUNK_BLCK_SIZE;
       Nb_CHUNK++;
       NZE_Mem = (NonZeroElem *) mxMalloc(CHUNK_BLCK_SIZE*sizeof(NonZeroElem));      /*The block of memory allocated*/
+      error_msg.test_mxMalloc(NZE_Mem, __LINE__, __FILE__, __func__, CHUNK_BLCK_SIZE*sizeof(NonZeroElem));
       NZE_Mem_Allocated.push_back(NZE_Mem);
       if (!NZE_Mem)
+        mexPrintf("Not enough memory available\n");
+      if (NZE_Mem_add)
         {
-          mexPrintf("Not enough memory available\n");
-          mexEvalString("drawnow;");
+          NZE_Mem_add = (NonZeroElem **) mxRealloc(NZE_Mem_add, CHUNK_SIZE*sizeof(NonZeroElem *));                                                                                                     /*We have to redefine the size of pointer on the memory*/
+          error_msg.test_mxMalloc(NZE_Mem_add, __LINE__, __FILE__, __func__, CHUNK_SIZE*sizeof(NonZeroElem *));
         }
-      if (NZE_Mem_add)
-        NZE_Mem_add = (NonZeroElem **) mxRealloc(NZE_Mem_add, CHUNK_SIZE*sizeof(NonZeroElem *));                                                                                                     /*We have to redefine the size of pointer on the memory*/
       else
-        NZE_Mem_add = (NonZeroElem **) mxMalloc(CHUNK_SIZE*sizeof(NonZeroElem *));                                                                                       /*We have to define the size of pointer on the memory*/
-      if (!NZE_Mem_add)
         {
-          mexPrintf("Not enough memory available\n");
-          mexEvalString("drawnow;");
+          NZE_Mem_add = (NonZeroElem **) mxMalloc(CHUNK_SIZE*sizeof(NonZeroElem *));                                                                                       /*We have to define the size of pointer on the memory*/
+          error_msg.test_mxMalloc(NZE_Mem_add, __LINE__, __FILE__, __func__, CHUNK_SIZE*sizeof(NonZeroElem *));
         }
+
+      if (!NZE_Mem_add)
+        mexPrintf("Not enough memory available\n");
       for (i = CHUNK_heap_pos; i < CHUNK_SIZE; i++)
-        {
-          NZE_Mem_add[i] = (NonZeroElem *) (NZE_Mem+(i-CHUNK_heap_pos));
-        }
+        NZE_Mem_add[i] = (NonZeroElem *) (NZE_Mem+(i-CHUNK_heap_pos));
       i = CHUNK_heap_pos++;
       return (NZE_Mem_add[i]);
     }
diff --git a/mex/sources/bytecode/Mem_Mngr.hh b/mex/sources/bytecode/Mem_Mngr.hh
index be3c3c404c3d22e2def0d2a8a435bc9187af434d..4bde597a04fc7c2c3f203fbb3db95cc8bc9b234e 100644
--- a/mex/sources/bytecode/Mem_Mngr.hh
+++ b/mex/sources/bytecode/Mem_Mngr.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2010 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -20,6 +20,7 @@
 #ifndef MEM_MNGR_HH_INCLUDED
 #define MEM_MNGR_HH_INCLUDED
 
+#include "ErrorHandling.hh"
 #include <vector>
 #include <fstream>
 #ifndef DEBUG_EX
@@ -27,7 +28,7 @@
 #else
 # include "mex_interface.hh"
 #endif
-using namespace std;
+//using namespace std;
 
 struct NonZeroElem
 {
@@ -41,7 +42,7 @@ typedef vector<NonZeroElem *> v_NonZeroElem;
 class Mem_Mngr
 {
 public:
-  void Print_heap();
+  //void Print_heap();
   void init_Mem();
   void mxFree_NZE(void *pos);
   NonZeroElem *mxMalloc_NZE();
@@ -50,6 +51,7 @@ public:
   Mem_Mngr();
   void fixe_file_name(string filename_arg);
   bool swp_f;
+  ErrorMsg error_msg;
 private:
   v_NonZeroElem Chunk_Stack;
   unsigned int CHUNK_SIZE, CHUNK_BLCK_SIZE, Nb_CHUNK;
@@ -59,7 +61,7 @@ private:
   vector<NonZeroElem *> NZE_Mem_Allocated;
   int swp_f_b;
   fstream  SaveCode_swp;
-  string filename;
+  string filename_mem;
 };
 
 #endif
diff --git a/mex/sources/bytecode/SparseMatrix.cc b/mex/sources/bytecode/SparseMatrix.cc
index 840f302a67679072b6eda38adb975d86892e50e5..7db7341cbac531666a356e256a1a1eb8ca0f6ce9 100644
--- a/mex/sources/bytecode/SparseMatrix.cc
+++ b/mex/sources/bytecode/SparseMatrix.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2013 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -28,67 +28,64 @@
 #include "SparseMatrix.hh"
 
 #ifdef CUDA
-#include "SparseMatrix_kernel.cu"
+# include "SparseMatrix_kernel.cu"
 #endif
 
 using namespace std;
 #ifdef _MSC_VER
-#include <windows.h>
+# include <windows.h>
 HINSTANCE hinstLib;
 
-#define UMFPACK_INFO 90
-#define UMFPACK_CONTROL 20
+# define UMFPACK_INFO 90
+# define UMFPACK_CONTROL 20
 /* used in all UMFPACK_report_* routines: */
-#define UMFPACK_PRL 0			/* print level */
+# define UMFPACK_PRL 0                   /* print level */
 /* returned by all routines that use Info: */
-#define UMFPACK_OK (0)
-#define UMFPACK_STATUS 0	/* UMFPACK_OK, or other result */
+# define UMFPACK_OK (0)
+# define UMFPACK_STATUS 0        /* UMFPACK_OK, or other result */
 
 typedef void (*t_umfpack_dl_free_numeric)(void **Numeric);
 t_umfpack_dl_free_numeric umfpack_dl_free_numeric;
 typedef void (*t_umfpack_dl_free_symbolic)(void **Symbolic);
 t_umfpack_dl_free_symbolic umfpack_dl_free_symbolic;
 typedef int64_t (*t_umfpack_dl_solve)(int64_t sys,
-                                      const int64_t Ap [ ],
-                                      const int64_t Ai [ ],
-                                      const double Ax [ ],
-                                      double X [ ],
-                                      const double B [ ],
+                                      const int64_t Ap [],
+                                      const int64_t Ai [],
+                                      const double Ax [],
+                                      double X [],
+                                      const double B [],
                                       void *Numeric,
                                       const double Control [UMFPACK_CONTROL],
                                       double Info [UMFPACK_INFO]);
 t_umfpack_dl_solve umfpack_dl_solve;
-typedef int64_t (*t_umfpack_dl_numeric)(const int64_t Ap [ ],
-                                        const int64_t Ai [ ],
-                                        const double Ax [ ],
+typedef int64_t (*t_umfpack_dl_numeric)(const int64_t Ap [],
+                                        const int64_t Ai [],
+                                        const double Ax [],
                                         void *Symbolic,
                                         void **Numeric,
                                         const double Control [UMFPACK_CONTROL],
                                         double Info [UMFPACK_INFO]);
 t_umfpack_dl_numeric umfpack_dl_numeric;
 typedef int64_t (*t_umfpack_dl_symbolic)(int64_t n_row,
-    int64_t n_col,
-    const int64_t Ap [ ],
-    const int64_t Ai [ ],
-    const double Ax [ ],
-    void **Symbolic,
-    const double Control [UMFPACK_CONTROL],
-    double Info [UMFPACK_INFO]);
+                                         int64_t n_col,
+                                         const int64_t Ap [],
+                                         const int64_t Ai [],
+                                         const double Ax [],
+                                         void **Symbolic,
+                                         const double Control [UMFPACK_CONTROL],
+                                         double Info [UMFPACK_INFO]);
 t_umfpack_dl_symbolic umfpack_dl_symbolic;
 typedef void (*t_umfpack_dl_report_info)(const double Control [UMFPACK_CONTROL],
-    const double Info [UMFPACK_INFO]);
+                                         const double Info [UMFPACK_INFO]);
 t_umfpack_dl_report_info umfpack_dl_report_info;
 typedef void (*t_umfpack_dl_report_status)(const double Control [UMFPACK_CONTROL],
-    int64_t status);
+                                           int64_t status);
 t_umfpack_dl_report_status umfpack_dl_report_status;
 typedef void (*t_umfpack_dl_defaults)(double Control [UMFPACK_CONTROL]);
 t_umfpack_dl_defaults umfpack_dl_defaults;
 
 #endif
 
-
-
-
 dynSparseMatrix::dynSparseMatrix()
 {
   pivotva = NULL;
@@ -183,11 +180,11 @@ dynSparseMatrix::dynSparseMatrix()
 }
 
 dynSparseMatrix::dynSparseMatrix(const int y_size_arg, const int y_kmin_arg, const int y_kmax_arg, const bool print_it_arg, const bool steady_state_arg, const int periods_arg,
-                           const int minimal_solving_periods_arg, const double slowc_arg
+                                 const int minimal_solving_periods_arg, const double slowc_arg
 #ifdef CUDA
-                           , const int CUDA_device_arg, cublasHandle_t cublas_handle_arg, cusparseHandle_t cusparse_handle_arg, cusparseMatDescr_t descr_arg
+                                 , const int CUDA_device_arg, cublasHandle_t cublas_handle_arg, cusparseHandle_t cusparse_handle_arg, cusparseMatDescr_t descr_arg
 #endif
-                           ):
+                                 ) :
   Evaluate(y_size_arg, y_kmin_arg, y_kmax_arg, print_it_arg, steady_state_arg, periods_arg, minimal_solving_periods_arg, slowc_arg)
 {
   pivotva = NULL;
@@ -286,7 +283,6 @@ dynSparseMatrix::dynSparseMatrix(const int y_size_arg, const int y_kmin_arg, con
 #endif
 }
 
-
 int
 dynSparseMatrix::NRow(int r)
 {
@@ -531,7 +527,7 @@ dynSparseMatrix::Read_SparseMatrix(string file_name, const int Size, int periods
   filename = file_name;
   mem_mngr.fixe_file_name(file_name);
   /*mexPrintf("steady_state=%d, size=%d, solve_algo=%d, stack_solve_algo=%d, two_boundaries=%d\n",steady_state, Size, solve_algo, stack_solve_algo, two_boundaries);
-  mexEvalString("drawnow;");*/
+    mexEvalString("drawnow;");*/
   if (!SaveCode.is_open())
     {
       if (steady_state)
@@ -622,6 +618,7 @@ dynSparseMatrix::Read_SparseMatrix(string file_name, const int Size, int periods
         }
     }
   index_vara = (int *) mxMalloc(Size*(periods+y_kmin+y_kmax)*sizeof(int));
+  test_mxMalloc(index_vara, __LINE__, __FILE__, __func__, Size*(periods+y_kmin+y_kmax)*sizeof(int));
   for (int j = 0; j < Size; j++)
     SaveCode.read(reinterpret_cast<char *>(&index_vara[j]), sizeof(*index_vara));
   if (periods+y_kmin+y_kmax > 1)
@@ -631,6 +628,7 @@ dynSparseMatrix::Read_SparseMatrix(string file_name, const int Size, int periods
           index_vara[j+Size*i] = index_vara[j+Size*(i-1)] + y_size;
       }
   index_equa = (int *) mxMalloc(Size*sizeof(int));
+  test_mxMalloc(index_equa, __LINE__, __FILE__, __func__, Size*sizeof(int));
   for (int j = 0; j < Size; j++)
     SaveCode.read(reinterpret_cast<char *>(&index_equa[j]), sizeof(*index_equa));
 }
@@ -642,24 +640,37 @@ dynSparseMatrix::Simple_Init(int Size, map<pair<pair<int, int>, int>, int> &IM,
   map<pair<pair<int, int>, int>, int>::iterator it4;
   NonZeroElem *first;
   pivot = (int *) mxMalloc(Size*sizeof(int));
+  test_mxMalloc(pivot, __LINE__, __FILE__, __func__, Size*sizeof(int));
   pivot_save = (int *) mxMalloc(Size*sizeof(int));
+  test_mxMalloc(pivot_save, __LINE__, __FILE__, __func__, Size*sizeof(int));
   pivotk = (int *) mxMalloc(Size*sizeof(int));
+  test_mxMalloc(pivotk, __LINE__, __FILE__, __func__, Size*sizeof(int));
   pivotv = (double *) mxMalloc(Size*sizeof(double));
+  test_mxMalloc(pivotv, __LINE__, __FILE__, __func__, Size*sizeof(double));
   pivotva = (double *) mxMalloc(Size*sizeof(double));
+  test_mxMalloc(pivotva, __LINE__, __FILE__, __func__, Size*sizeof(double));
   b = (int *) mxMalloc(Size*sizeof(int));
+  test_mxMalloc(b, __LINE__, __FILE__, __func__, Size*sizeof(int));
   line_done = (bool *) mxMalloc(Size*sizeof(bool));
+  test_mxMalloc(line_done, __LINE__, __FILE__, __func__, Size*sizeof(bool));
 
   mem_mngr.init_CHUNK_BLCK_SIZE(u_count);
   g_save_op = NULL;
   g_nop_all = 0;
   i = Size*sizeof(NonZeroElem *);
   FNZE_R = (NonZeroElem **) mxMalloc(i);
+  test_mxMalloc(FNZE_R, __LINE__, __FILE__, __func__, i);
   FNZE_C = (NonZeroElem **) mxMalloc(i);
+  test_mxMalloc(FNZE_C, __LINE__, __FILE__, __func__, i);
   NonZeroElem **temp_NZE_R = (NonZeroElem **) mxMalloc(i);
+  test_mxMalloc(temp_NZE_R, __LINE__, __FILE__, __func__, i);
   NonZeroElem **temp_NZE_C = (NonZeroElem **) mxMalloc(i);
+  test_mxMalloc(temp_NZE_C, __LINE__, __FILE__, __func__, i);
   i = Size*sizeof(int);
   NbNZRow = (int *) mxMalloc(i);
+  test_mxMalloc(NbNZRow, __LINE__, __FILE__, __func__, i);
   NbNZCol = (int *) mxMalloc(i);
+  test_mxMalloc(NbNZCol, __LINE__, __FILE__, __func__, i);
   it4 = IM.begin();
   eq = -1;
   for (i = 0; i < Size; i++)
@@ -833,12 +844,12 @@ dynSparseMatrix::Init_Matlab_Sparse_Simple(int Size, map<pair<pair<int, int>, in
   Aj[Size] = NZE;
 }
 
-
 void
 dynSparseMatrix::Init_UMFPACK_Sparse_Simple(int Size, map<pair<pair<int, int>, int>, int> &IM, SuiteSparse_long **Ap, SuiteSparse_long **Ai, double **Ax, double **b, bool &zero_solution, mxArray *x0_m)
 {
   int eq, var;
-  *b = (double*)mxMalloc(Size * sizeof(double));
+  *b = (double *) mxMalloc(Size * sizeof(double));
+  test_mxMalloc(*b, __LINE__, __FILE__, __func__, Size * sizeof(double));
   if (!(*b))
     {
       ostringstream tmp;
@@ -852,7 +863,8 @@ dynSparseMatrix::Init_UMFPACK_Sparse_Simple(int Size, map<pair<pair<int, int>, i
       tmp << " in Init_UMFPACK_Sparse_Simple, can't retrieve x0 vector\n";
       throw FatalExceptionHandling(tmp.str());
     }
-  *Ap = (SuiteSparse_long*)mxMalloc((Size+1) * sizeof(SuiteSparse_long));
+  *Ap = (SuiteSparse_long *) mxMalloc((Size+1) * sizeof(SuiteSparse_long));
+  test_mxMalloc(*Ap, __LINE__, __FILE__, __func__, (Size+1) * sizeof(SuiteSparse_long));
   if (!(*Ap))
     {
       ostringstream tmp;
@@ -860,14 +872,16 @@ dynSparseMatrix::Init_UMFPACK_Sparse_Simple(int Size, map<pair<pair<int, int>, i
       throw FatalExceptionHandling(tmp.str());
     }
   size_t prior_nz = IM.size();
-  *Ai = (SuiteSparse_long*)mxMalloc(prior_nz * sizeof(SuiteSparse_long));
+  *Ai = (SuiteSparse_long *) mxMalloc(prior_nz * sizeof(SuiteSparse_long));
+  test_mxMalloc(*Ai, __LINE__, __FILE__, __func__, prior_nz * sizeof(SuiteSparse_long));
   if (!(*Ai))
     {
       ostringstream tmp;
       tmp << " in Init_UMFPACK_Sparse, can't allocate Ai index vector\n";
       throw FatalExceptionHandling(tmp.str());
     }
-  *Ax = (double*)mxMalloc(prior_nz * sizeof(double));
+  *Ax = (double *) mxMalloc(prior_nz * sizeof(double));
+  test_mxMalloc(*Ax, __LINE__, __FILE__, __func__, prior_nz * sizeof(double));
   if (!(*Ax))
     {
       ostringstream tmp;
@@ -984,13 +998,13 @@ void
 dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Size, map<pair<pair<int, int>, int>, int> &IM, SuiteSparse_long **Ap, SuiteSparse_long **Ai, double **Ax, double **b, mxArray *x0_m, vector_table_conditional_local_type vector_table_conditional_local, int block_num)
 {
   int t, eq, var, lag, ti_y_kmin, ti_y_kmax;
-  double* jacob_exo ;
-  int row_x;
+  double *jacob_exo;
+  int row_x = 0;
 #ifdef DEBUG
   int col_x;
 #endif
   int n = periods * Size;
-  *b = (double*)mxMalloc(n * sizeof(double));
+  *b = (double *) mxMalloc(n * sizeof(double));
   if (!(*b))
     {
       ostringstream tmp;
@@ -1004,7 +1018,8 @@ dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Si
       tmp << " in Init_UMFPACK_Sparse_Simple, can't retrieve x0 vector\n";
       throw FatalExceptionHandling(tmp.str());
     }
-  *Ap = (SuiteSparse_long*)mxMalloc((n+1) * sizeof(SuiteSparse_long));
+  *Ap = (SuiteSparse_long *) mxMalloc((n+1) * sizeof(SuiteSparse_long));
+  test_mxMalloc(*Ap, __LINE__, __FILE__, __func__, (n+1) * sizeof(SuiteSparse_long));
   if (!(*Ap))
     {
       ostringstream tmp;
@@ -1012,14 +1027,16 @@ dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Si
       throw FatalExceptionHandling(tmp.str());
     }
   size_t prior_nz = IM.size() * periods;
-  *Ai = (SuiteSparse_long*)mxMalloc(prior_nz * sizeof(SuiteSparse_long));
+  *Ai = (SuiteSparse_long *) mxMalloc(prior_nz * sizeof(SuiteSparse_long));
+  test_mxMalloc(*Ai, __LINE__, __FILE__, __func__, prior_nz * sizeof(SuiteSparse_long));
   if (!(*Ai))
     {
       ostringstream tmp;
       tmp << " in Init_UMFPACK_Sparse, can't allocate Ai index vector\n";
       throw FatalExceptionHandling(tmp.str());
     }
-  *Ax = (double*)mxMalloc(prior_nz * sizeof(double));
+  *Ax = (double *) mxMalloc(prior_nz * sizeof(double));
+  test_mxMalloc(*Ax, __LINE__, __FILE__, __func__, prior_nz * sizeof(double));
   if (!(*Ax))
     {
       ostringstream tmp;
@@ -1047,10 +1064,14 @@ dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Si
       col_x = mxGetN(jacobian_exo_block[block_num]);
 #endif
     }
+  else
+    {
+      jacob_exo = NULL;
+    }
 #ifdef DEBUG
   int local_index;
 #endif
-  
+
   bool fliped = false;
   bool fliped_exogenous_derivatives_updated = false;
   int flip_exo;
@@ -1060,27 +1081,27 @@ dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Si
       last_var = -1;
       it4 = IM.begin();
       var = 0;
-      while (it4 != IM.end()) 
+      while (it4 != IM.end())
         {
           var = it4->first.first.first;
 #ifdef DEBUG
-           if (var < 0 || var >= Size)
-             {
-               ostringstream tmp;
-               tmp << " in Init_UMFPACK_Sparse, var (" << var << ") out of range\n";
-               throw FatalExceptionHandling(tmp.str());
-             }
+          if (var < 0 || var >= Size)
+            {
+              ostringstream tmp;
+              tmp << " in Init_UMFPACK_Sparse, var (" << var << ") out of range\n";
+              throw FatalExceptionHandling(tmp.str());
+            }
 #endif
           eq = it4->first.second+Size*t;
 #ifdef DEBUG
-           if (eq < 0 || eq >= Size)
-             {
-               ostringstream tmp;
-               tmp << " in Init_UMFPACK_Sparse, eq (" << eq << ") out of range\n";
-               throw FatalExceptionHandling(tmp.str());
-             }
+          if (eq < 0 || eq >= Size)
+            {
+              ostringstream tmp;
+              tmp << " in Init_UMFPACK_Sparse, eq (" << eq << ") out of range\n";
+              throw FatalExceptionHandling(tmp.str());
+            }
 #endif
-          lag = - it4->first.first.second;
+          lag = -it4->first.first.second;
           int index = it4->second+ (t-lag) * u_count_init;
           if (var != last_var)
             {
@@ -1117,27 +1138,27 @@ dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Si
                               (*Ax)[NZE] = jacob_exo[k + row_x*flip_exo];
                               (*Ai)[NZE] = k;
                               NZE++;
-                          
+
 #ifdef DEBUG
                               if (local_index < 0 || local_index >= Size * periods)
-                               {
-                                 ostringstream tmp;
-                                 tmp << " in Init_UMFPACK_Sparse, index (" << local_index << ") out of range for b vector\n";
-                                 throw FatalExceptionHandling(tmp.str());
-                               }
-                             if (k + row_x*flip_exo < 0 || k + row_x*flip_exo >= row_x * col_x)
-                               {
-                                 ostringstream tmp;
-                                 tmp << " in Init_UMFPACK_Sparse, index (" << var+Size*(y_kmin+t+lag) << ") out of range for jacob_exo vector\n";
-                                 throw FatalExceptionHandling(tmp.str());
-                               }
-                             if (t+y_kmin+flip_exo*nb_row_x < 0 || t+y_kmin+flip_exo*nb_row_x >= nb_row_x * this->col_x)
-                               {
-                                 ostringstream tmp;
-                                 tmp << " in Init_UMFPACK_Sparse, index (" << index_vara[var+Size*(y_kmin+t+lag)] << ") out of range for x vector max=" << nb_row_x * this->col_x << "\n";
-                                 throw FatalExceptionHandling(tmp.str());
-                               }
-#endif    
+                                {
+                                  ostringstream tmp;
+                                  tmp << " in Init_UMFPACK_Sparse, index (" << local_index << ") out of range for b vector\n";
+                                  throw FatalExceptionHandling(tmp.str());
+                                }
+                              if (k + row_x*flip_exo < 0 || k + row_x*flip_exo >= row_x * col_x)
+                                {
+                                  ostringstream tmp;
+                                  tmp << " in Init_UMFPACK_Sparse, index (" << var+Size*(y_kmin+t+lag) << ") out of range for jacob_exo vector\n";
+                                  throw FatalExceptionHandling(tmp.str());
+                                }
+                              if (t+y_kmin+flip_exo*nb_row_x < 0 || t+y_kmin+flip_exo*nb_row_x >= nb_row_x * this->col_x)
+                                {
+                                  ostringstream tmp;
+                                  tmp << " in Init_UMFPACK_Sparse, index (" << index_vara[var+Size*(y_kmin+t+lag)] << ") out of range for x vector max=" << nb_row_x * this->col_x << "\n";
+                                  throw FatalExceptionHandling(tmp.str());
+                                }
+#endif
                               u[k] -=  jacob_exo[k + row_x*flip_exo] * x[t+y_kmin+flip_exo*nb_row_x];
                             }
                         }
@@ -1146,12 +1167,12 @@ dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Si
             }
           /*if (t==0)
             {
-              if (min_lag > lag)
-                min_lag = lag;
-              if (max_lag < lag)
-                max_lag = lag;
+            if (min_lag > lag)
+            min_lag = lag;
+            if (max_lag < lag)
+            max_lag = lag;
             }*/
-          
+
           if (var < (periods+y_kmax)*Size)
             {
               ti_y_kmin = -min(t, y_kmin);
@@ -1195,16 +1216,16 @@ dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Si
                           tmp << " in Init_UMFPACK_Sparse, index (" << var+Size*(y_kmin+t) << ") out of range for index_vara vector\n";
                           throw FatalExceptionHandling(tmp.str());
                         }
-                      if (index_vara[var+Size*(y_kmin+t/*+lag*/)] < 0 || index_vara[var+Size*(y_kmin+t/*+lag*/)] >= y_size*(periods+y_kmin+y_kmax))
+                      if (index_vara[var+Size*(y_kmin+t /*+lag*/)] < 0 || index_vara[var+Size*(y_kmin+t /*+lag*/)] >= y_size*(periods+y_kmin+y_kmax))
                         {
                           ostringstream tmp;
-                          tmp << " in Init_UMFPACK_Sparse, index (" << index_vara[var+Size*(y_kmin+t/*+lag*/)] << ") out of range for y vector max=" << y_size*(periods+y_kmin+y_kmax) << "\n";
+                          tmp << " in Init_UMFPACK_Sparse, index (" << index_vara[var+Size*(y_kmin+t /*+lag*/)] << ") out of range for y vector max=" << y_size*(periods+y_kmin+y_kmax) << "\n";
                           throw FatalExceptionHandling(tmp.str());
-                          }
+                        }
 #endif
-                      (*b)[eq - lag * Size] += u[index] * y[index_vara[var+Size*(y_kmin+t/*+lag*/)]];
+                      (*b)[eq - lag * Size] += u[index] * y[index_vara[var+Size*(y_kmin+t /*+lag*/)]];
                     }
-                  
+
                 }
               if (lag > ti_y_kmax || lag < ti_y_kmin)
                 {
@@ -1256,17 +1277,17 @@ dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Si
 #ifdef DEBUG
   mexPrintf("*Ax = [");
   for (int i = 0; i < NZE; i++)
-    mexPrintf("%f ",(*Ax)[i]);
+    mexPrintf("%f ", (*Ax)[i]);
   mexPrintf("]\n");
 
   mexPrintf("*Ap = [");
   for (int i = 0; i < n+1; i++)
-    mexPrintf("%d ",(*Ap)[i]);
+    mexPrintf("%d ", (*Ap)[i]);
   mexPrintf("]\n");
 
   mexPrintf("*Ai = [");
   for (int i = 0; i < NZE; i++)
-    mexPrintf("%d ",(*Ai)[i]);
+    mexPrintf("%d ", (*Ai)[i]);
   mexPrintf("]\n");
 #endif
 }
@@ -1276,7 +1297,8 @@ dynSparseMatrix::Init_CUDA_Sparse_Simple(int Size, map<pair<pair<int, int>, int>
 {
   int eq, var;
 
-  *b = (double*)mxMalloc(Size * sizeof(double));
+  *b = (double *) mxMalloc(Size * sizeof(double));
+  test_mxMalloc(*b, __LINE__, __FILE__, __func__, Size * sizeof(double));
   if (!(*b))
     {
       ostringstream tmp;
@@ -1290,7 +1312,8 @@ dynSparseMatrix::Init_CUDA_Sparse_Simple(int Size, map<pair<pair<int, int>, int>
       tmp << " in Init_CUDA_Sparse_Simple, can't retrieve x0 vector\n";
       throw FatalExceptionHandling(tmp.str());
     }
-  *Ap = (SuiteSparse_long*)mxMalloc((Size+1) * sizeof(SuiteSparse_long));
+  *Ap = (SuiteSparse_long *) mxMalloc((Size+1) * sizeof(SuiteSparse_long));
+  test_mxMalloc(*Ap, __LINE__, __FILE__, __func__, (Size+1) * sizeof(SuiteSparse_long));
   if (!(*Ap))
     {
       ostringstream tmp;
@@ -1298,14 +1321,16 @@ dynSparseMatrix::Init_CUDA_Sparse_Simple(int Size, map<pair<pair<int, int>, int>
       throw FatalExceptionHandling(tmp.str());
     }
   size_t prior_nz = IM.size();
-  *Ai = (SuiteSparse_long*)mxMalloc(prior_nz * sizeof(SuiteSparse_long));
+  *Ai = (SuiteSparse_long *) mxMalloc(prior_nz * sizeof(SuiteSparse_long));
+  test_mxMalloc(*Ai, __LINE__, __FILE__, __func__, prior_nz * sizeof(SuiteSparse_long));
   if (!(*Ai))
     {
       ostringstream tmp;
       tmp << " in Init_CUDA_Sparse, can't allocate Ai index vector\n";
       throw FatalExceptionHandling(tmp.str());
     }
-  *Ax = (double*)mxMalloc(prior_nz * sizeof(double));
+  *Ax = (double *) mxMalloc(prior_nz * sizeof(double));
+  test_mxMalloc(*Ax, __LINE__, __FILE__, __func__, prior_nz * sizeof(double));
   if (!(*Ax))
     {
       ostringstream tmp;
@@ -1409,9 +1434,9 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size,
 
   cudaSetDevice(CUDA_device);
 
-
-  double *Host_b = (double*)mxMalloc(n * sizeof(double));
-  cudaChk(cudaMalloc((void**)b, n * sizeof(double)), " in Init_Cuda_Sparse, not enought memory to allocate b vector on the graphic card\n");
+  double *Host_b = (double *) mxMalloc(n * sizeof(double));
+  test_mxMalloc(Host_b, __LINE__, __FILE__, __func__, n * sizeof(double));
+  cudaChk(cudaMalloc((void **) b, n * sizeof(double)), " in Init_Cuda_Sparse, not enought memory to allocate b vector on the graphic card\n");
 
   double *Host_x0 = mxGetPr(x0_m);
   if (!Host_x0)
@@ -1420,39 +1445,41 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size,
       tmp << " in Init_Cuda_Sparse, can't retrieve x0 vector\n";
       throw FatalExceptionHandling(tmp.str());
     }
-  cudaChk(cudaMalloc((void**)x0, n * sizeof(double)), " in Init_Cuda_Sparse, not enought memory to allocate x0 vector on the graphic card\n");
-
-  int* Host_Ap = (int*)mxMalloc((n+1) * sizeof(int));
+  cudaChk(cudaMalloc((void **) x0, n * sizeof(double)), " in Init_Cuda_Sparse, not enought memory to allocate x0 vector on the graphic card\n");
 
+  int *Host_Ap = (int *) mxMalloc((n+1) * sizeof(int));
+  test_mxMalloc(Host_Ap, __LINE__, __FILE__, __func__, (n+1) * sizeof(int));
 
-  int* Host_Ai = (int*)mxMalloc(prior_nz * sizeof(int));
+  int *Host_Ai = (int *) mxMalloc(prior_nz * sizeof(int));
+  test_mxMalloc(Host_Ai, __LINE__, __FILE__, __func__, prior_nz * sizeof(int));
 
+  double *Host_Ax = (double *) mxMalloc(prior_nz * sizeof(double));
+  test_mxMalloc(Host_Ax, __LINE__, __FILE__, __func__, prior_nz * sizeof(double));
 
-  double* Host_Ax = (double*)mxMalloc(prior_nz * sizeof(double));
-
-  int* Host_Ai_tild, * Host_Ap_tild;
+  int *Host_Ai_tild, *Host_Ap_tild;
   if (preconditioner == 3)
     {
-      Host_Ap_tild = (int*) mxMalloc((n+1)*sizeof(int));
-      Host_Ai_tild = (int*) mxMalloc(prior_nz*sizeof(int));
+      Host_Ap_tild = (int *) mxMalloc((n+1)*sizeof(int));
+      test_mxMalloc(Host_Ap_tild, __LINE__, __FILE__, __func__, (n+1)*sizeof(int));
+      Host_Ai_tild = (int *) mxMalloc(prior_nz*sizeof(int));
+      test_mxMalloc(Host_Ai_tild, __LINE__, __FILE__, __func__, prior_nz*sizeof(int));
       Host_Ap_tild[0] = 0;
     }
 
-
   if (preconditioner == 0)
     preconditioner_size = n;
   else if (preconditioner == 1 || preconditioner == 2 || preconditioner == 3)
     preconditioner_size = prior_nz;
 
-  double *Host_A_tild = (double*)mxMalloc(preconditioner_size * sizeof(double));
-
+  double *Host_A_tild = (double *) mxMalloc(preconditioner_size * sizeof(double));
+  test_mxMalloc(Host_A_tild, __LINE__, __FILE__, __func__, preconditioner_size * sizeof(double));
 
   map<pair<pair<int, int>, int>, int>::iterator it4;
   for (int i = 0; i < y_size*(periods+y_kmin); i++)
     ya[i] = y[i];
-#ifdef DEBUG
+# ifdef DEBUG
   unsigned int max_nze = mxGetNzmax(A_m);
-#endif
+# endif
   unsigned int NZE = 0, NZE_tild = 0;
   int last_eq = 0;
   for (int i = 0; i < periods*Size; i++)
@@ -1473,17 +1500,17 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size,
           eq = it4->first.first.first;
           if (eq != last_eq)
             {
-#ifdef DEBUG
+# ifdef DEBUG
               if (1+last_eq + t * Size > (n + 1))
                 {
                   ostringstream tmp;
                   tmp << " in Init_CUDA_Sparse, 1+last_eq + t * Size (" << 1+last_eq + t * Size << ") out of range for Host_Ap vector\n";
                   throw FatalExceptionHandling(tmp.str());
                 }
-#endif
+# endif
               Host_Ap[1+last_eq + t * Size] = NZE;
               if (preconditioner == 3 && t == 0)
-                 Host_Ap_tild[1+last_eq ] = NZE_tild;
+                Host_Ap_tild[1+last_eq ] = NZE_tild;
               last_eq = eq;
             }
           var = it4->first.second+Size*t;
@@ -1495,7 +1522,7 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size,
               ti_y_kmax = min(periods-(t + 1), y_kmax);
               if ((lag <= ti_y_kmax && lag >= ti_y_kmin) || preconditioner == 3)  /*Build the index for sparse matrix containing the jacobian : u*/
                 {
-#ifdef DEBUG
+# ifdef DEBUG
                   if (index < 0 || index >= u_count_alloc || index > (periods-1)* IM.size() + Size * Size + periods * Size)
                     {
                       ostringstream tmp;
@@ -1508,7 +1535,7 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size,
                       tmp << " in Init_CUDA_Sparse, exceeds the capacity of A_i or A_x sparse matrix\n";
                       throw FatalExceptionHandling(tmp.str());
                     }
-#endif
+# endif
                   bool to_store = true;
                   if (preconditioner == 0)
                     {
@@ -1526,10 +1553,10 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size,
                         }
                       if (t == 0)
                         {
-                           map<pair<int, int>, int>::const_iterator it = jacob_struct.find(make_pair(eq + t * Size, var));
-                           if (it != jacob_struct.end())
-                             Host_A_tild[it->second] += u[index];
-                           else
+                          map<pair<int, int>, int>::const_iterator it = jacob_struct.find(make_pair(eq + t * Size, var));
+                          if (it != jacob_struct.end())
+                            Host_A_tild[it->second] += u[index];
+                          else
                             {
                               jacob_struct[make_pair(eq, var)] = NZE_tild;
                               Host_A_tild[NZE_tild] = u[index];
@@ -1547,7 +1574,7 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size,
                 }
               else
                 {
-#ifdef DEBUG
+# ifdef DEBUG
                   if (var < 0 || var >= Size * periods)
                     {
                       ostringstream tmp;
@@ -1566,13 +1593,13 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size,
                       tmp << " in Init_CUDA_Sparse, index (" << index_vara[var+Size*(y_kmin+lag)] << ") out of range for y vector max=" << y_size*(periods+y_kmin+y_kmax) << "\n";
                       throw FatalExceptionHandling(tmp.str());
                     }
-#endif
+# endif
                   Host_b[eq + t * Size]  += u[index]*y[index_vara[var+Size*(y_kmin+lag)]];
                 }
             }
           else           // ...and store it in the u vector
             {
-#ifdef DEBUG
+# ifdef DEBUG
               if (index < 0 || index >= u_count_alloc)
                 {
                   ostringstream tmp;
@@ -1585,7 +1612,7 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size,
                   tmp << " in Init_CUDA_Sparse, index (" << var << ") out of range for b vector\n";
                   throw FatalExceptionHandling(tmp.str());
                 }
-#endif
+# endif
               Host_b[var]  += u[index];
             }
           it4++;
@@ -1594,9 +1621,12 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size,
   Host_Ap[Size*periods] = NZE;
   if (preconditioner == 3)
     {
-      int* tmp_Ap_tild = (int*) mxMalloc((Size + 1) * sizeof(int) );
-      int* tmp_Ai_tild = (int*) mxMalloc(NZE_tild * sizeof(int) );
-      double* tmp_A_tild = (double*) mxMalloc(NZE_tild * sizeof(double) );
+      int *tmp_Ap_tild = (int *) mxMalloc((Size + 1) * sizeof(int));
+      test_mxMalloc(tmp_Ap_tild, __LINE__, __FILE__, __func__, (Size + 1) * sizeof(int));
+      int *tmp_Ai_tild = (int *) mxMalloc(NZE_tild * sizeof(int));
+      test_mxMalloc(tmp_Ai_tild, __LINE__, __FILE__, __func__, NZE_tild * sizeof(int));
+      double *tmp_A_tild = (double *) mxMalloc(NZE_tild * sizeof(double));
+      test_mxMalloc(tmp_A_tild, __LINE__, __FILE__, __func__, NZE_tild * sizeof(double));
       memcpy(tmp_Ap_tild, Host_Ap_tild, (Size + 1) * sizeof(int));
       memcpy(tmp_Ai_tild, Host_Ai_tild, NZE_tild * sizeof(int));
       memcpy(tmp_A_tild, Host_A_tild, NZE_tild * sizeof(double));
@@ -1606,8 +1636,8 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size,
 
       for (int i = 0; i < Size; i++)
         {
-          for(int j = tmp_Ap_tild[i]; j < tmp_Ap_tild[i+1]; j++)
-            if (abs(tmp_A_tild[j]) > 1.0e-20 )
+          for (int j = tmp_Ap_tild[i]; j < tmp_Ap_tild[i+1]; j++)
+            if (abs(tmp_A_tild[j]) > 1.0e-20)
               {
                 Host_A_tild[NZE_tild] = tmp_A_tild[j];
                 Host_Ai_tild[NZE_tild] = tmp_Ai_tild[j];
@@ -1625,32 +1655,31 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size,
   if (preconditioner == 1 || preconditioner == 2 || preconditioner == 3)
     preconditioner_size = NZE;
 
-
-#ifdef DEBUG
+# ifdef DEBUG
   mexPrintf("Host_Ax = [");
   for (int i = 0; i < NZE; i++)
-    mexPrintf("%f ",Host_Ax[i]);
+    mexPrintf("%f ", Host_Ax[i]);
   mexPrintf("]\n");
 
   mexPrintf("Host_Ap = [");
   for (int i = 0; i < n+1; i++)
-    mexPrintf("%d ",Host_Ap[i]);
+    mexPrintf("%d ", Host_Ap[i]);
   mexPrintf("]\n");
 
   mexPrintf("Host_Ai = [");
   for (int i = 0; i < NZE; i++)
-    mexPrintf("%d ",Host_Ai[i]);
+    mexPrintf("%d ", Host_Ai[i]);
   mexPrintf("]\n");
-#endif
-  cudaChk(cudaMalloc((void**)Ai, NZE * sizeof(int)), " in Init_Cuda_Sparse, can't allocate Ai index vector on the graphic card\n");
-  cudaChk(cudaMalloc((void**)Ax, NZE * sizeof(double)), "  in Init_Cuda_Sparse, can't allocate Ax on the graphic card\n");
-  cudaChk(cudaMalloc((void**)Ap, (n+1) * sizeof(int)), " in Init_Cuda_Sparse, can't allocate Ap index vector on the graphic card\n");
+# endif
+  cudaChk(cudaMalloc((void **) Ai, NZE * sizeof(int)), " in Init_Cuda_Sparse, can't allocate Ai index vector on the graphic card\n");
+  cudaChk(cudaMalloc((void **) Ax, NZE * sizeof(double)), "  in Init_Cuda_Sparse, can't allocate Ax on the graphic card\n");
+  cudaChk(cudaMalloc((void **) Ap, (n+1) * sizeof(int)), " in Init_Cuda_Sparse, can't allocate Ap index vector on the graphic card\n");
   if (preconditioner == 3)
     {
-      cudaChk(cudaMalloc((void**)Ai_tild, NZE_tild * sizeof(int)), " in Init_Cuda_Sparse, can't allocate Ai_tild index vector on the graphic card\n");
-      cudaChk(cudaMalloc((void**)Ap_tild, (n+1) * sizeof(int)), " in Init_Cuda_Sparse, can't allocate Ap_tild index vector on the graphic card\n");
+      cudaChk(cudaMalloc((void **) Ai_tild, NZE_tild * sizeof(int)), " in Init_Cuda_Sparse, can't allocate Ai_tild index vector on the graphic card\n");
+      cudaChk(cudaMalloc((void **) Ap_tild, (n+1) * sizeof(int)), " in Init_Cuda_Sparse, can't allocate Ap_tild index vector on the graphic card\n");
     }
-  cudaChk(cudaMalloc((void**)A_tild, preconditioner_size * sizeof(double)), "  in Init_Cuda_Sparse, can't allocate A_tild on the graphic card\n");
+  cudaChk(cudaMalloc((void **) A_tild, preconditioner_size * sizeof(double)), "  in Init_Cuda_Sparse, can't allocate A_tild on the graphic card\n");
 
   cudaChk(cudaMemcpy(*x0,     Host_x0,     n *                   sizeof(double), cudaMemcpyHostToDevice), " in Init_CUDA_Sparse, cudaMemcpy x0 = Host_x0 failed");
   cudaChk(cudaMemcpy(*b,      Host_b,      n *                   sizeof(double), cudaMemcpyHostToDevice), " in Init_CUDA_Sparse, cudaMemcpy b = Host_b failed");
@@ -1666,15 +1695,15 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size,
 }
 #endif
 
-
 void
-PrintM(int n, double* Ax, mwIndex *Ap, mwIndex *Ai)
+dynSparseMatrix::PrintM(int n, double *Ax, mwIndex *Ap, mwIndex *Ai)
 {
   int nnz = Ap[n];
-  double *A = (double*)mxMalloc(n * n * sizeof(double));
-  memset(A,0,n * n  * sizeof(double));
+  double *A = (double *) mxMalloc(n * n * sizeof(double));
+  test_mxMalloc(A, __LINE__, __FILE__, __func__, n * n * sizeof(double));
+  memset(A, 0, n * n  * sizeof(double));
   int k = 0;
-  for (int i = 0; i< n; i++)
+  for (int i = 0; i < n; i++)
     {
       for (int j = Ap[i]; j < (int) Ap[i + 1]; j++)
         {
@@ -1687,10 +1716,10 @@ PrintM(int n, double* Ax, mwIndex *Ap, mwIndex *Ai)
     mexPrintf("Problem nnz(%d) != number of elements(%d)\n", nnz, k);
   mexPrintf("----------------------\n");
   //mexEvalString("drawnow;");
-  for (int i = 0; i < n ; i++)
+  for (int i = 0; i < n; i++)
     {
       for (int j = 0; j < n; j++)
-        mexPrintf("%-6.3f ",A[i * n + j]);
+        mexPrintf("%-6.3f ", A[i * n + j]);
       mexPrintf("\n");
     }
   mxFree(A);
@@ -1849,23 +1878,36 @@ dynSparseMatrix::Init_GE(int periods, int y_kmin, int y_kmax, int Size, map<pair
   map<pair<pair<int, int>, int>, int>::iterator it4;
   NonZeroElem *first;
   pivot = (int *) mxMalloc(Size*periods*sizeof(int));
+  test_mxMalloc(pivot, __LINE__, __FILE__, __func__, Size*periods*sizeof(int));
   pivot_save = (int *) mxMalloc(Size*periods*sizeof(int));
+  test_mxMalloc(pivot_save, __LINE__, __FILE__, __func__, Size*periods*sizeof(int));
   pivotk = (int *) mxMalloc(Size*periods*sizeof(int));
+  test_mxMalloc(pivotk, __LINE__, __FILE__, __func__, Size*periods*sizeof(int));
   pivotv = (double *) mxMalloc(Size*periods*sizeof(double));
+  test_mxMalloc(pivotv, __LINE__, __FILE__, __func__, Size*periods*sizeof(double));
   pivotva = (double *) mxMalloc(Size*periods*sizeof(double));
+  test_mxMalloc(pivotva, __LINE__, __FILE__, __func__, Size*periods*sizeof(double));
   b = (int *) mxMalloc(Size*periods*sizeof(int));
+  test_mxMalloc(b, __LINE__, __FILE__, __func__, Size*periods*sizeof(int));
   line_done = (bool *) mxMalloc(Size*periods*sizeof(bool));
+  test_mxMalloc(line_done, __LINE__, __FILE__, __func__, Size*periods*sizeof(bool));
   mem_mngr.init_CHUNK_BLCK_SIZE(u_count);
   g_save_op = NULL;
   g_nop_all = 0;
   i = (periods+y_kmax+1)*Size*sizeof(NonZeroElem *);
   FNZE_R = (NonZeroElem **) mxMalloc(i);
+  test_mxMalloc(FNZE_R, __LINE__, __FILE__, __func__, i);
   FNZE_C = (NonZeroElem **) mxMalloc(i);
+  test_mxMalloc(FNZE_C, __LINE__, __FILE__, __func__, i);
   NonZeroElem **temp_NZE_R = (NonZeroElem **) mxMalloc(i);
+  test_mxMalloc(temp_NZE_R, __LINE__, __FILE__, __func__, i);
   NonZeroElem **temp_NZE_C = (NonZeroElem **) mxMalloc(i);
+  test_mxMalloc(temp_NZE_C, __LINE__, __FILE__, __func__, i);
   i = (periods+y_kmax+1)*Size*sizeof(int);
   NbNZRow = (int *) mxMalloc(i);
+  test_mxMalloc(NbNZRow, __LINE__, __FILE__, __func__, i);
   NbNZCol = (int *) mxMalloc(i);
+  test_mxMalloc(NbNZCol, __LINE__, __FILE__, __func__, i);
 
   for (int i = 0; i < periods*Size; i++)
     {
@@ -2029,7 +2071,9 @@ dynSparseMatrix::compare(int *save_op, int *save_opa, int *save_opaa, int beg_t,
   t_save_op_s *save_op_s, *save_opa_s, *save_opaa_s;
   int *diff1, *diff2;
   diff1 = (int *) mxMalloc(nop*sizeof(int));
+  test_mxMalloc(diff1, __LINE__, __FILE__, __func__, nop*sizeof(int));
   diff2 = (int *) mxMalloc(nop*sizeof(int));
+  test_mxMalloc(diff2, __LINE__, __FILE__, __func__, nop*sizeof(int));
   int max_save_ops_first = -1;
   j = i = 0;
   while (i < nop4 && OK)
@@ -2180,8 +2224,10 @@ dynSparseMatrix::complete(int beg_t, int Size, int periods, int *b)
 
   int size_of_save_code = (1+y_kmax)*Size*(Size+1+4)/2*4;
   save_code = (int *) mxMalloc(size_of_save_code*sizeof(int));
+  test_mxMalloc(save_code, __LINE__, __FILE__, __func__, size_of_save_code*sizeof(int));
   int size_of_diff = (1+y_kmax)*Size*(Size+1+4);
   diff = (int *) mxMalloc(size_of_diff*sizeof(int));
+  test_mxMalloc(diff, __LINE__, __FILE__, __func__, size_of_diff*sizeof(int));
   cal_y = y_size*y_kmin;
 
   i = (beg_t+1)*Size-1;
@@ -2439,6 +2485,7 @@ dynSparseMatrix::CheckIt(int y_size, int y_kmin, int y_kmax, int Size, int perio
   mexPrintf("row(2)=%d\n", row);
   double *B;
   B = (double *) mxMalloc(row*sizeof(double));
+  test_mxMalloc(B, __LINE__, __FILE__, __func__, row*sizeof(double));
   for (int i = 0; i < row; i++)
     SaveResult >> B[i];
   SaveResult.close();
@@ -2628,7 +2675,7 @@ dynSparseMatrix::mult_SAT_B(mxArray *A_m, mxArray *B_m)
   double *B_d = mxGetPr(B_m);
   mxArray *C_m = mxCreateDoubleMatrix(m_A, n_B, mxREAL);
   double *C_d = mxGetPr(C_m);
-  for (int j = 0; j < (int)n_B; j++)
+  for (int j = 0; j < (int) n_B; j++)
     {
       for (unsigned int i = 0; i < n_A; i++)
         {
@@ -2780,19 +2827,18 @@ dynSparseMatrix::Sparse_transpose(mxArray *A_m)
   return C_m;
 }
 
-
-#define sign(a,b) ((b) >= 0.0 ? fabs(a) : -fabs(a))
+#define sign(a, b) ((b) >= 0.0 ? fabs(a) : -fabs(a))
 bool
 dynSparseMatrix::mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc)
 {
-  const double GOLD=1.618034;
-  const double GLIMIT=100.0;
-  const double TINY=1.0e-20;
+  const double GOLD = 1.618034;
+  const double GLIMIT = 100.0;
+  const double TINY = 1.0e-20;
 
   double tmp;
-  mexPrintf("bracketing *ax=%f, *bx=%f\n",*ax, *bx);
+  mexPrintf("bracketing *ax=%f, *bx=%f\n", *ax, *bx);
   //mexEvalString("drawnow;");
-  double ulim,u,r,q,fu;
+  double ulim, u, r, q, fu;
   if (!compute_complete(*ax, fa))
     return false;
   if (!compute_complete(*bx, fb))
@@ -2807,35 +2853,35 @@ dynSparseMatrix::mnbrak(double *ax, double *bx, double *cx, double *fa, double *
       *fa = *fb;
       *fb = tmp;
     }
-  *cx=(*bx)+GOLD*(*bx-*ax);
+  *cx = (*bx)+GOLD*(*bx-*ax);
   if (!compute_complete(*cx, fc))
     return false;
   while (*fb > *fc)
     {
-      r=(*bx-*ax)*(*fb-*fc);
-      q=(*bx-*cx)*(*fb-*fa);
-      u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
-        (2.0*sign(fmax(fabs(q-r),TINY),q-r));
-      ulim=(*bx)+GLIMIT*(*cx-*bx);
+      r = (*bx-*ax)*(*fb-*fc);
+      q = (*bx-*cx)*(*fb-*fa);
+      u = (*bx)-((*bx-*cx)*q-(*bx-*ax)*r)
+        /(2.0*sign(fmax(fabs(q-r), TINY), q-r));
+      ulim = (*bx)+GLIMIT*(*cx-*bx);
       if ((*bx-u)*(u-*cx) > 0.0)
         {
           if (!compute_complete(u, &fu))
             return false;
           if (fu < *fc)
             {
-              *ax=(*bx);
-              *bx=u;
-              *fa=(*fb);
-              *fb=fu;
+              *ax = (*bx);
+              *bx = u;
+              *fa = (*fb);
+              *fb = fu;
               return true;
             }
           else if (fu > *fb)
             {
-              *cx=u;
-              *fc=fu;
+              *cx = u;
+              *fc = fu;
               return true;
             }
-          u=(*cx)+GOLD*(*cx-*bx);
+          u = (*cx)+GOLD*(*cx-*bx);
           if (!compute_complete(u, &fu))
             return false;
         }
@@ -2856,13 +2902,13 @@ dynSparseMatrix::mnbrak(double *ax, double *bx, double *cx, double *fa, double *
         }
       else if ((u-ulim)*(ulim-*cx) >= 0.0)
         {
-          u=ulim;
+          u = ulim;
           if (!compute_complete(u, &fu))
             return false;
         }
       else
         {
-          u=(*cx)+GOLD*(*cx-*bx);
+          u = (*cx)+GOLD*(*cx-*bx);
           if (!compute_complete(u, &fu))
             return false;
         }
@@ -2879,23 +2925,23 @@ dynSparseMatrix::mnbrak(double *ax, double *bx, double *cx, double *fa, double *
 bool
 dynSparseMatrix::golden(double ax, double bx, double cx, double tol, double solve_tolf, double *xmin)
 {
-  const double R=0.61803399;
-  const double C=(1.0-R);
+  const double R = 0.61803399;
+  const double C = (1.0-R);
   mexPrintf("golden\n");
   //mexEvalString("drawnow;");
-  double f1,f2,x0,x1,x2,x3;
-  int iter= 0, max_iter= 100;
-  x0=ax;
-  x3=cx;
+  double f1, f2, x0, x1, x2, x3;
+  int iter = 0, max_iter = 100;
+  x0 = ax;
+  x3 = cx;
   if (fabs(cx-bx) > fabs(bx-ax))
     {
-      x1=bx;
-      x2=bx+C*(cx-bx);
+      x1 = bx;
+      x2 = bx+C*(cx-bx);
     }
   else
     {
-      x2=bx;
-      x1=bx-C*(bx-ax);
+      x2 = bx;
+      x1 = bx-C*(bx-ax);
     }
   if (!compute_complete(x1, &f1))
     return false;
@@ -2925,12 +2971,12 @@ dynSparseMatrix::golden(double ax, double bx, double cx, double tol, double solv
     }
   if (f1 < f2)
     {
-      *xmin=x1;
+      *xmin = x1;
       return true;
     }
   else
     {
-      *xmin=x2;
+      *xmin = x2;
       return true;
     }
 }
@@ -3244,12 +3290,11 @@ void
 dynSparseMatrix::End_Matlab_LU_UMFPack()
 {
   if (Symbolic)
-    umfpack_dl_free_symbolic (&Symbolic) ;
+    umfpack_dl_free_symbolic(&Symbolic);
   if (Numeric)
-    umfpack_dl_free_numeric (&Numeric) ;
+    umfpack_dl_free_numeric(&Numeric);
 }
 
-
 void
 dynSparseMatrix::End_Solver()
 {
@@ -3261,17 +3306,17 @@ void
 dynSparseMatrix::Printfull_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, double *Ax, double *b, int n)
 {
   double A[n*n];
-  for (int i = 0 ; i  < n*n ; i++)
+  for (int i = 0; i  < n*n; i++)
     A[i] = 0;
   int k = 0;
   for (int i = 0; i < n; i++)
-      for (int j = Ap[i]; j < Ap[i+1]; j++)
-        A[Ai[j] * n + i] =  Ax[k++];
+    for (int j = Ap[i]; j < Ap[i+1]; j++)
+      A[Ai[j] * n + i] =  Ax[k++];
   for (int i = 0; i < n; i++)
     {
       for (int j = 0; j < n; j++)
-        mexPrintf("%4.1f ",A[i*n+j]);
-      mexPrintf("     %6.3f\n",b[i]);
+        mexPrintf("%4.1f ", A[i*n+j]);
+      mexPrintf("     %6.3f\n", b[i]);
     }
 }
 
@@ -3280,8 +3325,8 @@ dynSparseMatrix::Print_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, doubl
 {
   int k = 0;
   for (int i = 0; i < n; i++)
-      for (int j = Ap[i]; j < Ap[i+1]; j++)
-        mexPrintf("(%d, %d)    %f\n", Ai[j]+1, i+1, Ax[k++]);
+    for (int j = Ap[i]; j < Ap[i+1]; j++)
+      mexPrintf("(%d, %d)    %f\n", Ai[j]+1, i+1, Ax[k++]);
 }
 
 void
@@ -3292,9 +3337,12 @@ dynSparseMatrix::Solve_LU_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, do
   double Control [UMFPACK_CONTROL], Info [UMFPACK_INFO], res [n];
 #else
   double *Control, *Info, *res;
-  Control = (double*)mxMalloc(UMFPACK_CONTROL * sizeof(double));
-  Info = (double*)mxMalloc(UMFPACK_INFO * sizeof(double));
-  res = (double*)mxMalloc(n * sizeof(double));
+  Control = (double *) mxMalloc(UMFPACK_CONTROL * sizeof(double));
+  test_mxMalloc(Control, __LINE__, __FILE__, __func__, UMFPACK_CONTROL * sizeof(double));
+  Info = (double *) mxMalloc(UMFPACK_INFO * sizeof(double));
+  test_mxMalloc(Info, __LINE__, __FILE__, __func__, UMFPACK_INFO * sizeof(double));
+  res = (double *) mxMalloc(n * sizeof(double));
+  test_mxMalloc(res, __LINE__, __FILE__, __func__, n * sizeof(double));
 #endif
 
   umfpack_dl_defaults(Control);
@@ -3313,8 +3361,8 @@ dynSparseMatrix::Solve_LU_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, do
         }
     }
   if (iter > 0)
-    umfpack_dl_free_numeric(&Numeric) ;
-  status = umfpack_dl_numeric (Ap, Ai, Ax, Symbolic, &Numeric, Control, Info);
+    umfpack_dl_free_numeric(&Numeric);
+  status = umfpack_dl_numeric(Ap, Ai, Ax, Symbolic, &Numeric, Control, Info);
   if (status < 0)
     {
       umfpack_dl_report_info(Control, Info);
@@ -3346,9 +3394,9 @@ dynSparseMatrix::Solve_LU_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, do
                     {
                       int eq = index_vara[i+Size*(y_kmin)];
                       int flip_exo = vector_table_conditional_local[i].var_exo;
-                      double  yy = -(res[i] + x[y_kmin + flip_exo*/*row_x*/nb_row_x]);
+                      double  yy = -(res[i] + x[y_kmin + flip_exo*nb_row_x]);
                       direction[eq] = 0;
-                      x[flip_exo*/*row_x*/nb_row_x + y_kmin] += slowc_l * yy;
+                      x[flip_exo*nb_row_x + y_kmin] += slowc_l * yy;
                     }
                   else
                     {
@@ -3396,8 +3444,8 @@ dynSparseMatrix::Solve_LU_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, do
             direction[eq] = yy;
             y[eq+it_*y_size] += slowc_l * yy;
           }
-      }
-  
+    }
+
   mxFree(Ap);
   mxFree(Ai);
   mxFree(Ax);
@@ -3409,7 +3457,6 @@ dynSparseMatrix::Solve_LU_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, do
 #endif
 }
 
-
 void
 dynSparseMatrix::Solve_LU_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, double *Ax, double *b, int n, int Size, double slowc_l, bool is_two_boundaries, int  it_)
 {
@@ -3418,9 +3465,12 @@ dynSparseMatrix::Solve_LU_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, do
   double Control [UMFPACK_CONTROL], Info [UMFPACK_INFO], res [n];
 #else
   double *Control, *Info, *res;
-  Control = (double*)mxMalloc(UMFPACK_CONTROL * sizeof(double));
-  Info = (double*)mxMalloc(UMFPACK_INFO * sizeof(double));
-  res = (double*)mxMalloc(n * sizeof(double));
+  Control = (double *) mxMalloc(UMFPACK_CONTROL * sizeof(double));
+  test_mxMalloc(Control, __LINE__, __FILE__, __func__, UMFPACK_CONTROL * sizeof(double));
+  Info = (double *) mxMalloc(UMFPACK_INFO * sizeof(double));
+  test_mxMalloc(Info, __LINE__, __FILE__, __func__, UMFPACK_INFO * sizeof(double));
+  res = (double *) mxMalloc(n * sizeof(double));
+  test_mxMalloc(res, __LINE__, __FILE__, __func__, n * sizeof(double));
 #endif
 
   umfpack_dl_defaults(Control);
@@ -3439,8 +3489,8 @@ dynSparseMatrix::Solve_LU_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, do
         }
     }
   if (iter > 0)
-    umfpack_dl_free_numeric(&Numeric) ;
-  status = umfpack_dl_numeric (Ap, Ai, Ax, Symbolic, &Numeric, Control, Info);
+    umfpack_dl_free_numeric(&Numeric);
+  status = umfpack_dl_numeric(Ap, Ai, Ax, Symbolic, &Numeric, Control, Info);
   if (status < 0)
     {
       umfpack_dl_report_info(Control, Info);
@@ -3486,40 +3536,42 @@ dynSparseMatrix::Solve_LU_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, do
 #endif
 }
 
-
 void
 dynSparseMatrix::Solve_LU_UMFPack(mxArray *A_m, mxArray *b_m, int Size, double slowc_l, bool is_two_boundaries, int  it_)
 {
   SuiteSparse_long n = mxGetM(A_m);
 
-  SuiteSparse_long *Ap = (SuiteSparse_long*)mxGetJc (A_m);
+  SuiteSparse_long *Ap = (SuiteSparse_long *) mxGetJc(A_m);
 
-  SuiteSparse_long *Ai = (SuiteSparse_long*)mxGetIr(A_m);
-  double*  Ax = mxGetPr(A_m);
-  double*  B  = mxGetPr(b_m);
+  SuiteSparse_long *Ai = (SuiteSparse_long *) mxGetIr(A_m);
+  double *Ax = mxGetPr(A_m);
+  double *B  = mxGetPr(b_m);
   SuiteSparse_long status, sys = 0;
 #ifndef _MSC_VER
   double Control [UMFPACK_CONTROL], Info [UMFPACK_INFO], res [n];
 #else
   double *Control, *Info, *res;
-  Control = (double*)mxMalloc(UMFPACK_CONTROL * sizeof(double));
-  Info = (double*)mxMalloc(UMFPACK_INFO * sizeof(double));
-  res = (double*)mxMalloc(n * sizeof(double));
+  Control = (double *) mxMalloc(UMFPACK_CONTROL * sizeof(double));
+  test_mxMalloc(Control, __LINE__, __FILE__, __func__, UMFPACK_CONTROL * sizeof(double));
+  Info = (double *) mxMalloc(UMFPACK_INFO * sizeof(double));
+  test_mxMalloc(Info, __LINE__, __FILE__, __func__, UMFPACK_INFO * sizeof(double));
+  res = (double *) mxMalloc(n * sizeof(double));
+  test_mxMalloc(res, __LINE__, __FILE__, __func__, n * sizeof(double));
 #endif
-  void *Symbolic, *Numeric ;
-  umfpack_dl_defaults (Control) ;
+  void *Symbolic, *Numeric;
+  umfpack_dl_defaults(Control);
 
-  status = umfpack_dl_symbolic (n, n, Ap, Ai, Ax, &Symbolic, Control, Info) ;
+  status = umfpack_dl_symbolic(n, n, Ap, Ai, Ax, &Symbolic, Control, Info);
   if (status != UMFPACK_OK)
-    umfpack_dl_report_info ((double*) NULL, Info) ;
+    umfpack_dl_report_info((double *) NULL, Info);
 
-  status = umfpack_dl_numeric (Ap, Ai, Ax, Symbolic, &Numeric, Control, Info) ;
+  status = umfpack_dl_numeric(Ap, Ai, Ax, Symbolic, &Numeric, Control, Info);
   if (status != UMFPACK_OK)
-    umfpack_dl_report_info ((double*) NULL, Info) ;
+    umfpack_dl_report_info((double *) NULL, Info);
 
-  status = umfpack_dl_solve (sys, Ap, Ai, Ax, res, B, Numeric, Control, Info) ;
+  status = umfpack_dl_solve(sys, Ap, Ai, Ax, res, B, Numeric, Control, Info);
   if (status != UMFPACK_OK)
-    umfpack_dl_report_info ((double*) NULL, Info) ;
+    umfpack_dl_report_info((double *) NULL, Info);
   //double *res = mxGetPr(z);
   if (is_two_boundaries)
     for (int i = 0; i < n; i++)
@@ -3547,41 +3599,38 @@ dynSparseMatrix::Solve_LU_UMFPack(mxArray *A_m, mxArray *b_m, int Size, double s
 
 }
 
-
 #ifdef CUDA
 void
-printM(int n,double *Ax, int* Ap, int* Ai,  cusparseMatDescr_t descrA, cusparseHandle_t cusparse_handle)
+printM(int n, double *Ax, int *Ap, int *Ai,  cusparseMatDescr_t descrA, cusparseHandle_t cusparse_handle)
 {
   //cudaError_t cuda_error;
   //cusparseStatus_t cusparse_status;
-  double * A_dense;
-  cudaChk(cudaMalloc((void**) &A_dense, n * n *sizeof(double)), "A_dense cudaMalloc has failed\n");
-
+  double *A_dense;
+  cudaChk(cudaMalloc((void **) &A_dense, n * n *sizeof(double)), "A_dense cudaMalloc has failed\n");
 
   cusparseChk(cusparseDcsr2dense(cusparse_handle, n, n, descrA,
-                                 Ax, Ap,Ai, A_dense, n), "cusparseDcsr2dense has failed\n");
-  double *A_dense_hoste = (double*)mxMalloc(n * n * sizeof(double));
-  cudaChk(cudaMemcpy(A_dense_hoste, A_dense, n * n * sizeof(double),cudaMemcpyDeviceToHost), " cudaMemcpy(A_dense_hoste, A_dense) has failed\n");
+                                 Ax, Ap, Ai, A_dense, n), "cusparseDcsr2dense has failed\n");
+  double *A_dense_hoste = (double *) mxMalloc(n * n * sizeof(double));
+  test_mxMalloc(A_dense_hoste, __LINE__, __FILE__, __func__, n * n * sizeof(double));
+  cudaChk(cudaMemcpy(A_dense_hoste, A_dense, n * n * sizeof(double), cudaMemcpyDeviceToHost), " cudaMemcpy(A_dense_hoste, A_dense) has failed\n");
   mexPrintf("----------------------\n");
-  mexPrintf("FillMode=%d, IndexBase=%d, MatType=%d, DiagType=%d\n",cusparseGetMatFillMode(descrA), cusparseGetMatIndexBase(descrA), cusparseGetMatType(descrA), cusparseGetMatDiagType(descrA));
+  mexPrintf("FillMode=%d, IndexBase=%d, MatType=%d, DiagType=%d\n", cusparseGetMatFillMode(descrA), cusparseGetMatIndexBase(descrA), cusparseGetMatType(descrA), cusparseGetMatDiagType(descrA));
   //mexEvalString("drawnow;");
-  for (int i = 0; i < n ; i++)
+  for (int i = 0; i < n; i++)
     {
       for (int j = 0; j < n; j++)
-        mexPrintf("%-6.3f ",A_dense_hoste[i + j * n]);
+        mexPrintf("%-6.3f ", A_dense_hoste[i + j * n]);
       mexPrintf("\n");
     }
   mxFree(A_dense_hoste);
   cudaChk(cudaFree(A_dense), "cudaFree(A_dense) has failed\n");
 }
 
-
-
 void
-dynSparseMatrix::Solve_CUDA_BiCGStab_Free(double* tmp_vect_host, double* p, double* r, double* v, double* s, double* t, double* y_, double* z, double* tmp_,
-                                       int* Ai, double* Ax, int* Ap, double* x0, double* b, double* A_tild, int* A_tild_i, int* A_tild_p/*, double* Lx, int* Li, int* Lp,
-                                       double* Ux, int* Ui, int* Up, int* device_n*/, cusparseSolveAnalysisInfo_t infoL, cusparseSolveAnalysisInfo_t infoU,
-                                       cusparseMatDescr_t descrL, cusparseMatDescr_t descrU, int preconditioner)
+dynSparseMatrix::Solve_CUDA_BiCGStab_Free(double *tmp_vect_host, double *p, double *r, double *v, double *s, double *t, double *y_, double *z, double *tmp_,
+                                          int *Ai, double *Ax, int *Ap, double *x0, double *b, double *A_tild, int *A_tild_i, int *A_tild_p/*, double* Lx, int* Li, int* Lp,
+                                                                                                                                             double* Ux, int* Ui, int* Up, int* device_n*/, cusparseSolveAnalysisInfo_t infoL, cusparseSolveAnalysisInfo_t infoU,
+                                          cusparseMatDescr_t descrL, cusparseMatDescr_t descrU, int preconditioner)
 {
   //cudaError_t cuda_error;
   //cusparseStatus_t cusparse_status;
@@ -3601,18 +3650,18 @@ dynSparseMatrix::Solve_CUDA_BiCGStab_Free(double* tmp_vect_host, double* p, doub
   cudaChk(cudaFree(b), "  in Solve_Cuda_BiCGStab, can't free b\n");
   /*if (preconditioner == 0)
     {*/
-      cudaChk(cudaFree(A_tild), "  in Solve_Cuda_BiCGStab, can't free A_tild (1)\n");
-      cudaChk(cudaFree(A_tild_i), "  in Solve_Cuda_BiCGStab, can't free A_tild_i (1)\n");
-      cudaChk(cudaFree(A_tild_p), "  in Solve_Cuda_BiCGStab, can't free A_tild_p (1)\n");
-    /*}
-  else
-    {
-      cudaChk(cudaFree(Lx), "  in Solve_Cuda_BiCGStab, can't free Lx\n");
-      cudaChk(cudaFree(Li), "  in Solve_Cuda_BiCGStab, can't free Li\n");
-      cudaChk(cudaFree(Lp), "  in Solve_Cuda_BiCGStab, can't free Lp\n");
-      cudaChk(cudaFree(Ux), "  in Solve_Cuda_BiCGStab, can't free Ux\n");
-      cudaChk(cudaFree(Ui), "  in Solve_Cuda_BiCGStab, can't free Ui\n");
-      cudaChk(cudaFree(Up), "  in Solve_Cuda_BiCGStab, can't free Up\n");
+  cudaChk(cudaFree(A_tild), "  in Solve_Cuda_BiCGStab, can't free A_tild (1)\n");
+  cudaChk(cudaFree(A_tild_i), "  in Solve_Cuda_BiCGStab, can't free A_tild_i (1)\n");
+  cudaChk(cudaFree(A_tild_p), "  in Solve_Cuda_BiCGStab, can't free A_tild_p (1)\n");
+  /*}
+    else
+    {
+    cudaChk(cudaFree(Lx), "  in Solve_Cuda_BiCGStab, can't free Lx\n");
+    cudaChk(cudaFree(Li), "  in Solve_Cuda_BiCGStab, can't free Li\n");
+    cudaChk(cudaFree(Lp), "  in Solve_Cuda_BiCGStab, can't free Lp\n");
+    cudaChk(cudaFree(Ux), "  in Solve_Cuda_BiCGStab, can't free Ux\n");
+    cudaChk(cudaFree(Ui), "  in Solve_Cuda_BiCGStab, can't free Ui\n");
+    cudaChk(cudaFree(Up), "  in Solve_Cuda_BiCGStab, can't free Up\n");
     }*/
   //cudaChk(cudaFree(device_n), "  in Solve_Cuda_BiCGStab, can't free device_n\n");
   if (preconditioner == 1 || preconditioner == 2 || preconditioner == 3)
@@ -3630,14 +3679,14 @@ dynSparseMatrix::Solve_CUDA_BiCGStab_Free(double* tmp_vect_host, double* p, doub
 #endif
 
 void
-Solve(double* Ax, int* Ap, int* Ai, double *b, int n, bool Lower, double *x)
+Solve(double *Ax, int *Ap, int *Ai, double *b, int n, bool Lower, double *x)
 {
   if (Lower)
     {
       for (int i = 0; i < n; i++)
         {
           double sum = 0;
-          for(int j = Ap[i]; j < Ap[i+1]; j++)
+          for (int j = Ap[i]; j < Ap[i+1]; j++)
             {
               int k = Ai[j];
               if (k < i)
@@ -3648,10 +3697,10 @@ Solve(double* Ax, int* Ap, int* Ai, double *b, int n, bool Lower, double *x)
     }
   else
     {
-      for (int i = n-1 ; i >= 0; i--)
+      for (int i = n-1; i >= 0; i--)
         {
           double sum = 0, mul = 1;
-          for(int j = Ap[i]; j < Ap[i+1]; j++)
+          for (int j = Ap[i]; j < Ap[i+1]; j++)
             {
               int k = Ai[j];
               if (k > i)
@@ -3665,14 +3714,14 @@ Solve(double* Ax, int* Ap, int* Ai, double *b, int n, bool Lower, double *x)
 }
 
 void
-Check(int n, double* Ax, int* Ap, int* Ai, double* b, double *x, bool Lower)
+Check(int n, double *Ax, int *Ap, int *Ai, double *b, double *x, bool Lower)
 {
   if (Lower)
     {
       for (int i = 0; i < n; i++)
         {
           double sum = 0;
-          for(int j = Ap[i]; j < Ap[i+1]; j++)
+          for (int j = Ap[i]; j < Ap[i+1]; j++)
             {
               int k = Ai[j];
               if (k < i)
@@ -3680,15 +3729,15 @@ Check(int n, double* Ax, int* Ap, int* Ai, double* b, double *x, bool Lower)
             }
           double err =  b[i] - sum - x[i];
           if (abs(err) > 1e-10)
-            mexPrintf("error at i=%d\n",i);
+            mexPrintf("error at i=%d\n", i);
         }
     }
   else
     {
-      for (int i = n-1 ; i >= 0; i--)
+      for (int i = n-1; i >= 0; i--)
         {
           double sum = 0;
-          for(int j = Ap[i]; j < Ap[i+1]; j++)
+          for (int j = Ap[i]; j < Ap[i+1]; j++)
             {
               int k = Ai[j];
               if (k >= i)
@@ -3696,7 +3745,7 @@ Check(int n, double* Ax, int* Ap, int* Ai, double* b, double *x, bool Lower)
             }
           double err =  b[i] - sum;
           if (abs(err) > 1e-10)
-            mexPrintf("error at i=%d\n",i);
+            mexPrintf("error at i=%d\n", i);
         }
     }
 }
@@ -3704,7 +3753,7 @@ Check(int n, double* Ax, int* Ap, int* Ai, double* b, double *x, bool Lower)
 #ifdef CUDA
 int
 dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, int *Ai_tild, double *A_tild, double *b, double *x0, int n, int Size, double slowc_l, bool is_two_boundaries,
-                                  int  it_, int nnz, int nnz_tild, int preconditioner, int max_iterations, int block)
+                                     int  it_, int nnz, int nnz_tild, int preconditioner, int max_iterations, int block)
 {
   cusparseSolveAnalysisInfo_t info, infoL, infoU;
   cusparseMatDescr_t descrL, descrU;
@@ -3721,8 +3770,8 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
   double bnorm;
   double tmp1, tmp2;
   int refinement_needed = 0, stagnation = 0;
-  int max_refinement = min(min(int(floor(double(n)/50)),10),n-max_iterations), max_stagnation = 3;
-  int nblocks = ceil(double(n) / double(1024));
+  int max_refinement = min(min(int (floor(double (n)/50)), 10), n-max_iterations), max_stagnation = 3;
+  int nblocks = ceil(double (n) / double (1024));
   int n_threads;
   if (nblocks == 0)
     n_threads = n;
@@ -3730,9 +3779,10 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
     n_threads = 1024;
   int periods = n / Size;
 
-  double * tmp_vect_host = (double*)mxMalloc(n * sizeof(double));
+  double *tmp_vect_host = (double *) mxMalloc(n * sizeof(double));
+  test_mxMalloc(tmp_vect_host, __LINE__, __FILE__, __func__, n * sizeof(double));
 
-  cublasChk(cublasDnrm2(cublas_handle, n,b, 1, &bnorm),
+  cublasChk(cublasDnrm2(cublas_handle, n, b, 1, &bnorm),
             "  in Solve_Cuda_BiCGStab, cublasDnrm2(b) has failed\n");
 
   double tolb = tol * bnorm;
@@ -3774,26 +3824,26 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
   bool convergence = false;
   double zeros = 0.0, one = 1.0, m_one = -1.0;
 
-  cudaChk(cudaMalloc((void**)&tmp_, n * sizeof(double)), "  in Solve_Cuda_Sparse, can't allocate tmp_ on the graphic card\n");
+  cudaChk(cudaMalloc((void **) &tmp_, n * sizeof(double)), "  in Solve_Cuda_Sparse, can't allocate tmp_ on the graphic card\n");
 
-  cudaChk(cudaMalloc((void**)&r, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate r on the graphic card\n");
+  cudaChk(cudaMalloc((void **) &r, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate r on the graphic card\n");
 
   cudaChk(cudaMemcpy(r, b, n * sizeof(double), cudaMemcpyDeviceToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy r = b has failed\n");
 
   //r = b - A * x0
   cusparseChk(cusparseDcsrmv(cusparse_handle, CUSPARSE_OPERATION_NON_TRANSPOSE, n,
-                                   n, nnz, &m_one,
-                                   CUDA_descr, Ax,
-                                   Ap, Ai,
-                                   x0, &one,
-                                   r), "in Solve_Cuda_BiCGStab, cusparseDcsrmv A * x0 has failed");
+                             n, nnz, &m_one,
+                             CUDA_descr, Ax,
+                             Ap, Ai,
+                             x0, &one,
+                             r), "in Solve_Cuda_BiCGStab, cusparseDcsrmv A * x0 has failed");
 
   cudaChk(cudaMemcpy(tmp_vect_host, r, n*sizeof(double), cudaMemcpyDeviceToHost), "  in Solve_Cuda_BiCGStab, cudaMemcpy tmp_vect_host = p_tild has failed\n");
   /*mexPrintf("r\n");
-  for (int i = 0; i < n; i++)
+    for (int i = 0; i < n; i++)
     mexPrintf("%f\n",tmp_vect_host[i]);*/
 
-  cudaChk(cudaMalloc((void**)&r0, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate r0 on the graphic card\n");
+  cudaChk(cudaMalloc((void **) &r0, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate r0 on the graphic card\n");
   cudaChk(cudaMemcpy(r0, r, n * sizeof(double), cudaMemcpyDeviceToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy r0 = r has failed\n");
 
   cublasChk(cublasDnrm2(cublas_handle, n, // numerator
@@ -3820,12 +3870,11 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
       return 0;
     }
 
-
   if (preconditioner == 0)
     {
       //Apply the Jacobi preconditioner
       /*VecDiv<<<nblocks, n_threads>>>(r_, A_tild, z_, n);
-      cuda_error = cudaMemcpy(zz_, z_, n * sizeof(double), cudaMemcpyDeviceToDevice);*/
+        cuda_error = cudaMemcpy(zz_, z_, n * sizeof(double), cudaMemcpyDeviceToDevice);*/
     }
   else if (preconditioner == 1)
     {
@@ -3845,21 +3894,26 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
                   "  in Solve_Cuda_BiCGStab, cusparseDcsrilu0 has failed\n");
 
       //Make a copy of the indexes in A_tild_i and A_tild_p to use it the Bicgstab algorithm
-      cudaChk(cudaMalloc((void**)&A_tild_i, nnz * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate A_tild_i on the graphic card\n");
+      cudaChk(cudaMalloc((void **) &A_tild_i, nnz * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate A_tild_i on the graphic card\n");
       cudaChk(cudaMemcpy(A_tild_i, Ai, nnz * sizeof(int), cudaMemcpyDeviceToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_i = Ai has failed\n");
-      cudaChk(cudaMalloc((void**)&A_tild_p, (n + 1) * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate A_tild_p on the graphic card\n");
+      cudaChk(cudaMalloc((void **) &A_tild_p, (n + 1) * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate A_tild_p on the graphic card\n");
       cudaChk(cudaMemcpy(A_tild_p, Ap, (n + 1) * sizeof(int), cudaMemcpyDeviceToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_p = Ap has failed\n");
     }
   else if (preconditioner == 2)
     {
       //Because the Jacobian matrix A is store in CSC format in matlab
       // we have to transpose it to get a CSR format used by CUDA
-      mwIndex* Awi, *Awp;
-      double* A_tild_host = (double*)mxMalloc(nnz*sizeof(double));
-      Awi = (mwIndex*)mxMalloc(nnz * sizeof(mwIndex));
-      Awp = (mwIndex*)mxMalloc((n + 1) * sizeof(mwIndex));
-      int* Aii = (int*)mxMalloc(nnz * sizeof(int));
-      int* Aip = (int*)mxMalloc((n + 1) * sizeof(int));
+      mwIndex *Awi, *Awp;
+      double *A_tild_host = (double *) mxMalloc(nnz*sizeof(double));
+      test_mxMalloc(A_tild_host, __LINE__, __FILE__, __func__, nnz*sizeof(double));
+      Awi = (mwIndex *) mxMalloc(nnz * sizeof(mwIndex));
+      test_mxMalloc(Awi, __LINE__, __FILE__, __func__, nnz * sizeof(mwIndex));
+      Awp = (mwIndex *) mxMalloc((n + 1) * sizeof(mwIndex));
+      test_mxMalloc(Awp, __LINE__, __FILE__, __func__, (n + 1) * sizeof(mwIndex));
+      int *Aii = (int *) mxMalloc(nnz * sizeof(int));
+      test_mxMalloc(Aii, __LINE__, __FILE__, __func__, nnz * sizeof(int));
+      int *Aip = (int *) mxMalloc((n + 1) * sizeof(int));
+      test_mxMalloc(Aip, __LINE__, __FILE__, __func__, (n + 1) * sizeof(int));
       cudaChk(cudaMemcpy(A_tild_host, A_tild, nnz*sizeof(double), cudaMemcpyDeviceToHost), "  in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_host = A_tild has failed\n");
       cudaChk(cudaMemcpy(Aii, Ai, nnz*sizeof(int), cudaMemcpyDeviceToHost), "  in Solve_Cuda_BiCGStab, cudaMemcpy Aii = Ai has failed\n");
       cudaChk(cudaMemcpy(Aip, Ap, (n+1)*sizeof(int), cudaMemcpyDeviceToHost), "  in Solve_Cuda_BiCGStab, cudaMemcpy Aip = Ai has failed\n");
@@ -3869,7 +3923,7 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
         Awp[i] = Aip[i];
       mxFree(Aii);
       mxFree(Aip);
-      mxArray * At_m = mxCreateSparse(n,n,nnz,mxREAL);
+      mxArray *At_m = mxCreateSparse(n, n, nnz, mxREAL);
       mxSetIr(At_m, Awi);
       mxSetJc(At_m, Awp);
       mxSetPr(At_m, A_tild_host);
@@ -3878,9 +3932,9 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
       mxDestroyArray(At_m);
 
       /*mexPrintf("A_m\n");
-      mexCallMATLAB(0, NULL, 1, &A_m, "disp_dense");*/
+        mexCallMATLAB(0, NULL, 1, &A_m, "disp_dense");*/
       /*mxFree(Awi);
-      mxFree(Awp);*/
+        mxFree(Awp);*/
 
       /*[L1, U1] = ilu(g1a=;*/
       const char *field_names[] = {"type", "droptol", "milu", "udiag", "thresh"};
@@ -3889,7 +3943,7 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
       const int milu = 2;
       const int udiag = 3;
       const int thresh = 4;
-      mwSize dims[1] = {(mwSize)1 };
+      mwSize dims[1] = {(mwSize) 1 };
       mxArray *Setup = mxCreateStructArray(1, dims, 5, field_names);
       mxSetFieldByNumber(Setup, 0, type, mxCreateString("ilutp"));
       //mxSetFieldByNumber(Setup, 0, type, mxCreateString("nofill"));
@@ -3910,38 +3964,39 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
         }
       mxDestroyArray(Setup);
 
-
- /*     //ILUT preconditionner computed by Matlab (todo: in futur version of cuda replace it by a new equivalent cuda function)
-      const char *field_names[] = {"type", "droptol", "milu", "udiag", "thresh"};
-      const int type = 0;
-      const int droptol = 1;
-      const int milu = 2;
-      const int udiag = 3;
-      const int thresh = 4;
-      mwSize dims[1] = {(mwSize)1 };
-      mxArray *Setup = mxCreateStructArray(1, dims, 5, field_names);
-      mxSetFieldByNumber(Setup, 0, type, mxCreateString("ilutp"));
-      mxSetFieldByNumber(Setup, 0, droptol, mxCreateDoubleScalar(lu_inc_tol));
-      mxSetFieldByNumber(Setup, 0, milu, mxCreateString("off"));
-      mxSetFieldByNumber(Setup, 0, udiag, mxCreateDoubleScalar(0));
-      mxSetFieldByNumber(Setup, 0, thresh, mxCreateDoubleScalar(0));
-      mxArray *lhs0[2], *rhs0[2];
-      rhs0[0] = A_m;
-      rhs0[1] = Setup;
-      mexCallMATLAB(1, lhs0, 2, rhs0, "ilu");
-*/
+      /*     //ILUT preconditionner computed by Matlab (todo: in futur version of cuda replace it by a new equivalent cuda function)
+             const char *field_names[] = {"type", "droptol", "milu", "udiag", "thresh"};
+             const int type = 0;
+             const int droptol = 1;
+             const int milu = 2;
+             const int udiag = 3;
+             const int thresh = 4;
+             mwSize dims[1] = {(mwSize)1 };
+             mxArray *Setup = mxCreateStructArray(1, dims, 5, field_names);
+             mxSetFieldByNumber(Setup, 0, type, mxCreateString("ilutp"));
+             mxSetFieldByNumber(Setup, 0, droptol, mxCreateDoubleScalar(lu_inc_tol));
+             mxSetFieldByNumber(Setup, 0, milu, mxCreateString("off"));
+             mxSetFieldByNumber(Setup, 0, udiag, mxCreateDoubleScalar(0));
+             mxSetFieldByNumber(Setup, 0, thresh, mxCreateDoubleScalar(0));
+             mxArray *lhs0[2], *rhs0[2];
+             rhs0[0] = A_m;
+             rhs0[1] = Setup;
+             mexCallMATLAB(1, lhs0, 2, rhs0, "ilu");
+      */
       // To store the resultng matrix in a CSR format we have to transpose it
       mxArray *Wt = lhs0[0];
-      mwIndex* Wtj = mxGetJc(Wt);
+      mwIndex *Wtj = mxGetJc(Wt);
       nnz = Wtj[n];
-      mxArray* W;
+      mxArray *W;
       mexCallMATLAB(1, &W, 1, &Wt, "transpose");
       mxDestroyArray(Wt);
-      double* pW = mxGetPr(W);
-      mwIndex* Wi = mxGetIr(W);
-      mwIndex* Wp = mxGetJc(W);
-      int *Wii = (int*)mxMalloc(nnz * sizeof(int));
-      int *Wip = (int*)mxMalloc((n + 1) * sizeof(int));
+      double *pW = mxGetPr(W);
+      mwIndex *Wi = mxGetIr(W);
+      mwIndex *Wp = mxGetJc(W);
+      int *Wii = (int *) mxMalloc(nnz * sizeof(int));
+      test_mxMalloc(Wii, __LINE__, __FILE__, __func__, nnz * sizeof(int));
+      int *Wip = (int *) mxMalloc((n + 1) * sizeof(int));
+      test_mxMalloc(Wip, __LINE__, __FILE__, __func__, (n + 1) * sizeof(int));
       for (int i = 0; i < nnz; i++)
         Wii[i] = Wi[i];
       for (int i = 0; i < n + 1; i++)
@@ -3951,27 +4006,32 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
 
       cudaChk(cudaFree(A_tild), "cudaFree(A_tild) has failed\n");
 
-      cudaChk(cudaMalloc((void**)&A_tild, nnz * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate A_tild on the graphic card\n");
+      cudaChk(cudaMalloc((void **) &A_tild, nnz * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate A_tild on the graphic card\n");
       cudaChk(cudaMemcpy(A_tild, pW, nnz * sizeof(double), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy A_tild = pW has failed\n");
-      cudaChk(cudaMalloc((void**)&A_tild_i, nnz * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate Ai on the graphic card\n");
+      cudaChk(cudaMalloc((void **) &A_tild_i, nnz * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate Ai on the graphic card\n");
       cudaChk(cudaMemcpy(A_tild_i, Wii, nnz * sizeof(int), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_i = A_tild_i_host has failed\n");
-      cudaChk(cudaMalloc((void**)&A_tild_p, (n + 1) * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate A_tild_p on the graphic card\n");
+      cudaChk(cudaMalloc((void **) &A_tild_p, (n + 1) * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate A_tild_p on the graphic card\n");
       cudaChk(cudaMemcpy(A_tild_p, Wip, (n + 1) * sizeof(int), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_p = A_tild_j_host has failed\n");
       /*mxFree(pW);
-      mxFree(Wi);
-      mxFree(Wj);*/
+        mxFree(Wi);
+        mxFree(Wj);*/
       mxDestroyArray(W);
       mxFree(Wii);
       mxFree(Wip);
     }
   else if (preconditioner == 3)
     {
-      mwIndex* Aowi, *Aowp;
-      double* A_host = (double*)mxMalloc(nnz*sizeof(double));
-      Aowi = (mwIndex*)mxMalloc(nnz * sizeof(mwIndex));
-      Aowp = (mwIndex*)mxMalloc((n + 1) * sizeof(mwIndex));
-      int* Aoii = (int*)mxMalloc(nnz * sizeof(int));
-      int* Aoip = (int*)mxMalloc((n + 1) * sizeof(int));
+      mwIndex *Aowi, *Aowp;
+      double *A_host = (double *) mxMalloc(nnz*sizeof(double));
+      test_mxMalloc(A_host, __LINE__, __FILE__, __func__, nnz*sizeof(double));
+      Aowi = (mwIndex *) mxMalloc(nnz * sizeof(mwIndex));
+      test_mxMalloc(Aowi, __LINE__, __FILE__, __func__, nnz * sizeof(mwIndex));
+      Aowp = (mwIndex *) mxMalloc((n + 1) * sizeof(mwIndex));
+      test_mxMalloc(Aowp, __LINE__, __FILE__, __func__, (n + 1) * sizeof(mwIndex));
+      int *Aoii = (int *) mxMalloc(nnz * sizeof(int));
+      test_mxMalloc(Aoii, __LINE__, __FILE__, __func__, nnz * sizeof(int));
+      int *Aoip = (int *) mxMalloc((n + 1) * sizeof(int));
+      test_mxMalloc(Aoip, __LINE__, __FILE__, __func__, (n + 1) * sizeof(int));
       cudaChk(cudaMemcpy(A_host, Ax, nnz*sizeof(double), cudaMemcpyDeviceToHost), "  in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_host = A_tild has failed\n");
       cudaChk(cudaMemcpy(Aoii, Ai, nnz*sizeof(int), cudaMemcpyDeviceToHost), "  in Solve_Cuda_BiCGStab, cudaMemcpy Aii = Ai_tild has failed\n");
       cudaChk(cudaMemcpy(Aoip, Ap, (n+1)*sizeof(int), cudaMemcpyDeviceToHost), "  in Solve_Cuda_BiCGStab, cudaMemcpy Aip = Ap_tild has failed\n");
@@ -3981,25 +4041,30 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
         Aowp[i] = Aoip[i];
       mxFree(Aoii);
       mxFree(Aoip);
-      mxArray * Ao_m = mxCreateSparse(n,n,nnz,mxREAL);
+      mxArray *Ao_m = mxCreateSparse(n, n, nnz, mxREAL);
       mxSetIr(Ao_m, Aowi);
       mxSetJc(Ao_m, Aowp);
       mxSetPr(Ao_m, A_host);
       /*mexPrintf("A_m\n");
-      mxArray *Aoo;
-      mexCallMATLAB(1, &Aoo, 1, &Ao_m, "transpose");
-      mexCallMATLAB(0, NULL, 1, &Aoo, "disp_dense");
-      mxDestroyArray(Ao_m);
-      mxDestroyArray(Aoo);*/
+        mxArray *Aoo;
+        mexCallMATLAB(1, &Aoo, 1, &Ao_m, "transpose");
+        mexCallMATLAB(0, NULL, 1, &Aoo, "disp_dense");
+        mxDestroyArray(Ao_m);
+        mxDestroyArray(Aoo);*/
 
       //Because the Jacobian matrix A is store in CSC format in matlab
       // we have to transpose it to get a CSR format used by CUDA
-      mwIndex* Awi, *Awp;
-      double* A_tild_host = (double*)mxMalloc(nnz_tild*sizeof(double));
-      Awi = (mwIndex*)mxMalloc(nnz_tild * sizeof(mwIndex));
-      Awp = (mwIndex*)mxMalloc((Size + 1) * sizeof(mwIndex));
-      int* Aii = (int*)mxMalloc(nnz_tild * sizeof(int));
-      int* Aip = (int*)mxMalloc((Size + 1) * sizeof(int));
+      mwIndex *Awi, *Awp;
+      double *A_tild_host = (double *) mxMalloc(nnz_tild*sizeof(double));
+      test_mxMalloc(A_tild_host, __LINE__, __FILE__, __func__, nnz_tild*sizeof(double));
+      Awi = (mwIndex *) mxMalloc(nnz_tild * sizeof(mwIndex));
+      test_mxMalloc(Awi, __LINE__, __FILE__, __func__, nnz_tild * sizeof(mwIndex));
+      Awp = (mwIndex *) mxMalloc((Size + 1) * sizeof(mwIndex));
+      test_mxMalloc(Awp, __LINE__, __FILE__, __func__, (Size + 1) * sizeof(mwIndex));
+      int *Aii = (int *) mxMalloc(nnz_tild * sizeof(int));
+      test_mxMalloc(Aii, __LINE__, __FILE__, __func__, nnz_tild * sizeof(int));
+      int *Aip = (int *) mxMalloc((Size + 1) * sizeof(int));
+      test_mxMalloc(Aip, __LINE__, __FILE__, __func__, (Size + 1) * sizeof(int));
       cudaChk(cudaMemcpy(A_tild_host, A_tild, nnz_tild*sizeof(double), cudaMemcpyDeviceToHost), "  in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_host = A_tild has failed\n");
       cudaChk(cudaMemcpy(Aii, Ai_tild, nnz_tild*sizeof(int), cudaMemcpyDeviceToHost), "  in Solve_Cuda_BiCGStab, cudaMemcpy Aii = Ai_tild has failed\n");
       cudaChk(cudaMemcpy(Aip, Ap_tild, (Size+1)*sizeof(int), cudaMemcpyDeviceToHost), "  in Solve_Cuda_BiCGStab, cudaMemcpy Aip = Ap_tild has failed\n");
@@ -4011,14 +4076,14 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
         mexPrintf("%20.17f\n",A_tild_host[i]);*/
       mxFree(Aii);
       mxFree(Aip);
-      mxArray * At_m = mxCreateSparse(Size,Size,nnz_tild,mxREAL);
+      mxArray *At_m = mxCreateSparse(Size, Size, nnz_tild, mxREAL);
       mxSetIr(At_m, Awi);
       mxSetJc(At_m, Awp);
       mxSetPr(At_m, A_tild_host);
       mxArray *A_m;
       mexCallMATLAB(1, &A_m, 1, &At_m, "transpose");
       /*mexPrintf("A_tild_m\n");
-      mexCallMATLAB(0, NULL, 1, &A_m, "disp_dense");*/
+        mexCallMATLAB(0, NULL, 1, &A_m, "disp_dense");*/
       mxDestroyArray(At_m);
       mxArray *P, *Q, *L, *U;
       mxArray *lhs0[4];
@@ -4038,30 +4103,33 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
       mxDestroyArray(L0);
       mxDestroyArray(U0);
       /*L = lhs0[0];
-      U = lhs0[1];
-      P = lhs0[2];
-      Q = lhs0[3];*/
+        U = lhs0[1];
+        P = lhs0[2];
+        Q = lhs0[3];*/
 
       /*mexPrintf("L\n");
-      mexCallMATLAB(0, NULL, 1, &L, "disp_dense");
+        mexCallMATLAB(0, NULL, 1, &L, "disp_dense");
 
-      mexPrintf("U\n");
-      mexCallMATLAB(0, NULL, 1, &U, "disp_dense");
+        mexPrintf("U\n");
+        mexCallMATLAB(0, NULL, 1, &U, "disp_dense");
 
-      mexPrintf("P\n");
-      mexCallMATLAB(0, NULL, 1, &P, "disp_dense");
+        mexPrintf("P\n");
+        mexCallMATLAB(0, NULL, 1, &P, "disp_dense");
 
-      mexPrintf("Q\n");
-      mexCallMATLAB(0, NULL, 1, &Q, "disp_dense");*/
+        mexPrintf("Q\n");
+        mexCallMATLAB(0, NULL, 1, &Q, "disp_dense");*/
 
-      mwIndex* Qiw_host = mxGetIr(Q);
-      mwIndex* Qjw_host = mxGetJc(Q);
-      double*  Qx_host = mxGetPr(Q);
+      mwIndex *Qiw_host = mxGetIr(Q);
+      mwIndex *Qjw_host = mxGetJc(Q);
+      double *Qx_host = mxGetPr(Q);
       Q_nnz = Qjw_host[Size];
-      mexPrintf("Q_nnz=%d\n",Q_nnz);
-      int *Qi_host = (int*)mxMalloc(Q_nnz * periods * sizeof(int));
-      double *Q_x_host = (double*)mxMalloc(Q_nnz * periods * sizeof(double));
-      int *Qj_host = (int*)mxMalloc((n + 1) * sizeof(int));
+      mexPrintf("Q_nnz=%d\n", Q_nnz);
+      int *Qi_host = (int *) mxMalloc(Q_nnz * periods * sizeof(int));
+      test_mxMalloc(Qi_host, __LINE__, __FILE__, __func__, Q_nnz * periods * sizeof(int));
+      double *Q_x_host = (double *) mxMalloc(Q_nnz * periods * sizeof(double));
+      test_mxMalloc(Q_x_host, __LINE__, __FILE__, __func__, Q_nnz * periods * sizeof(double));
+      int *Qj_host = (int *) mxMalloc((n + 1) * sizeof(int));
+      test_mxMalloc(Qj_host, __LINE__, __FILE__, __func__, (n + 1) * sizeof(int));
       for (int t = 0; t < periods; t++)
         {
           for (int i = 0; i < Q_nnz; i++)
@@ -4076,52 +4144,51 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
         }
       Qj_host[periods * Size] = periods * Q_nnz;
 
-
       /*mwIndex *Qtiw_host  = (mwIndex*) mxMalloc(Q_nnz * periods * sizeof(mwIndex));
-      double *Qt_x_host = (double*)mxMalloc(Q_nnz * periods * sizeof(double));
-      mwIndex *Qtjw_host = (mwIndex*)mxMalloc((n + 1) * sizeof(mwIndex));
-      mexPrintf("n = %d\n",n);
-      for (int i = 0; i < n + 1; i++)
+        double *Qt_x_host = (double*)mxMalloc(Q_nnz * periods * sizeof(double));
+        mwIndex *Qtjw_host = (mwIndex*)mxMalloc((n + 1) * sizeof(mwIndex));
+        mexPrintf("n = %d\n",n);
+        for (int i = 0; i < n + 1; i++)
         Qtjw_host[i] = Qj_host[i];
-      for (int i = 0; i < Q_nnz * periods; i++)
+        for (int i = 0; i < Q_nnz * periods; i++)
         {
-          Qtiw_host[i] = Qi_host[i];
-          Qt_x_host[i] = Q_x_host[i];
+        Qtiw_host[i] = Qi_host[i];
+        Qt_x_host[i] = Q_x_host[i];
         }
-      mxArray* Qt_m = mxCreateSparse(n,n,Q_nnz * periods,mxREAL);
-      mxSetIr(Qt_m, Qtiw_host);
-      mxSetJc(Qt_m, Qtjw_host);
-      mxSetPr(Qt_m, Qt_x_host);
-      mexPrintf("Qt_m\n");
-      mexCallMATLAB(0, NULL, 1, &Qt_m, "disp_dense");*/
-
+        mxArray* Qt_m = mxCreateSparse(n,n,Q_nnz * periods,mxREAL);
+        mxSetIr(Qt_m, Qtiw_host);
+        mxSetJc(Qt_m, Qtjw_host);
+        mxSetPr(Qt_m, Qt_x_host);
+        mexPrintf("Qt_m\n");
+        mexCallMATLAB(0, NULL, 1, &Qt_m, "disp_dense");*/
 
       /*mexPrintf("Qtjw_host[periods * Size=%d]=%d\n", periods * Size, Qtjw_host[periods * Size]);
-      for (int i = 0; i < n; i++)
+        for (int i = 0; i < n; i++)
         for (int j = Qtjw_host[i]; j < Qtjw_host[i+1]; j++)
-           mexPrintf("(i=%d, j=%d) = %f\n", i, Qtiw_host[j], Qt_x_host[j]);*/
+        mexPrintf("(i=%d, j=%d) = %f\n", i, Qtiw_host[j], Qt_x_host[j]);*/
       //mxDestroyArray(Qt_m);
 
-
-      cudaChk(cudaMalloc((void**)&Qx, Q_nnz * periods * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate Qx on the graphic card\n");
+      cudaChk(cudaMalloc((void **) &Qx, Q_nnz * periods * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate Qx on the graphic card\n");
       cudaChk(cudaMemcpy(Qx, Q_x_host, Q_nnz * periods * sizeof(double), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy Qx = Qx_host has failed\n");
-      cudaChk(cudaMalloc((void**)&Qi, Q_nnz * periods * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate Qi on the graphic card\n");
+      cudaChk(cudaMalloc((void **) &Qi, Q_nnz * periods * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate Qi on the graphic card\n");
       cudaChk(cudaMemcpy(Qi, Qi_host, Q_nnz * periods * sizeof(int), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy Qi = Qi_host has failed\n");
-      cudaChk(cudaMalloc((void**)&Qj, (Size * periods + 1) * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate Qj on the graphic card\n");
+      cudaChk(cudaMalloc((void **) &Qj, (Size * periods + 1) * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate Qj on the graphic card\n");
       cudaChk(cudaMemcpy(Qj, Qj_host, (Size * periods + 1) * sizeof(int), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy Qj = Qj_host has failed\n");
       mxFree(Qi_host);
       mxFree(Qj_host);
       mxFree(Q_x_host);
       mxDestroyArray(Q);
 
-
-      mwIndex* Piw_host = mxGetIr(P);
-      mwIndex* Pjw_host = mxGetJc(P);
-      double*  Px_host = mxGetPr(P);
+      mwIndex *Piw_host = mxGetIr(P);
+      mwIndex *Pjw_host = mxGetJc(P);
+      double *Px_host = mxGetPr(P);
       P_nnz = Pjw_host[Size];
-      int *Pi_host = (int*)mxMalloc(P_nnz * periods * sizeof(int));
-      double *P_x_host = (double*)mxMalloc(P_nnz * periods * sizeof(double));
-      int *Pj_host = (int*)mxMalloc((n + 1) * sizeof(int));
+      int *Pi_host = (int *) mxMalloc(P_nnz * periods * sizeof(int));
+      test_mxMalloc(Pi_host, __LINE__, __FILE__, __func__, P_nnz * periods * sizeof(int));
+      double *P_x_host = (double *) mxMalloc(P_nnz * periods * sizeof(double));
+      test_mxMalloc(P_x_host, __LINE__, __FILE__, __func__, P_nnz * periods * sizeof(double));
+      int *Pj_host = (int *) mxMalloc((n + 1) * sizeof(int));
+      test_mxMalloc(Pj_host, __LINE__, __FILE__, __func__, (n + 1) * sizeof(int));
       for (int t = 0; t < periods; t++)
         {
           for (int i = 0; i < P_nnz; i++)
@@ -4135,29 +4202,28 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
       Pj_host[periods * Size] = periods * P_nnz;
 
       /*mwIndex *Ptiw_host  = (mwIndex*) mxMalloc(P_nnz * periods * sizeof(mwIndex));
-      double *Pt_x_host = (double*)mxMalloc(P_nnz * periods * sizeof(double));
-      mwIndex *Ptjw_host = (mwIndex*)mxMalloc((n + 1) * sizeof(mwIndex));
-      for (int i = 0; i < n + 1; i++)
+        double *Pt_x_host = (double*)mxMalloc(P_nnz * periods * sizeof(double));
+        mwIndex *Ptjw_host = (mwIndex*)mxMalloc((n + 1) * sizeof(mwIndex));
+        for (int i = 0; i < n + 1; i++)
         Ptjw_host[i] = Pj_host[i];
-      for (int i = 0; i < P_nnz * periods; i++)
+        for (int i = 0; i < P_nnz * periods; i++)
         {
-          Ptiw_host[i] = Pi_host[i];
-          Pt_x_host[i] = P_x_host[i];
+        Ptiw_host[i] = Pi_host[i];
+        Pt_x_host[i] = P_x_host[i];
         }
-      mxArray* Pt_m = mxCreateSparse(n,n,P_nnz * periods,mxREAL);
-      mxSetIr(Pt_m, Ptiw_host);
-      mxSetJc(Pt_m, Ptjw_host);
-      mxSetPr(Pt_m, Pt_x_host);
-      mexPrintf("Pt_m\n");
-      mexCallMATLAB(0, NULL, 1, &Pt_m, "disp_dense");
-      mxDestroyArray(Pt_m);*/
+        mxArray* Pt_m = mxCreateSparse(n,n,P_nnz * periods,mxREAL);
+        mxSetIr(Pt_m, Ptiw_host);
+        mxSetJc(Pt_m, Ptjw_host);
+        mxSetPr(Pt_m, Pt_x_host);
+        mexPrintf("Pt_m\n");
+        mexCallMATLAB(0, NULL, 1, &Pt_m, "disp_dense");
+        mxDestroyArray(Pt_m);*/
 
-
-      cudaChk(cudaMalloc((void**)&Px, P_nnz * periods * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate Px on the graphic card\n");
+      cudaChk(cudaMalloc((void **) &Px, P_nnz * periods * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate Px on the graphic card\n");
       cudaChk(cudaMemcpy(Px, P_x_host, P_nnz * periods * sizeof(double), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy Px = Px_host has failed\n");
-      cudaChk(cudaMalloc((void**)&Pi, P_nnz * periods * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate Pi on the graphic card\n");
+      cudaChk(cudaMalloc((void **) &Pi, P_nnz * periods * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate Pi on the graphic card\n");
       cudaChk(cudaMemcpy(Pi, Pi_host, P_nnz * periods * sizeof(int), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy Pi = Pi_host has failed\n");
-      cudaChk(cudaMalloc((void**)&Pj, (Size * periods + 1) * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate Pj on the graphic card\n");
+      cudaChk(cudaMalloc((void **) &Pj, (Size * periods + 1) * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate Pj on the graphic card\n");
       cudaChk(cudaMemcpy(Pj, Pj_host, (Size * periods + 1) * sizeof(int), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy Pj = Pj_host has failed\n");
       mxFree(Pi_host);
       mxFree(Pj_host);
@@ -4165,49 +4231,52 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
       mxDestroyArray(P);
 
       /*mwIndex* Piw_host = mxGetIr(P);
-      mwIndex* Pjw_host = mxGetJc(P);
-      double*  Px_host = mxGetPr(P);
-      P_nnz = Pjw_host[Size];
-      int *Pi_host = (int*)mxMalloc(P_nnz * sizeof(int));
-      int *Pj_host = (int*)mxMalloc((Size + 1) * sizeof(int));
-      for (int i = 0; i < P_nnz; i++)
+        mwIndex* Pjw_host = mxGetJc(P);
+        double*  Px_host = mxGetPr(P);
+        P_nnz = Pjw_host[Size];
+        int *Pi_host = (int*)mxMalloc(P_nnz * sizeof(int));
+        int *Pj_host = (int*)mxMalloc((Size + 1) * sizeof(int));
+        for (int i = 0; i < P_nnz; i++)
         Pi_host[i] = Piw_host[i];
-      for (int i = 0; i < Size + 1; i++)
+        for (int i = 0; i < Size + 1; i++)
         Pj_host[i] = Pjw_host[i];
 
-      cudaChk(cudaMalloc((void**)&Px, P_nnz * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate Px on the graphic card\n");
-      cudaChk(cudaMemcpy(Px, Px_host, P_nnz * sizeof(double), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy Px = Px_host has failed\n");
-      cudaChk(cudaMalloc((void**)&Pi, P_nnz * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate Pi on the graphic card\n");
-      cudaChk(cudaMemcpy(Pi, Pi_host, P_nnz * sizeof(int), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy Pi = Pi_host has failed\n");
-      cudaChk(cudaMalloc((void**)&Pj, (Size + 1) * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate Pj on the graphic card\n");
-      cudaChk(cudaMemcpy(Pj, Pj_host, (Size + 1) * sizeof(int), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy Pj = Pj_host has failed\n");
-      mxFree(Pi_host);
-      mxFree(Pj_host);
-      mxDestroyArray(P);*/
+        cudaChk(cudaMalloc((void**)&Px, P_nnz * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate Px on the graphic card\n");
+        cudaChk(cudaMemcpy(Px, Px_host, P_nnz * sizeof(double), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy Px = Px_host has failed\n");
+        cudaChk(cudaMalloc((void**)&Pi, P_nnz * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate Pi on the graphic card\n");
+        cudaChk(cudaMemcpy(Pi, Pi_host, P_nnz * sizeof(int), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy Pi = Pi_host has failed\n");
+        cudaChk(cudaMalloc((void**)&Pj, (Size + 1) * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate Pj on the graphic card\n");
+        cudaChk(cudaMemcpy(Pj, Pj_host, (Size + 1) * sizeof(int), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy Pj = Pj_host has failed\n");
+        mxFree(Pi_host);
+        mxFree(Pj_host);
+        mxDestroyArray(P);*/
 
       /*mexPrintf("L\n");
-      mexCallMATLAB(0, NULL, 1, &L, "disp_dense");
+        mexCallMATLAB(0, NULL, 1, &L, "disp_dense");
 
-      mexPrintf("U\n");
-      mexCallMATLAB(0, NULL, 1, &U, "disp_dense");*/
+        mexPrintf("U\n");
+        mexCallMATLAB(0, NULL, 1, &U, "disp_dense");*/
 
-      mwIndex* Liw_host = mxGetIr(L);
-      mwIndex* Ljw_host = mxGetJc(L);
-      double*  Lx_host = mxGetPr(L);
+      mwIndex *Liw_host = mxGetIr(L);
+      mwIndex *Ljw_host = mxGetJc(L);
+      double *Lx_host = mxGetPr(L);
       int L_nnz = Ljw_host[Size];
 
-      mwIndex* Uiw_host = mxGetIr(U);
-      mwIndex* Ujw_host = mxGetJc(U);
-      double*  Ux_host = mxGetPr(U);
+      mwIndex *Uiw_host = mxGetIr(U);
+      mwIndex *Ujw_host = mxGetJc(U);
+      double *Ux_host = mxGetPr(U);
       int U_nnz = Ujw_host[Size];
 
-      double *pW = (double*)mxMalloc((L_nnz + U_nnz - Size) * periods * sizeof(double));
-      int *Wi = (int*)mxMalloc((L_nnz + U_nnz - Size) * periods * sizeof(int));
-      int *Wj = (int*)mxMalloc((n + 1) * sizeof(int));
+      double *pW = (double *) mxMalloc((L_nnz + U_nnz - Size) * periods * sizeof(double));
+      test_mxMalloc(pW, __LINE__, __FILE__, __func__, (L_nnz + U_nnz - Size) * periods * sizeof(double));
+      int *Wi = (int *) mxMalloc((L_nnz + U_nnz - Size) * periods * sizeof(int));
+      test_mxMalloc(Wi, __LINE__, __FILE__, __func__, (L_nnz + U_nnz - Size) * periods * sizeof(int));
+      int *Wj = (int *) mxMalloc((n + 1) * sizeof(int));
+      test_mxMalloc(Wj, __LINE__, __FILE__, __func__, (n + 1) * sizeof(int));
       Wj[0] = 0;
       W_nnz = 0;
       for (int t = 0; t < periods; t++)
-        for (int i = 0; i < Size ; i++)
+        for (int i = 0; i < Size; i++)
           {
             for (mwIndex l  = Ujw_host[i]; l < Ujw_host[i+1]; l++)
               {
@@ -4229,89 +4298,88 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
             Wj[i + 1 + t * Size] = W_nnz;
           }
       //mexPrintf("Wj[%d] = %d, n=%d\n", periods * Size, Wj[periods * Size], n);
-      cudaChk(cudaMalloc((void**)&A_tild, W_nnz * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate Px on the graphic card\n");
+      cudaChk(cudaMalloc((void **) &A_tild, W_nnz * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate Px on the graphic card\n");
       cudaChk(cudaMemcpy(A_tild, pW, W_nnz * sizeof(double), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy A_tild = pW has failed\n");
-      cudaChk(cudaMalloc((void**)&A_tild_i, W_nnz * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate Pi on the graphic card\n");
+      cudaChk(cudaMalloc((void **) &A_tild_i, W_nnz * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate Pi on the graphic card\n");
       cudaChk(cudaMemcpy(A_tild_i, Wi, W_nnz * sizeof(int), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_i = Wi has failed\n");
-      cudaChk(cudaMalloc((void**)&A_tild_p, (n + 1) * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate Pj on the graphic card\n");
+      cudaChk(cudaMalloc((void **) &A_tild_p, (n + 1) * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate Pj on the graphic card\n");
       cudaChk(cudaMemcpy(A_tild_p, Wj, (n + 1) * sizeof(int), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_p = Wj has failed\n");
 
       /*mwIndex *Wwi = (mwIndex*)mxMalloc(W_nnz * sizeof(mwIndex));
-      mwIndex *Wwj = (mwIndex*)mxMalloc((n + 1) * sizeof(mwIndex));
-      for (int i = 0; i < W_nnz; i++)
+        mwIndex *Wwj = (mwIndex*)mxMalloc((n + 1) * sizeof(mwIndex));
+        for (int i = 0; i < W_nnz; i++)
         Wwi[i] = Wi[i];
-      for (int i = 0; i < n + 1; i++)
+        for (int i = 0; i < n + 1; i++)
         Wwj[i] = Wj[i];
-      mxFree(Wi);
-      mxFree(Wj);
-      mxArray* Ao_tild = mxCreateSparse(n,n,W_nnz,mxREAL);
-      mxSetIr(Ao_tild, Wwi);
-      mxSetJc(Ao_tild, Wwj);
-      mxSetPr(Ao_tild, pW);
-      mexPrintf("Ao_tild\n");
-      mexCallMATLAB(0, NULL, 1, &Ao_tild, "disp_dense");
-      mxDestroyArray(Ao_tild);*/
-
+        mxFree(Wi);
+        mxFree(Wj);
+        mxArray* Ao_tild = mxCreateSparse(n,n,W_nnz,mxREAL);
+        mxSetIr(Ao_tild, Wwi);
+        mxSetJc(Ao_tild, Wwj);
+        mxSetPr(Ao_tild, pW);
+        mexPrintf("Ao_tild\n");
+        mexCallMATLAB(0, NULL, 1, &Ao_tild, "disp_dense");
+        mxDestroyArray(Ao_tild);*/
 
       /*ostringstream tmp;
-      tmp << "debugging";
-      mexWarnMsgTxt(tmp.str().c_str());
-      return 4;*/
+        tmp << "debugging";
+        mexWarnMsgTxt(tmp.str().c_str());
+        return 4;*/
 
       /* Apply the permutation matrices (P and Q) to the b vector of system to solve :
-       b_tild = P-1 . b  = P' . b */
+         b_tild = P-1 . b  = P' . b */
       /*cudaChk(cudaMalloc((void**)&b_tild, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate b_tild on the graphic card\n");
-      cusparseChk(cusparseDcsrmv(cusparse_handle, CUSPARSE_OPERATION_TRANSPOSE,
-                                 n, n, nnz, &one, CUDA_descr,
-                                 Px, Pj, Pi,
-                                 b, &zeros,
-                                 b_tild),
-                  "  in Solve_Cuda_BiCGStab, b_tild = cusparseDcsrmv(P', b) has failed\n");
-
-      cusparseChk(cusparseDcsrmv(cusparse_handle, CUSPARSE_OPERATION_TRANSPOSE,
-                                 n, n, nnz, &one, CUDA_descr,
-                                 Px, Pj, Pi,
-                                 b, &zeros,
-                                 b),
-                  "  in Solve_Cuda_BiCGStab, b = cusparseDcsrmv(P', b) has failed\n");
+        cusparseChk(cusparseDcsrmv(cusparse_handle, CUSPARSE_OPERATION_TRANSPOSE,
+        n, n, nnz, &one, CUDA_descr,
+        Px, Pj, Pi,
+        b, &zeros,
+        b_tild),
+        "  in Solve_Cuda_BiCGStab, b_tild = cusparseDcsrmv(P', b) has failed\n");
+
+        cusparseChk(cusparseDcsrmv(cusparse_handle, CUSPARSE_OPERATION_TRANSPOSE,
+        n, n, nnz, &one, CUDA_descr,
+        Px, Pj, Pi,
+        b, &zeros,
+        b),
+        "  in Solve_Cuda_BiCGStab, b = cusparseDcsrmv(P', b) has failed\n");
       */
       /*mexPrintf("Wt = lu(A_m)\n");
-      mexCallMATLAB(0, NULL, 1, &Wt, "disp_dense");*/
+        mexCallMATLAB(0, NULL, 1, &Wt, "disp_dense");*/
       /*ostringstream tmp;
-      tmp << "debugging";
-      mexWarnMsgTxt(tmp.str().c_str());
-      return 4;*/
+        tmp << "debugging";
+        mexWarnMsgTxt(tmp.str().c_str());
+        return 4;*/
       // To store the resultng matrix in a CSR format we have to transpose it
       /*mwIndex* Wtj = mxGetJc(Wt);
-      nnz = Wtj[n];
-      mxArray* W;
-      mexCallMATLAB(1, &W, 1, &Wt, "transpose");
-      mxDestroyArray(Wt);
-      pW = mxGetPr(W);
-      Wwi = mxGetIr(W);
-      mwIndex* Wp = mxGetJc(W);
-      int *Wii = (int*)mxMalloc(nnz * sizeof(int));
-      int *Wip = (int*)mxMalloc((n + 1) * sizeof(int));
-      for (int i = 0; i < nnz; i++)
+        nnz = Wtj[n];
+        mxArray* W;
+        mexCallMATLAB(1, &W, 1, &Wt, "transpose");
+        mxDestroyArray(Wt);
+        pW = mxGetPr(W);
+        Wwi = mxGetIr(W);
+        mwIndex* Wp = mxGetJc(W);
+        int *Wii = (int*)mxMalloc(nnz * sizeof(int));
+        int *Wip = (int*)mxMalloc((n + 1) * sizeof(int));
+        for (int i = 0; i < nnz; i++)
         Wii[i] = Wi[i];
-      for (int i = 0; i < n + 1; i++)
+        for (int i = 0; i < n + 1; i++)
         Wip[i] = Wp[i];
 
-      //mxFree(A_tild_host);
+        //mxFree(A_tild_host);
 
-      cudaChk(cudaFree(Ai_tild), "  in Solve_Cuda_BiCGStab, cudaFree(Ai_tild) has failed\n");
-      cudaChk(cudaFree(Ap_tild), "  in Solve_Cuda_BiCGStab, cudaFree(Ap_tild) has failed\n");
-      cudaChk(cudaFree(A_tild), "  in Solve_Cuda_BiCGStab, cudaFree(A_tild) has failed\n");
+        cudaChk(cudaFree(Ai_tild), "  in Solve_Cuda_BiCGStab, cudaFree(Ai_tild) has failed\n");
+        cudaChk(cudaFree(Ap_tild), "  in Solve_Cuda_BiCGStab, cudaFree(Ap_tild) has failed\n");
+        cudaChk(cudaFree(A_tild), "  in Solve_Cuda_BiCGStab, cudaFree(A_tild) has failed\n");
 
-      cudaChk(cudaMalloc((void**)&A_tild, nnz * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate A_tild on the graphic card\n");
-      cudaChk(cudaMemcpy(A_tild, pW, nnz * sizeof(double), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy A_tild = pW has failed\n");
-      cudaChk(cudaMalloc((void**)&A_tild_i, nnz * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate Ai on the graphic card\n");
-      cudaChk(cudaMemcpy(A_tild_i, Wii, nnz * sizeof(int), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_i = A_tild_i_host has failed\n");
-      cudaChk(cudaMalloc((void**)&A_tild_p, (n + 1) * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate A_tild_p on the graphic card\n");
-      cudaChk(cudaMemcpy(A_tild_p, Wip, (n + 1) * sizeof(int), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_p = A_tild_j_host has failed\n");
-      mxDestroyArray(W);
-      mxFree(Wii);
-      mxFree(Wip);*/
+        cudaChk(cudaMalloc((void**)&A_tild, nnz * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate A_tild on the graphic card\n");
+        cudaChk(cudaMemcpy(A_tild, pW, nnz * sizeof(double), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy A_tild = pW has failed\n");
+        cudaChk(cudaMalloc((void**)&A_tild_i, nnz * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate Ai on the graphic card\n");
+        cudaChk(cudaMemcpy(A_tild_i, Wii, nnz * sizeof(int), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_i = A_tild_i_host has failed\n");
+        cudaChk(cudaMalloc((void**)&A_tild_p, (n + 1) * sizeof(int)), "  in Solve_Cuda_BiCGStab, can't allocate A_tild_p on the graphic card\n");
+        cudaChk(cudaMemcpy(A_tild_p, Wip, (n + 1) * sizeof(int), cudaMemcpyHostToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_p = A_tild_j_host has failed\n");
+        mxDestroyArray(W);
+        mxFree(Wii);
+        mxFree(Wip);*/
     }
   if (preconditioner == 1 || preconditioner == 2 || preconditioner == 3)
     {
@@ -4364,22 +4432,20 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
                   "  in Solve_Cuda_BiCGStab, cusparseDcsrsm_analysis for infoU has failed\n");
     }
 
-  cudaChk(cudaMalloc((void**)&v, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate v on the graphic card\n");
-  cudaChk(cudaMalloc((void**)&p, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate p on the graphic card\n");
+  cudaChk(cudaMalloc((void **) &v, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate v on the graphic card\n");
+  cudaChk(cudaMalloc((void **) &p, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate p on the graphic card\n");
   //cudaChk(cudaMemset(p, 0, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, cudaMemset p = 0 has failed\n");
-  cudaChk(cudaMalloc((void**)&s, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate s on the graphic card\n");
-  cudaChk(cudaMalloc((void**)&t, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate t on the graphic card\n");
-  cudaChk(cudaMalloc((void**)&y_, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate y_ on the graphic card\n");
-  cudaChk(cudaMalloc((void**)&z, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate z on the graphic card\n");
+  cudaChk(cudaMalloc((void **) &s, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate s on the graphic card\n");
+  cudaChk(cudaMalloc((void **) &t, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate t on the graphic card\n");
+  cudaChk(cudaMalloc((void **) &y_, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate y_ on the graphic card\n");
+  cudaChk(cudaMalloc((void **) &z, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate z on the graphic card\n");
 
   double rho = 1.0, alpha = 1.0, omega = 1.0;
 
-
   //residual = P*B*Q - L*U;
   //norm(Z,1) should be close to 0
 
-
-  while (iteration < 50/*max_iterations*/ && !convergence)
+  while (iteration < 50 /*max_iterations*/ && !convergence)
     {
       double rho_prev = rho;
       /**store in s previous value of r*/
@@ -4392,7 +4458,7 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
                            &rho),
                 "  in Solve_Cuda_BiCGStab, rho = cublasDdot(r0, r) has failed\n");
 
-      mexPrintf("rho=%f\n",rho);
+      mexPrintf("rho=%f\n", rho);
 
       double beta;
 
@@ -4407,9 +4473,9 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
 
           /**p = r + beta * (p - omega * v)*/
           // tmp_ = p - omega * v
-          VecAdd<<<nblocks, n_threads>>>(tmp_, p, -omega, v, n);
+          VecAdd<<< nblocks, n_threads>>> (tmp_, p, -omega, v, n);
           //p = r + beta * tmp_
-          VecAdd<<<nblocks, n_threads>>>(p, r, beta, tmp_, n);
+          VecAdd<<< nblocks, n_threads>>> (p, r, beta, tmp_, n);
         }
 
       /**y_ solution of A_tild * y_ = p <=> L . U . y_ = p*/
@@ -4421,10 +4487,10 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
 
           cudaChk(cudaMemcpy(tmp_vect_host, p, n*sizeof(double), cudaMemcpyDeviceToHost), "  in Solve_Cuda_BiCGStab, cudaMemcpy tmp_vect_host = p has failed\n");
           /*mexPrintf("p\n");
-          for (int i = 0; i < n; i++)
-             mexPrintf("%f\n",tmp_vect_host[i]);*/
+            for (int i = 0; i < n; i++)
+            mexPrintf("%f\n",tmp_vect_host[i]);*/
 
-          cudaChk(cudaMalloc((void**)&p_tild, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate b_tild on the graphic card\n");
+          cudaChk(cudaMalloc((void **) &p_tild, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate b_tild on the graphic card\n");
           cusparseChk(cusparseDcsrmv(cusparse_handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
                                      n, n, P_nnz * periods, &one, CUDA_descr,
                                      Px, Pj, Pi,
@@ -4433,12 +4499,12 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
                       "  in Solve_Cuda_BiCGStab, p_tild = cusparseDcsrmv(P', p) has failed\n");
 
           /*mexPrintf("P\n");
-          printM(n, Px, Pj, Pi, CUDA_descr, cusparse_handle);*/
+            printM(n, Px, Pj, Pi, CUDA_descr, cusparse_handle);*/
 
           cudaChk(cudaMemcpy(tmp_vect_host, p_tild, n*sizeof(double), cudaMemcpyDeviceToHost), "  in Solve_Cuda_BiCGStab, cudaMemcpy tmp_vect_host = p_tild has failed\n");
           /*mexPrintf("p_tild\n");
-          for (int i = 0; i < n; i++)
-             mexPrintf("%f\n",tmp_vect_host[i]);*/
+            for (int i = 0; i < n; i++)
+            mexPrintf("%f\n",tmp_vect_host[i]);*/
 
           cusparseChk(cusparseDcsrsv_solve(cusparse_handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
                                            n, &one,
@@ -4451,8 +4517,8 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
 
           cudaChk(cudaMemcpy(tmp_vect_host, tmp_, n*sizeof(double), cudaMemcpyDeviceToHost), "  in Solve_Cuda_BiCGStab, cudaMemcpy tmp_vect_host = v has failed\n");
           /*mexPrintf("tmp_\n");
-          for (int i = 0; i < n; i++)
-             mexPrintf("%f\n",tmp_vect_host[i]);*/
+            for (int i = 0; i < n; i++)
+            mexPrintf("%f\n",tmp_vect_host[i]);*/
         }
       else
         cusparseChk(cusparseDcsrsv_solve(cusparse_handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
@@ -4473,14 +4539,14 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
                   "  in Solve_Cuda_BiCGStab, cusparseDcsrsv_solve for U . y_ = tmp_ has failed\n");
 
       /*cudaChk(cudaMemcpy(tmp_vect_host, y_, n*sizeof(double), cudaMemcpyDeviceToHost), "  in Solve_Cuda_BiCGStab, cudaMemcpy tmp_vect_host = v has failed\n");
-      mexPrintf("y_\n");
-      for (int i = 0; i < n; i++)
+        mexPrintf("y_\n");
+        for (int i = 0; i < n; i++)
         mexPrintf("%f\n",tmp_vect_host[i]);*/
 
       if (preconditioner == 3)
         {
           double *y_tild;
-          cudaChk(cudaMalloc((void**)&y_tild, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate b_tild on the graphic card\n");
+          cudaChk(cudaMalloc((void **) &y_tild, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate b_tild on the graphic card\n");
           cudaChk(cudaMemcpy(y_tild, y_, n  * sizeof(double), cudaMemcpyDeviceToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy y_tild = y_ has failed\n");
           cusparseChk(cusparseDcsrmv(cusparse_handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
                                      n, n, Q_nnz * periods, &one, CUDA_descr,
@@ -4491,8 +4557,8 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
           cudaChk(cudaFree(y_tild), "  in Solve_Cuda_BiCGStab, can't free y_tild\n");
         }
       /*cudaChk(cudaMemcpy(tmp_vect_host, y_, n*sizeof(double), cudaMemcpyDeviceToHost), "  in Solve_Cuda_BiCGStab, cudaMemcpy tmp_vect_host = v has failed\n");
-      mexPrintf("y_\n");
-      for (int i = 0; i < n; i++)
+        mexPrintf("y_\n");
+        for (int i = 0; i < n; i++)
         mexPrintf("%f\n",tmp_vect_host[i]);*/
       /**v = A*y_*/
       cusparseChk(cusparseDcsrmv(cusparse_handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
@@ -4503,11 +4569,9 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
                   "  in Solve_Cuda_BiCGStab, v = cusparseDcsrmv(A, y_) has failed\n");
       cudaChk(cudaMemcpy(tmp_vect_host, v, n*sizeof(double), cudaMemcpyDeviceToHost), "  in Solve_Cuda_BiCGStab, cudaMemcpy tmp_vect_host = v has failed\n");
       /*mexPrintf("v\n");
-      for (int i = 0; i < n; i++)
+        for (int i = 0; i < n; i++)
         mexPrintf("%f\n",tmp_vect_host[i]);*/
 
-
-
       /**alpha = rho / (rr0 . v) with rr0 = r0*/
       cublasChk(cublasDdot(cublas_handle, n, // numerator
                            r0, 1,
@@ -4537,17 +4601,17 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
                             x0, 1,
                             &tmp2),
                 "  in Solve_Cuda_BiCGStab, cublasDnrm2(y_) has failed\n");
-      mexPrintf("abs(alpha)*tmp1  = %f, alpha = %f, tmp1 = %f, tmp2 = %f, eps = %f\n",abs(alpha)*tmp1 , alpha, tmp1, tmp2, eps);
+      mexPrintf("abs(alpha)*tmp1  = %f, alpha = %f, tmp1 = %f, tmp2 = %f, eps = %f\n", abs(alpha)*tmp1, alpha, tmp1, tmp2, eps);
       if (abs(alpha)*tmp1  < eps * tmp2)
         stagnation++;
       else
         stagnation = 0;
 
       /**x = x + alpha * y_*/
-      VecInc<<<nblocks, n_threads>>>(x0, alpha, y_, n);
+      VecInc<<< nblocks, n_threads>>> (x0, alpha, y_, n);
 
       /**s = r_prev - alpha *v with r_prev = s*/
-      VecInc<<<nblocks, n_threads>>>(s, -alpha, v, n);
+      VecInc<<< nblocks, n_threads>>> (s, -alpha, v, n);
 
       /**Has BiCGStab converged?*/
       cublasChk(cublasDnrm2(cublas_handle, n, // numerator
@@ -4599,7 +4663,7 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
       if (preconditioner == 3)
         {
           double *s_tild;
-          cudaChk(cudaMalloc((void**)&s_tild, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate b_tild on the graphic card\n");
+          cudaChk(cudaMalloc((void **) &s_tild, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate b_tild on the graphic card\n");
           cusparseChk(cusparseDcsrmv(cusparse_handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
                                      n, n, P_nnz * periods, &one, CUDA_descr,
                                      Px, Pj, Pi,
@@ -4636,7 +4700,7 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
       if (preconditioner == 3)
         {
           double *z_tild;
-          cudaChk(cudaMalloc((void**)&z_tild, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate z_tild on the graphic card\n");
+          cudaChk(cudaMalloc((void **) &z_tild, n * sizeof(double)), "  in Solve_Cuda_BiCGStab, can't allocate z_tild on the graphic card\n");
           cudaChk(cudaMemcpy(z_tild, z, n  * sizeof(double), cudaMemcpyDeviceToDevice), "  in Solve_Cuda_BiCGStab, cudaMemcpy z_tild = z has failed\n");
           cusparseChk(cusparseDcsrmv(cusparse_handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
                                      n, n, Q_nnz * periods, &one, CUDA_descr,
@@ -4680,10 +4744,10 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
         }
 
       /**x = x +  omega * z*/
-      VecInc<<<nblocks, n_threads>>>(x0, omega, z, n);
+      VecInc<<< nblocks, n_threads>>> (x0, omega, z, n);
 
       /**r = s - omega * t*/
-      VecAdd<<<nblocks, n_threads>>>(r, s, -omega, t, n);
+      VecAdd<<< nblocks, n_threads>>> (r, s, -omega, t, n);
 
       /**Has BiCGStab converged?*/
       cublasChk(cublasDnrm2(cublas_handle, n, // numerator
@@ -4722,7 +4786,7 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild,
               refinement_needed++;
               if (refinement_needed > max_refinement)
                 {
-                  Solve_CUDA_BiCGStab_Free(tmp_vect_host, p, r, v, s, t, y_, z, tmp_, Ai, Ax, Ap, x0, b, A_tild, A_tild_i, A_tild_p, /*Lx, Li, Lp, Ux, Ui, Up, device_n, */infoL, infoU, descrL, descrU, preconditioner);
+                  Solve_CUDA_BiCGStab_Free(tmp_vect_host, p, r, v, s, t, y_, z, tmp_, Ai, Ax, Ap, x0, b, A_tild, A_tild_i, A_tild_p, /*Lx, Li, Lp, Ux, Ui, Up, device_n, */ infoL, infoU, descrL, descrU, preconditioner);
                   ostringstream tmp;
                   mexEvalString("diary off;");
                   tmp << "Error in bytecode: BiCGStab stagnated (Two consecutive iterates were the same.), in block " << block+1;
@@ -4798,7 +4862,7 @@ dynSparseMatrix::Solve_Matlab_GMRES(mxArray *A_m, mxArray *b_m, int Size, double
   rhs[1] = b_m;
   rhs[2] = mxCreateDoubleScalar(Size);
   rhs[3] = mxCreateDoubleScalar(1e-6);
-  rhs[4] = mxCreateDoubleScalar((double)n);
+  rhs[4] = mxCreateDoubleScalar((double) n);
   rhs[5] = L1;
   rhs[6] = U1;
   rhs[7] = x0_m;
@@ -4866,6 +4930,9 @@ dynSparseMatrix::Solve_Matlab_BiCGStab(mxArray *A_m, mxArray *b_m, int Size, dou
      precond = 1  => Incomplet LU decomposition*/
   size_t n = mxGetM(A_m);
   mxArray *L1, *U1, *Diag;
+  L1 = NULL;
+  U1 = NULL;
+  Diag = NULL;
 
   mxArray *rhs0[4];
   if (preconditioner == 0)
@@ -4874,8 +4941,8 @@ dynSparseMatrix::Solve_Matlab_BiCGStab(mxArray *A_m, mxArray *b_m, int Size, dou
       rhs0[0] = A_m;
       rhs0[1] = mxCreateDoubleScalar(0);
       mexCallMATLAB(1, lhs0, 2, rhs0, "spdiags");
-      mxArray* tmp = lhs0[0];
-      double* tmp_val = mxGetPr(tmp);
+      mxArray *tmp = lhs0[0];
+      double *tmp_val = mxGetPr(tmp);
       Diag = mxCreateSparse(n, n, n, mxREAL);
       mwIndex *Diag_i = mxGetIr(Diag);
       mwIndex *Diag_j = mxGetJc(Diag);
@@ -4897,7 +4964,7 @@ dynSparseMatrix::Solve_Matlab_BiCGStab(mxArray *A_m, mxArray *b_m, int Size, dou
       const int milu = 2;
       const int udiag = 3;
       const int thresh = 4;
-      mwSize dims[1] = {(mwSize)1 };
+      mwSize dims[1] = {(mwSize) 1 };
       mxArray *Setup = mxCreateStructArray(1, dims, 5, field_names);
       mxSetFieldByNumber(Setup, 0, type, mxCreateString("ilutp"));
       mxSetFieldByNumber(Setup, 0, droptol, mxCreateDoubleScalar(lu_inc_tol));
@@ -4911,7 +4978,7 @@ dynSparseMatrix::Solve_Matlab_BiCGStab(mxArray *A_m, mxArray *b_m, int Size, dou
       if (mexCallMATLAB(2, lhs0, 2, rhs0, "ilu"))
         {
           ostringstream tmp;
-          tmp  << " In BiCGStab, the incomplet LU decomposition (ilu) ahs failed.\n";
+          tmp << " In BiCGStab, the incomplet LU decomposition (ilu) ahs failed.\n";
           throw FatalExceptionHandling(tmp.str());
         }
       L1 = lhs0[0];
@@ -4920,12 +4987,13 @@ dynSparseMatrix::Solve_Matlab_BiCGStab(mxArray *A_m, mxArray *b_m, int Size, dou
     }
   double flags = 2;
   mxArray *z;
+  z = NULL;
   if (steady_state)  /*Octave BicStab algorihtm involves a 0 division in case of a preconditionner equal to the LU decomposition of A matrix*/
     {
       mxArray *res = mult_SAT_B(Sparse_transpose(A_m), x0_m);
       double *resid = mxGetPr(res);
       double *b = mxGetPr(b_m);
-      for (int i = 0; i < (int)n; i++)
+      for (int i = 0; i < (int) n; i++)
         resid[i] = b[i] - resid[i];
       mxArray *rhs[2];
       mxArray *lhs[1];
@@ -4938,14 +5006,14 @@ dynSparseMatrix::Solve_Matlab_BiCGStab(mxArray *A_m, mxArray *b_m, int Size, dou
       z = lhs[0];
       double *phat = mxGetPr(z);
       double *x0 = mxGetPr(x0_m);
-      for (int i = 0; i < (int)n; i++)
+      for (int i = 0; i < (int) n; i++)
         phat[i] = x0[i] + phat[i];
 
       /*Check the solution*/
       res = mult_SAT_B(Sparse_transpose(A_m), z);
       resid = mxGetPr(res);
       double cum_abs = 0;
-      for (int i = 0; i < (int)n; i++)
+      for (int i = 0; i < (int) n; i++)
         {
           resid[i] = b[i] - resid[i];
           cum_abs += fabs(resid[i]);
@@ -4967,7 +5035,7 @@ dynSparseMatrix::Solve_Matlab_BiCGStab(mxArray *A_m, mxArray *b_m, int Size, dou
           rhs[0] = A_m;
           rhs[1] = b_m;
           rhs[2] = mxCreateDoubleScalar(1e-6);
-          rhs[3] = mxCreateDoubleScalar((double)n);
+          rhs[3] = mxCreateDoubleScalar((double) n);
           rhs[4] = Diag;
           //rhs[5] = x0_m;
           mxArray *lhs[2];
@@ -4988,7 +5056,7 @@ dynSparseMatrix::Solve_Matlab_BiCGStab(mxArray *A_m, mxArray *b_m, int Size, dou
           rhs[0] = A_m;
           rhs[1] = b_m;
           rhs[2] = mxCreateDoubleScalar(1e-6);
-          rhs[3] = mxCreateDoubleScalar((double)n);
+          rhs[3] = mxCreateDoubleScalar((double) n);
           rhs[4] = L1;
           rhs[5] = U1;
           rhs[6] = x0_m;
@@ -5006,7 +5074,6 @@ dynSparseMatrix::Solve_Matlab_BiCGStab(mxArray *A_m, mxArray *b_m, int Size, dou
         }
     }
 
-
   if (flags > 0)
     {
       ostringstream tmp;
@@ -5077,8 +5144,8 @@ dynSparseMatrix::Singular_display(int block, int Size)
     }
   mxArray *lhs[3];
   mexCallMATLAB(3, lhs, 1, rhs, "svd");
-  mxArray* SVD_u = lhs[0];
-  mxArray* SVD_s = lhs[1];
+  mxArray *SVD_u = lhs[0];
+  mxArray *SVD_s = lhs[1];
   //mxArray* SVD_v = lhs[2];
   double *SVD_ps = mxGetPr(SVD_s);
   double *SVD_pu = mxGetPr(SVD_u);
@@ -5095,35 +5162,35 @@ dynSparseMatrix::Singular_display(int block, int Size)
           for (int j = 0; j < Size; j++)
             {
               double rr = SVD_pu[j + i * Size] / max_u;
-              if ( rr < -1e-10)
+              if (rr < -1e-10)
                 {
                   equ_list.push_back(j);
                   if (rr != -1)
-                    mexPrintf(" - %3.2f*Dequ_%d_dy",abs(rr),j+1);
+                    mexPrintf(" - %3.2f*Dequ_%d_dy", abs(rr), j+1);
                   else
-                    mexPrintf(" - Dequ_%d_dy",j+1);
+                    mexPrintf(" - Dequ_%d_dy", j+1);
                 }
               else if (rr > 1e-10)
                 {
                   equ_list.push_back(j);
                   if (j > 0)
                     if (rr != 1)
-                      mexPrintf(" + %3.2f*Dequ_%d_dy",rr,j+1);
+                      mexPrintf(" + %3.2f*Dequ_%d_dy", rr, j+1);
                     else
-                      mexPrintf(" + Dequ_%d_dy",j+1);
+                      mexPrintf(" + Dequ_%d_dy", j+1);
                   else if (rr != 1)
-                    mexPrintf(" %3.2f*Dequ_%d_dy",rr,j+1);
+                    mexPrintf(" %3.2f*Dequ_%d_dy", rr, j+1);
                   else
-                    mexPrintf(" Dequ_%d_dy",j+1);
+                    mexPrintf(" Dequ_%d_dy", j+1);
                 }
             }
           mexPrintf(" = 0\n");
           /*mexPrintf(" with:\n");
-          it_code = get_begin_block(block);
-          for (int j=0; j < Size; j++)
+            it_code = get_begin_block(block);
+            for (int j=0; j < Size; j++)
             {
-              if (find(equ_list.begin(), equ_list.end(), j) != equ_list.end())
-                mexPrintf("  equ_%d: %s\n",j, print_expression(it_code_expr, false, Size, block, steady_state, 0, 0, it_code, true).c_str());
+            if (find(equ_list.begin(), equ_list.end(), j) != equ_list.end())
+            mexPrintf("  equ_%d: %s\n",j, print_expression(it_code_expr, false, Size, block, steady_state, 0, 0, it_code, true).c_str());
             }*/
         }
     }
@@ -5138,7 +5205,6 @@ dynSparseMatrix::Singular_display(int block, int Size)
   throw FatalExceptionHandling(tmp.str());
 }
 
-
 bool
 dynSparseMatrix::Solve_ByteCode_Sparse_GaussianElimination(int Size, int blck, int it_)
 {
@@ -5151,10 +5217,15 @@ dynSparseMatrix::Solve_ByteCode_Sparse_GaussianElimination(int Size, int blck, i
   double piv_abs;
   NonZeroElem **bc;
   bc = (NonZeroElem **) mxMalloc(Size*sizeof(*bc));
+  test_mxMalloc(bc, __LINE__, __FILE__, __func__, Size*sizeof(*bc));
   piv_v = (double *) mxMalloc(Size*sizeof(double));
+  test_mxMalloc(piv_v, __LINE__, __FILE__, __func__, Size*sizeof(double));
   pivj_v = (int *) mxMalloc(Size*sizeof(int));
+  test_mxMalloc(pivj_v, __LINE__, __FILE__, __func__, Size*sizeof(int));
   pivk_v = (int *) mxMalloc(Size*sizeof(int));
+  test_mxMalloc(pivk_v, __LINE__, __FILE__, __func__, Size*sizeof(int));
   NR = (int *) mxMalloc(Size*sizeof(int));
+  test_mxMalloc(NR, __LINE__, __FILE__, __func__, Size*sizeof(int));
 
   for (int i = 0; i < Size; i++)
     {
@@ -5419,30 +5490,36 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo
   int tbreak = 0, last_period = periods;
 
   piv_v = (double *) mxMalloc(Size*sizeof(double));
+  test_mxMalloc(piv_v, __LINE__, __FILE__, __func__, Size*sizeof(double));
   pivj_v = (int *) mxMalloc(Size*sizeof(int));
+  test_mxMalloc(pivj_v, __LINE__, __FILE__, __func__, Size*sizeof(int));
   pivk_v = (int *) mxMalloc(Size*sizeof(int));
+  test_mxMalloc(pivk_v, __LINE__, __FILE__, __func__, Size*sizeof(int));
   NR = (int *) mxMalloc(Size*sizeof(int));
+  test_mxMalloc(NR, __LINE__, __FILE__, __func__, Size*sizeof(int));
   //clock_t time00 = clock();
   NonZeroElem **bc;
   bc = (NonZeroElem **) mxMalloc(Size*sizeof(first));
+  test_mxMalloc(bc, __LINE__, __FILE__, __func__, Size*sizeof(first));
 
   for (int t = 0; t < periods; t++)
     {
       /*clock_t time11 = clock();
-      mexPrintf("t=%d, record = %d\n",t, record);*/
+        mexPrintf("t=%d, record = %d\n",t, record);*/
 #ifdef MATLAB_MEX_FILE
-    	if ( utIsInterruptPending() )
-		    throw UserExceptionHandling();
+      if (utIsInterruptPending())
+        throw UserExceptionHandling();
 #endif
 
       if (record && symbolic)
         {
           /*if (save_op)
             {
-              mxFree(save_op);
-              save_op = NULL;
+            mxFree(save_op);
+            save_op = NULL;
             }*/
           save_op = (int *) mxMalloc(nop*sizeof(int));
+          test_mxMalloc(save_op, __LINE__, __FILE__, __func__, nop*sizeof(int));
           nopa = nop;
         }
       nop = 0;
@@ -5636,7 +5713,7 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo
                     bc[nb_eq_todo++] = first;
                   first = first->NZE_C_N;
                 }
-//#pragma omp parallel for num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) shared(nb_var_piva, first_piva, nopa, save_op) reduction(+:nop)
+              //#pragma omp parallel for num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) shared(nb_var_piva, first_piva, nopa, save_op) reduction(+:nop)
               for (int j = 0; j < nb_eq_todo; j++)
                 {
                   t_save_op_s *save_op_s_l;
@@ -5663,7 +5740,7 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo
                   int sub_c_index = first_sub->c_index;
                   int piv_c_index = first_piv->c_index;
                   int tmp_lag = first_sub->lag_index;
-                  while (l_sub < (nb_var_sub/*=NRow(row)*/) || l_piv < nb_var_piv)
+                  while (l_sub < (nb_var_sub /*=NRow(row)*/) || l_piv < nb_var_piv)
                     {
                       if (l_sub < nb_var_sub && (sub_c_index < piv_c_index || l_piv >= nb_var_piv))
                         {
@@ -5681,9 +5758,9 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo
                           tmp_u_count = Get_u();
                           lag = first_piv->c_index/Size-row/Size;
                           //#pragma omp critical
-                            {
-                              Insert(row, first_piv->c_index, tmp_u_count, lag);
-                            }
+                          {
+                            Insert(row, first_piv->c_index, tmp_u_count, lag);
+                          }
                           u[tmp_u_count] = -u[first_piv->u_index]*first_elem;
                           if (nop+2 >= nopa)
                             {
@@ -5710,9 +5787,9 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo
                               NonZeroElem *firsta = first;
                               NonZeroElem *first_suba = first_sub->NZE_R_N;
                               //#pragma omp critical
-                                {
-                                  Delete(first_sub->r_index, first_sub->c_index);
-                                }
+                              {
+                                Delete(first_sub->r_index, first_sub->c_index);
+                              }
                               first = firsta->NZE_C_N;
                               first_sub = first_suba;
                               if (first_sub)
@@ -5771,7 +5848,7 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo
                   nop += 3;
                 }
             }
-          else if(symbolic)
+          else if (symbolic)
             {
               nop += 2;
               if (piv_abs < eps)
@@ -5805,7 +5882,7 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo
                     bc[nb_eq_todo++] = first;
                   first = first->NZE_C_N;
                 }
-//#pragma omp parallel for num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) shared(nb_var_piva, first_piva, nopa, save_op) reduction(+:nop)
+              //#pragma omp parallel for num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) shared(nb_var_piva, first_piva, nopa, save_op) reduction(+:nop)
               for (int j = 0; j < nb_eq_todo; j++)
                 {
                   NonZeroElem *first = bc[j];
@@ -5838,9 +5915,9 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo
                           tmp_u_count = Get_u();
                           lag = first_piv->c_index/Size-row/Size;
                           //#pragma omp critical
-                           {
-                             Insert(row, first_piv->c_index, tmp_u_count, lag);
-                           }
+                          {
+                            Insert(row, first_piv->c_index, tmp_u_count, lag);
+                          }
                           u[tmp_u_count] = -u[first_piv->u_index]*first_elem;
                           nop += 3;
                           first_piv = first_piv->NZE_R_N;
@@ -5857,9 +5934,9 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo
                               NonZeroElem *firsta = first;
                               NonZeroElem *first_suba = first_sub->NZE_R_N;
                               //#pragma omp critical
-                                {
-                                  Delete(first_sub->r_index, first_sub->c_index);
-                                }
+                              {
+                                Delete(first_sub->r_index, first_sub->c_index);
+                              }
                               first = firsta->NZE_C_N;
                               first_sub = first_suba;
                               if (first_sub)
@@ -5900,7 +5977,7 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo
         }
       if (symbolic)
         {
-		  if (t > int(periods*0.35))
+          if (t > int (periods*0.35))
             {
               symbolic = false;
               mxFree(save_opaa);
@@ -5909,7 +5986,7 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo
             }
           else if (record && (nop == nop1))
             {
-              if (t > int(periods*0.35))
+              if (t > int (periods*0.35))
                 {
                   symbolic = false;
                   if (save_opaa)
@@ -5979,8 +6056,8 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo
   mxFree(pivk_v);
   mxFree(NR);
   /*mexPrintf("tbreak=%d, periods=%d time required=%f\n",tbreak,periods, (1000.0*(double (clock())-double (time00)))/double (CLOCKS_PER_SEC));
-  mexEvalString("drawnow;");
-  time00 = clock();*/
+    mexEvalString("drawnow;");
+    time00 = clock();*/
   nop_all += nop;
   if (symbolic)
     {
@@ -5999,13 +6076,12 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo
   slowc_save = slowc;
   bksub(tbreak, last_period, Size, slowc_lbx);
   /*mexPrintf("remaining operations and bksub time required=%f\n",tbreak,periods, (1000.0*(double (clock())-double (time00)))/double (CLOCKS_PER_SEC));
-  mexEvalString("drawnow;");*/
+    mexEvalString("drawnow;");*/
   End_GE(Size);
 }
 
-
 void
-dynSparseMatrix::Grad_f_product(int n, mxArray *b_m, double* vectr, mxArray *A_m, SuiteSparse_long *Ap, SuiteSparse_long *Ai, double* Ax, double* b_)
+dynSparseMatrix::Grad_f_product(int n, mxArray *b_m, double *vectr, mxArray *A_m, SuiteSparse_long *Ap, SuiteSparse_long *Ai, double *Ax, double *b_)
 {
   if ((solve_algo == 5 && steady_state) || (stack_solve_algo == 5 && !steady_state))
     {
@@ -6080,9 +6156,9 @@ dynSparseMatrix::Check_and_Correct_Previous_Iteration(int block_num, int y_size,
               y[eq+it_*y_size] = ya[eq+it_*y_size] + slowc_save * direction[eq+it_*y_size];
             }
           /*mexPrintf("reducing solwc_save = %e, it_=%d, y_size=%d, size=%d, y[%d]=%e, ya[%d]=%e,\n y[%d]=%e, ya[%d]=%e\n",slowc_save, it_, y_size, size-1, index_vara[0]+it_*y_size, y[index_vara[0]+it_*y_size], index_vara[0]+it_*y_size, ya[index_vara[0]+it_*y_size]
-                                                                                                       , index_vara[size-1]+it_*y_size, y[index_vara[size-1]+it_*y_size], index_vara[size-1]+it_*y_size, ya[index_vara[size-1]+it_*y_size]);*/
-           //mexPrintf("->slowc_save=%f\n",slowc_save);
-           compute_complete(true, res1, res2, max_res, max_res_idx);
+            , index_vara[size-1]+it_*y_size, y[index_vara[size-1]+it_*y_size], index_vara[size-1]+it_*y_size, ya[index_vara[size-1]+it_*y_size]);*/
+          //mexPrintf("->slowc_save=%f\n",slowc_save);
+          compute_complete(true, res1, res2, max_res, max_res_idx);
         }
 
       while (res2 > g0 && slowc_save > 1e-1)
@@ -6099,7 +6175,7 @@ dynSparseMatrix::Check_and_Correct_Previous_Iteration(int block_num, int y_size,
           compute_complete(true, res1, res2, max_res, max_res_idx);
         }
       double ax = slowc_save-0.001, bx = slowc_save+0.001, cx = slowc_save, fa, fb, fc, xmin;
-      if (false/*slowc_save > 2e-1*/)
+      if (false /*slowc_save > 2e-1*/)
         if (mnbrak(&ax, &bx, &cx, &fa, &fb, &fc))
           if (golden(ax, bx, cx, 1e-1, solve_tolf, &xmin))
             slowc_save = xmin;
@@ -6110,72 +6186,73 @@ dynSparseMatrix::Check_and_Correct_Previous_Iteration(int block_num, int y_size,
       if (false)
         {
 
-          double *p = (double*)mxMalloc(size * sizeof(double));
+          double *p = (double *) mxMalloc(size * sizeof(double));
+          test_mxMalloc(p, __LINE__, __FILE__, __func__, size * sizeof(double));
           Grad_f_product(size, b_m_save, p, A_m_save, Ap_save, Ai_save, Ax_save, b_save);
-          double slope=0.0;
+          double slope = 0.0;
           for (int i = 1; i < size; i++)
-            slope += - direction[i] * p[i];
+            slope += -direction[i] * p[i];
           /*if (slope > 0)
             mexPrintf("Roundoff in lnsearch\n");
-          else*/
-            {
-              prev_slowc_save = 1;
-              double crit_opt = res2/2;
-              double max_try_iteration = 100;
-              double small_ = 1.0e-4;
-              bool try_at_cvg = false;
-              while ((try_at_iteration < max_try_iteration) && (!try_at_cvg) && (abs(prev_slowc_save - slowc_save) > 1e-10))
-                {
-                  crit_opt = res2 / 2;
-                  if (slowc_save < 1e-7)
-                    {
-                      try_at_cvg = true;
-                      continue;
-                    }
-                  else if ((crit_opt <= crit_opt_old + small_ * slowc_save * slope) && !(isnan(res1) || isinf(res1)))
-                    {
-                      try_at_cvg = true;
-                      continue;
-                    }
-                  else if (try_at_iteration == 0)
-                    {
-                      prev_slowc_save = slowc_save;
-                      //slowc_save = max(- top * slope / ( (crit_opt - crit_opt_old - slope)), bottom);
-                      slowc_save /= 1.2;
-                    }
-                  else
-                    {
-                      double t1 = crit_opt - slope * slowc_save - crit_opt_old;
-                      double t2 = glambda2 - slope * prev_slowc_save - crit_opt_old;
-                      double a = (1/(slowc_save * slowc_save) * t1 - 1/(prev_slowc_save * prev_slowc_save) * t2) / (slowc_save - prev_slowc_save);
-                      double b = (-prev_slowc_save/(slowc_save * slowc_save) * t1 + slowc_save/(prev_slowc_save * prev_slowc_save) * t2) / (slowc_save - prev_slowc_save);
-                      if (a == 0)
-                        slowc_save = max(min( - slope/(2 * b) , top * slowc_save), bottom * slowc_save);
-                      else
-                        {
-                          double delta = b*b - 3 * a * slope;
-                          if (delta <= 0)
-                            slowc_save = top * slowc_save;
-                          else if (b <= 0)
-                            slowc_save = max(min(-b + sqrt(delta) / (3 * a), top * slowc_save), bottom * slowc_save);
-                          else
-                            slowc_save = max(min(- slope / (b + sqrt(delta)), top * slowc_save), bottom * slowc_save);
-                        }
-                    }
-                  if (abs(prev_slowc_save - slowc_save) < 1e-10)
-                    slowc_save /= 1.1;
-                  //mexPrintf("=>slowc_save=%f, prev_slowc_save=%f\n",slowc_save, prev_slowc_save);
-                  prev_slowc_save = slowc_save;
-                  glambda2 = crit_opt;
-                  try_at_iteration++;
-                  for (int i = 0; i < size; i++)
-                    {
-                      int eq = index_vara[i];
-                      y[eq+it_*y_size] = ya[eq+it_*y_size] + slowc_save * direction[eq+it_*y_size];
-                    }
-                  compute_complete(true, res1, res2, max_res, max_res_idx);
-                }
-            }
+            else*/
+          {
+            prev_slowc_save = 1;
+            double crit_opt = res2/2;
+            double max_try_iteration = 100;
+            double small_ = 1.0e-4;
+            bool try_at_cvg = false;
+            while ((try_at_iteration < max_try_iteration) && (!try_at_cvg) && (abs(prev_slowc_save - slowc_save) > 1e-10))
+              {
+                crit_opt = res2 / 2;
+                if (slowc_save < 1e-7)
+                  {
+                    try_at_cvg = true;
+                    continue;
+                  }
+                else if ((crit_opt <= crit_opt_old + small_ * slowc_save * slope) && !(isnan(res1) || isinf(res1)))
+                  {
+                    try_at_cvg = true;
+                    continue;
+                  }
+                else if (try_at_iteration == 0)
+                  {
+                    prev_slowc_save = slowc_save;
+                    //slowc_save = max(- top * slope / ( (crit_opt - crit_opt_old - slope)), bottom);
+                    slowc_save /= 1.2;
+                  }
+                else
+                  {
+                    double t1 = crit_opt - slope * slowc_save - crit_opt_old;
+                    double t2 = glambda2 - slope * prev_slowc_save - crit_opt_old;
+                    double a = (1/(slowc_save * slowc_save) * t1 - 1/(prev_slowc_save * prev_slowc_save) * t2) / (slowc_save - prev_slowc_save);
+                    double b = (-prev_slowc_save/(slowc_save * slowc_save) * t1 + slowc_save/(prev_slowc_save * prev_slowc_save) * t2) / (slowc_save - prev_slowc_save);
+                    if (a == 0)
+                      slowc_save = max(min(-slope/(2 * b), top * slowc_save), bottom * slowc_save);
+                    else
+                      {
+                        double delta = b*b - 3 * a * slope;
+                        if (delta <= 0)
+                          slowc_save = top * slowc_save;
+                        else if (b <= 0)
+                          slowc_save = max(min(-b + sqrt(delta) / (3 * a), top * slowc_save), bottom * slowc_save);
+                        else
+                          slowc_save = max(min(-slope / (b + sqrt(delta)), top * slowc_save), bottom * slowc_save);
+                      }
+                  }
+                if (abs(prev_slowc_save - slowc_save) < 1e-10)
+                  slowc_save /= 1.1;
+                //mexPrintf("=>slowc_save=%f, prev_slowc_save=%f\n",slowc_save, prev_slowc_save);
+                prev_slowc_save = slowc_save;
+                glambda2 = crit_opt;
+                try_at_iteration++;
+                for (int i = 0; i < size; i++)
+                  {
+                    int eq = index_vara[i];
+                    y[eq+it_*y_size] = ya[eq+it_*y_size] + slowc_save * direction[eq+it_*y_size];
+                  }
+                compute_complete(true, res1, res2, max_res, max_res_idx);
+              }
+          }
           mxFree(p);
         }
       //if (print_it)
@@ -6208,7 +6285,6 @@ dynSparseMatrix::Simulate_One_Boundary(int block_num, int y_size, int y_kmin, in
   double *Ax = NULL, *b = NULL;
   int preconditioner = 1;
 
-
   try_at_iteration = 0;
   Clear_u();
   bool singular_system = false;
@@ -6277,8 +6353,8 @@ dynSparseMatrix::Simulate_One_Boundary(int block_num, int y_size, int y_kmin, in
               mexPrintf("MODEL STEADY STATE: Sparse LU\n");
               break;
             case 7:
-                mexPrintf(preconditioner_print_out("MODEL STEADY STATE: (method=GMRES)\n", preconditioner, true).c_str());
-                //mexPrintf("MODEL STEADY STATE: (method=GMRES)\n");
+              mexPrintf(preconditioner_print_out("MODEL STEADY STATE: (method=GMRES)\n", preconditioner, true).c_str());
+              //mexPrintf("MODEL STEADY STATE: (method=GMRES)\n");
               break;
             case 8:
               mexPrintf(preconditioner_print_out("MODEL STEADY STATE: (method=BiCGStab)\n", preconditioner, true).c_str());
@@ -6336,8 +6412,10 @@ dynSparseMatrix::Simulate_One_Boundary(int block_num, int y_size, int y_kmin, in
             {
               mxFree(Ai_save);
               mxFree(Ax_save);
-              Ai_save = (SuiteSparse_long*)mxMalloc(Ap[size] * sizeof(SuiteSparse_long));
-              Ax_save = (double*)mxMalloc(Ap[size] * sizeof(double));
+              Ai_save = (SuiteSparse_long *) mxMalloc(Ap[size] * sizeof(SuiteSparse_long));
+              test_mxMalloc(Ai_save, __LINE__, __FILE__, __func__, Ap[size] * sizeof(SuiteSparse_long));
+              Ax_save = (double *) mxMalloc(Ap[size] * sizeof(double));
+              test_mxMalloc(Ax_save, __LINE__, __FILE__, __func__, Ap[size] * sizeof(double));
             }
           memcpy(Ap_save, Ap, (size + 1) * sizeof(SuiteSparse_long));
           memcpy(Ai_save, Ai, Ap[size] * sizeof(SuiteSparse_long));
@@ -6369,9 +6447,6 @@ dynSparseMatrix::Simulate_One_Boundary(int block_num, int y_size, int y_kmin, in
   return singular_system;
 }
 
-
-
-
 bool
 dynSparseMatrix::solve_linear(const int block_num, const int y_size, const int y_kmin, const int y_kmax, const int size, const int iter)
 {
@@ -6420,15 +6495,21 @@ void
 dynSparseMatrix::Simulate_Newton_One_Boundary(const bool forward)
 {
   g1 = (double *) mxMalloc(size*size*sizeof(double));
+  test_mxMalloc(g1, __LINE__, __FILE__, __func__, size*size*sizeof(double));
   r = (double *) mxMalloc(size*sizeof(double));
+  test_mxMalloc(r, __LINE__, __FILE__, __func__, size*sizeof(double));
   iter = 0;
   if ((solve_algo == 6 && steady_state) || ((stack_solve_algo == 0 || stack_solve_algo == 1 || stack_solve_algo == 4) && !steady_state))
     {
-      Ap_save = (SuiteSparse_long*)mxMalloc((size + 1) * sizeof(SuiteSparse_long));
+      Ap_save = (SuiteSparse_long *) mxMalloc((size + 1) * sizeof(SuiteSparse_long));
+      test_mxMalloc(Ap_save, __LINE__, __FILE__, __func__, (size + 1) * sizeof(SuiteSparse_long));
       Ap_save[size] = 0;
-      Ai_save = (SuiteSparse_long*)mxMalloc(1 * sizeof(SuiteSparse_long));
-      Ax_save = (double*)mxMalloc(1 * sizeof(double));
-      b_save = (double*)mxMalloc((size) * sizeof(SuiteSparse_long));
+      Ai_save = (SuiteSparse_long *) mxMalloc(1 * sizeof(SuiteSparse_long));
+      test_mxMalloc(Ai_save, __LINE__, __FILE__, __func__, 1 * sizeof(SuiteSparse_long));
+      Ax_save = (double *) mxMalloc(1 * sizeof(double));
+      test_mxMalloc(Ax_save, __LINE__, __FILE__, __func__, 1 * sizeof(double));
+      b_save = (double *) mxMalloc((size) * sizeof(SuiteSparse_long));
+      test_mxMalloc(b_save, __LINE__, __FILE__, __func__, (size) * sizeof(SuiteSparse_long));
     }
   if (steady_state)
     {
@@ -6480,7 +6561,7 @@ dynSparseMatrix::preconditioner_print_out(string s, int preconditioner, bool ss)
 {
   int n = s.length();
   string tmp = ", preconditioner=";
-  switch(preconditioner)
+  switch (preconditioner)
     {
     case 0:
       if (ss)
@@ -6491,7 +6572,7 @@ dynSparseMatrix::preconditioner_print_out(string s, int preconditioner, bool ss)
     case 1:
       if (ss)
         tmp.append("incomplet lutp on static jacobian");
-      else 
+      else
         tmp.append("incomplet lu0 on dynamic jacobian");
       break;
     case 2:
@@ -6527,7 +6608,6 @@ dynSparseMatrix::Simulate_Newton_Two_Boundaries(int blck, int y_size, int y_kmin
   double *Ax = NULL, *b;
   SuiteSparse_long *Ap = NULL, *Ai = NULL;
 
-
   if (iter > 0)
     {
       if (print_it)
@@ -6541,6 +6621,7 @@ dynSparseMatrix::Simulate_Newton_Two_Boundaries(int blck, int y_size, int y_kmin
     {
       if (iter == 0 || fabs(slowc_save) < 1e-8)
         {
+          mexPrintf("res1 = %f, res2 = %f g0 = %f iter = %d\n", res1, res2, g0, iter);
           for (int j = 0; j < y_size; j++)
             {
               ostringstream res;
@@ -6751,7 +6832,7 @@ dynSparseMatrix::Simulate_Newton_Two_Boundaries(int blck, int y_size, int y_kmin
       mexPrintf("(** %f milliseconds **)\n", 1000.0*(double (t2) - double (t1))/double (CLOCKS_PER_SEC));
       mexEvalString("drawnow;");
     }
-  if ((!steady_state && (stack_solve_algo == 4 /*|| stack_solve_algo == 0*/))/* || steady_state*/)
+  if ((!steady_state && (stack_solve_algo == 4 /*|| stack_solve_algo == 0*/)) /* || steady_state*/)
     {
       clock_t t2 = clock();
       double ax = -0.1, bx = 1.1, cx = 0.5, fa, fb, fc, xmin;
@@ -6781,10 +6862,10 @@ dynSparseMatrix::fixe_u(double **u, int u_count_int, int max_lag_plus_max_lead_p
   mexPrintf("fixe_u : alloc(%d double)\n", u_count_alloc);
 #endif
   (*u) = (double *) mxMalloc(u_count_alloc*sizeof(double));
+  test_mxMalloc(*u, __LINE__, __FILE__, __func__, u_count_alloc*sizeof(double));
 #ifdef DEBUG
   mexPrintf("*u=%d\n", *u);
 #endif
   memset((*u), 0, u_count_alloc*sizeof(double));
   u_count_init = max_lag_plus_max_lead_plus_1;
 }
-
diff --git a/mex/sources/bytecode/SparseMatrix.hh b/mex/sources/bytecode/SparseMatrix.hh
index 82fd5a3ab3db1d55e41c8837c31cac0cb50a9a72..08785375503a98fb25b56561663233f12bfe9697 100644
--- a/mex/sources/bytecode/SparseMatrix.hh
+++ b/mex/sources/bytecode/SparseMatrix.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2013 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -27,14 +27,14 @@
 #include <ctime>
 #include "dynblas.h"
 #if !(defined _MSC_VER)
-#include "dynumfpack.h"
+# include "dynumfpack.h"
 #endif
 
 #ifdef CUDA
-#include "cuda.h"
-#include "cuda_runtime_api.h"
-#include "cublas_v2.h"
-#include "cusparse_v2.h"
+# include "cuda.h"
+# include "cuda_runtime_api.h"
+# include "cublas_v2.h"
+# include "cusparse_v2.h"
 #endif
 
 #include "Mem_Mngr.hh"
@@ -42,38 +42,38 @@
 //#include "Interpreter.hh"
 #include "Evaluate.hh"
 
-#define cudaChk(x, y) \
-        { \
-          cudaError_t cuda_error = x; \
-          if (cuda_error != cudaSuccess) \
-            { \
-              ostringstream tmp; \
-              tmp << y; \
-              throw FatalExceptionHandling(tmp.str()); \
-            } \
-        };
+#define cudaChk(x, y)                                   \
+  {                                                     \
+    cudaError_t cuda_error = x;                         \
+    if (cuda_error != cudaSuccess)                      \
+      {                                                 \
+        ostringstream tmp;                              \
+        tmp << y;                                       \
+        throw FatalExceptionHandling(tmp.str());        \
+      }                                                 \
+  };
 
-#define cusparseChk(x, y) \
-        { \
-          cusparseStatus_t cusparse_status = x; \
-          if (cusparse_status != CUSPARSE_STATUS_SUCCESS) \
-            { \
-              ostringstream tmp; \
-              tmp << y; \
-              throw FatalExceptionHandling(tmp.str()); \
-            } \
-        };
+#define cusparseChk(x, y)                               \
+  {                                                     \
+    cusparseStatus_t cusparse_status = x;               \
+    if (cusparse_status != CUSPARSE_STATUS_SUCCESS)     \
+      {                                                 \
+        ostringstream tmp;                              \
+        tmp << y;                                       \
+        throw FatalExceptionHandling(tmp.str());        \
+      }                                                 \
+  };
 
-#define cublasChk(x, y) \
-        { \
-          cublasStatus_t cublas_status = x; \
-          if (cublas_status != CUBLAS_STATUS_SUCCESS) \
-            { \
-              ostringstream tmp; \
-              tmp << y; \
-              throw FatalExceptionHandling(tmp.str()); \
-            } \
-        };
+#define cublasChk(x, y)                                 \
+  {                                                     \
+    cublasStatus_t cublas_status = x;                   \
+    if (cublas_status != CUBLAS_STATUS_SUCCESS)         \
+      {                                                 \
+        ostringstream tmp;                              \
+        tmp << y;                                       \
+        throw FatalExceptionHandling(tmp.str());        \
+      }                                                 \
+  };
 
 #define NEW_ALLOC
 #define MARKOVITZ
@@ -99,20 +99,18 @@ const double very_big = 1e24;
 const int alt_symbolic_count_max = 1;
 const double mem_increasing_factor = 1.1;
 
-
-
 class dynSparseMatrix : public Evaluate
 {
 public:
-  #if (defined _MSC_VER)
+#if (defined _MSC_VER)
   typedef int64_t SuiteSparse_long;
-  #endif
+#endif
   dynSparseMatrix();
   dynSparseMatrix(const int y_size_arg, const int y_kmin_arg, const int y_kmax_arg, const bool print_it_arg, const bool steady_state_arg, const int periods_arg, const int minimal_solving_periods_arg, const double slowc_arg
 #ifdef CUDA
-               ,const int CUDA_device_arg, cublasHandle_t cublas_handle_arg, cusparseHandle_t cusparse_handle_arg, cusparseMatDescr_t descr_arg
+                  , const int CUDA_device_arg, cublasHandle_t cublas_handle_arg, cusparseHandle_t cusparse_handle_arg, cusparseMatDescr_t descr_arg
 #endif
-               );
+                  );
   void Simulate_Newton_Two_Boundaries(int blck, int y_size, int y_kmin, int y_kmax, int Size, int periods, bool cvg, int minimal_solving_periods, int stack_solve_algo, unsigned int endo_name_length, char *P_endo_names, vector_table_conditional_local_type vector_table_conditional_local);
   void Simulate_Newton_One_Boundary(bool forward);
   void fixe_u(double **u, int u_count_int, int max_lag_plus_max_lead_plus_1);
@@ -146,17 +144,17 @@ private:
   void Solve_Matlab_LU_UMFPack(mxArray *A_m, mxArray *b_m, int Size, double slowc_l, bool is_two_boundaries, int it_);
   void Print_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, double *Ax, int n);
   void Printfull_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, double *Ax, double *b, int n);
-
+  void PrintM(int n, double *Ax, mwIndex *Ap, mwIndex *Ai);
   void Solve_LU_UMFPack(mxArray *A_m, mxArray *b_m, int Size, double slowc_l, bool is_two_boundaries, int  it_);
   void Solve_LU_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, double *Ax, double *b, int n, int Size, double slowc_l, bool is_two_boundaries, int  it_, vector_table_conditional_local_type vector_table_conditional_local);
   void Solve_LU_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, double *Ax, double *b, int n, int Size, double slowc_l, bool is_two_boundaries, int  it_);
 
   void End_Matlab_LU_UMFPack();
 #ifdef CUDA
-  void Solve_CUDA_BiCGStab_Free(double* tmp_vect_host, double* p, double* r, double* v, double* s, double* t, double* y_, double* z, double* tmp_,
-                                       int* Ai, double* Ax, int* Ap, double* x0, double* b, double* A_tild, int* A_tild_i, int* A_tild_p,
-                                       cusparseSolveAnalysisInfo_t infoL, cusparseSolveAnalysisInfo_t infoU,
-                                       cusparseMatDescr_t descrL, cusparseMatDescr_t descrU, int preconditioner);
+  void Solve_CUDA_BiCGStab_Free(double *tmp_vect_host, double *p, double *r, double *v, double *s, double *t, double *y_, double *z, double *tmp_,
+                                int *Ai, double *Ax, int *Ap, double *x0, double *b, double *A_tild, int *A_tild_i, int *A_tild_p,
+                                cusparseSolveAnalysisInfo_t infoL, cusparseSolveAnalysisInfo_t infoU,
+                                cusparseMatDescr_t descrL, cusparseMatDescr_t descrU, int preconditioner);
   int Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, int *Ai_tild, double *A_tild, double *b, double *x0, int n, int Size, double slowc_l, bool is_two_boundaries, int  it_, int nnz, int nnz_tild, int preconditioner, int max_iterations, int block);
 #endif
   void Solve_Matlab_GMRES(mxArray *A_m, mxArray *b_m, int Size, double slowc, int block, bool is_two_boundaries, int it_, mxArray *x0_m);
@@ -171,7 +169,7 @@ private:
                , long int *ndiv, long int *nsub
 #endif
                );
-  void Grad_f_product(int n, mxArray *b_m, double* vectr, mxArray *A_m, SuiteSparse_long *Ap, SuiteSparse_long *Ai, double* Ax, double *b);
+  void Grad_f_product(int n, mxArray *b_m, double *vectr, mxArray *A_m, SuiteSparse_long *Ap, SuiteSparse_long *Ai, double *Ax, double *b);
   void Insert(const int r, const int c, const int u_index, const int lag_index);
   void Delete(const int r, const int c);
   int At_Row(int r, NonZeroElem **first);
@@ -186,15 +184,15 @@ private:
   void Delete_u(int pos);
   void Clear_u();
   void Print_u();
-  void *Symbolic, *Numeric ;
+  void *Symbolic, *Numeric;
   void CheckIt(int y_size, int y_kmin, int y_kmax, int Size, int periods);
   void Check_the_Solution(int periods, int y_kmin, int y_kmax, int Size, double *u, int *pivot, int *b);
   int complete(int beg_t, int Size, int periods, int *b);
   void bksub(int tbreak, int last_period, int Size, double slowc_l
 #ifdef PROFILER
-               , long int *nmul
+             , long int *nmul
 #endif
-               );
+             );
   void simple_bksub(int it_, int Size, double slowc_l);
   mxArray *Sparse_transpose(mxArray *A_m);
   mxArray *Sparse_mult_SAT_SB(mxArray *A_m, mxArray *B_m);
@@ -254,7 +252,7 @@ protected:
   int restart;
   double g_lambda1, g_lambda2, gp_0;
   double lu_inc_tol;
-//private:
+  //private:
   SuiteSparse_long *Ap_save, *Ai_save;
   double *Ax_save, *b_save;
   mxArray *A_m_save, *b_m_save;
diff --git a/mex/sources/bytecode/bytecode.cc b/mex/sources/bytecode/bytecode.cc
index 25260c82b511ef780f0af2ae9ea7325ff7bcd3e3..80ba1b4509344876c93df587e0257029d5a89b6a 100644
--- a/mex/sources/bytecode/bytecode.cc
+++ b/mex/sources/bytecode/bytecode.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2013 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -22,46 +22,42 @@
 #include <ctime>
 #include <math.h>
 #ifdef DYN_MEX_FUNC_ERR_MSG_TXT
-  #undef DYN_MEX_FUNC_ERR_MSG_TXT
+# undef DYN_MEX_FUNC_ERR_MSG_TXT
 #endif // DYN_MEX_FUNC_ERR_MSG_TXT
 
-#define DYN_MEX_FUNC_ERR_MSG_TXT(str)                                                                   \
- do {                                                                                                     \
-    mexPrintf("%s\n", str);                                                                             \
-    if (nlhs > 0)                                                                                       \
-      {                                                                                                 \
-        plhs[0] = mxCreateDoubleScalar(1);                                                              \
-        if (nlhs > 1)                                                                                   \
-          {                                                                                             \
-            double *pind;                                                                               \
-            plhs[1] = mxCreateDoubleMatrix(int(row_y), int(col_y), mxREAL);                             \
-            pind = mxGetPr(plhs[1]);                                                                    \
-            if (evaluate )                                                                              \
-              {                                                                                         \
-                for (unsigned int i = 0; i < row_y*col_y; i++)                                                   \
-                  pind[i] = 0;                                                                          \
-              }                                                                                         \
-            else                                                                                        \
-              {                                                                                         \
-                for (unsigned int i = 0; i < row_y*col_y; i++)                                                   \
-                  pind[i] = yd[i];                                                                      \
-              }                                                                                         \
-            for (int i = 2; i < nlhs; i++)                                                              \
-              plhs[i] = mxCreateDoubleScalar(1);                                                        \
-          }                                                                                             \
-      }                                                                                                 \
-    return;                                                                                             \
+#define DYN_MEX_FUNC_ERR_MSG_TXT(str)                                   \
+  do {                                                                  \
+    mexPrintf("%s\n", str);                                             \
+    if (nlhs > 0)                                                       \
+      {                                                                 \
+        plhs[0] = mxCreateDoubleScalar(1);                              \
+        if (nlhs > 1)                                                   \
+          {                                                             \
+            double *pind;                                               \
+            plhs[1] = mxCreateDoubleMatrix(int (row_y), int (col_y), mxREAL); \
+            pind = mxGetPr(plhs[1]);                                    \
+            if (evaluate)                                               \
+              {                                                         \
+                for (unsigned int i = 0; i < row_y*col_y; i++)          \
+                  pind[i] = 0;                                          \
+              }                                                         \
+            else                                                        \
+              {                                                         \
+                for (unsigned int i = 0; i < row_y*col_y; i++)          \
+                  pind[i] = yd[i];                                      \
+              }                                                         \
+            for (int i = 2; i < nlhs; i++)                              \
+              plhs[i] = mxCreateDoubleScalar(1);                        \
+          }                                                             \
+      }                                                                 \
+    return;                                                             \
   } while (0)
 
-
 #ifdef DEBUG_EX
 
 using namespace std;
 # include <sstream>
 
-
-
-
 string
 Get_Argument(const char *argv)
 {
@@ -73,7 +69,6 @@ Get_Argument(const char *argv)
 
 void (*prev_fn)(int);
 
-
 string
 Get_Argument(const mxArray *prhs)
 {
@@ -90,10 +85,8 @@ Get_Argument(const mxArray *prhs)
 }
 #endif
 
-
-//#include <windows.h> 
-#include <stdio.h> 
- 
+//#include <windows.h>
+#include <stdio.h>
 
 #ifdef CUDA
 int
@@ -103,7 +96,7 @@ GPU_Test_and_Info(cublasHandle_t *cublas_handle, cusparseHandle_t *cusparse_hand
   int device_count, device, version, version_max = 0;
   cublasStatus_t cublas_status;
   cudaError_t cuda_error;
-  *descr=0;
+  *descr = 0;
 
   /* ask cuda how many devices it can find */
   cudaGetDeviceCount(&device_count);
@@ -124,9 +117,9 @@ GPU_Test_and_Info(cublasHandle_t *cublas_handle, cusparseHandle_t *cusparse_hand
           cuda_error = cudaGetDeviceProperties(&deviceProp, i);
           if (cuda_error != cudaSuccess)
             {
-               ostringstream tmp;
-               tmp << "  bytecode cudaGetDeviceProperties failed\n";
-               throw FatalExceptionHandling(tmp.str());
+              ostringstream tmp;
+              tmp << "  bytecode cudaGetDeviceProperties failed\n";
+              throw FatalExceptionHandling(tmp.str());
             }
           mexPrintf("> GPU device %d: \"%s\" has:\n   - %d Multi-Processors,\n   - %d threads per multiprocessor,\n", i, deviceProp.name, deviceProp.multiProcessorCount, deviceProp.maxThreadsPerMultiProcessor);
           mexEvalString("drawnow;");
@@ -136,7 +129,7 @@ GPU_Test_and_Info(cublasHandle_t *cublas_handle, cusparseHandle_t *cusparse_hand
               device = i;
               version_max = version;
             }
-          mexPrintf("   - %4.2fMhz clock rate,\n   - %2.0fMb of memory,\n   - %d.%d compute capabilities.\n", double(deviceProp.clockRate) / (1024 * 1024), double(deviceProp.totalGlobalMem) / (1024 * 1024), deviceProp.major, deviceProp.minor);
+          mexPrintf("   - %4.2fMhz clock rate,\n   - %2.0fMb of memory,\n   - %d.%d compute capabilities.\n", double (deviceProp.clockRate) / (1024 * 1024), double (deviceProp.totalGlobalMem) / (1024 * 1024), deviceProp.major, deviceProp.minor);
           mexEvalString("drawnow;");
         }
     }
@@ -146,17 +139,17 @@ GPU_Test_and_Info(cublasHandle_t *cublas_handle, cusparseHandle_t *cusparse_hand
   cuda_error = cudaSetDevice(device);
   if (cuda_error != cudaSuccess)
     {
-       ostringstream tmp;
-       tmp << "  bytecode cudaSetDevice failed\n";
-       throw FatalExceptionHandling(tmp.str());
+      ostringstream tmp;
+      tmp << "  bytecode cudaSetDevice failed\n";
+      throw FatalExceptionHandling(tmp.str());
     }
 
-  if(version_max < 0x11)
+  if (version_max < 0x11)
     {
-       ostringstream tmp;
-       tmp << "  bytecode requires a minimum CUDA compute 1.1 capability\n";
-       cudaDeviceReset();
-       throw FatalExceptionHandling(tmp.str());
+      ostringstream tmp;
+      tmp << "  bytecode requires a minimum CUDA compute 1.1 capability\n";
+      cudaDeviceReset();
+      throw FatalExceptionHandling(tmp.str());
     }
 
   // Initialize CuBlas library
@@ -164,16 +157,16 @@ GPU_Test_and_Info(cublasHandle_t *cublas_handle, cusparseHandle_t *cusparse_hand
   if (cublas_status != CUBLAS_STATUS_SUCCESS)
     {
       ostringstream tmp;
-      switch(cublas_status)
+      switch (cublas_status)
         {
-          case CUBLAS_STATUS_NOT_INITIALIZED:
-            tmp << " the CUBLAS initialization failed.\n";
-            break;
-          case CUBLAS_STATUS_ALLOC_FAILED:
-            tmp << " the resources could not be allocated.\n";
-            break;
-          default:
-            tmp << " unknown error during the initialization of cusparse library.\n";
+        case CUBLAS_STATUS_NOT_INITIALIZED:
+          tmp << " the CUBLAS initialization failed.\n";
+          break;
+        case CUBLAS_STATUS_ALLOC_FAILED:
+          tmp << " the resources could not be allocated.\n";
+          break;
+        default:
+          tmp << " unknown error during the initialization of cusparse library.\n";
         }
       throw FatalExceptionHandling(tmp.str());
     }
@@ -184,19 +177,19 @@ GPU_Test_and_Info(cublasHandle_t *cublas_handle, cusparseHandle_t *cusparse_hand
   if (cusparse_status != CUSPARSE_STATUS_SUCCESS)
     {
       ostringstream tmp;
-      switch(cusparse_status)
+      switch (cusparse_status)
         {
-          case CUSPARSE_STATUS_NOT_INITIALIZED:
-            tmp << " the CUDA Runtime initialization failed.\n";
-            break;
-          case CUSPARSE_STATUS_ALLOC_FAILED:
-            tmp <<  " the resources could not be allocated.\n";
-            break;
-          case CUSPARSE_STATUS_ARCH_MISMATCH:
-            tmp <<  " the device compute capability (CC) is less than 1.1. The CC of at least 1.1 is required.\n";
-            break;
-          default:
-            tmp << " unknown error during the initialization of cusparse library.\n";
+        case CUSPARSE_STATUS_NOT_INITIALIZED:
+          tmp << " the CUDA Runtime initialization failed.\n";
+          break;
+        case CUSPARSE_STATUS_ALLOC_FAILED:
+          tmp <<  " the resources could not be allocated.\n";
+          break;
+        case CUSPARSE_STATUS_ARCH_MISMATCH:
+          tmp <<  " the device compute capability (CC) is less than 1.1. The CC of at least 1.1 is required.\n";
+          break;
+        default:
+          tmp << " unknown error during the initialization of cusparse library.\n";
         }
       throw FatalExceptionHandling(tmp.str());
     }
@@ -221,7 +214,7 @@ GPU_Test_and_Info(cublasHandle_t *cublas_handle, cusparseHandle_t *cusparse_hand
       tmp << " cudaGetVersion has failed\n";
       throw FatalExceptionHandling(tmp.str());
     }
-  mexPrintf("   - CUDA version %5.3f\n", double(cuda_version) / 1000);
+  mexPrintf("   - CUDA version %5.3f\n", double (cuda_version) / 1000);
   int cublas_version;
   cublas_status = cublasGetVersion(*cublas_handle, &cublas_version);
   if (cublas_status != CUBLAS_STATUS_SUCCESS)
@@ -230,7 +223,7 @@ GPU_Test_and_Info(cublasHandle_t *cublas_handle, cusparseHandle_t *cusparse_hand
       tmp << " cublasGetVersion has failed\n";
       throw FatalExceptionHandling(tmp.str());
     }
-  mexPrintf("   - CUBLAS version %5.3f\n", double(cublas_version) / 1000);
+  mexPrintf("   - CUBLAS version %5.3f\n", double (cublas_version) / 1000);
   int cusparse_version;
   cusparse_status = cusparseGetVersion(*cusparse_handle, &cusparse_version);
   if (cusparse_status != CUSPARSE_STATUS_SUCCESS)
@@ -239,7 +232,7 @@ GPU_Test_and_Info(cublasHandle_t *cublas_handle, cusparseHandle_t *cusparse_hand
       tmp << " cusparseGetVersion has failed\n";
       throw FatalExceptionHandling(tmp.str());
     }
-  mexPrintf("   - CUSPARSE version %5.3f\n", double(cusparse_version) / 1000);
+  mexPrintf("   - CUSPARSE version %5.3f\n", double (cusparse_version) / 1000);
   mexPrintf("-----------------------------------------\n");
   return device;
 }
@@ -247,16 +240,16 @@ GPU_Test_and_Info(cublasHandle_t *cublas_handle, cusparseHandle_t *cusparse_hand
 void
 GPU_close(cublasHandle_t cublas_handle, cusparseHandle_t cusparse_handle, cusparseMatDescr_t descr)
 {
-  cublasChk(cublasDestroy(cublas_handle),"in bytecode cublasDestroy failed\n");
+  cublasChk(cublasDestroy(cublas_handle), "in bytecode cublasDestroy failed\n");
   cusparseChk(cusparseDestroyMatDescr(descr), "in bytecode cusparseDestroyMatDescr failed\n");
-  cusparseChk(cusparseDestroy(cusparse_handle),"in bytecode cusparseDestroy failed\n");
+  cusparseChk(cusparseDestroy(cusparse_handle), "in bytecode cusparseDestroy failed\n");
 }
 
 #endif
 string
 deblank(string x)
 {
-  for(int i = 0; i < (int) x.length(); i++)
+  for (int i = 0; i < (int) x.length(); i++)
     if (x[i] == ' ')
       x.erase(i--, 1);
   return x;
@@ -317,7 +310,7 @@ Get_Arguments_and_global_variables(int nrhs,
                 steady_col_y = mxGetN(prhs[i]);
                 break;
               case 4:
-                periods = int(mxGetScalar(prhs[i]));
+                periods = int (mxGetScalar(prhs[i]));
                 break;
               case 5:
                 *block_structur = mxDuplicateArray(prhs[i]);
@@ -327,7 +320,7 @@ Get_Arguments_and_global_variables(int nrhs,
                 *GlobalTemporaryTerms = mxDuplicateArray(prhs[i]);
                 break;
               default:
-                mexPrintf("Unknown argument count_array_argument=%d\n",count_array_argument);
+                mexPrintf("Unknown argument count_array_argument=%d\n", count_array_argument);
                 break;
               }
             count_array_argument++;
@@ -358,7 +351,7 @@ Get_Arguments_and_global_variables(int nrhs,
                     pos += 5;
                   block =  atoi(Get_Argument(prhs[i]).substr(pos, string::npos).c_str())-1;
                 }
-              else if (Get_Argument(prhs[i]).substr(0,13) == "extended_path")
+              else if (Get_Argument(prhs[i]).substr(0, 13) == "extended_path")
                 {
                   *extended_path = true;
                   if ((i+1) >= nrhs)
@@ -430,7 +423,6 @@ Get_Arguments_and_global_variables(int nrhs,
     }
 }
 
-
 #ifdef DEBUG_EX
 int
 main(int nrhs, const char *prhs[])
@@ -450,6 +442,7 @@ main(int nrhs, const char *prhs[])
   load_global((char *) prhs[1]);
 #endif
   mxArray *pfplan_struct = NULL;
+  ErrorMsg error_msg;
   size_t i, row_y = 0, col_y = 0, row_x = 0, col_x = 0, nb_row_xd = 0;
   size_t steady_row_y, steady_col_y;
   int y_kmin = 0, y_kmax = 0, y_decal = 0;
@@ -466,7 +459,7 @@ main(int nrhs, const char *prhs[])
   double *steady_yd = NULL, *steady_xd = NULL;
   string plan, pfplan;
   bool extended_path;
-  mxArray* extended_path_struct;
+  mxArray *extended_path_struct;
 
   table_conditional_local_type conditional_local;
   vector<s_plan> splan, spfplan, sextended_path, sconditional_extended_path;
@@ -519,76 +512,76 @@ main(int nrhs, const char *prhs[])
           string tmp = "The 'extended_path' option must be followed by the extended_path descriptor";
           DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
         }
-      mxArray* date_str = mxGetField(extended_path_struct, 0, "date_str");
+      mxArray *date_str = mxGetField(extended_path_struct, 0, "date_str");
       if (date_str == NULL)
         {
           string tmp = "date_str";
-          tmp.insert(0,"The extended_path description structure does not contain the member: ");
+          tmp.insert(0, "The extended_path description structure does not contain the member: ");
           DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
         }
       int nb_periods = mxGetM(date_str) * mxGetN(date_str);
-      
-      mxArray* constrained_vars_ = mxGetField(extended_path_struct, 0, "constrained_vars_");
+
+      mxArray *constrained_vars_ = mxGetField(extended_path_struct, 0, "constrained_vars_");
       if (constrained_vars_ == NULL)
         {
           string tmp = "constrained_vars_";
-          tmp.insert(0,"The extended_path description structure does not contain the member: ");
+          tmp.insert(0, "The extended_path description structure does not contain the member: ");
           DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
         }
-      mxArray* constrained_paths_ = mxGetField(extended_path_struct, 0, "constrained_paths_");
+      mxArray *constrained_paths_ = mxGetField(extended_path_struct, 0, "constrained_paths_");
       if (constrained_paths_ == NULL)
         {
           string tmp = "constrained_paths_";
-          tmp.insert(0,"The extended_path description structure does not contain the member: ");
+          tmp.insert(0, "The extended_path description structure does not contain the member: ");
           DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
         }
-      mxArray* constrained_int_date_ = mxGetField(extended_path_struct, 0, "constrained_int_date_");
+      mxArray *constrained_int_date_ = mxGetField(extended_path_struct, 0, "constrained_int_date_");
       if (constrained_int_date_ == NULL)
         {
           string tmp = "constrained_int_date_";
-          tmp.insert(0,"The extended_path description structure does not contain the member: ");
+          tmp.insert(0, "The extended_path description structure does not contain the member: ");
           DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
         }
-      mxArray* constrained_perfect_foresight_ = mxGetField(extended_path_struct, 0, "constrained_perfect_foresight_");
+      mxArray *constrained_perfect_foresight_ = mxGetField(extended_path_struct, 0, "constrained_perfect_foresight_");
       if (constrained_perfect_foresight_ == NULL)
         {
           string tmp = "constrained_perfect_foresight_";
-          tmp.insert(0,"The extended_path description structure does not contain the member: ");
+          tmp.insert(0, "The extended_path description structure does not contain the member: ");
           DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
         }
-      
-      mxArray* shock_var_ = mxGetField(extended_path_struct, 0, "shock_vars_");
+
+      mxArray *shock_var_ = mxGetField(extended_path_struct, 0, "shock_vars_");
       if (shock_var_ == NULL)
         {
           string tmp = "shock_vars_";
-          tmp.insert(0,"The extended_path description structure does not contain the member: ");
+          tmp.insert(0, "The extended_path description structure does not contain the member: ");
           DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
         }
-      mxArray* shock_paths_ = mxGetField(extended_path_struct, 0, "shock_paths_");
+      mxArray *shock_paths_ = mxGetField(extended_path_struct, 0, "shock_paths_");
       if (shock_paths_ == NULL)
         {
           string tmp = "shock_paths_";
-          tmp.insert(0,"The extended_path description structure does not contain the member: ");
+          tmp.insert(0, "The extended_path description structure does not contain the member: ");
           DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
         }
-      mxArray* shock_int_date_ = mxGetField(extended_path_struct, 0, "shock_int_date_");
+      mxArray *shock_int_date_ = mxGetField(extended_path_struct, 0, "shock_int_date_");
       if (shock_int_date_ == NULL)
         {
           string tmp = "shock_int_date_";
-          tmp.insert(0,"The extended_path description structure does not contain the member: ");
+          tmp.insert(0, "The extended_path description structure does not contain the member: ");
           DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
         }
-      mxArray* shock_str_date_ = mxGetField(extended_path_struct, 0, "shock_str_date_");
+      mxArray *shock_str_date_ = mxGetField(extended_path_struct, 0, "shock_str_date_");
       if (shock_str_date_ == NULL)
         {
           string tmp = "shock_str_date_";
-          tmp.insert(0,"The extended_path description structure does not contain the member: ");
+          tmp.insert(0, "The extended_path description structure does not contain the member: ");
           DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
         }
       int nb_constrained = mxGetM(constrained_vars_) * mxGetN(constrained_vars_);
       int nb_controlled = 0;
-      mxArray* options_cond_fcst_ = mxGetField(extended_path_struct, 0, "options_cond_fcst_");
-      mxArray* controlled_varexo = NULL;
+      mxArray *options_cond_fcst_ = mxGetField(extended_path_struct, 0, "options_cond_fcst_");
+      mxArray *controlled_varexo = NULL;
       if (options_cond_fcst_  != NULL)
         {
           controlled_varexo = mxGetField(options_cond_fcst_, 0, "controlled_varexo");
@@ -598,13 +591,13 @@ main(int nrhs, const char *prhs[])
               DYN_MEX_FUNC_ERR_MSG_TXT("The number of exogenized variables and the number of exogenous controlled variables should be equal.");
             }
         }
-      double * controlled_varexo_value = NULL;
+      double *controlled_varexo_value = NULL;
       if (controlled_varexo != NULL)
         controlled_varexo_value = mxGetPr(controlled_varexo);
-      double * constrained_var_value = mxGetPr(constrained_vars_);
+      double *constrained_var_value = mxGetPr(constrained_vars_);
       sconditional_extended_path.resize(nb_constrained);
       max_periods = 0;
-      if ( nb_constrained)
+      if (nb_constrained)
         {
           conditional_local.is_cond = false;
           conditional_local.var_exo = 0;
@@ -621,28 +614,29 @@ main(int nrhs, const char *prhs[])
               table_conditional_global[i] = vector_conditional_local;
             }
         }
-      
+
       vector_table_conditional_local_type vv3 = table_conditional_global[0];
       for (int i = 0; i < nb_constrained; i++)
         {
           sconditional_extended_path[i].exo_num = ceil(constrained_var_value[i]);
           sconditional_extended_path[i].var_num = ceil(controlled_varexo_value[i]);
-          mxArray* Array_constrained_paths_ = mxGetCell(constrained_paths_, i);
+          mxArray *Array_constrained_paths_ = mxGetCell(constrained_paths_, i);
           double *specific_constrained_paths_ = mxGetPr(Array_constrained_paths_);
           double *specific_constrained_int_date_ = mxGetPr(mxGetCell(constrained_int_date_, i));
           int nb_local_periods = mxGetM(Array_constrained_paths_) * mxGetN(Array_constrained_paths_);
-          int* constrained_int_date = (int*)mxMalloc(nb_local_periods * sizeof(int));
+          int *constrained_int_date = (int *) mxMalloc(nb_local_periods * sizeof(int));
+          error_msg.test_mxMalloc(constrained_int_date, __LINE__, __FILE__, __func__, nb_local_periods * sizeof(int));
           if (nb_periods < nb_local_periods)
             {
               ostringstream oss;
               oss << nb_periods;
               string tmp = oss.str();
-              tmp.insert(0,"The total number of simulation periods (");
+              tmp.insert(0, "The total number of simulation periods (");
               tmp.append(") is lesser than the number of periods in the shock definitions (");
               oss << nb_local_periods;
               string tmp1 = oss.str();
               tmp.append(tmp1);
-              tmp.append(")");  
+              tmp.append(")");
               DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
             }
           (sconditional_extended_path[i]).per_value.resize(nb_local_periods);
@@ -651,7 +645,7 @@ main(int nrhs, const char *prhs[])
             sconditional_extended_path[i].value[j] = 0;
           for (int j = 0; j < nb_local_periods; j++)
             {
-              constrained_int_date[j] = int(specific_constrained_int_date_[j]) - 1;
+              constrained_int_date[j] = int (specific_constrained_int_date_[j]) - 1;
               conditional_local.is_cond = true;
               conditional_local.var_exo = sconditional_extended_path[i].var_num - 1;
               conditional_local.var_endo = sconditional_extended_path[i].exo_num - 1;
@@ -660,18 +654,18 @@ main(int nrhs, const char *prhs[])
               sconditional_extended_path[i].per_value[j] = make_pair(constrained_int_date[j], specific_constrained_paths_[j]);
               sconditional_extended_path[i].value[constrained_int_date[j]] = specific_constrained_paths_[j];
               if (max_periods < constrained_int_date[j] + 1)
-                  max_periods = constrained_int_date[j] + 1;
+                max_periods = constrained_int_date[j] + 1;
             }
           mxFree(constrained_int_date);
         }
       vector_table_conditional_local_type vv = table_conditional_global[0];
-      double * shock_var_value = mxGetPr(shock_var_);
+      double *shock_var_value = mxGetPr(shock_var_);
       int nb_shocks = mxGetM(shock_var_) * mxGetN(shock_var_);
       sextended_path.resize(nb_shocks);
       for (int i = 0; i < nb_shocks; i++)
         {
           sextended_path[i].exo_num = ceil(shock_var_value[i]);
-          mxArray* Array_shock_paths_ = mxGetCell(shock_paths_, i);
+          mxArray *Array_shock_paths_ = mxGetCell(shock_paths_, i);
           double *specific_shock_paths_ = mxGetPr(Array_shock_paths_);
           double *specific_shock_int_date_ = mxGetPr(mxGetCell(shock_int_date_, i));
           int nb_local_periods = mxGetM(Array_shock_paths_) * mxGetN(Array_shock_paths_);
@@ -680,12 +674,12 @@ main(int nrhs, const char *prhs[])
               ostringstream oss;
               oss << nb_periods;
               string tmp = oss.str();
-              tmp.insert(0,"The total number of simulation periods (");
+              tmp.insert(0, "The total number of simulation periods (");
               tmp.append(") is lesser than the number of periods in the shock definitions (");
               oss << nb_local_periods;
               string tmp1 = oss.str();
               tmp.append(tmp1);
-              tmp.append(")");  
+              tmp.append(")");
               DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
             }
           (sextended_path[i]).per_value.resize(nb_local_periods);
@@ -694,16 +688,16 @@ main(int nrhs, const char *prhs[])
             sextended_path[i].value[j] = 0;
           for (int j = 0; j < nb_local_periods; j++)
             {
-              sextended_path[i].per_value[j] = make_pair(int(specific_shock_int_date_[j]), specific_shock_paths_[j]);
-              sextended_path[i].value[int(specific_shock_int_date_[j]-1)] = specific_shock_paths_[j];
-              if (max_periods < int(specific_shock_int_date_[j]) )
-                  max_periods = int(specific_shock_int_date_[j]);
+              sextended_path[i].per_value[j] = make_pair(int (specific_shock_int_date_[j]), specific_shock_paths_[j]);
+              sextended_path[i].value[int (specific_shock_int_date_[j]-1)] = specific_shock_paths_[j];
+              if (max_periods < int (specific_shock_int_date_[j]))
+                max_periods = int (specific_shock_int_date_[j]);
             }
         }
-      for (int i=0; i < nb_periods; i++)
+      for (int i = 0; i < nb_periods; i++)
         {
           int buflen = mxGetNumberOfElements(mxGetCell(date_str, i)) + 1;
-          char* buf = (char*)mxCalloc(buflen, sizeof(char));
+          char *buf = (char *) mxCalloc(buflen, sizeof(char));
           int info = mxGetString(mxGetCell(date_str, i), buf, buflen);
           if (info)
             {
@@ -714,13 +708,13 @@ main(int nrhs, const char *prhs[])
           mxFree(buf);
         }
     }
-  if (plan.length()>0)
+  if (plan.length() > 0)
     {
-      mxArray* plan_struct = mexGetVariable("base", plan.c_str());
+      mxArray *plan_struct = mexGetVariable("base", plan.c_str());
       if (plan_struct == NULL)
         {
           string tmp = plan;
-          tmp.insert(0,"Can't find the plan: ");
+          tmp.insert(0, "Can't find the plan: ");
           DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
         }
       size_t n_plan = mxGetN(plan_struct);
@@ -729,7 +723,7 @@ main(int nrhs, const char *prhs[])
         {
           splan[i].var = "";
           splan[i].exo = "";
-          mxArray* tmp = mxGetField(plan_struct, i, "exo");
+          mxArray *tmp = mxGetField(plan_struct, i, "exo");
           if (tmp)
             {
               char name [100];
@@ -742,7 +736,7 @@ main(int nrhs, const char *prhs[])
               else
                 {
                   string tmp = name;
-                  tmp.insert(0,"the variable '");
+                  tmp.insert(0, "the variable '");
                   tmp.append("'  defined as var in plan is not an exogenous or a deterministic exogenous\n");
                   DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
                 }
@@ -760,7 +754,7 @@ main(int nrhs, const char *prhs[])
               else
                 {
                   string tmp = name;
-                  tmp.insert(0,"the variable '");
+                  tmp.insert(0, "the variable '");
                   tmp.append("'  defined as exo in plan is not an endogenous variable\n");
                   DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
                 }
@@ -770,7 +764,7 @@ main(int nrhs, const char *prhs[])
             {
               size_t num_shocks = mxGetM(tmp);
               (splan[i]).per_value.resize(num_shocks);
-              double * per_value = mxGetPr(tmp);
+              double *per_value = mxGetPr(tmp);
               for (int j = 0; j < (int) num_shocks; j++)
                 (splan[i]).per_value[j] = make_pair(ceil(per_value[j]), per_value[j + num_shocks]);
             }
@@ -786,19 +780,19 @@ main(int nrhs, const char *prhs[])
             mexPrintf(" plan shocks on var=%s for the following periods and with the following values:\n", it->var.c_str());
           for (vector<pair<int, double> >::iterator it1 = it->per_value.begin(); it1 != it->per_value.end(); it1++)
             {
-              mexPrintf("  %3d %10.5f\n",it1->first, it1->second);
+              mexPrintf("  %3d %10.5f\n", it1->first, it1->second);
             }
           i++;
         }
     }
 
-  if (pfplan.length()>0)
+  if (pfplan.length() > 0)
     {
       pfplan_struct = mexGetVariable("base", pfplan.c_str());
       if (!pfplan_struct)
         {
           string tmp = pfplan;
-          tmp.insert(0,"Can't find the pfplan: ");
+          tmp.insert(0, "Can't find the pfplan: ");
           DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
         }
       size_t n_plan = mxGetN(pfplan_struct);
@@ -807,7 +801,7 @@ main(int nrhs, const char *prhs[])
         {
           spfplan[i].var = "";
           spfplan[i].exo = "";
-          mxArray* tmp = mxGetField(pfplan_struct, i, "var");
+          mxArray *tmp = mxGetField(pfplan_struct, i, "var");
           if (tmp)
             {
               char name [100];
@@ -820,7 +814,7 @@ main(int nrhs, const char *prhs[])
               else
                 {
                   string tmp = name;
-                  tmp.insert(0,"the variable '");
+                  tmp.insert(0, "the variable '");
                   tmp.append("' defined as var in pfplan is not an exogenous or a deterministic exogenous\n");
                   DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
                 }
@@ -838,7 +832,7 @@ main(int nrhs, const char *prhs[])
               else
                 {
                   string tmp = name;
-                  tmp.insert(0,"the variable '");
+                  tmp.insert(0, "the variable '");
                   tmp.append("' defined as exo in pfplan  is not an endogenous variable\n");
                   DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
                 }
@@ -847,7 +841,7 @@ main(int nrhs, const char *prhs[])
           if (tmp)
             {
               size_t num_shocks = mxGetM(tmp);
-              double * per_value = mxGetPr(tmp);
+              double *per_value = mxGetPr(tmp);
               (spfplan[i]).per_value.resize(num_shocks);
               for (int j = 0; j < (int) num_shocks; j++)
                 spfplan[i].per_value[j] = make_pair(ceil(per_value[j]), per_value[j+ num_shocks]);
@@ -864,14 +858,12 @@ main(int nrhs, const char *prhs[])
             mexPrintf(" plan shocks on var=%s (%d) for the following periods and with the following values:\n", it->var.c_str(), it->var_num);
           for (vector<pair<int, double> >::iterator it1 = it->per_value.begin(); it1 != it->per_value.end(); it1++)
             {
-              mexPrintf("  %3d %10.5f\n",it1->first, it1->second);
+              mexPrintf("  %3d %10.5f\n", it1->first, it1->second);
             }
           i++;
         }
     }
 
-
-
   int field_steady_state = mxGetFieldNumber(oo_, "steady_state");
   if (field_steady_state < 0)
     DYN_MEX_FUNC_ERR_MSG_TXT("steady_state is not a field of oo_");
@@ -891,11 +883,11 @@ main(int nrhs, const char *prhs[])
 
       if (!count_array_argument)
         {
-          mxArray* endo_sim_arr = mxGetFieldByNumber(oo_, 0, field_endo_simul);
+          mxArray *endo_sim_arr = mxGetFieldByNumber(oo_, 0, field_endo_simul);
           yd = mxGetPr(endo_sim_arr);
           row_y = mxGetM(endo_sim_arr);
           col_y = mxGetN(endo_sim_arr);
-          mxArray* exo_sim_arr = mxGetFieldByNumber(oo_, 0, field_exo_simul);
+          mxArray *exo_sim_arr = mxGetFieldByNumber(oo_, 0, field_exo_simul);
           xd = mxGetPr(exo_sim_arr);
           row_x = mxGetM(exo_sim_arr);
           col_x = mxGetN(exo_sim_arr);
@@ -926,9 +918,9 @@ main(int nrhs, const char *prhs[])
             DYN_MEX_FUNC_ERR_MSG_TXT("options_ is not a field of options_");
         }
 
-      if (!steady_yd )
+      if (!steady_yd)
         {
-          mxArray* steady_state_arr = mxGetFieldByNumber(oo_, 0, field_steady_state);
+          mxArray *steady_state_arr = mxGetFieldByNumber(oo_, 0, field_steady_state);
           steady_yd = mxGetPr(steady_state_arr);
           steady_row_y = mxGetM(steady_state_arr);
           steady_col_y = mxGetN(steady_state_arr);
@@ -939,12 +931,12 @@ main(int nrhs, const char *prhs[])
     {
       if (!count_array_argument)
         {
-          mxArray* steady_state_arr = mxGetFieldByNumber(oo_, 0, field_steady_state);
+          mxArray *steady_state_arr = mxGetFieldByNumber(oo_, 0, field_steady_state);
           yd = mxGetPr(steady_state_arr);
           row_y = mxGetM(steady_state_arr);
           col_y = mxGetN(steady_state_arr);
 
-          mxArray* exo_steady_state_arr = mxGetFieldByNumber(oo_, 0, field_exo_steady_state);
+          mxArray *exo_steady_state_arr = mxGetFieldByNumber(oo_, 0, field_exo_steady_state);
           xd = mxGetPr(exo_steady_state_arr);
           row_x = mxGetM(exo_steady_state_arr);
           col_x = mxGetN(exo_steady_state_arr);
@@ -954,7 +946,7 @@ main(int nrhs, const char *prhs[])
   int field = mxGetFieldNumber(options_, "verbosity");
   int verbose = 0;
   if (field >= 0)
-    verbose = int(*mxGetPr((mxGetFieldByNumber(options_, 0, field))));
+    verbose = int (*mxGetPr((mxGetFieldByNumber(options_, 0, field))));
   else
     DYN_MEX_FUNC_ERR_MSG_TXT("verbosity is not a field of options_");
   if (verbose)
@@ -974,7 +966,7 @@ main(int nrhs, const char *prhs[])
         DYN_MEX_FUNC_ERR_MSG_TXT("steady is not a field of options_");
     }
   field = mxGetFieldNumber(temporaryfield, "maxit");
-  if (field<0)
+  if (field < 0)
     {
       if (!steady_state)
         DYN_MEX_FUNC_ERR_MSG_TXT("maxit is not a field of options_.simul");
@@ -1025,7 +1017,7 @@ main(int nrhs, const char *prhs[])
         DYN_MEX_FUNC_ERR_MSG_TXT("dynatol is not a field of options_");
       field = mxGetFieldNumber(dynatol, "f");
       if (field >= 0)
-        solve_tolf= *mxGetPr((mxGetFieldByNumber(dynatol, 0, field)));
+        solve_tolf = *mxGetPr((mxGetFieldByNumber(dynatol, 0, field)));
       else
         DYN_MEX_FUNC_ERR_MSG_TXT("f is not a field of options_.dynatol");
     }
@@ -1038,7 +1030,7 @@ main(int nrhs, const char *prhs[])
   size_t buflen = mxGetM(mxa) * mxGetN(mxa) + 1;
   char *fname;
   fname = (char *) mxCalloc(buflen+1, sizeof(char));
-  size_t status = mxGetString(mxa, fname, int(buflen));
+  size_t status = mxGetString(mxa, fname, int (buflen));
   fname[buflen] = ' ';
   if (status != 0)
     mexWarnMsgTxt("Not enough space. Filename is truncated.");
@@ -1058,13 +1050,17 @@ main(int nrhs, const char *prhs[])
   if (stack_solve_algo == 7 && !steady_state)
     DYN_MEX_FUNC_ERR_MSG_TXT("bytecode has not been compiled with CUDA option. Bytecode Can't use options_.stack_solve_algo=7\n");
 #endif
-
   size_t size_of_direction = col_y*row_y*sizeof(double);
   double *y = (double *) mxMalloc(size_of_direction);
+  error_msg.test_mxMalloc(y, __LINE__, __FILE__, __func__, size_of_direction);
   double *ya = (double *) mxMalloc(size_of_direction);
+  error_msg.test_mxMalloc(ya, __LINE__, __FILE__, __func__, size_of_direction);
   direction = (double *) mxMalloc(size_of_direction);
+  error_msg.test_mxMalloc(direction, __LINE__, __FILE__, __func__, size_of_direction);
   memset(direction, 0, size_of_direction);
+  /*mexPrintf("col_x : %d, row_x : %d\n",col_x, row_x);*/
   double *x = (double *) mxMalloc(col_x*row_x*sizeof(double));
+  error_msg.test_mxMalloc(x, __LINE__, __FILE__, __func__, col_x*row_x*sizeof(double));
   for (i = 0; i < row_x*col_x; i++)
     {
       x[i] = double (xd[i]);
@@ -1076,10 +1072,11 @@ main(int nrhs, const char *prhs[])
     }
   size_t y_size = row_y;
   size_t nb_row_x = row_x;
+
   clock_t t0 = clock();
   Interpreter interprete(params, y, ya, x, steady_yd, steady_xd, direction, y_size, nb_row_x, nb_row_xd, periods, y_kmin, y_kmax, maxit_, solve_tolf, size_of_direction, slowc, y_decal,
                          markowitz_c, file_name, minimal_solving_periods, stack_solve_algo, solve_algo, global_temporary_terms, print, print_error, GlobalTemporaryTerms, steady_state,
-                         print_it, col_x
+                         print_it, col_x, col_y
 #ifdef CUDA
                          , CUDA_device, cublas_handle, cusparse_handle, descr
 #endif
@@ -1089,27 +1086,28 @@ main(int nrhs, const char *prhs[])
   int nb_blocks = 0;
   double *pind;
   bool no_error = true;
+
   if (extended_path)
     {
-        try
-          {
-            interprete.extended_path(f, f, evaluate, block, nb_blocks, max_periods, sextended_path, sconditional_extended_path, dates, table_conditional_global);
-          }
-        catch (GeneralExceptionHandling &feh)
-          {
-            DYN_MEX_FUNC_ERR_MSG_TXT(feh.GetErrorMsg().c_str());
-          }
+      try
+        {
+          interprete.extended_path(f, f, evaluate, block, nb_blocks, max_periods, sextended_path, sconditional_extended_path, dates, table_conditional_global);
+        }
+      catch (GeneralExceptionHandling &feh)
+        {
+          DYN_MEX_FUNC_ERR_MSG_TXT(feh.GetErrorMsg().c_str());
+        }
     }
   else
     {
-        try
-          {
-            interprete.compute_blocks(f, f, evaluate, block, nb_blocks);
-          }
-        catch (GeneralExceptionHandling &feh)
-          {
-            DYN_MEX_FUNC_ERR_MSG_TXT(feh.GetErrorMsg().c_str());
-          }
+      try
+        {
+          interprete.compute_blocks(f, f, evaluate, block, nb_blocks);
+        }
+      catch (GeneralExceptionHandling &feh)
+        {
+          DYN_MEX_FUNC_ERR_MSG_TXT(feh.GetErrorMsg().c_str());
+        }
     }
 
 #ifdef CUDA
@@ -1137,22 +1135,32 @@ main(int nrhs, const char *prhs[])
               if (evaluate)
                 {
                   vector<double> residual = interprete.get_residual();
-                  plhs[1] = mxCreateDoubleMatrix(int(residual.size()/double(col_y)), int(col_y), mxREAL);
+                  plhs[1] = mxCreateDoubleMatrix(int (residual.size()/double (col_y)), int (col_y), mxREAL);
                   pind = mxGetPr(plhs[1]);
                   for (i = 0; i < residual.size(); i++)
                     pind[i] = residual[i];
                 }
               else
                 {
-                  plhs[1] = mxCreateDoubleMatrix(int(row_y), int(col_y), mxREAL);
+                  int out_periods;
+                  if (extended_path)
+                    out_periods = max_periods + y_kmin;
+                  else
+                    out_periods = row_y;
+                  plhs[1] = mxCreateDoubleMatrix(out_periods, int (col_y), mxREAL);
                   pind = mxGetPr(plhs[1]);
-                  for (i = 0; i < row_y*col_y; i++)
+                  for (i = 0; i < out_periods*col_y; i++)
                     pind[i] = y[i];
                 }
             }
           else
             {
-              plhs[1] = mxCreateDoubleMatrix(int(row_y), int(col_y), mxREAL);
+              int out_periods;
+              if (extended_path)
+                out_periods = max_periods + y_kmin;
+              else
+                out_periods = col_y;
+              plhs[1] = mxCreateDoubleMatrix(int (row_y), out_periods, mxREAL);
               pind = mxGetPr(plhs[1]);
               if (evaluate)
                 {
@@ -1161,7 +1169,7 @@ main(int nrhs, const char *prhs[])
                     pind[i] = residual[i];
                 }
               else
-                for (i = 0; i < row_y*col_y; i++)
+                for (i = 0; i < row_y*out_periods; i++)
                   pind[i] = y[i];
             }
           if (nlhs > 2)
@@ -1176,7 +1184,7 @@ main(int nrhs, const char *prhs[])
                       jacob_exo_field_number = 1;
                       jacob_exo_det_field_number = 2;
                       jacob_other_endo_field_number = 3;
-                      mwSize dims[1] = {(mwSize)nb_blocks };
+                      mwSize dims[1] = {(mwSize) nb_blocks };
                       plhs[2] = mxCreateStructArray(1, dims, 4, field_names);
                     }
                   else if (!mxIsStruct(block_structur))
@@ -1217,14 +1225,17 @@ main(int nrhs, const char *prhs[])
                 }
               else
                 {
-                  plhs[2] = mxCreateDoubleMatrix(int(row_x), int(col_x), mxREAL);
+                  plhs[2] = mxCreateDoubleMatrix(int (row_x), int (col_x), mxREAL);
                   pind = mxGetPr(plhs[2]);
                   for (i = 0; i < row_x*col_x; i++)
-                    pind[i] = x[i];
+                    {
+                      pind[i] = x[i];
+                    }
+
                 }
               if (nlhs > 3)
                 {
-                  plhs[3] = mxCreateDoubleMatrix(int(row_y), int(col_y), mxREAL);
+                  plhs[3] = mxCreateDoubleMatrix(int (row_y), int (col_y), mxREAL);
                   pind = mxGetPr(plhs[3]);
                   for (i = 0; i < row_y*col_y; i++)
                     pind[i] = y[i];
@@ -1232,7 +1243,7 @@ main(int nrhs, const char *prhs[])
                     {
                       mxArray *GlobalTemporaryTerms = interprete.get_Temporary_Terms();
                       size_t nb_temp_terms = mxGetM(GlobalTemporaryTerms);
-                      plhs[4] = mxCreateDoubleMatrix(int(nb_temp_terms), 1, mxREAL);
+                      plhs[4] = mxCreateDoubleMatrix(int (nb_temp_terms), 1, mxREAL);
                       pind = mxGetPr(plhs[4]);
                       double *tt = mxGetPr(GlobalTemporaryTerms);
                       for (i = 0; i < nb_temp_terms; i++)
diff --git a/mex/sources/bytecode/testing/mex_interface.hh b/mex/sources/bytecode/testing/mex_interface.hh
index 9ae11800e90cf2842261349d4cb529d30e3ddd4a..aaee45edf888025d2fcb71d0a08c34233d18f5f6 100644
--- a/mex/sources/bytecode/testing/mex_interface.hh
+++ b/mex/sources/bytecode/testing/mex_interface.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2011 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -142,7 +142,7 @@ mxCreateStructArray(unsigned int rows, mwSize *cols, int nfields, const string &
   return mxCreateStructMatrix(rows, *cols, nfields, fieldnames);
 };
 mxArray *mxCreatNULLMatrix();
-void mexCallMATLAB(unsigned int n_lhs, mxArray* lhs[], unsigned int n_rhs, mxArray* rhs[], const char *function);
+void mexCallMATLAB(unsigned int n_lhs, mxArray *lhs[], unsigned int n_rhs, mxArray *rhs[], const char *function);
 void mxDestroyArray(mxArray *A_m);
 mxArray *read_struct(FILE *fid);
 mxArray *read_Array(FILE *fid);
diff --git a/mex/sources/dynumfpack.h b/mex/sources/dynumfpack.h
index 60182c47106453f543b98f456a07b45e709fb14b..1eb5511d30f126ae6d1c246149bbf8cff926d5dd 100644
--- a/mex/sources/dynumfpack.h
+++ b/mex/sources/dynumfpack.h
@@ -3,7 +3,7 @@
  */
 
 /*
- * Copyright (C) 2013 Dynare Team
+ * Copyright (C) 2013-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -28,60 +28,60 @@
 extern "C" {
 #endif
 
-/* -------------------------------------------------------------------------- */
-/* size of Info and Control arrays */
-/* -------------------------------------------------------------------------- */
+  /* -------------------------------------------------------------------------- */
+  /* size of Info and Control arrays */
+  /* -------------------------------------------------------------------------- */
 
-/* These might be larger in future versions, since there are only 3 unused
- * entries in Info, and no unused entries in Control. */
+  /* These might be larger in future versions, since there are only 3 unused
+   * entries in Info, and no unused entries in Control. */
 
 #define UMFPACK_INFO 90
 #define UMFPACK_CONTROL 20
-/* used in all UMFPACK_report_* routines: */
-#define UMFPACK_PRL 0			/* print level */
-/* returned by all routines that use Info: */
+  /* used in all UMFPACK_report_* routines: */
+#define UMFPACK_PRL 0                   /* print level */
+  /* returned by all routines that use Info: */
 #define UMFPACK_OK (0)
-#define UMFPACK_STATUS 0	/* UMFPACK_OK, or other result */
+#define UMFPACK_STATUS 0        /* UMFPACK_OK, or other result */
 
 #ifdef _WIN64
-typedef long long int SuiteSparse_long;
+  typedef long long int SuiteSparse_long;
 #else
-typedef long SuiteSparse_long;
+  typedef long SuiteSparse_long;
 #endif
 
-void umfpack_dl_defaults(double Control[UMFPACK_CONTROL]);
+  void umfpack_dl_defaults(double Control[UMFPACK_CONTROL]);
 
-SuiteSparse_long umfpack_dl_symbolic(SuiteSparse_long n_row, SuiteSparse_long n_col,
-                                     const SuiteSparse_long Ap [ ], const SuiteSparse_long Ai [ ],
-                                     const double Ax [ ], void **Symbolic,
-                                     const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO]);
+  SuiteSparse_long umfpack_dl_symbolic(SuiteSparse_long n_row, SuiteSparse_long n_col,
+                                       const SuiteSparse_long Ap [], const SuiteSparse_long Ai [],
+                                       const double Ax [], void **Symbolic,
+                                       const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO]);
 
-SuiteSparse_long umfpack_dl_numeric(const SuiteSparse_long Ap [ ], const SuiteSparse_long Ai [ ],
-                                    const double Ax [ ], void *Symbolic, void **Numeric,
-                                    const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO]);
+  SuiteSparse_long umfpack_dl_numeric(const SuiteSparse_long Ap [], const SuiteSparse_long Ai [],
+                                      const double Ax [], void *Symbolic, void **Numeric,
+                                      const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO]);
 
-SuiteSparse_long umfpack_dl_solve(SuiteSparse_long sys, const SuiteSparse_long Ap [ ],
-                                  const SuiteSparse_long Ai [ ], const double Ax [ ],
-                                  double X [ ], const double B [ ], void *Numeric,
-                                  const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO]);
+  SuiteSparse_long umfpack_dl_solve(SuiteSparse_long sys, const SuiteSparse_long Ap [],
+                                    const SuiteSparse_long Ai [], const double Ax [],
+                                    double X [], const double B [], void *Numeric,
+                                    const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO]);
 
-void umfpack_dl_report_info(const double Control [UMFPACK_CONTROL],
-                            const double Info [UMFPACK_INFO]);
+  void umfpack_dl_report_info(const double Control [UMFPACK_CONTROL],
+                              const double Info [UMFPACK_INFO]);
 
-void umfpack_dl_report_status(const double Control [UMFPACK_CONTROL],
-                              SuiteSparse_long status);
+  void umfpack_dl_report_status(const double Control [UMFPACK_CONTROL],
+                                SuiteSparse_long status);
 
-void umfpack_dl_free_symbolic(void **Symbolic);
+  void umfpack_dl_free_symbolic(void **Symbolic);
 
-void umfpack_dl_free_numeric(void **Numeric);
+  void umfpack_dl_free_numeric(void **Numeric);
 
-SuiteSparse_long umfpack_dl_load_symbolic (void **Symbolic, char *filename) ;
+  SuiteSparse_long umfpack_dl_load_symbolic(void **Symbolic, char *filename);
 
-SuiteSparse_long umfpack_dl_load_numeric (void **Numeric, char *filename) ;
+  SuiteSparse_long umfpack_dl_load_numeric(void **Numeric, char *filename);
 
-SuiteSparse_long umfpack_dl_save_symbolic (void *Symbolic, char *filename) ;
+  SuiteSparse_long umfpack_dl_save_symbolic(void *Symbolic, char *filename);
 
-SuiteSparse_long umfpack_dl_save_numeric (void *Numeric, char *filename) ;
+  SuiteSparse_long umfpack_dl_save_numeric(void *Numeric, char *filename);
 
 #ifdef __cplusplus
 } /* extern "C" */
diff --git a/mex/sources/estimation/DecisionRules.cc b/mex/sources/estimation/DecisionRules.cc
index 48f5c236c13d5f15620e8c6a6f65a725c6c16d1d..41c095925b796a533f5bfb04784a5d303c6bca83 100644
--- a/mex/sources/estimation/DecisionRules.cc
+++ b/mex/sources/estimation/DecisionRules.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -213,4 +213,3 @@ operator<<(std::ostream &out, const DecisionRules::BlanchardKahnException &e)
     out << "The Blanchard Kahn rank condition is not satisfied";
   return out;
 }
-
diff --git a/mex/sources/estimation/DecisionRules.hh b/mex/sources/estimation/DecisionRules.hh
index 22e30bdf11967609f930fc0da3f0c60d13ca84cc..65b965aea412a9bdc0d6c64258656de6dfb75e82 100644
--- a/mex/sources/estimation/DecisionRules.hh
+++ b/mex/sources/estimation/DecisionRules.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -49,7 +49,9 @@ public:
     //! True if the model fails the order condition. False if it fails the rank condition.
     const bool order;
     const int n_fwrd_vars, n_explosive_eigenvals;
-    BlanchardKahnException(bool order_arg, int n_fwrd_vars_arg, int n_explosive_eigenvals_arg) : order(order_arg), n_fwrd_vars(n_fwrd_vars_arg), n_explosive_eigenvals(n_explosive_eigenvals_arg) {};
+    BlanchardKahnException(bool order_arg, int n_fwrd_vars_arg, int n_explosive_eigenvals_arg) : order(order_arg), n_fwrd_vars(n_fwrd_vars_arg), n_explosive_eigenvals(n_explosive_eigenvals_arg)
+    {
+    };
   };
   /*!
     The zetas are supposed to follow C convention (first vector index is zero).
@@ -57,7 +59,9 @@ public:
   DecisionRules(size_t n_arg, size_t p_arg, const std::vector<size_t> &zeta_fwrd_arg,
                 const std::vector<size_t> &zeta_back_arg, const std::vector<size_t> &zeta_mixed_arg,
                 const std::vector<size_t> &zeta_static_arg, double qz_criterium);
-  virtual ~DecisionRules(){};
+  virtual ~DecisionRules()
+  {
+  };
 
   /*!
     \param jacobian First columns are backetermined vars at t-1 (in the order of zeta_back_mixed), then all vars at t (in the orig order), then forward vars at t+1 (in the order of zeta_fwrd_mixed), then exogenous vars.
diff --git a/mex/sources/estimation/DetrendData.cc b/mex/sources/estimation/DetrendData.cc
index 6349932c9de29dcd7fdff0ec40f665d0b312020e..f9fa1b76dbf45d7fdb906540436648a052c9a913 100644
--- a/mex/sources/estimation/DetrendData.cc
+++ b/mex/sources/estimation/DetrendData.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2013 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -44,4 +44,3 @@ DetrendData::detrend(const VectorView &SteadyState, const MatrixConstView &dataV
           detrendedDataView(i, j) = dataView(i, j) - SteadyState(varobs[i]);
     }
 };
-
diff --git a/mex/sources/estimation/DetrendData.hh b/mex/sources/estimation/DetrendData.hh
index 59cfc3d0f2174ab913d6a6907917e32ac887760f..408b14a11254f7bed21efd4ef15a16f52513c417 100644
--- a/mex/sources/estimation/DetrendData.hh
+++ b/mex/sources/estimation/DetrendData.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2013 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -31,7 +31,9 @@ class DetrendData
 {
 
 public:
-  virtual ~DetrendData(){};
+  virtual ~DetrendData()
+  {
+  };
   DetrendData(const std::vector<size_t> &varobs_arg, bool noconstant_arg);
   void detrend(const VectorView &SteadyState, const MatrixConstView &dataView, MatrixView &detrendedDataView);
 
diff --git a/mex/sources/estimation/EstimatedParameter.cc b/mex/sources/estimation/EstimatedParameter.cc
index bf59ae15601f2612dd21f7844266b3f49a15cdc2..5fd2bad2bc9e076f6c422c1bcff63fcd01770c12 100644
--- a/mex/sources/estimation/EstimatedParameter.cc
+++ b/mex/sources/estimation/EstimatedParameter.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2011 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -37,4 +37,3 @@ EstimatedParameter::EstimatedParameter(const EstimatedParameter::pType type_arg,
 EstimatedParameter::~EstimatedParameter()
 {
 }
-
diff --git a/mex/sources/estimation/EstimatedParameter.hh b/mex/sources/estimation/EstimatedParameter.hh
index e323b125bbf5178590f6348da93884709c047f42..52cc26187d4c85c0e53a4824ae10adad055ddb01 100644
--- a/mex/sources/estimation/EstimatedParameter.hh
+++ b/mex/sources/estimation/EstimatedParameter.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2011 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -33,19 +33,20 @@ struct EstimatedParameter
 public:
   // parameter types
   enum pType
-  {
-    shock_SD = 1, // standard deviation of a structural shock
-    measureErr_SD = 2, // standard deviation of a measurement error
-    shock_Corr = 3, // correlation betwwen two structural shocks
-    measureErr_Corr = 4, // correlation between two measurement errors
-    deepPar = 5 // deep parameter
-  };
+    {
+      shock_SD = 1, // standard deviation of a structural shock
+      measureErr_SD = 2, // standard deviation of a measurement error
+      shock_Corr = 3, // correlation betwwen two structural shocks
+      measureErr_Corr = 4, // correlation between two measurement errors
+      deepPar = 5 // deep parameter
+    };
 
   EstimatedParameter(const EstimatedParameter::pType type,
                      size_t ID1, size_t ID2, const std::vector<size_t> &subSampleIDs,
                      double lower_bound, double upper_bound, Prior *prior
                      );
-  virtual ~EstimatedParameter();
+  virtual
+  ~EstimatedParameter();
 
   enum pType ptype;
   size_t ID1;
diff --git a/mex/sources/estimation/EstimatedParametersDescription.hh b/mex/sources/estimation/EstimatedParametersDescription.hh
index 0e4a14fac672406ae228f6660ff1d17d23466ad2..2fc2ad8ea67062b1cf6ae8360d0d2593065b711a 100644
--- a/mex/sources/estimation/EstimatedParametersDescription.hh
+++ b/mex/sources/estimation/EstimatedParametersDescription.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2010 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -45,7 +45,8 @@
 class EstimatedParametersDescription
 {
 public:
-  virtual ~EstimatedParametersDescription();
+  virtual
+  ~EstimatedParametersDescription();
   EstimatedParametersDescription(std::vector<EstimationSubsample> &estSubsamples, std::vector<EstimatedParameter> &estParams);
   std::vector<EstimationSubsample> estSubsamples;
   std::vector<EstimatedParameter> estParams;
diff --git a/mex/sources/estimation/EstimationSubsample.cc b/mex/sources/estimation/EstimationSubsample.cc
index f8e937377e84c305c3246a89a88c7981e0767aac..a8dba8039e230b9c8aa6453a91094a6d0b8af5c7 100644
--- a/mex/sources/estimation/EstimationSubsample.cc
+++ b/mex/sources/estimation/EstimationSubsample.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2010 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -33,4 +33,3 @@ EstimationSubsample::EstimationSubsample(size_t INstartPeriod, size_t INendPerio
 EstimationSubsample::~EstimationSubsample()
 {
 }
-
diff --git a/mex/sources/estimation/EstimationSubsample.hh b/mex/sources/estimation/EstimationSubsample.hh
index 5d76e1293e5e3bd896970721106ab1c2c0914ca6..d8c90723a81677c85ff7b9abe43435d9d0d632eb 100644
--- a/mex/sources/estimation/EstimationSubsample.hh
+++ b/mex/sources/estimation/EstimationSubsample.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2011 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -59,7 +59,8 @@ class EstimationSubsample
 {
 public:
   EstimationSubsample(size_t startPeriod, size_t endPeriod);
-  virtual ~EstimationSubsample();
+  virtual
+  ~EstimationSubsample();
 
   size_t startPeriod;
   size_t endPeriod;
diff --git a/mex/sources/estimation/InitializeKalmanFilter.cc b/mex/sources/estimation/InitializeKalmanFilter.cc
index 53ea5df6c7339cea9285fb0b08bafe8df76b6613..095032494e2590886978f3424e36f6f3156a42cf 100644
--- a/mex/sources/estimation/InitializeKalmanFilter.cc
+++ b/mex/sources/estimation/InitializeKalmanFilter.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -74,4 +74,3 @@ InitializeKalmanFilter::setPstar(Matrix &Pstar, Matrix &Pinf, const Matrix &T, c
 
   Pinf.setAll(0.0);
 }
-
diff --git a/mex/sources/estimation/InitializeKalmanFilter.hh b/mex/sources/estimation/InitializeKalmanFilter.hh
index 83e25a19fcd3f2fb940aae260df088701aab583e..a78b5970e7e203e2b204033d84470b219048a305 100644
--- a/mex/sources/estimation/InitializeKalmanFilter.hh
+++ b/mex/sources/estimation/InitializeKalmanFilter.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -49,13 +49,15 @@ public:
                          const std::vector<size_t> &varobs_arg,
                          double qz_criterium_arg, double lyapunov_tol_arg,
                          bool noconstant_arg);
-  virtual ~InitializeKalmanFilter();
+  virtual
+  ~InitializeKalmanFilter();
   // initialise parameter dependent KF matrices only but not Ps
   template <class Vec1, class Vec2, class Mat1, class Mat2>
-  void initialize(Vec1 &steadyState, const Vec2 &deepParams, Mat1 &R,
-				     const Mat2 &Q, Matrix &RQRt, Matrix &T,
-				     const MatrixConstView &dataView,
-				     MatrixView &detrendedDataView)
+  void
+  initialize(Vec1 &steadyState, const Vec2 &deepParams, Mat1 &R,
+             const Mat2 &Q, Matrix &RQRt, Matrix &T,
+             const MatrixConstView &dataView,
+             MatrixView &detrendedDataView)
   {
     modelSolution.compute(steadyState, deepParams, g_x, g_u);
     detrendData.detrend(steadyState, dataView, detrendedDataView);
@@ -66,10 +68,11 @@ public:
 
   // initialise all KF matrices
   template <class Vec1, class Vec2, class Mat1, class Mat2>
-  void initialize(Vec1 &steadyState, const Vec2 &deepParams, Mat1 &R,
-				     const Mat2 &Q, Matrix &RQRt, Matrix &T, Matrix &Pstar, Matrix &Pinf,
-				     const MatrixConstView &dataView,
-				     MatrixView &detrendedDataView)
+  void
+  initialize(Vec1 &steadyState, const Vec2 &deepParams, Mat1 &R,
+             const Mat2 &Q, Matrix &RQRt, Matrix &T, Matrix &Pstar, Matrix &Pinf,
+             const MatrixConstView &dataView,
+             MatrixView &detrendedDataView)
   {
     initialize(steadyState, deepParams, R, Q, RQRt, T, dataView, detrendedDataView);
     setPstar(Pstar, Pinf, T, RQRt);
@@ -90,7 +93,8 @@ private:
   void setT(Matrix &T);
 
   template <class Mat1, class Mat2>
-  void setRQR(Mat1 &R, const Mat2 &Q, Matrix &RQRt)
+  void
+  setRQR(Mat1 &R, const Mat2 &Q, Matrix &RQRt)
   {
     mat::assignByVectors(R, mat::nullVec, mat::nullVec, g_u, zeta_varobs_back_mixed, mat::nullVec);
 
diff --git a/mex/sources/estimation/KalmanFilter.cc b/mex/sources/estimation/KalmanFilter.cc
index 32f121899caba3bd746056d1b281c60b8902cda4..db9628b81adde7339f6f163689f66113bd5b3cef 100644
--- a/mex/sources/estimation/KalmanFilter.cc
+++ b/mex/sources/estimation/KalmanFilter.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2013 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -74,7 +74,6 @@ KalmanFilter::compute_zeta_varobs_back_mixed(const std::vector<size_t> &zeta_bac
   return zeta_varobs_back_mixed;
 }
 
-
 /**
  * Multi-variate standard Kalman Filter
  */
@@ -86,7 +85,7 @@ KalmanFilter::filter(const MatrixView &detrendedDataView,  const Matrix &H, Vect
   bool nonstationary = true;
   a_init.setAll(0.0);
   int info;
-  
+
   for (size_t t = 0; t < detrendedDataView.getCols(); ++t)
     {
       if (nonstationary)
@@ -192,4 +191,3 @@ KalmanFilter::filter(const MatrixView &detrendedDataView,  const Matrix &H, Vect
 
   return loglik;
 }
-
diff --git a/mex/sources/estimation/KalmanFilter.hh b/mex/sources/estimation/KalmanFilter.hh
index 25a4699faf3db72a8e8e11cca04afd25fc4703ad..4de6e156e1e4d09d7af03583da429f6cd33cebe8 100644
--- a/mex/sources/estimation/KalmanFilter.hh
+++ b/mex/sources/estimation/KalmanFilter.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2013 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -48,7 +48,8 @@ class KalmanFilter
 {
 
 public:
-  virtual ~KalmanFilter();
+  virtual
+  ~KalmanFilter();
   KalmanFilter(const std::string &basename, size_t n_endo, size_t n_exo, const std::vector<size_t> &zeta_fwrd_arg,
                const std::vector<size_t> &zeta_back_arg, const std::vector<size_t> &zeta_mixed_arg, const std::vector<size_t> &zeta_static_arg,
                double qz_criterium_arg, const std::vector<size_t> &varobs_arg,
@@ -56,18 +57,19 @@ public:
                bool noconstant_arg);
 
   template <class Vec1, class Vec2, class Mat1>
-  double compute(const MatrixConstView &dataView, Vec1 &steadyState,
-                 const Mat1 &Q, const Matrix &H, const Vec2 &deepParams,
-                 VectorView &vll, MatrixView &detrendedDataView, size_t start, size_t period)
+  double
+  compute(const MatrixConstView &dataView, Vec1 &steadyState,
+          const Mat1 &Q, const Matrix &H, const Vec2 &deepParams,
+          VectorView &vll, MatrixView &detrendedDataView, size_t start, size_t period)
   {
-	if (period == 0) // initialise all KF matrices
-	  initKalmanFilter.initialize(steadyState, deepParams, R, Q, RQRt, T, Pstar, Pinf,
-                                dataView, detrendedDataView);
-	else             // initialise parameter dependent KF matrices only but not Ps
-	  initKalmanFilter.initialize(steadyState, deepParams, R, Q, RQRt, T,
-                                dataView, detrendedDataView);
+    if (period == 0) // initialise all KF matrices
+      initKalmanFilter.initialize(steadyState, deepParams, R, Q, RQRt, T, Pstar, Pinf,
+                                  dataView, detrendedDataView);
+    else                           // initialise parameter dependent KF matrices only but not Ps
+      initKalmanFilter.initialize(steadyState, deepParams, R, Q, RQRt, T,
+                                  dataView, detrendedDataView);
 
-  return filter(detrendedDataView, H, vll, start);
+    return filter(detrendedDataView, H, vll, start);
   }
 
 private:
diff --git a/mex/sources/estimation/LogLikelihoodMain.cc b/mex/sources/estimation/LogLikelihoodMain.cc
index 8109ad99a74f55e49ab8e2275b6ce8500ad6ed4d..e775dbc3b80007899786514a845b332f09b8b5ce 100644
--- a/mex/sources/estimation/LogLikelihoodMain.cc
+++ b/mex/sources/estimation/LogLikelihoodMain.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2013 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -31,11 +31,11 @@ LogLikelihoodMain::LogLikelihoodMain(const std::string &basename, EstimatedParam
                                      const std::vector<size_t> &varobs, double riccati_tol, double lyapunov_tol,
                                      bool noconstant_arg)
 
-  : estSubsamples(estiParDesc.estSubsamples),
-    logLikelihoodSubSample(basename, estiParDesc, n_endo, n_exo, zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, zeta_static_arg, qz_criterium,
-                           varobs, riccati_tol, lyapunov_tol, noconstant_arg),
-    vll(estiParDesc.getNumberOfPeriods()), // time dimension size of data
-    detrendedData(varobs.size(), estiParDesc.getNumberOfPeriods())
+: estSubsamples(estiParDesc.estSubsamples),
+  logLikelihoodSubSample(basename, estiParDesc, n_endo, n_exo, zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, zeta_static_arg, qz_criterium,
+                         varobs, riccati_tol, lyapunov_tol, noconstant_arg),
+  vll(estiParDesc.getNumberOfPeriods()), // time dimension size of data
+  detrendedData(varobs.size(), estiParDesc.getNumberOfPeriods())
 {
 
 }
@@ -44,5 +44,3 @@ LogLikelihoodMain::~LogLikelihoodMain()
 {
 
 }
-
-
diff --git a/mex/sources/estimation/LogLikelihoodMain.hh b/mex/sources/estimation/LogLikelihoodMain.hh
index 731336a25baadc61daa747496fbcee80dd28ec35..33863f336584c5286c2328077d9db2fe8ed20a0e 100644
--- a/mex/sources/estimation/LogLikelihoodMain.hh
+++ b/mex/sources/estimation/LogLikelihoodMain.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2013 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -36,7 +36,8 @@ private:
   Matrix detrendedData;
 
 public:
-  virtual ~LogLikelihoodMain();
+  virtual
+  ~LogLikelihoodMain();
   LogLikelihoodMain(const std::string &basename, EstimatedParametersDescription &estiParDesc, size_t n_endo, size_t n_exo,
                     const std::vector<size_t> &zeta_fwrd_arg, const std::vector<size_t> &zeta_back_arg, const std::vector<size_t> &zeta_mixed_arg,
                     const std::vector<size_t> &zeta_static_arg, const double qz_criterium_arg, const std::vector<size_t> &varobs_arg,
@@ -53,25 +54,30 @@ public:
    */
 
   template <class VEC1, class VEC2>
-  double compute(VEC1 &steadyState, VEC2 &estParams, VectorView &deepParams, const MatrixConstView &data, 
-		 MatrixView &Q, Matrix &H, size_t start)
+  double
+  compute(VEC1 &steadyState, VEC2 &estParams, VectorView &deepParams, const MatrixConstView &data,
+          MatrixView &Q, Matrix &H, size_t start)
   {
     double logLikelihood = 0;
     for (size_t i = 0; i < estSubsamples.size(); ++i)
       {
-	MatrixConstView dataView(data, 0, estSubsamples[i].startPeriod,
-				 data.getRows(), estSubsamples[i].endPeriod-estSubsamples[i].startPeriod+1);
-	MatrixView detrendedDataView(detrendedData, 0, estSubsamples[i].startPeriod,
-				     data.getRows(), estSubsamples[i].endPeriod-estSubsamples[i].startPeriod+1);
+        MatrixConstView dataView(data, 0, estSubsamples[i].startPeriod,
+                                 data.getRows(), estSubsamples[i].endPeriod-estSubsamples[i].startPeriod+1);
+        MatrixView detrendedDataView(detrendedData, 0, estSubsamples[i].startPeriod,
+                                     data.getRows(), estSubsamples[i].endPeriod-estSubsamples[i].startPeriod+1);
 
-	VectorView vllView(vll, estSubsamples[i].startPeriod, estSubsamples[i].endPeriod-estSubsamples[i].startPeriod+1);
-	logLikelihood += logLikelihoodSubSample.compute(steadyState, dataView, estParams, deepParams,
-							Q, H, vllView, detrendedDataView, start, i);
+        VectorView vllView(vll, estSubsamples[i].startPeriod, estSubsamples[i].endPeriod-estSubsamples[i].startPeriod+1);
+        logLikelihood += logLikelihoodSubSample.compute(steadyState, dataView, estParams, deepParams,
+                                                        Q, H, vllView, detrendedDataView, start, i);
       }
     return logLikelihood;
   };
 
-  Vector &getVll() { return vll; };
+  Vector &
+  getVll()
+  {
+    return vll;
+  };
 };
 
 #endif // !defined(E126AEF5_AC28_400a_821A_3BCFD1BC4C22__INCLUDED_)
diff --git a/mex/sources/estimation/LogLikelihoodSubSample.cc b/mex/sources/estimation/LogLikelihoodSubSample.cc
index 9a3aabf80ee70fb113c4d6bca468cd52df8ce44b..6c647c1f86c66bb7661e79bb664f557b46d140fc 100644
--- a/mex/sources/estimation/LogLikelihoodSubSample.cc
+++ b/mex/sources/estimation/LogLikelihoodSubSample.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2013 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -38,4 +38,3 @@ LogLikelihoodSubSample::LogLikelihoodSubSample(const std::string &basename, Esti
                varobs, riccati_tol, lyapunov_tol, noconstant_arg), eigQ(n_exo), eigH(varobs.size())
 {
 };
-
diff --git a/mex/sources/estimation/LogLikelihoodSubSample.hh b/mex/sources/estimation/LogLikelihoodSubSample.hh
index 4e0fa509f3ee496e8444ba61e0a3a9708a44ca52..e9f0dbe9a22c4c1b05e334a679bacae0889e2561 100644
--- a/mex/sources/estimation/LogLikelihoodSubSample.hh
+++ b/mex/sources/estimation/LogLikelihoodSubSample.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2013 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -42,15 +42,17 @@ public:
                          const std::vector<size_t> &varobs_arg, double riccati_tol_in, double lyapunov_tol, bool noconstant_arg);
 
   template <class VEC1, class VEC2>
-  double compute(VEC1 &steadyState, const MatrixConstView &dataView, VEC2 &estParams, VectorView &deepParams,
-		 MatrixView &Q, Matrix &H, VectorView &vll, MatrixView &detrendedDataView, size_t start, size_t period)
+  double
+  compute(VEC1 &steadyState, const MatrixConstView &dataView, VEC2 &estParams, VectorView &deepParams,
+          MatrixView &Q, Matrix &H, VectorView &vll, MatrixView &detrendedDataView, size_t start, size_t period)
   {
     updateParams(estParams, deepParams, Q, H, period);
 
     return kalmanFilter.compute(dataView, steadyState,  Q, H, deepParams, vll, detrendedDataView, start, period);
   }
 
-  virtual ~LogLikelihoodSubSample();
+  virtual
+  ~LogLikelihoodSubSample();
 
   class UpdateParamsException
   {
@@ -69,8 +71,9 @@ private:
 
   // methods
   template <class VEC>
-  void updateParams(VEC &estParams, VectorView &deepParams,
-                    MatrixView &Q, Matrix &H, size_t period)
+  void
+  updateParams(VEC &estParams, VectorView &deepParams,
+               MatrixView &Q, Matrix &H, size_t period)
   {
     size_t i, k, k1, k2;
     int test;
@@ -79,97 +82,96 @@ private:
 
     for (i = 0; i <  estParams.getSize(); ++i)
       {
-	found = false;
-	it = find(estiParDesc.estParams[i].subSampleIDs.begin(),
-		  estiParDesc.estParams[i].subSampleIDs.end(), period);
-	if (it != estiParDesc.estParams[i].subSampleIDs.end())
-	  found = true;
-	if (found)
-	  {
-	    switch (estiParDesc.estParams[i].ptype)
-	      {
-	      case EstimatedParameter::shock_SD:
-		k = estiParDesc.estParams[i].ID1;
-		Q(k, k) = estParams(i)*estParams(i);
-		break;
-
-	      case EstimatedParameter::measureErr_SD:
-		k = estiParDesc.estParams[i].ID1;
-		H(k, k) = estParams(i)*estParams(i);
-		break;
-
-	      case EstimatedParameter::shock_Corr:
-		k1 = estiParDesc.estParams[i].ID1;
-		k2 = estiParDesc.estParams[i].ID2;
-		Q(k1, k2) = estParams(i)*sqrt(Q(k1, k1)*Q(k2, k2));
-		Q(k2, k1) = Q(k1, k2);
-		//   [CholQ,testQ] = chol(Q);
-		test = lapack::choleskyDecomp(Q, "L");
+        found = false;
+        it = find(estiParDesc.estParams[i].subSampleIDs.begin(),
+                  estiParDesc.estParams[i].subSampleIDs.end(), period);
+        if (it != estiParDesc.estParams[i].subSampleIDs.end())
+          found = true;
+        if (found)
+          {
+            switch (estiParDesc.estParams[i].ptype)
+              {
+              case EstimatedParameter::shock_SD:
+                k = estiParDesc.estParams[i].ID1;
+                Q(k, k) = estParams(i)*estParams(i);
+                break;
+
+              case EstimatedParameter::measureErr_SD:
+                k = estiParDesc.estParams[i].ID1;
+                H(k, k) = estParams(i)*estParams(i);
+                break;
+
+              case EstimatedParameter::shock_Corr:
+                k1 = estiParDesc.estParams[i].ID1;
+                k2 = estiParDesc.estParams[i].ID2;
+                Q(k1, k2) = estParams(i)*sqrt(Q(k1, k1)*Q(k2, k2));
+                Q(k2, k1) = Q(k1, k2);
+                //   [CholQ,testQ] = chol(Q);
+                test = lapack::choleskyDecomp(Q, "L");
                 assert(test >= 0);
-                
-		if (test > 0)
-		  {
-		    // The variance-covariance matrix of the structural innovations is not definite positive.
-		    // We have to compute the eigenvalues of this matrix in order to build the penalty.
-		    double delta = 0;
-		    eigQ.calculate(Q);  // get eigenvalues
-		    //k = find(a < 0);
-		    if (eigQ.hasConverged())
-		      {
-			const Vector &evQ = eigQ.getD();
-			for (i = 0; i < evQ.getSize(); ++i)
-			  if (evQ(i) < 0)
-			    delta -= evQ(i);
-		      }
-
-		    throw UpdateParamsException(delta);
-		  } // if
-		break;
-
-	      case EstimatedParameter::measureErr_Corr:
-		k1 = estiParDesc.estParams[i].ID1;
-		k2 = estiParDesc.estParams[i].ID2;
-		//      H(k1,k2) = xparam1(i)*sqrt(H(k1,k1)*H(k2,k2));
-		//      H(k2,k1) = H(k1,k2);
-		H(k1, k2) = estParams(i)*sqrt(H(k1, k1)*H(k2, k2));
-		H(k2, k1) = H(k1, k2);
-
-		//[CholH,testH] = chol(H);
-		test = lapack::choleskyDecomp(H, "L");
-		assert(test >= 0);
-
-		if (test > 0)
-		  {
-		    // The variance-covariance matrix of the measurement errors is not definite positive.
-		    // We have to compute the eigenvalues of this matrix in order to build the penalty.
-		    //a = diag(eig(H));
-		    double delta = 0;
-		    eigH.calculate(H);  // get eigenvalues
-		    //k = find(a < 0);
-		    if (eigH.hasConverged())
-		      {
-			const Vector &evH = eigH.getD();
-			for (i = 0; i < evH.getSize(); ++i)
-			  if (evH(i) < 0)
-			    delta -= evH(i);
-		      }
-		    throw UpdateParamsException(delta);
-		  } //   end if
-		break;
-
-		//if estim_params_.np > 0  // i.e. num of deep parameters >0
-	      case EstimatedParameter::deepPar:
-		k = estiParDesc.estParams[i].ID1;
-		deepParams(k) = estParams(i);
-		break;
-	      default:
+
+                if (test > 0)
+                  {
+                    // The variance-covariance matrix of the structural innovations is not definite positive.
+                    // We have to compute the eigenvalues of this matrix in order to build the penalty.
+                    double delta = 0;
+                    eigQ.calculate(Q);  // get eigenvalues
+                    //k = find(a < 0);
+                    if (eigQ.hasConverged())
+                      {
+                        const Vector &evQ = eigQ.getD();
+                        for (i = 0; i < evQ.getSize(); ++i)
+                          if (evQ(i) < 0)
+                            delta -= evQ(i);
+                      }
+
+                    throw UpdateParamsException(delta);
+                  } // if
+                break;
+
+              case EstimatedParameter::measureErr_Corr:
+                k1 = estiParDesc.estParams[i].ID1;
+                k2 = estiParDesc.estParams[i].ID2;
+                //      H(k1,k2) = xparam1(i)*sqrt(H(k1,k1)*H(k2,k2));
+                //      H(k2,k1) = H(k1,k2);
+                H(k1, k2) = estParams(i)*sqrt(H(k1, k1)*H(k2, k2));
+                H(k2, k1) = H(k1, k2);
+
+                //[CholH,testH] = chol(H);
+                test = lapack::choleskyDecomp(H, "L");
+                assert(test >= 0);
+
+                if (test > 0)
+                  {
+                    // The variance-covariance matrix of the measurement errors is not definite positive.
+                    // We have to compute the eigenvalues of this matrix in order to build the penalty.
+                    //a = diag(eig(H));
+                    double delta = 0;
+                    eigH.calculate(H);  // get eigenvalues
+                    //k = find(a < 0);
+                    if (eigH.hasConverged())
+                      {
+                        const Vector &evH = eigH.getD();
+                        for (i = 0; i < evH.getSize(); ++i)
+                          if (evH(i) < 0)
+                            delta -= evH(i);
+                      }
+                    throw UpdateParamsException(delta);
+                  } //   end if
+                break;
+
+                //if estim_params_.np > 0  // i.e. num of deep parameters >0
+              case EstimatedParameter::deepPar:
+                k = estiParDesc.estParams[i].ID1;
+                deepParams(k) = estParams(i);
+                break;
+              default:
                 assert(false);
-	      } // end switch
-	  } // end found
+              } // end switch
+          } // end found
       } //end for
   };
 
-
 };
 
 #endif // !defined(DF8B7AF5_8169_4587_9037_2CD2C82E2DDF__INCLUDED_)
diff --git a/mex/sources/estimation/LogPosteriorDensity.cc b/mex/sources/estimation/LogPosteriorDensity.cc
index a9da75fc11d3ce6d24cb2d001fee2b6b4d603d1d..c87e6dee75918ed0fb3018d830de9041008f3628 100644
--- a/mex/sources/estimation/LogPosteriorDensity.cc
+++ b/mex/sources/estimation/LogPosteriorDensity.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2013 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -41,7 +41,6 @@ LogPosteriorDensity::LogPosteriorDensity(const std::string &modName, EstimatedPa
 
 }
 
-
 /**
  * vector of log likelihoods for each Kalman step
  */
@@ -50,4 +49,3 @@ LogPosteriorDensity::getLikVector()
 {
   return logLikelihoodMain.getVll();
 }
-
diff --git a/mex/sources/estimation/LogPosteriorDensity.hh b/mex/sources/estimation/LogPosteriorDensity.hh
index 820f2a575380275441603ef64341a7d15074d967..425eb625a678319895dfc6b312f896508c3ef627 100644
--- a/mex/sources/estimation/LogPosteriorDensity.hh
+++ b/mex/sources/estimation/LogPosteriorDensity.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2013 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -42,7 +42,8 @@ private:
   LogLikelihoodMain logLikelihoodMain;
 
 public:
-  virtual ~LogPosteriorDensity();
+  virtual
+  ~LogPosteriorDensity();
 
   LogPosteriorDensity(const std::string &modName, EstimatedParametersDescription &estParamsDesc, size_t n_endo, size_t n_exo,
                       const std::vector<size_t> &zeta_fwrd_arg, const std::vector<size_t> &zeta_back_arg, const std::vector<size_t> &zeta_mixed_arg,
diff --git a/mex/sources/estimation/LogPriorDensity.hh b/mex/sources/estimation/LogPriorDensity.hh
index 5a07402be09a93de0b3cbba76da30ddbde03477f..c7c57a6bdeccdef1c71dcc3fb140474ec162615c 100644
--- a/mex/sources/estimation/LogPriorDensity.hh
+++ b/mex/sources/estimation/LogPriorDensity.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2012 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -35,18 +35,20 @@ class LogPriorDensity
 
 public:
   LogPriorDensity(EstimatedParametersDescription &estParsDesc);
-  virtual ~LogPriorDensity();
+  virtual
+  ~LogPriorDensity();
 
   template<class VEC>
-  double compute(VEC &ep)
+  double
+  compute(VEC &ep)
   {
     assert(estParsDesc.estParams.size() == ep.getSize());
     double logPriorDensity = 0;
     for (size_t i = 0; i <  ep.getSize(); ++i)
       {
-	logPriorDensity += log(((*(estParsDesc.estParams[i]).prior)).pdf(ep(i)));
-	if (std::isinf(fabs(logPriorDensity)))
-	  return logPriorDensity;
+        logPriorDensity += log(((*(estParsDesc.estParams[i]).prior)).pdf(ep(i)));
+        if (std::isinf(fabs(logPriorDensity)))
+          return logPriorDensity;
       }
     return logPriorDensity;
   };
diff --git a/mex/sources/estimation/ModelSolution.cc b/mex/sources/estimation/ModelSolution.cc
index 64543bf09d3a78cd0ded0e0044dd5a69fd98c449..abeb02124490ea8f234e4d16cdde1b6452d7dcca 100644
--- a/mex/sources/estimation/ModelSolution.cc
+++ b/mex/sources/estimation/ModelSolution.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -51,5 +51,3 @@ ModelSolution::ModelSolution(const std::string &basename,  size_t n_endo_arg, si
             zeta_mixed_arg.begin(), zeta_mixed_arg.end(),
             back_inserter(zeta_back_mixed));
 }
-
-
diff --git a/mex/sources/estimation/ModelSolution.hh b/mex/sources/estimation/ModelSolution.hh
index 92e03a5446c428772c77a5b118c3fa98a62fd4b7..8bdc4a66a40bbe7a78fc67ba740186d68fb55abb 100644
--- a/mex/sources/estimation/ModelSolution.hh
+++ b/mex/sources/estimation/ModelSolution.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -42,9 +42,12 @@ public:
   ModelSolution(const std::string &basename,  size_t n_endo, size_t n_exo, const std::vector<size_t> &zeta_fwrd_arg,
                 const std::vector<size_t> &zeta_back_arg, const std::vector<size_t> &zeta_mixed_arg,
                 const std::vector<size_t> &zeta_static_arg, double qz_criterium);
-  virtual ~ModelSolution() {};
+  virtual ~ModelSolution()
+  {
+  };
   template <class Vec1, class Vec2, class Mat1, class Mat2>
-  void compute(Vec1 &steadyState, const Vec2 &deepParams, Mat1 &ghx, Mat2 &ghu) throw (DecisionRules::BlanchardKahnException, GeneralizedSchurDecomposition::GSDException, SteadyStateSolver::SteadyStateException)
+  void
+  compute(Vec1 &steadyState, const Vec2 &deepParams, Mat1 &ghx, Mat2 &ghu) throw (DecisionRules::BlanchardKahnException, GeneralizedSchurDecomposition::GSDException, SteadyStateSolver::SteadyStateException)
   {
     // compute Steady State
     steadyStateSolver.compute(steadyState, Mx, deepParams);
@@ -69,8 +72,9 @@ private:
   Vector llXsteadyState;
   //Matrix jacobian;
   template <class Vec1, class Vec2, class Mat1, class Mat2>
-  void ComputeModelSolution(Vec1 &steadyState, const Vec2 &deepParams,
-                            Mat1 &ghx, Mat2 &ghu)
+  void
+  ComputeModelSolution(Vec1 &steadyState, const Vec2 &deepParams,
+                       Mat1 &ghx, Mat2 &ghu)
     throw (DecisionRules::BlanchardKahnException, GeneralizedSchurDecomposition::GSDException)
   {
     // set extended Steady State
diff --git a/mex/sources/estimation/Prior.hh b/mex/sources/estimation/Prior.hh
index de29bf7898716075fb0b4b3d2593e74a9ea57c62..f550e2b75f8072e3cf2e84d422e81aa6c123be7e 100644
--- a/mex/sources/estimation/Prior.hh
+++ b/mex/sources/estimation/Prior.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2011 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -47,17 +47,18 @@ struct Prior
 public:
   //! probablity density functions
   enum pShape
-  {
-    Beta = 1,
-    Gamma = 2,
-    Gaussian = 3, // i.e. Normal density
-    Inv_gamma_1 = 4, // Inverse gamma (type 1) density
-    Uniform = 5,
-    Inv_gamma_2 = 6 //Inverse gamma (type 2) density
-  };
+    {
+      Beta = 1,
+      Gamma = 2,
+      Gaussian = 3, // i.e. Normal density
+      Inv_gamma_1 = 4, // Inverse gamma (type 1) density
+      Uniform = 5,
+      Inv_gamma_2 = 6 //Inverse gamma (type 2) density
+    };
 
   Prior(double mean, double standard, double lower_bound, double upper_bound, double fhp, double shp);
-  virtual ~Prior();
+  virtual
+  ~Prior();
 
   const double mean;
   const double standard;
@@ -100,7 +101,9 @@ public:
     distribution(fhp, shp)
   {
   };
-  virtual ~BetaPrior(){};
+  virtual ~BetaPrior()
+  {
+  };
   virtual pShape
   getShape()
   {
@@ -134,7 +137,9 @@ public:
     distribution(fhp, shp)
   {
   };
-  virtual ~GammaPrior(){};
+  virtual ~GammaPrior()
+  {
+  };
   virtual pShape
   getShape()
   {
@@ -164,7 +169,9 @@ public:
     distribution(shp/2, 2/fhp)
   {
   };
-  virtual ~InvGamma1_Prior(){};
+  virtual ~InvGamma1_Prior()
+  {
+  };
   virtual pShape
   getShape()
   {
@@ -199,7 +206,9 @@ public:
     distribution(shp/2, 2/fhp)
   {
   };
-  virtual ~InvGamma2_Prior(){};
+  virtual ~InvGamma2_Prior()
+  {
+  };
   virtual pShape
   getShape()
   {
@@ -239,7 +248,9 @@ public:
     distribution(fhp, shp) //pdf distribution(mean, standard)
   {
   };
-  virtual ~GaussianPrior(){};
+  virtual ~GaussianPrior()
+  {
+  };
   virtual pShape
   getShape()
   {
@@ -277,7 +288,9 @@ public:
     distribution(fhp, shp) //pdf distribution(lower_bound, upper_bound)
   {
   };
-  virtual ~UniformPrior(){};
+  virtual ~UniformPrior()
+  {
+  };
   virtual pShape
   getShape()
   {
diff --git a/mex/sources/estimation/Proposal.cc b/mex/sources/estimation/Proposal.cc
index 7e7b633d85d38d923ef4eb7bc27072df7aeb2fab..8bf5933d452998c1550e3ed15c1ecc14f7ac57c0 100644
--- a/mex/sources/estimation/Proposal.cc
+++ b/mex/sources/estimation/Proposal.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2010 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -88,4 +88,3 @@ Proposal::selectionTestDraw()
 {
   return uniformVrng();
 }
-
diff --git a/mex/sources/estimation/Proposal.hh b/mex/sources/estimation/Proposal.hh
index 13be358fb11703860839072d7bbf85b40a8f6b3b..4beb1c9dd39b2cbda3cab845ecfd95e726c37441 100644
--- a/mex/sources/estimation/Proposal.hh
+++ b/mex/sources/estimation/Proposal.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2011 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -63,7 +63,9 @@ public:
 
 public:
   Proposal(const VectorConstView &vJscale, const MatrixConstView &covariance);
-  virtual ~Proposal() {};
+  virtual ~Proposal()
+  {
+  };
   virtual void draw(Vector &mean, Vector &draw);
   virtual Matrix&getVar();
   virtual int seed();
diff --git a/mex/sources/estimation/RandomWalkMetropolisHastings.hh b/mex/sources/estimation/RandomWalkMetropolisHastings.hh
index f281939bac044a69958cda72e1264a2a03078c8d..c09b2c9df0dba8e78905148ebd9f4363804cbdf5 100644
--- a/mex/sources/estimation/RandomWalkMetropolisHastings.hh
+++ b/mex/sources/estimation/RandomWalkMetropolisHastings.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -42,13 +42,16 @@ public:
     parDraw(size), newParDraw(size)
   {
   };
-  virtual ~RandomWalkMetropolisHastings() {};
+  virtual ~RandomWalkMetropolisHastings()
+  {
+  };
 
   template<class VEC1>
-  double compute(VectorView &mhLogPostDens, MatrixView &mhParams, VEC1 &steadyState,
-		 Vector &estParams, VectorView &deepParams, const MatrixConstView &data, MatrixView &Q, Matrix &H,
-		 const size_t presampleStart, const size_t startDraw, size_t nMHruns,
-		 LogPosteriorDensity &lpd, Proposal &pDD, EstimatedParametersDescription &epd)
+  double
+  compute(VectorView &mhLogPostDens, MatrixView &mhParams, VEC1 &steadyState,
+          Vector &estParams, VectorView &deepParams, const MatrixConstView &data, MatrixView &Q, Matrix &H,
+          const size_t presampleStart, const size_t startDraw, size_t nMHruns,
+          LogPosteriorDensity &lpd, Proposal &pDD, EstimatedParametersDescription &epd)
   {
     //streambuf *likbuf, *drawbuf *backup;
     std::ofstream urandfilestr, drawfilestr;
@@ -64,46 +67,46 @@ public:
 
     for (size_t run = startDraw - 1; run < nMHruns; ++run)
       {
-	overbound = false;
-	pDD.draw(parDraw, newParDraw);
-	for (count = 0; count < parDraw.getSize(); ++count)
-	  {
-	    overbound = (newParDraw(count) < epd.estParams[count].lower_bound || newParDraw(count) > epd.estParams[count].upper_bound);
-	    if (overbound)
-	      {
-		newLogpost = -INFINITY;
-		break;
-	      }
-	  }
-	if (!overbound)
-	  {
-	    try
-	      {
-		newLogpost = -lpd.compute(steadyState, newParDraw, deepParams, data, Q, H, presampleStart);
-	      }
-	    catch (const std::exception &e)
-	      {
-		throw; // for now handle the system and other errors higher-up
-	      }
-	    catch (...)
-	      {
-		newLogpost = -INFINITY;
-	      }
-	  }
-	urand = pDD.selectionTestDraw();
-	if ((newLogpost > -INFINITY) && log(urand) < newLogpost-logpost)
-	  {
-	    parDraw = newParDraw;
-	    logpost = newLogpost;
-	    accepted++;
-	  }
-	mat::get_row(mhParams, run) = parDraw;
-	mhLogPostDens(run) = logpost;
+        overbound = false;
+        pDD.draw(parDraw, newParDraw);
+        for (count = 0; count < parDraw.getSize(); ++count)
+          {
+            overbound = (newParDraw(count) < epd.estParams[count].lower_bound || newParDraw(count) > epd.estParams[count].upper_bound);
+            if (overbound)
+              {
+                newLogpost = -INFINITY;
+                break;
+              }
+          }
+        if (!overbound)
+          {
+            try
+              {
+                newLogpost = -lpd.compute(steadyState, newParDraw, deepParams, data, Q, H, presampleStart);
+              }
+            catch (const std::exception &e)
+              {
+                throw; // for now handle the system and other errors higher-up
+              }
+            catch (...)
+              {
+                newLogpost = -INFINITY;
+              }
+          }
+        urand = pDD.selectionTestDraw();
+        if ((newLogpost > -INFINITY) && log(urand) < newLogpost-logpost)
+          {
+            parDraw = newParDraw;
+            logpost = newLogpost;
+            accepted++;
+          }
+        mat::get_row(mhParams, run) = parDraw;
+        mhLogPostDens(run) = logpost;
 
-	urandfilestr << urand << "\n"; //","
-	for (size_t c = 0; c < newParDraw.getSize()-1; ++c)
-	  drawfilestr << newParDraw(c) << ",";
-	drawfilestr <<  newParDraw(newParDraw.getSize()-1) << "\n";
+        urandfilestr << urand << "\n"; //","
+        for (size_t c = 0; c < newParDraw.getSize()-1; ++c)
+          drawfilestr << newParDraw(c) << ",";
+        drawfilestr <<  newParDraw(newParDraw.getSize()-1) << "\n";
       }
 
     urandfilestr.close();
diff --git a/mex/sources/estimation/SteadyStateSolver.cc b/mex/sources/estimation/SteadyStateSolver.cc
index e2e9980aebf6b29c6185e1daf6aaba0c8b12b665..a0bb7cbe05bb317a6ffd6e830cf056831a57c42c 100644
--- a/mex/sources/estimation/SteadyStateSolver.cc
+++ b/mex/sources/estimation/SteadyStateSolver.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Dynare Team
+ * Copyright (C) 2013-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -33,12 +33,12 @@ SteadyStateSolver::static_f(const gsl_vector *yy, void *p, gsl_vector *F)
   params *pp = (params *) p;
   VectorConstView deepParams(pp->deepParams, pp->n_params, 1);
   MatrixConstView x(pp->x, 1, pp->n_exo, 1);
-  
+
   VectorView y(yy->data, yy->size, yy->stride);
   VectorView residual(F->data, F->size, F->stride);
 
   pp->static_dll->eval(y, x, deepParams, residual, NULL, NULL);
-  
+
   return GSL_SUCCESS;
 }
 
@@ -48,11 +48,11 @@ SteadyStateSolver::static_df(const gsl_vector *yy, void *p, gsl_matrix *J)
   params *pp = (params *) p;
   VectorConstView deepParams(pp->deepParams, pp->n_params, 1);
   MatrixConstView x(pp->x, 1, pp->n_exo, 1);
-  
+
   VectorView y(yy->data, yy->size, yy->stride);
 
   pp->static_dll->eval(y, x, deepParams, *pp->residual, pp->g1, NULL);
-  
+
   assert(J->size1 == J->size2 && J->size1 == J->tda);
   MatrixView g1t(J->data, J->size1, J->size2, J->tda);
   mat::transpose(g1t, *pp->g1); // GSL wants row-major order
@@ -66,16 +66,15 @@ SteadyStateSolver::static_fdf(const gsl_vector *yy, void *p, gsl_vector *F, gsl_
   params *pp = (params *) p;
   VectorConstView deepParams(pp->deepParams, pp->n_params, 1);
   MatrixConstView x(pp->x, 1, pp->n_exo, 1);
-  
+
   VectorView y(yy->data, yy->size, yy->stride);
   VectorView residual(F->data, F->size, F->stride);
 
   pp->static_dll->eval(y, x, deepParams, residual, pp->g1, NULL);
-  
+
   assert(J->size1 == J->size2 && J->size1 == J->tda);
   MatrixView g1t(J->data, J->size1, J->size2, J->tda);
   mat::transpose(g1t, *pp->g1); // GSL wants row-major order
 
   return GSL_SUCCESS;
 }
-
diff --git a/mex/sources/estimation/SteadyStateSolver.hh b/mex/sources/estimation/SteadyStateSolver.hh
index e52f5f433cf7f3d00746c39dbe831c90167d8dbc..726d8594bb2319e851f27e0a54985d6aba526e02 100644
--- a/mex/sources/estimation/SteadyStateSolver.hh
+++ b/mex/sources/estimation/SteadyStateSolver.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Dynare Team
+ * Copyright (C) 2013-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -55,7 +55,7 @@ public:
   {
   public:
     std::string message;
-    SteadyStateException(const std::string &message_arg) : message(message_arg) 
+    SteadyStateException(const std::string &message_arg) : message(message_arg)
     {
     }
   };
@@ -63,7 +63,8 @@ public:
   SteadyStateSolver(const std::string &basename, size_t n_endo_arg);
 
   template <class Vec1, class Mat, class Vec2>
-  void compute(Vec1 &steadyState, const Mat &Mx, const Vec2 &deepParams) throw (SteadyStateException)
+  void
+  compute(Vec1 &steadyState, const Mat &Mx, const Vec2 &deepParams) throw (SteadyStateException)
   {
     assert(steadyState.getStride() == 1);
     assert(deepParams.getStride() == 1);
@@ -97,7 +98,7 @@ public:
 
         status = gsl_multiroot_test_residual(s->f, tolerance);
       }
-    while(status == GSL_CONTINUE && iter < max_iterations);
+    while (status == GSL_CONTINUE && iter < max_iterations);
 
     if (status != GSL_SUCCESS)
       throw SteadyStateException(std::string(gsl_strerror(status)));
@@ -107,5 +108,3 @@ public:
     gsl_multiroot_fdfsolver_free(s);
   }
 };
-
-
diff --git a/mex/sources/estimation/libmat/DiscLyapFast.hh b/mex/sources/estimation/libmat/DiscLyapFast.hh
index cd0b014c0c34d81f5abd7097a53aa044049662c5..b85d73728972b9f6b6f3a3a2ef99057520abf4e0 100644
--- a/mex/sources/estimation/libmat/DiscLyapFast.hh
+++ b/mex/sources/estimation/libmat/DiscLyapFast.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -60,7 +60,9 @@ public:
   {
     mat::set_identity(I);
   };
-  virtual ~DiscLyapFast() {};
+  virtual ~DiscLyapFast()
+  {
+  };
   template <class MatG, class MatV, class MatX >
   void solve_lyap(const MatG &G, const MatV &V, MatX &X, double tol = 1e-16, size_t flag_ch = 0) throw (DLPException);
 
diff --git a/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc b/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc
index 0b9e5d01b1cbd83f59cf08f453139aacddef6d6e..47fc2816e5dc9d13ac89fb0bbeb50f60815587b8 100644
--- a/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc
+++ b/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -51,7 +51,7 @@ GeneralizedSchurDecomposition::~GeneralizedSchurDecomposition()
 lapack_int
 GeneralizedSchurDecomposition::selctg(const double *alphar, const double *alphai, const double *beta)
 {
-  return ((*alphar * *alphar + *alphai * *alphai) < criterium_static * *beta * *beta);
+  return ((*alphar **alphar + *alphai **alphai) < criterium_static **beta **beta);
 }
 
 std::ostream &
diff --git a/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.hh b/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.hh
index f776ba3330a7f86d4eda22326c23cde261412515..e6d9396048ca529919187ab2f70f4752ececfba5 100644
--- a/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.hh
+++ b/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -37,11 +37,14 @@ public:
   {
   public:
     const lapack_int info, n;
-    GSDException(lapack_int info_arg, lapack_int n_arg) : info(info_arg), n(n_arg) {};
+    GSDException(lapack_int info_arg, lapack_int n_arg) : info(info_arg), n(n_arg)
+    {
+    };
   };
   //! \todo Replace heuristic choice for workspace size by a query to determine the optimal size
   GeneralizedSchurDecomposition(size_t n_arg, double criterium_arg);
-  virtual ~GeneralizedSchurDecomposition();
+  virtual
+  ~GeneralizedSchurDecomposition();
   //! \todo Add a lock around the modification of criterium_static for making it thread-safe
   template<class Mat1, class Mat2, class Mat3>
   void compute(Mat1 &S, Mat2 &T, Mat3 &Z, size_t &sdim) throw (GSDException);
diff --git a/mex/sources/estimation/libmat/LUSolver.hh b/mex/sources/estimation/libmat/LUSolver.hh
index e78c18c74327799b5a370a34e36a062e06824198..16ab45dad205856e401d8b30fa6ad268620dcbe7 100644
--- a/mex/sources/estimation/libmat/LUSolver.hh
+++ b/mex/sources/estimation/libmat/LUSolver.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -32,10 +32,13 @@ public:
   {
   public:
     const lapack_int info;
-    LUException(lapack_int info_arg) : info(info_arg) {};
+    LUException(lapack_int info_arg) : info(info_arg)
+    {
+    };
   };
   LUSolver(size_t dim_arg);
-  virtual ~LUSolver();
+  virtual
+  ~LUSolver();
   /*!
     Computes A^(-1)*B (possibly transposing A).
     The output is stored in B.
diff --git a/mex/sources/estimation/libmat/Matrix.hh b/mex/sources/estimation/libmat/Matrix.hh
index 860af9507e9d916e193ae8a62eb6aee0b65519ba..b17e5b3ce3458e03f45fafd06fb66f42fd4ec0bf 100644
--- a/mex/sources/estimation/libmat/Matrix.hh
+++ b/mex/sources/estimation/libmat/Matrix.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2012 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -69,19 +69,52 @@ public:
   Matrix(size_t rows_arg, size_t cols_arg);
   Matrix(size_t size_arg);
   Matrix(const Matrix &arg);
-  virtual ~Matrix();
-  inline size_t getRows() const { return rows; }
-  inline size_t getCols() const { return cols; }
-  inline size_t getLd() const { return rows; }
-  inline double *getData() { return data; }
-  inline const double *getData() const { return data; }
-  inline void setAll(double val) { std::fill_n(data, rows*cols, val); }
-  inline double &operator() (size_t i, size_t j) { return data[i+j*rows]; }
-  inline const double &operator() (size_t i, size_t j) const { return data[i+j*rows]; }
+  virtual
+  ~Matrix();
+  inline size_t
+  getRows() const
+  {
+    return rows;
+  }
+  inline size_t
+  getCols() const
+  {
+    return cols;
+  }
+  inline size_t
+  getLd() const
+  {
+    return rows;
+  }
+  inline double *
+  getData()
+  {
+    return data;
+  }
+  inline const double *
+  getData() const
+  {
+    return data;
+  }
+  inline void
+  setAll(double val)
+  {
+    std::fill_n(data, rows*cols, val);
+  }
+  inline double &
+  operator()(size_t i, size_t j)
+  {
+    return data[i+j*rows];
+  }
+  inline const double &
+  operator()(size_t i, size_t j) const
+  {
+    return data[i+j*rows];
+  }
   //! Assignment operator, only works for matrices of same dimension
   template<class Mat>
   Matrix &
-  operator= (const Mat &arg)
+  operator=(const Mat &arg)
   {
     assert(rows == arg.getRows() && cols == arg.getCols());
     for (size_t j = 0; j < cols; j++)
@@ -112,23 +145,54 @@ public:
            && col_offset < arg.getCols()
            && col_offset + cols_arg <= arg.getCols());
   }
-  virtual ~MatrixView(){};
-  inline size_t getRows() const { return rows; }
-  inline size_t getCols() const { return cols; }
-  inline size_t getLd() const { return ld; }
-  inline double *getData() { return data; }
-  inline const double *getData() const { return data; }
-  inline void setAll(double val)
+  virtual ~MatrixView()
+  {
+  };
+  inline size_t
+  getRows() const
+  {
+    return rows;
+  }
+  inline size_t
+  getCols() const
+  {
+    return cols;
+  }
+  inline size_t
+  getLd() const
+  {
+    return ld;
+  }
+  inline double *
+  getData()
+  {
+    return data;
+  }
+  inline const double *
+  getData() const
+  {
+    return data;
+  }
+  inline void
+  setAll(double val)
   {
     for (double *p = data; p < data + cols*ld; p += ld)
       std::fill_n(p, rows, val);
   }
-  inline double &operator() (size_t i, size_t j) { return data[i+j*ld]; }
-  inline const double &operator() (size_t i, size_t j) const { return data[i+j*ld]; }
+  inline double &
+  operator()(size_t i, size_t j)
+  {
+    return data[i+j*ld];
+  }
+  inline const double &
+  operator()(size_t i, size_t j) const
+  {
+    return data[i+j*ld];
+  }
   //! Assignment operator, only works for matrices of same dimension
   template<class Mat>
   MatrixView &
-  operator= (const Mat &arg)
+  operator=(const Mat &arg)
   {
     assert(rows == arg.getRows() && cols == arg.getCols());
     for (size_t j = 0; j < cols; j++)
@@ -158,12 +222,34 @@ public:
            && col_offset < arg.getCols()
            && col_offset + cols_arg <= arg.getCols());
   }
-  virtual ~MatrixConstView(){};
-  inline size_t getRows() const { return rows; }
-  inline size_t getCols() const { return cols; }
-  inline size_t getLd() const { return ld; }
-  inline const double *getData() const { return data; }
-  inline const double &operator() (size_t i, size_t j) const { return data[i+j*ld]; }
+  virtual ~MatrixConstView()
+  {
+  };
+  inline size_t
+  getRows() const
+  {
+    return rows;
+  }
+  inline size_t
+  getCols() const
+  {
+    return cols;
+  }
+  inline size_t
+  getLd() const
+  {
+    return ld;
+  }
+  inline const double *
+  getData() const
+  {
+    return data;
+  }
+  inline const double &
+  operator()(size_t i, size_t j) const
+  {
+    return data[i+j*ld];
+  }
 };
 
 std::ostream &operator<<(std::ostream &out, const Matrix &M);
@@ -561,9 +647,9 @@ namespace mat
 
     if (vToRows.size() == 0 && vToCols.size() == 0 && vrows.size() == 0 && vcols.size() == 0)
       a = b;
-    else if (vToRows.size() == 0 && vrows.size() == 0)                                                                                                                                                                                                                                                                                                                                            // just reorder columns
+    else if (vToRows.size() == 0 && vrows.size() == 0)                                                                                                                                                                                                                                                                                                                                                                                                    // just reorder columns
       reorderColumnsByVectors(a, vToCols, b, vcols);
-    else if (vToCols.size() == 0 && vcols.size() == 0)                                                                                                                                                                                                                                                                                                                                            // just reorder rows
+    else if (vToCols.size() == 0 && vcols.size() == 0)                                                                                                                                                                                                                                                                                                                                                                                                    // just reorder rows
       reorderRowsByVectors(a, vToRows, b, vrows);
     else
       {
diff --git a/mex/sources/estimation/libmat/QRDecomposition.hh b/mex/sources/estimation/libmat/QRDecomposition.hh
index d8022a7e5cc66d60fd971f9865a3345b6021081f..d77c2baaff754a3fe81396812e040761e14d1acb 100644
--- a/mex/sources/estimation/libmat/QRDecomposition.hh
+++ b/mex/sources/estimation/libmat/QRDecomposition.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -41,7 +41,8 @@ public:
     \param[in] cols2_arg Number of columns of the matrix to be multiplied by Q
   */
   QRDecomposition(size_t rows_arg, size_t cols_arg, size_t cols2_arg);
-  virtual ~QRDecomposition();
+  virtual
+  ~QRDecomposition();
   //! Performs the QR decomposition of a matrix, and left-multiplies another matrix by Q
   /*!
     \param[in,out] A On input, the matrix to be decomposed. On output, equals to the output of dgeqrf
diff --git a/mex/sources/estimation/libmat/Vector.hh b/mex/sources/estimation/libmat/Vector.hh
index d020beaf4664698f0cbeca6aa158ca56921be9fd..f4c71c404500d55c0fea04df0e93c3e2f697e188 100644
--- a/mex/sources/estimation/libmat/Vector.hh
+++ b/mex/sources/estimation/libmat/Vector.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -63,17 +63,47 @@ private:
 public:
   Vector(size_t size_arg);
   Vector(const Vector &arg);
-  virtual ~Vector();
-  inline size_t getSize() const { return size; }
-  inline size_t getStride() const { return 1; }
-  inline double *getData() { return data; }
-  inline const double *getData() const { return data; }
-  inline void setAll(double val) { std::fill_n(data, size, val); }
-  inline double &operator() (size_t i) { return data[i]; }
-  inline const double &operator() (size_t i) const { return data[i]; }
+  virtual
+  ~Vector();
+  inline size_t
+  getSize() const
+  {
+    return size;
+  }
+  inline size_t
+  getStride() const
+  {
+    return 1;
+  }
+  inline double *
+  getData()
+  {
+    return data;
+  }
+  inline const double *
+  getData() const
+  {
+    return data;
+  }
+  inline void
+  setAll(double val)
+  {
+    std::fill_n(data, size, val);
+  }
+  inline double &
+  operator()(size_t i)
+  {
+    return data[i];
+  }
+  inline const double &
+  operator()(size_t i) const
+  {
+    return data[i];
+  }
   //! Assignment operator, only works for vectors of same size
   template<class Vec>
-  Vector &operator=(const Vec &arg)
+  Vector &
+  operator=(const Vec &arg)
   {
     assert(size == arg.getSize());
     const double *p2 = arg.getData();
@@ -99,25 +129,52 @@ private:
 public:
   VectorView(double *data_arg, size_t size_arg, size_t stride_arg);
   /* Can't use a template for the 2 constructors below: this would override the
-  constructor which uses a pointer, because the argument list is the same */
+     constructor which uses a pointer, because the argument list is the same */
   VectorView(Vector &arg, size_t offset, size_t size_arg);
   VectorView(VectorView &arg, size_t offset, size_t size_arg);
-  virtual ~VectorView(){};
-  inline size_t getSize() const { return size; }
-  inline size_t getStride() const { return stride; }
-  inline double *getData() { return data; }
-  inline const double *getData() const { return data; }
-  inline void setAll(double val)
+  virtual ~VectorView()
+  {
+  };
+  inline size_t
+  getSize() const
+  {
+    return size;
+  }
+  inline size_t
+  getStride() const
+  {
+    return stride;
+  }
+  inline double *
+  getData()
+  {
+    return data;
+  }
+  inline const double *
+  getData() const
+  {
+    return data;
+  }
+  inline void
+  setAll(double val)
   {
     for (double *p = data; p < data + size*stride; p += stride)
       *p = val;
   }
-  inline double &operator() (size_t i) { return data[i*stride]; }
-  inline const double &operator() (size_t i) const { return data[i*stride]; }
+  inline double &
+  operator()(size_t i)
+  {
+    return data[i*stride];
+  }
+  inline const double &
+  operator()(size_t i) const
+  {
+    return data[i*stride];
+  }
   //! Assignment operator, only works for vectors of same size
   template<class Vec>
   VectorView &
-  operator= (const Vec &arg)
+  operator=(const Vec &arg)
   {
     assert(size == arg.getSize());
     double *p1;
@@ -145,11 +202,29 @@ public:
   VectorConstView(const VectorView &arg, size_t offset, size_t size_arg);
   VectorConstView(const VectorConstView &arg, size_t offset, size_t size_arg);
 
-  virtual ~VectorConstView() {};
-  inline size_t getSize() const { return size; }
-  inline size_t getStride() const { return stride; }
-  inline const double *getData() const { return data; }
-  inline const double &operator() (size_t i) const { return data[i*stride]; }
+  virtual ~VectorConstView()
+  {
+  };
+  inline size_t
+  getSize() const
+  {
+    return size;
+  }
+  inline size_t
+  getStride() const
+  {
+    return stride;
+  }
+  inline const double *
+  getData() const
+  {
+    return data;
+  }
+  inline const double &
+  operator()(size_t i) const
+  {
+    return data[i*stride];
+  }
 };
 
 std::ostream &operator<<(std::ostream &out, const Vector &V);
diff --git a/mex/sources/estimation/logMHMCMCposterior.cc b/mex/sources/estimation/logMHMCMCposterior.cc
index 5fd7faaae7a8b7ea5eb512e4e13cc1160ac0d844..6551701d8677ebacd40724773a27e0ead1057809 100644
--- a/mex/sources/estimation/logMHMCMCposterior.cc
+++ b/mex/sources/estimation/logMHMCMCposterior.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -47,7 +47,11 @@ public:
   LogMHMCMCposteriorMexErrMsgTxtException(const std::string &msg) : errMsg(msg)
   {
   }
-  inline const char *getErrMsg() { return errMsg.c_str(); }
+  inline const char *
+  getErrMsg()
+  {
+    return errMsg.c_str();
+  }
 };
 
 void
@@ -279,7 +283,7 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh,
               // new or different size result arrays/matrices
               currInitSizeArray = (size_t) InitSizeArray(b-1);
               if (mxMhLogPostDensPtr)
-                mxDestroyArray(mxMhLogPostDensPtr);                                                                                                          // log post density array
+                mxDestroyArray(mxMhLogPostDensPtr);                                                                                                                                                                // log post density array
               mxMhLogPostDensPtr = mxCreateDoubleMatrix(currInitSizeArray, 1, mxREAL);
               if (mxMhLogPostDensPtr == NULL)
                 {
@@ -287,7 +291,7 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh,
                   return (-1);
                 }
               if (mxMhParamDrawsPtr)
-                mxDestroyArray(mxMhParamDrawsPtr);                                                                                                        // accepted MCMC MH draws
+                mxDestroyArray(mxMhParamDrawsPtr);                                                                                                                                                             // accepted MCMC MH draws
               mxMhParamDrawsPtr =  mxCreateDoubleMatrix(currInitSizeArray, npar,  mxREAL);
               if (mxMhParamDrawsPtr == NULL)
                 {
@@ -375,7 +379,7 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh,
               // new or different size result arrays/matrices
               currInitSizeArray = (size_t) InitSizeArray(b-1);
               if (mxMhLogPostDensPtr)
-                mxDestroyArray(mxMhLogPostDensPtr);                                                                                                          // log post density array
+                mxDestroyArray(mxMhLogPostDensPtr);                                                                                                                                                                // log post density array
               mxMhLogPostDensPtr = mxCreateDoubleMatrix(currInitSizeArray, 1, mxREAL);
               if (mxMhLogPostDensPtr == NULL)
                 {
@@ -383,7 +387,7 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh,
                   return (-1);
                 }
               if (mxMhParamDrawsPtr)
-                mxDestroyArray(mxMhParamDrawsPtr);                                                                                                        // accepted MCMC MH draws
+                mxDestroyArray(mxMhParamDrawsPtr);                                                                                                                                                             // accepted MCMC MH draws
               mxMhParamDrawsPtr =  mxCreateDoubleMatrix(currInitSizeArray, npar,  mxREAL);
               if (mxMhParamDrawsPtr == NULL)
                 {
@@ -603,9 +607,9 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh,
 
  cleanup:
   if (mxMhLogPostDensPtr)
-    mxDestroyArray(mxMhLogPostDensPtr);                                            // delete log post density array
+    mxDestroyArray(mxMhLogPostDensPtr);                                                                                      // delete log post density array
   if (mxMhParamDrawsPtr)
-    mxDestroyArray(mxMhParamDrawsPtr);                                            // delete accepted MCMC MH draws
+    mxDestroyArray(mxMhParamDrawsPtr);                                                                                     // delete accepted MCMC MH draws
 
 #ifdef MATLAB_MEX_FILE
   // Waitbar
@@ -631,7 +635,7 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh,
 int
 logMCMCposterior(VectorConstView &estParams, const MatrixConstView &data,
                  const size_t fblock, const size_t nBlocks, const VectorConstView &nMHruns, const MatrixConstView &D,
-		 VectorView &steadyState, VectorView &deepParams, MatrixView &Q, Matrix &H)
+                 VectorView &steadyState, VectorView &deepParams, MatrixView &Q, Matrix &H)
 {
   // Retrieve pointers to global variables
   const mxArray *M_ = mexGetVariablePtr("global", "M_");
@@ -712,7 +716,6 @@ logMCMCposterior(VectorConstView &estParams, const MatrixConstView &data,
                     estParamsInfo);
   EstimatedParametersDescription epd(estSubsamples, estParamsInfo);
 
-
   bool noconstant = (bool) *mxGetPr(mxGetField(options_, 0, "noconstant"));
 
   // Allocate LogPosteriorDensity object
@@ -771,20 +774,20 @@ mexFunction(int nlhs, mxArray *plhs[],
 
   assert(nMHruns.getSize() == nBlocks);
 
-  mxArray *dataset_data = mxGetField(dataset,0,"data");
+  mxArray *dataset_data = mxGetField(dataset, 0, "data");
   MatrixConstView data(mxGetPr(dataset_data), mxGetM(dataset_data), mxGetN(dataset_data), mxGetM(dataset_data));
 
-  int endo_nbr = *(int*)mxGetPr(mxGetField(M_, 0, "endo_nbr"));
-  int exo_nbr = *(int*)mxGetPr(mxGetField(M_, 0, "exo_nbr"));
-  int param_nbr = *(int*)mxGetPr(mxGetField(M_, 0, "param_nbr"));
+  int endo_nbr = *(int *) mxGetPr(mxGetField(M_, 0, "endo_nbr"));
+  int exo_nbr = *(int *) mxGetPr(mxGetField(M_, 0, "exo_nbr"));
+  int param_nbr = *(int *) mxGetPr(mxGetField(M_, 0, "param_nbr"));
   int varobs_nbr = mxGetN(mxGetField(options_, 0, "varobs"));
 
-  VectorView steadyState(mxGetPr(mxGetField(oo_,0,"steady_state")),endo_nbr, 1);
-  VectorView deepParams(mxGetPr(mxGetField(M_, 0, "params")),param_nbr,1);
+  VectorView steadyState(mxGetPr(mxGetField(oo_, 0, "steady_state")), endo_nbr, 1);
+  VectorView deepParams(mxGetPr(mxGetField(M_, 0, "params")), param_nbr, 1);
 
   MatrixView Q(mxGetPr(mxGetField(M_, 0, "Sigma_e")), exo_nbr, exo_nbr, exo_nbr);
 
-  Matrix H(varobs_nbr,varobs_nbr);
+  Matrix H(varobs_nbr, varobs_nbr);
   const mxArray *H_mx = mxGetField(M_, 0, "H");
   if (mxGetM(H_mx) == 1 && mxGetN(H_mx) == 1 && *mxGetPr(H_mx) == 0)
     H.setAll(0.0);
diff --git a/mex/sources/estimation/logposterior.cc b/mex/sources/estimation/logposterior.cc
index 641244ce490b517039a253040824c8e1d0723a0b..95e4e3cbe50c397d4a97c6329ab198e1eb7dfa55 100644
--- a/mex/sources/estimation/logposterior.cc
+++ b/mex/sources/estimation/logposterior.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -36,7 +36,11 @@ public:
   LogposteriorMexErrMsgTxtException(const std::string &msg) : errMsg(msg)
   {
   }
-  inline const char *getErrMsg() { return errMsg.c_str(); }
+  inline const char *
+  getErrMsg()
+  {
+    return errMsg.c_str();
+  }
 };
 
 void
@@ -103,8 +107,8 @@ template <class VEC1, class VEC2>
 double
 logposterior(VEC1 &estParams, const MatrixConstView &data,
              const mxArray *options_, const mxArray *M_, const mxArray *estim_params_,
-	     const mxArray *bayestopt_, const mxArray *oo_, VEC2 &steadyState, double *trend_coeff,
-	     VectorView &deepParams, Matrix &H, MatrixView &Q)
+             const mxArray *bayestopt_, const mxArray *oo_, VEC2 &steadyState, double *trend_coeff,
+             VectorView &deepParams, Matrix &H, MatrixView &Q)
 {
   double loglinear = *mxGetPr(mxGetField(options_, 0, "loglinear"));
   if (loglinear == 1)
@@ -203,10 +207,10 @@ void
 mexFunction(int nlhs, mxArray *plhs[],
             int nrhs, const mxArray *prhs[])
 {
-  if (nrhs != 7 )
+  if (nrhs != 7)
     DYN_MEX_FUNC_ERR_MSG_TXT("logposterior: exactly 7 input arguments are required.");
 
-  if (nlhs > 9 )
+  if (nlhs > 9)
     DYN_MEX_FUNC_ERR_MSG_TXT("logposterior returns 8 output arguments at the most.");
 
   // Check and retrieve the RHS arguments
@@ -219,9 +223,9 @@ mexFunction(int nlhs, mxArray *plhs[],
   for (int i = 1; i < 7; ++i)
     if (!mxIsStruct(prhs[i]))
       {
-	std::stringstream msg;
-	msg << "logposterior: argument " << i+1 << " must be a Matlab structure";
-	DYN_MEX_FUNC_ERR_MSG_TXT(msg.str().c_str());
+        std::stringstream msg;
+        msg << "logposterior: argument " << i+1 << " must be a Matlab structure";
+        DYN_MEX_FUNC_ERR_MSG_TXT(msg.str().c_str());
       }
 
   const mxArray *dataset = prhs[1];
@@ -231,7 +235,7 @@ mexFunction(int nlhs, mxArray *plhs[],
   const mxArray *bayestopt_ = prhs[5];
   const mxArray *oo_ = prhs[6];
 
-  const mxArray *dataset_data = mxGetField(dataset,0,"data");
+  const mxArray *dataset_data = mxGetField(dataset, 0, "data");
   MatrixConstView data(mxGetPr(dataset_data), mxGetM(dataset_data), mxGetN(dataset_data), mxGetM(dataset_data));
 
   // Creaete LHS arguments
@@ -251,12 +255,12 @@ mexFunction(int nlhs, mxArray *plhs[],
   double *lik = mxGetPr(plhs[0]);
   double *exit_flag = mxGetPr(plhs[1]);
 
-  VectorView steadyState(mxGetPr(mxGetField(oo_,0,"steady_state")),endo_nbr, 1);
-  VectorView deepParams(mxGetPr(mxGetField(M_, 0, "params")),param_nbr,1);
+  VectorView steadyState(mxGetPr(mxGetField(oo_, 0, "steady_state")), endo_nbr, 1);
+  VectorView deepParams(mxGetPr(mxGetField(M_, 0, "params")), param_nbr, 1);
 
   MatrixView Q(mxGetPr(mxGetField(M_, 0, "Sigma_e")), exo_nbr, exo_nbr, exo_nbr);
 
-  Matrix H(varobs_nbr,varobs_nbr);
+  Matrix H(varobs_nbr, varobs_nbr);
   const mxArray *H_mx = mxGetField(M_, 0, "H");
   if (mxGetM(H_mx) == 1 && mxGetN(H_mx) == 1 && *mxGetPr(H_mx) == 0)
     H.setAll(0.0);
@@ -270,7 +274,7 @@ mexFunction(int nlhs, mxArray *plhs[],
   try
     {
       *lik = logposterior(estParams, data, options_, M_, estim_params_, bayestopt_, oo_,
-				steadyState, trend_coeff, deepParams, H, Q);
+                          steadyState, trend_coeff, deepParams, H, Q);
       *info_mx = 0;
       *exit_flag = 0;
     }
diff --git a/mex/sources/estimation/tests/testInitKalman.cc b/mex/sources/estimation/tests/testInitKalman.cc
index 37884a6cc39317a5ca416c7fed1e61a8ab852e03..28139ccdb5c2961aab9ea10de200964541bc554f 100644
--- a/mex/sources/estimation/tests/testInitKalman.cc
+++ b/mex/sources/estimation/tests/testInitKalman.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -147,4 +147,3 @@ main(int argc, char **argv)
   std::cout << "Matrix Pinf: " << std::endl << Pinf << std::endl;
 
 }
-
diff --git a/mex/sources/estimation/tests/testKalman.cc b/mex/sources/estimation/tests/testKalman.cc
index cd1401c6959e5531fd06d9dfd2fa927d25be296c..f75f3459e8aa3c3fe9ce6963a0eb523493c80862 100644
--- a/mex/sources/estimation/tests/testKalman.cc
+++ b/mex/sources/estimation/tests/testKalman.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -130,4 +130,3 @@ main(int argc, char **argv)
 
   std::cout << "ll: " << std::endl << ll << std::endl;
 }
-
diff --git a/mex/sources/estimation/utils/dynamic_dll.cc b/mex/sources/estimation/utils/dynamic_dll.cc
index b50d67c414773eda997937b0a6e03d2972935167..e9d126d9e432bf3e7a279bc0c61fe2c5a4dcad68 100644
--- a/mex/sources/estimation/utils/dynamic_dll.cc
+++ b/mex/sources/estimation/utils/dynamic_dll.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -88,4 +88,3 @@ DynamicModelDLL::~DynamicModelDLL()
   dlclose(dynamicHinstance);
 #endif
 }
-
diff --git a/mex/sources/estimation/utils/dynamic_dll.hh b/mex/sources/estimation/utils/dynamic_dll.hh
index 36f5b9ec30eb7306737e331584584149b4bfff98..5e19472eec5385ec02cfc364402dfc238ee344af 100644
--- a/mex/sources/estimation/utils/dynamic_dll.hh
+++ b/mex/sources/estimation/utils/dynamic_dll.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -32,9 +32,8 @@
 #include "ts_exception.h"
 
 // <model>_Dynamic DLL pointer
-typedef void (*DynamicFn)
-(const double *y, const double *x, int nb_row_x, const double *params, const double *steady_state,
- int it_, double *residual, double *g1, double *g2, double *g3);
+typedef void (*DynamicFn)(const double *y, const double *x, int nb_row_x, const double *params, const double *steady_state,
+                          int it_, double *residual, double *g1, double *g2, double *g3);
 
 /**
  * creates pointer to Dynamic function inside <model>_dynamic.dll
@@ -53,12 +52,14 @@ private:
 public:
   // construct and load Dynamic model DLL
   DynamicModelDLL(const std::string &basename) throw (TSException);
-  virtual ~DynamicModelDLL();
+  virtual
+  ~DynamicModelDLL();
 
   //! evaluate Dynamic model DLL
   template<class Vec1, class Vec2, class Vec3, class Vec4, class Mat1>
-  void eval(const Vec1 &y, const Mat1 &x, const Vec2 &modParams, const Vec3 &ySteady,
-            Vec4 &residual, Matrix *g1, Matrix *g2, Matrix *g3) throw (TSException)
+  void
+  eval(const Vec1 &y, const Mat1 &x, const Vec2 &modParams, const Vec3 &ySteady,
+       Vec4 &residual, Matrix *g1, Matrix *g2, Matrix *g3) throw (TSException)
   {
     assert(y.getStride() == 1);
     assert(x.getLd() == x.getRows());
@@ -70,6 +71,6 @@ public:
     assert(g3->getLd() == g3->getRows());
 
     Dynamic(y.getData(), x.getData(), 1, modParams.getData(), ySteady.getData(), 0, residual.getData(),
-	    g1 == NULL ? NULL : g1->getData(), g2 == NULL ? NULL : g2->getData(), g3 == NULL ? NULL : g3->getData());
+            g1 == NULL ? NULL : g1->getData(), g2 == NULL ? NULL : g2->getData(), g3 == NULL ? NULL : g3->getData());
   };
 };
diff --git a/mex/sources/estimation/utils/static_dll.hh b/mex/sources/estimation/utils/static_dll.hh
index 77f183890aa45f5399ed7df406c7e48dbf187cf9..36b28a9f249576b39c94e0aa3b9d35f519fee7a1 100644
--- a/mex/sources/estimation/utils/static_dll.hh
+++ b/mex/sources/estimation/utils/static_dll.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -32,8 +32,7 @@
 #include "ts_exception.h"
 
 // Pointer to the Static function in the MEX
-typedef void (*StaticFn)
-(const double *y, const double *x, int nb_row_x, const double *params, double *residual, double *g1, double *v2);
+typedef void (*StaticFn)(const double *y, const double *x, int nb_row_x, const double *params, double *residual, double *g1, double *v2);
 
 /**
  * creates pointer to Dynamic function inside <model>_static.dll
@@ -52,12 +51,14 @@ private:
 public:
   // construct and load Static model DLL
   StaticModelDLL(const std::string &basename) throw (TSException);
-  virtual ~StaticModelDLL();
+  virtual
+  ~StaticModelDLL();
 
   //! evaluate Static model DLL
   template<class Vec1, class Vec2, class Vec3, class Mat1>
-  void eval(const Vec1 &y, const Mat1 &x, const Vec2 &modParams,
-            Vec3 &residual, Matrix *g1, Matrix *v2) throw (TSException)
+  void
+  eval(const Vec1 &y, const Mat1 &x, const Vec2 &modParams,
+       Vec3 &residual, Matrix *g1, Matrix *v2) throw (TSException)
   {
     assert(y.getStride() == 1);
     assert(x.getLd() == x.getRows());
@@ -67,6 +68,6 @@ public:
     assert(v2->getLd() == v2->getRows());
 
     Static(y.getData(), x.getData(), 1, modParams.getData(), residual.getData(),
-	    g1 == NULL ? NULL : g1->getData(), v2 == NULL ? NULL : v2->getData());
+           g1 == NULL ? NULL : g1->getData(), v2 == NULL ? NULL : v2->getData());
   };
 };
diff --git a/mex/sources/estimation/utils/ts_exception.h b/mex/sources/estimation/utils/ts_exception.h
index b0f8ca71a0c49e0f243765ad7deb8e323fa0c34e..c3d3ea3c7795196857ff09c94d8506bc16892d2d 100644
--- a/mex/sources/estimation/utils/ts_exception.h
+++ b/mex/sources/estimation/utils/ts_exception.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -70,4 +70,3 @@ public:
 
 ;
 #endif
-
diff --git a/mex/sources/k_order_perturbation/dynamic_dll.hh b/mex/sources/k_order_perturbation/dynamic_dll.hh
index cf3755058e005ee2d83dcca74dc4694dd76062a7..15b4acfe90d10db84a30ff55c2b0bbb99da49017 100644
--- a/mex/sources/k_order_perturbation/dynamic_dll.hh
+++ b/mex/sources/k_order_perturbation/dynamic_dll.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008-2012 Dynare Team
+ * Copyright (C) 2008-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -35,9 +35,8 @@
 #include "dynare_exception.h"
 
 // <model>_Dynamic DLL pointer
-typedef void (*DynamicDLLFn)
-(const double *y, const double *x, int nb_row_x, const double *params, const double *steady_state,
- int it_, double *residual, double *g1, double *g2, double *g3);
+typedef void (*DynamicDLLFn)(const double *y, const double *x, int nb_row_x, const double *params, const double *steady_state,
+                             int it_, double *residual, double *g1, double *g2, double *g3);
 
 /**
  * creates pointer to Dynamic function inside <model>_dynamic.dll
@@ -56,7 +55,8 @@ private:
 public:
   // construct and load Dynamic model DLL
   DynamicModelDLL(const string &fname) throw (DynareException);
-  virtual ~DynamicModelDLL();
+  virtual
+  ~DynamicModelDLL();
 
   void eval(const Vector &y, const Vector &x, const Vector &params, const Vector &ySteady,
             Vector &residual, TwoDMatrix *g1, TwoDMatrix *g2, TwoDMatrix *g3) throw (DynareException);
diff --git a/mex/sources/k_order_perturbation/dynamic_m.hh b/mex/sources/k_order_perturbation/dynamic_m.hh
index 632dcdd7acd157585748e3cb9cde434bf49ebdc3..260d07ef80c182583c800a011c485d1273eaa79d 100644
--- a/mex/sources/k_order_perturbation/dynamic_m.hh
+++ b/mex/sources/k_order_perturbation/dynamic_m.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -37,7 +37,8 @@ private:
   const static int nrhs_dynamic = 5;
 public:
   DynamicModelMFile(const string &modName) throw (DynareException);
-  virtual ~DynamicModelMFile();
+  virtual
+  ~DynamicModelMFile();
   void eval(const Vector &y, const Vector &x, const Vector &params, const Vector &ySteady,
             Vector &residual, TwoDMatrix *g1, TwoDMatrix *g2, TwoDMatrix *g3) throw (DynareException);
 };
diff --git a/mex/sources/k_order_perturbation/k_ord_dynare.cc b/mex/sources/k_order_perturbation/k_ord_dynare.cc
index 5f7572a94ff179e6fedba379ea14fb0fe965fd3d..7602b550d2308c32e927b706b8c8359bc1e51d33 100644
--- a/mex/sources/k_order_perturbation/k_ord_dynare.cc
+++ b/mex/sources/k_order_perturbation/k_ord_dynare.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008-2014 Dynare Team
+ * Copyright (C) 2008-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -63,7 +63,7 @@ KordpDynare::KordpDynare(const vector<string> &endo, int num_endo,
                          const int nsteps, int norder,
                          Journal &jr, DynamicModelAC *dynamicModelFile_arg, double sstol,
                          const vector<int> &var_order, const TwoDMatrix &llincidence, double criterium,
-			 TwoDMatrix *g1_arg, TwoDMatrix *g2_arg, TwoDMatrix *g3_arg) throw (TLException) :
+                         TwoDMatrix *g1_arg, TwoDMatrix *g2_arg, TwoDMatrix *g3_arg) throw (TLException) :
   nStat(nstat), nBoth(nboth), nPred(npred), nForw(nforw), nExog(nexog), nPar(npar),
   nYs(npred + nboth), nYss(nboth + nforw), nY(num_endo), nJcols(jcols), NNZD(nnzd), nSteps(nsteps),
   nOrder(norder), journal(jr), ySteady(ysteady), params(inParams), vCov(vcov),
@@ -116,30 +116,30 @@ KordpDynare::calcDerivativesAtSteady()
     {
       g1p = new TwoDMatrix(nY, nJcols);
       g1p->zeros();
-      
+
       if (nOrder > 1)
-	{
-	  // allocate space for sparse Hessian
-	  g2p = new TwoDMatrix((int) NNZD[1], 3);
-	  g2p->zeros();
-	}
-      
+        {
+          // allocate space for sparse Hessian
+          g2p = new TwoDMatrix((int) NNZD[1], 3);
+          g2p->zeros();
+        }
+
       if (nOrder > 2)
-	{
-	  g3p = new TwoDMatrix((int) NNZD[2], 3);
-	  g3p->zeros();
-	}
+        {
+          g3p = new TwoDMatrix((int) NNZD[2], 3);
+          g3p->zeros();
+        }
 
       Vector xx(nexog());
       xx.zeros();
-      
+
       Vector out(nY);
       out.zeros();
       Vector llxSteady(nJcols-nExog);
       LLxSteady(ySteady, llxSteady);
-      
+
       dynamicModelFile->eval(llxSteady, xx, params, ySteady, out, g1p, g2p, g3p);
-                
+
     }
 
   populateDerivativesContainer(*g1p, 1, JacobianIndices);
diff --git a/mex/sources/k_order_perturbation/k_ord_dynare.hh b/mex/sources/k_order_perturbation/k_ord_dynare.hh
index 62fcc7c0fbe970b34f100c65da7e5ed2e3c6215b..b5d942f6b9c92e624e3aa560d4d9a4b73c4d20b3 100644
--- a/mex/sources/k_order_perturbation/k_ord_dynare.hh
+++ b/mex/sources/k_order_perturbation/k_ord_dynare.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008-2012 Dynare Team
+ * Copyright (C) 2008-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -135,7 +135,8 @@ public:
               const vector<int> &varOrder, const TwoDMatrix &ll_Incidence,
               double qz_criterium, TwoDMatrix *g1_arg, TwoDMatrix *g2_arg, TwoDMatrix *g3_arg) throw (TLException);
 
-  virtual ~KordpDynare();
+  virtual
+  ~KordpDynare();
   int
   nstat() const
   {
diff --git a/mex/sources/k_order_perturbation/k_order_perturbation.cc b/mex/sources/k_order_perturbation/k_order_perturbation.cc
index f2eb3f80daeea3aef18ecb0bdd65fa950430071b..1159b810bf98b6f1441b0f29d1a9d55692b5c1a3 100644
--- a/mex/sources/k_order_perturbation/k_order_perturbation.cc
+++ b/mex/sources/k_order_perturbation/k_order_perturbation.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008-2014 Dynare Team
+ * Copyright (C) 2008-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -62,14 +62,15 @@ DynareMxArrayToString(const mxArray *mxFldp, const int len, const int width, vec
         out[j] += cNamesCharStr[j+i*len];
 }
 
-void copy_derivatives(mxArray *destin,const Symmetry &sym,const FGSContainer *derivs,const std::string &fieldname)
+void
+copy_derivatives(mxArray *destin, const Symmetry &sym, const FGSContainer *derivs, const std::string &fieldname)
 {
-  const TwoDMatrix* x = derivs->get(sym);
+  const TwoDMatrix *x = derivs->get(sym);
   int n = x->numRows();
   int m = x->numCols();
   mxArray *tmp = mxCreateDoubleMatrix(n, m, mxREAL);
-  memcpy(mxGetPr(tmp),x->getData().base(),n*m*sizeof(double));
-  mxSetField(destin,0,fieldname.c_str(),tmp);
+  memcpy(mxGetPr(tmp), x->getData().base(), n*m*sizeof(double));
+  mxSetField(destin, 0, fieldname.c_str(), tmp);
 }
 
 extern "C" {
@@ -176,7 +177,7 @@ extern "C" {
     //get NNZH =NNZD(2) = the total number of non-zero Hessian elements
     mxFldp = mxGetField(M_, 0, "NNZDerivatives");
     dparams = mxGetPr(mxFldp);
-    Vector NNZD(dparams, (int) mxGetM(mxFldp));
+    Vector NNZD(dparams, (int)mxGetM(mxFldp));
     if (NNZD[kOrder-1] == -1)
       DYN_MEX_FUNC_ERR_MSG_TXT("The derivatives were not computed for the required order. Make sure that you used the right order option inside the stoch_simul command");
 
@@ -197,32 +198,31 @@ extern "C" {
     if ((nEndo != nendo) || (nExog != nexo))
       DYN_MEX_FUNC_ERR_MSG_TXT("Incorrect number of input parameters.");
 
-    TwoDMatrix *g1m=NULL;
-    TwoDMatrix *g2m=NULL;
-    TwoDMatrix *g3m=NULL;
+    TwoDMatrix *g1m = NULL;
+    TwoDMatrix *g2m = NULL;
+    TwoDMatrix *g3m = NULL;
     // derivatives passed as arguments */
-    if (nrhs > 3) 
+    if (nrhs > 3)
       {
-	const mxArray *g1 = prhs[3];
-	int m = (int) mxGetM(g1);
-	int n = (int) mxGetN(g1);
-	g1m = new TwoDMatrix(m, n, mxGetPr(g1));
-	if (nrhs > 4)
-	  {
-	    const mxArray *g2 = prhs[4];
-	    int m = (int) mxGetM(g2);
-	    int n = (int) mxGetN(g2);
-	    g2m = new TwoDMatrix(m, n, mxGetPr(g2));
-	    if (nrhs > 5)
-	      {
-		const mxArray *g3 = prhs[5];
-		int m = (int) mxGetM(g3);
-		int n = (int) mxGetN(g3);
-		g3m = new TwoDMatrix(m, n, mxGetPr(g3));
-	      }
-	  }
+        const mxArray *g1 = prhs[3];
+        int m = (int) mxGetM(g1);
+        int n = (int) mxGetN(g1);
+        g1m = new TwoDMatrix(m, n, mxGetPr(g1));
+        if (nrhs > 4)
+          {
+            const mxArray *g2 = prhs[4];
+            int m = (int) mxGetM(g2);
+            int n = (int) mxGetN(g2);
+            g2m = new TwoDMatrix(m, n, mxGetPr(g2));
+            if (nrhs > 5)
+              {
+                const mxArray *g3 = prhs[5];
+                int m = (int) mxGetM(g3);
+                int n = (int) mxGetN(g3);
+                g3m = new TwoDMatrix(m, n, mxGetPr(g3));
+              }
+          }
       }
-	    
 
     const int nSteps = 0; // Dynare++ solving steps, for time being default to 0 = deterministic steady state
     const double sstol = 1.e-13; //NL solver tolerance from
@@ -250,7 +250,7 @@ extern "C" {
                            ySteady, vCov, modParams, nStat, nPred, nForw, nBoth,
                            jcols, NNZD, nSteps, kOrder, journal, dynamicModelFile,
                            sstol, var_order_vp, llincidence, qz_criterium,
-			   g1m, g2m, g3m);
+                           g1m, g2m, g3m);
 
         // construct main K-order approximation class
 
@@ -283,40 +283,40 @@ extern "C" {
             for (map<string, ConstTwoDMatrix>::const_iterator cit = mm.begin();
                  ((cit != mm.end()) && (ii < nlhs)); ++cit)
               {
-		plhs[ii] = mxCreateDoubleMatrix((*cit).second.numRows(), (*cit).second.numCols(), mxREAL);
-		
-		// Copy Dynare++ matrix into MATLAB matrix
-		const ConstVector &vec = (*cit).second.getData();
-		assert(vec.skip() == 1);
-		memcpy(mxGetPr(plhs[ii]), vec.base(), vec.length() * sizeof(double));
-		
-		++ii;
-		
+                plhs[ii] = mxCreateDoubleMatrix((*cit).second.numRows(), (*cit).second.numCols(), mxREAL);
+
+                // Copy Dynare++ matrix into MATLAB matrix
+                const ConstVector &vec = (*cit).second.getData();
+                assert(vec.skip() == 1);
+                memcpy(mxGetPr(plhs[ii]), vec.base(), vec.length() * sizeof(double));
+
+                ++ii;
+
               }
-	    if (kOrder == 3 && nlhs > 4)
-	      {
-		const FGSContainer *derivs = app.get_rule_ders();
-		const std::string fieldnames[] = {"gy", "gu", "gyy", "gyu", "guu", "gss", 
-				      "gyyy", "gyyu", "gyuu", "guuu", "gyss", "guss"};
-		// creates the char** expected by mxCreateStructMatrix()
-		const char* c_fieldnames[12];
-		for (int i=0; i < 12;++i)
-		  c_fieldnames[i] = fieldnames[i].c_str();
-		plhs[ii] = mxCreateStructMatrix(1,1,12,c_fieldnames);
-		copy_derivatives(plhs[ii],Symmetry(1,0,0,0),derivs,"gy");
-		copy_derivatives(plhs[ii],Symmetry(0,1,0,0),derivs,"gu");
-		copy_derivatives(plhs[ii],Symmetry(2,0,0,0),derivs,"gyy");
-		copy_derivatives(plhs[ii],Symmetry(0,2,0,0),derivs,"guu");
-		copy_derivatives(plhs[ii],Symmetry(1,1,0,0),derivs,"gyu");
-		copy_derivatives(plhs[ii],Symmetry(0,0,0,2),derivs,"gss");
-		copy_derivatives(plhs[ii],Symmetry(3,0,0,0),derivs,"gyyy");
-		copy_derivatives(plhs[ii],Symmetry(0,3,0,0),derivs,"guuu");
-		copy_derivatives(plhs[ii],Symmetry(2,1,0,0),derivs,"gyyu");
-		copy_derivatives(plhs[ii],Symmetry(1,2,0,0),derivs,"gyuu");
-		copy_derivatives(plhs[ii],Symmetry(1,0,0,2),derivs,"gyss");
-		copy_derivatives(plhs[ii],Symmetry(0,1,0,2),derivs,"guss");
-	      }
-	  }
+            if (kOrder == 3 && nlhs > 4)
+              {
+                const FGSContainer *derivs = app.get_rule_ders();
+                const std::string fieldnames[] = {"gy", "gu", "gyy", "gyu", "guu", "gss",
+                                                  "gyyy", "gyyu", "gyuu", "guuu", "gyss", "guss"};
+                // creates the char** expected by mxCreateStructMatrix()
+                const char *c_fieldnames[12];
+                for (int i = 0; i < 12; ++i)
+                  c_fieldnames[i] = fieldnames[i].c_str();
+                plhs[ii] = mxCreateStructMatrix(1, 1, 12, c_fieldnames);
+                copy_derivatives(plhs[ii], Symmetry(1, 0, 0, 0), derivs, "gy");
+                copy_derivatives(plhs[ii], Symmetry(0, 1, 0, 0), derivs, "gu");
+                copy_derivatives(plhs[ii], Symmetry(2, 0, 0, 0), derivs, "gyy");
+                copy_derivatives(plhs[ii], Symmetry(0, 2, 0, 0), derivs, "guu");
+                copy_derivatives(plhs[ii], Symmetry(1, 1, 0, 0), derivs, "gyu");
+                copy_derivatives(plhs[ii], Symmetry(0, 0, 0, 2), derivs, "gss");
+                copy_derivatives(plhs[ii], Symmetry(3, 0, 0, 0), derivs, "gyyy");
+                copy_derivatives(plhs[ii], Symmetry(0, 3, 0, 0), derivs, "guuu");
+                copy_derivatives(plhs[ii], Symmetry(2, 1, 0, 0), derivs, "gyyu");
+                copy_derivatives(plhs[ii], Symmetry(1, 2, 0, 0), derivs, "gyuu");
+                copy_derivatives(plhs[ii], Symmetry(1, 0, 0, 2), derivs, "gyss");
+                copy_derivatives(plhs[ii], Symmetry(0, 1, 0, 2), derivs, "guss");
+              }
+          }
       }
     catch (const KordException &e)
       {
diff --git a/mex/sources/kronecker/sparse_hessian_times_B_kronecker_C.cc b/mex/sources/kronecker/sparse_hessian_times_B_kronecker_C.cc
index d4f50cc57d6096d4fb42bf4045cdc57cc5a5a84e..492a18ff6cf087adaa42a87f79e3586604399a05 100644
--- a/mex/sources/kronecker/sparse_hessian_times_B_kronecker_C.cc
+++ b/mex/sources/kronecker/sparse_hessian_times_B_kronecker_C.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2011 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -143,7 +143,7 @@ void
 mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
 {
   // Check input and output:
-  if ((nrhs > 4) || (nrhs < 3) )
+  if ((nrhs > 4) || (nrhs < 3))
     DYN_MEX_FUNC_ERR_MSG_TXT("sparse_hessian_times_B_kronecker_C takes 3 or 4 input arguments and provides 2 output arguments.");
 
   if (!mxIsSparse(prhs[0]))
diff --git a/mex/sources/linsolve/linsolve.cc b/mex/sources/linsolve/linsolve.cc
index b33cf2f4564496715f367757e8539c03dfd24291..c8e55eecbc1052f7952393f31e02a533596f2bec 100644
--- a/mex/sources/linsolve/linsolve.cc
+++ b/mex/sources/linsolve/linsolve.cc
@@ -10,7 +10,7 @@
  */
 
 /*
- * Copyright (C) 2012-2013 Dynare Team
+ * Copyright (C) 2012-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -28,7 +28,6 @@
  * along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
  */
 
-
 #include <octave/oct.h>
 #include <octave/ov-struct.h>
 
@@ -81,10 +80,9 @@ If requested, @var{r} will contain the reciprocal condition number.\n\
       return retval;
     }
 
-  
   MatrixType typA;
   typA.mark_as_full();
-  
+
   bool transa = false;
   if (nargin == 3)
     {
diff --git a/mex/sources/local_state_space_iterations/local_state_space_iteration_2.cc b/mex/sources/local_state_space_iterations/local_state_space_iteration_2.cc
index de78ff2e4503de2933df1229008fd812a8b96a96..3b45d193a67073211136743646818af3e7a433a9 100644
--- a/mex/sources/local_state_space_iterations/local_state_space_iteration_2.cc
+++ b/mex/sources/local_state_space_iterations/local_state_space_iteration_2.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2013 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -29,23 +29,24 @@
 #include <dynblas.h>
 
 #ifdef USE_OMP
-#include <omp.h>
+# include <omp.h>
 #endif
 
 using namespace std;
 
 #define FIRST_ORDER_LOOP 1// Comment out this line to use mkl-blas instead of loops when computing ghx*yhat and ghu*epsilon
 
-void set_vector_of_indices(const int n, const int r, vector<int> &v1, vector<int> &v2, vector<int> &v3)
+void
+set_vector_of_indices(const int n, const int r, vector<int> &v1, vector<int> &v2, vector<int> &v3)
 {
   const int m = n*(n+1)/2;
-  v1.resize(m,0);
-  v2.resize(m,0);
-  v3.resize(m,0);
-  for(int i=0, index=0, jndex=0;i<n; i++)
+  v1.resize(m, 0);
+  v2.resize(m, 0);
+  v3.resize(m, 0);
+  for (int i = 0, index = 0, jndex = 0; i < n; i++)
     {
-      jndex+=i;
-      for(int j=i; j<n; j++, index++, jndex++)
+      jndex += i;
+      for (int j = i; j < n; j++, index++, jndex++)
         {
           v1[index] = i;
           v2[index] = j;
@@ -54,191 +55,191 @@ void set_vector_of_indices(const int n, const int r, vector<int> &v1, vector<int
     }
 }
 
-void ss2Iteration_pruning(double* y2, double* y1, const double* yhat2, const double* yhat1, const double *epsilon,
-                  double* ghx, double* ghu,
-                  const double* constant, const double* ghxx, const double* ghuu, const double* ghxu, const double* ss,
-			  const blas_int m, const blas_int n, const blas_int q, const blas_int s, const int number_of_threads)
+void
+ss2Iteration_pruning(double *y2, double *y1, const double *yhat2, const double *yhat1, const double *epsilon,
+                     double *ghx, double *ghu,
+                     const double *constant, const double *ghxx, const double *ghuu, const double *ghxu, const double *ss,
+                     const blas_int m, const blas_int n, const blas_int q, const blas_int s, const int number_of_threads)
 {
-  #ifndef FIRST_ORDER_LOOP
-      const char transpose[2] = "N";
-      const double one = 1.0;
-      const blas_int ONE = 1;
-  #endif
+#ifndef FIRST_ORDER_LOOP
+  const char transpose[2] = "N";
+  const double one = 1.0;
+  const blas_int ONE = 1;
+#endif
   vector<int> ii1, ii2, ii3;// vector indices for ghxx
   vector<int> jj1, jj2, jj3;// vector indices for ghuu
   set_vector_of_indices(n, m, ii1, ii2, ii3);
   set_vector_of_indices(q, m, jj1, jj2, jj3);
-  #ifdef USE_OMP
-  #pragma omp parallel for num_threads(number_of_threads)
-  #endif
-  for (int particle = 0; particle<s; particle++)
-  {
-    int particle_ = particle*m;
-    int particle__ = particle*n;
-    int particle___ = particle*q;
-    memcpy(&y2[particle_],&constant[0],m*sizeof(double));
-    memcpy(&y1[particle_],&ss[0],m*sizeof(double));
-    #ifndef FIRST_ORDER_LOOP
-        dgemv(transpose,&m,&n,&one,&ghx[0],&m,&yhat2[particle__],&ONE,&one,&y2[particle_],&ONE);
-	dgemv(transpose,&m,&q,&one,&ghu[0],&m,&epsilon[particle___],&ONE,&one,&y2[particle_],&ONE);
-    #endif
-    for (int variable = 0; variable<m; variable++)
-      {
-        int variable_ = variable + particle_;
-        // +ghx*yhat2+ghu*u
-        #ifdef FIRST_ORDER_LOOP
-            for (int column = 0, column_=0; column<q; column++, column_ += m)
-	      {
-		int i1 = variable+column_;
-		int i2 = column+particle__;
-		int i3 = column+particle___;
-		y2[variable_] += ghx[i1]*yhat2[i2];
-		y2[variable_] += ghu[i1]*epsilon[i3];
-	      }
-	    for (int column = q, column_=q*m; column<n; column++, column_ += m)
-	      {
-		y2[variable_] += ghx[variable+column_]*yhat2[column+particle__];
-	      }
-        #endif
-        // +ghxx*kron(yhat1,yhat1)
-        for(int i=0; i<n*(n+1)/2; i++)
-          {
-            int i1 = particle__+ii1[i];
-            int i2 = particle__+ii2[i];
-            if(i1==i2)
-              {
-                y2[variable_] += .5*ghxx[variable+ii3[i]]*yhat1[i1]*yhat1[i1];
-              }
-            else
-              {
-                y2[variable_] += ghxx[variable+ii3[i]]*yhat1[i1]*yhat1[i2];
-              }
-          }
-        // +ghuu*kron(u,u)
-        for(int j=0; j<q*(q+1)/2; j++)
-          {
-            int j1 = particle___+jj1[j];
-            int j2 = particle___+jj2[j];
-            if(j1==j2)
-              {
-                y2[variable_] += .5*ghuu[variable+jj3[j]]*epsilon[j1]*epsilon[j1];
-              }
-            else
-              {
-                y2[variable_] += ghuu[variable+jj3[j]]*epsilon[j1]*epsilon[j2];
-              }
-          }
-        // +ghxu*kron(yhat1,u)
-        for (int v = particle__, i = 0; v<particle__+n; v++)
-          for (int s = particle___; s<particle___+q; s++, i += m)
-            y2[variable_] += ghxu[variable+i]*epsilon[s]*yhat2[v];
-            #ifdef FIRST_ORDER_LOOP
-                for (int column = 0, column_=0; column<q; column++, column_ += m)
-		  {
-		    int i1 = variable+column_;
-		    int i2 = column+particle__;
-		    int i3 = column+particle___;
-		    y1[variable_] += ghx[i1]*yhat1[i2];
-		    y1[variable_] += ghu[i1]*epsilon[i3];
-		  }
-		for (int column = q, column_=q*m; column<n; column++, column_ += m)
-		  {
-		    y1[variable_] += ghx[variable+column_]*yhat1[column+particle__];
-		  }
-            #endif
-      }
-      #ifndef FIRST_ORDER_LOOP
-          dgemv(transpose,&m,&n,&one,&ghx[0],&m,&yhat1[particle__],&ONE,&one,&y1[particle_],&ONE);
-	  dgemv(transpose,&m,&q,&one,&ghu[0],&m,&epsilon[particle___],&ONE,&one,&y1[particle_],&ONE);
-      #endif
-  }
+#ifdef USE_OMP
+# pragma omp parallel for num_threads(number_of_threads)
+#endif
+  for (int particle = 0; particle < s; particle++)
+    {
+      int particle_ = particle*m;
+      int particle__ = particle*n;
+      int particle___ = particle*q;
+      memcpy(&y2[particle_], &constant[0], m*sizeof(double));
+      memcpy(&y1[particle_], &ss[0], m*sizeof(double));
+#ifndef FIRST_ORDER_LOOP
+      dgemv(transpose, &m, &n, &one, &ghx[0], &m, &yhat2[particle__], &ONE, &one, &y2[particle_], &ONE);
+      dgemv(transpose, &m, &q, &one, &ghu[0], &m, &epsilon[particle___], &ONE, &one, &y2[particle_], &ONE);
+#endif
+      for (int variable = 0; variable < m; variable++)
+        {
+          int variable_ = variable + particle_;
+          // +ghx*yhat2+ghu*u
+#ifdef FIRST_ORDER_LOOP
+          for (int column = 0, column_ = 0; column < q; column++, column_ += m)
+            {
+              int i1 = variable+column_;
+              int i2 = column+particle__;
+              int i3 = column+particle___;
+              y2[variable_] += ghx[i1]*yhat2[i2];
+              y2[variable_] += ghu[i1]*epsilon[i3];
+            }
+          for (int column = q, column_ = q*m; column < n; column++, column_ += m)
+            {
+              y2[variable_] += ghx[variable+column_]*yhat2[column+particle__];
+            }
+#endif
+          // +ghxx*kron(yhat1,yhat1)
+          for (int i = 0; i < n*(n+1)/2; i++)
+            {
+              int i1 = particle__+ii1[i];
+              int i2 = particle__+ii2[i];
+              if (i1 == i2)
+                {
+                  y2[variable_] += .5*ghxx[variable+ii3[i]]*yhat1[i1]*yhat1[i1];
+                }
+              else
+                {
+                  y2[variable_] += ghxx[variable+ii3[i]]*yhat1[i1]*yhat1[i2];
+                }
+            }
+          // +ghuu*kron(u,u)
+          for (int j = 0; j < q*(q+1)/2; j++)
+            {
+              int j1 = particle___+jj1[j];
+              int j2 = particle___+jj2[j];
+              if (j1 == j2)
+                {
+                  y2[variable_] += .5*ghuu[variable+jj3[j]]*epsilon[j1]*epsilon[j1];
+                }
+              else
+                {
+                  y2[variable_] += ghuu[variable+jj3[j]]*epsilon[j1]*epsilon[j2];
+                }
+            }
+          // +ghxu*kron(yhat1,u)
+          for (int v = particle__, i = 0; v < particle__+n; v++)
+            for (int s = particle___; s < particle___+q; s++, i += m)
+              y2[variable_] += ghxu[variable+i]*epsilon[s]*yhat2[v];
+#ifdef FIRST_ORDER_LOOP
+          for (int column = 0, column_ = 0; column < q; column++, column_ += m)
+            {
+              int i1 = variable+column_;
+              int i2 = column+particle__;
+              int i3 = column+particle___;
+              y1[variable_] += ghx[i1]*yhat1[i2];
+              y1[variable_] += ghu[i1]*epsilon[i3];
+            }
+          for (int column = q, column_ = q*m; column < n; column++, column_ += m)
+            {
+              y1[variable_] += ghx[variable+column_]*yhat1[column+particle__];
+            }
+#endif
+        }
+#ifndef FIRST_ORDER_LOOP
+      dgemv(transpose, &m, &n, &one, &ghx[0], &m, &yhat1[particle__], &ONE, &one, &y1[particle_], &ONE);
+      dgemv(transpose, &m, &q, &one, &ghu[0], &m, &epsilon[particle___], &ONE, &one, &y1[particle_], &ONE);
+#endif
+    }
 }
 
-void ss2Iteration(double* y, const double* yhat, const double *epsilon,
-                  double* ghx, double* ghu,
-                  const double* constant, const double* ghxx, const double* ghuu, const double* ghxu,
-                  const blas_int m, const blas_int n, const blas_int q, const blas_int s, const int number_of_threads)
+void
+ss2Iteration(double *y, const double *yhat, const double *epsilon,
+             double *ghx, double *ghu,
+             const double *constant, const double *ghxx, const double *ghuu, const double *ghxu,
+             const blas_int m, const blas_int n, const blas_int q, const blas_int s, const int number_of_threads)
 {
-  #ifndef FIRST_ORDER_LOOP
-      const char transpose[2] = "N";
-      const double one = 1.0;
-      const blas_int ONE = 1;
-  #endif
+#ifndef FIRST_ORDER_LOOP
+  const char transpose[2] = "N";
+  const double one = 1.0;
+  const blas_int ONE = 1;
+#endif
   vector<int> ii1, ii2, ii3;// vector indices for ghxx
   vector<int> jj1, jj2, jj3;// vector indices for ghuu
   set_vector_of_indices(n, m, ii1, ii2, ii3);
   set_vector_of_indices(q, m, jj1, jj2, jj3);
-  #ifdef USE_OMP
-  #pragma omp parallel for num_threads(number_of_threads)
-  #endif
-  for (int particle = 0; particle<s; particle++)
-  {
-    int particle_ = particle*m;
-    int particle__ = particle*n;
-    int particle___ = particle*q;
-    memcpy(&y[particle_],&constant[0],m*sizeof(double));
-    #ifndef FIRST_ORDER_LOOP
-        dgemv(transpose,&m,&n,&one,&ghx[0],&m,&yhat[particle__],&ONE,&one,&y[particle_],&ONE);
-        dgemv(transpose,&m,&q,&one,&ghu[0],&m,&epsilon[particle___],&ONE,&one,&y[particle_],&ONE);
-    #endif
-    for (int variable = 0; variable<m; variable++)
-      {
-        int variable_ = variable + particle_;
-        // +ghx*yhat+ghu*u
-        #ifdef FIRST_ORDER_LOOP
-            for (int column = 0, column_=0; column<q; column++, column_ += m)
-	      {
-		int i1 = variable+column_;
-		int i2 = column+particle__;
-		int i3 = column+particle___;
-		y[variable_] += ghx[i1]*yhat[i2];
-		y[variable_] += ghu[i1]*epsilon[i3];
-	      }
-	    for (int column = q, column_=q*m; column<n; column++, column_ += m)
-	      {
-		y[variable_] += ghx[variable+column_]*yhat[column+particle__];
-	      }
-        #endif
-        // +ghxx*kron(yhat,yhat)
-	for(int i=0; i<n*(n+1)/2; i++)
-          {
-            int i1 = particle__+ii1[i];
-            int i2 = particle__+ii2[i];
-            if(i1==i2)
-              {
-                y[variable_] += .5*ghxx[variable+ii3[i]]*yhat[i1]*yhat[i1];
-              }
-            else
-              {
-                y[variable_] += ghxx[variable+ii3[i]]*yhat[i1]*yhat[i2];
-              }
-          }
-        // +ghuu*kron(u,u)
-        for(int j=0; j<q*(q+1)/2; j++)
-          {
-            int j1 = particle___+jj1[j];
-            int j2 = particle___+jj2[j];
-            if(j1==j2)
-              {
-                y[variable_] += .5*ghuu[variable+jj3[j]]*epsilon[j1]*epsilon[j1];
-              }
-            else
-              {
-                y[variable_] += ghuu[variable+jj3[j]]*epsilon[j1]*epsilon[j2];
-              }
-          }
-        // +ghxu*kron(yhat,u)
-        for (int v = particle__, i = 0; v<particle__+n; v++)
-          for (int s = particle___; s<particle___+q; s++, i += m)
-            y[variable_] += ghxu[variable+i]*epsilon[s]*yhat[v];
-      }
-  }
+#ifdef USE_OMP
+# pragma omp parallel for num_threads(number_of_threads)
+#endif
+  for (int particle = 0; particle < s; particle++)
+    {
+      int particle_ = particle*m;
+      int particle__ = particle*n;
+      int particle___ = particle*q;
+      memcpy(&y[particle_], &constant[0], m*sizeof(double));
+#ifndef FIRST_ORDER_LOOP
+      dgemv(transpose, &m, &n, &one, &ghx[0], &m, &yhat[particle__], &ONE, &one, &y[particle_], &ONE);
+      dgemv(transpose, &m, &q, &one, &ghu[0], &m, &epsilon[particle___], &ONE, &one, &y[particle_], &ONE);
+#endif
+      for (int variable = 0; variable < m; variable++)
+        {
+          int variable_ = variable + particle_;
+          // +ghx*yhat+ghu*u
+#ifdef FIRST_ORDER_LOOP
+          for (int column = 0, column_ = 0; column < q; column++, column_ += m)
+            {
+              int i1 = variable+column_;
+              int i2 = column+particle__;
+              int i3 = column+particle___;
+              y[variable_] += ghx[i1]*yhat[i2];
+              y[variable_] += ghu[i1]*epsilon[i3];
+            }
+          for (int column = q, column_ = q*m; column < n; column++, column_ += m)
+            {
+              y[variable_] += ghx[variable+column_]*yhat[column+particle__];
+            }
+#endif
+          // +ghxx*kron(yhat,yhat)
+          for (int i = 0; i < n*(n+1)/2; i++)
+            {
+              int i1 = particle__+ii1[i];
+              int i2 = particle__+ii2[i];
+              if (i1 == i2)
+                {
+                  y[variable_] += .5*ghxx[variable+ii3[i]]*yhat[i1]*yhat[i1];
+                }
+              else
+                {
+                  y[variable_] += ghxx[variable+ii3[i]]*yhat[i1]*yhat[i2];
+                }
+            }
+          // +ghuu*kron(u,u)
+          for (int j = 0; j < q*(q+1)/2; j++)
+            {
+              int j1 = particle___+jj1[j];
+              int j2 = particle___+jj2[j];
+              if (j1 == j2)
+                {
+                  y[variable_] += .5*ghuu[variable+jj3[j]]*epsilon[j1]*epsilon[j1];
+                }
+              else
+                {
+                  y[variable_] += ghuu[variable+jj3[j]]*epsilon[j1]*epsilon[j2];
+                }
+            }
+          // +ghxu*kron(yhat,u)
+          for (int v = particle__, i = 0; v < particle__+n; v++)
+            for (int s = particle___; s < particle___+q; s++, i += m)
+              y[variable_] += ghxu[variable+i]*epsilon[s]*yhat[v];
+        }
+    }
 }
 
-
-
-
-void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
+void
+mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
 {
   /*
   ** prhs[0] yhat          [double]  n*s array, time t particles.
@@ -275,27 +276,27 @@ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
   //mexPrintf("\n The number of column of epsilon is %d.", mxGetN(prhs[1]));
   // Check the dimensions.
   if (
-      (s != mxGetN(prhs[1]))   || // Number of columns for epsilon
-      (n != mxGetN(prhs[2]))   || // Number of columns for ghx
-      (m != mxGetM(prhs[3]))   || // Number of rows for ghu
-      (q != mxGetN(prhs[3]))   || // Number of columns for ghu
-      (m != mxGetM(prhs[4]))   || // Number of rows for 2nd order constant correction + deterministic steady state
-      (m != mxGetM(prhs[5]))   || // Number of rows for ghxx
-      (n*n != mxGetN(prhs[5])) || // Number of columns for ghxx
-      (m != mxGetM(prhs[6]))   || // Number of rows for ghuu
-      (q*q != mxGetN(prhs[6])) || // Number of columns for ghuu
-      (m != mxGetM(prhs[7]))   || // Number of rows for ghxu
-      (n*q != mxGetN(prhs[7]))    // Number of rows for ghxu
+      (s != mxGetN(prhs[1]))      // Number of columns for epsilon
+      || (n != mxGetN(prhs[2])) // Number of columns for ghx
+      || (m != mxGetM(prhs[3])) // Number of rows for ghu
+      || (q != mxGetN(prhs[3])) // Number of columns for ghu
+      || (m != mxGetM(prhs[4])) // Number of rows for 2nd order constant correction + deterministic steady state
+      || (m != mxGetM(prhs[5])) // Number of rows for ghxx
+      || (n*n != mxGetN(prhs[5])) // Number of columns for ghxx
+      || (m != mxGetM(prhs[6])) // Number of rows for ghuu
+      || (q*q != mxGetN(prhs[6])) // Number of columns for ghuu
+      || (m != mxGetM(prhs[7])) // Number of rows for ghxu
+      || (n*q != mxGetN(prhs[7]))    // Number of rows for ghxu
       )
     {
       mexErrMsgTxt("Input dimension mismatch!.");
     }
-  if (nrhs>9)
+  if (nrhs > 9)
     {
       if (
-          (n != mxGetM(prhs[8]))   || // Number of rows for yhat_
-          (s != mxGetN(prhs[8]))   || // Number of columns for yhat_
-          (m != mxGetM(prhs[9]))      // Number of rows for ss
+          (n != mxGetM(prhs[8]))      // Number of rows for yhat_
+          || (s != mxGetN(prhs[8])) // Number of columns for yhat_
+          || (m != mxGetM(prhs[9]))      // Number of rows for ss
           )
         {
           mexErrMsgTxt("Input dimension mismatch!.");
@@ -311,12 +312,12 @@ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
   double *ghuu = mxGetPr(prhs[6]);
   double *ghxu = mxGetPr(prhs[7]);
   double *yhat_ = NULL, *ss = NULL;
-  if (nrhs>9)
+  if (nrhs > 9)
     {
       yhat_ = mxGetPr(prhs[8]);
       ss = mxGetPr(prhs[9]);
     }
-  if (nrhs==9)
+  if (nrhs == 9)
     {
       int numthreads = (int) mxGetScalar(prhs[8]);
       double *y;
diff --git a/mex/sources/mjdgges/mjdgges.c b/mex/sources/mjdgges/mjdgges.c
index 700f769b8ef848ba57b153a5d852c9c42e756985..5086dc8d458856d87993fb07fc20f07efef9efa2 100644
--- a/mex/sources/mjdgges/mjdgges.c
+++ b/mex/sources/mjdgges/mjdgges.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006-2016 Dynare Team
+ * Copyright (C) 2006-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -28,7 +28,7 @@ double criterium;
 lapack_int
 my_criteria(const double *alphar, const double *alphai, const double *beta)
 {
-  return ((*alphar * *alphar + *alphai * *alphai) < criterium * *beta * *beta);
+  return ((*alphar **alphar + *alphai **alphai) < criterium **beta **beta);
 }
 
 void
@@ -60,15 +60,15 @@ mjdgges(double *a, double *b, double *z, double *n, double *sdim, double *eval_r
   pei = eval_i;
   for (per = eval_r; per <= &eval_r[i_n-1]; ++per)
     {
-      if ((fabs(*par) > zhreshold) || (fabs(*pb) > zhreshold)) 
-	*per = *par / *pb;
+      if ((fabs(*par) > zhreshold) || (fabs(*pb) > zhreshold))
+        *per = *par / *pb;
       else
-	{
-	  /* the ratio is too close to 0/0;
-	     returns specific error number only if no other error */
-	  if (i_info == 0)
-	    *info = -30;
-	}
+        {
+          /* the ratio is too close to 0/0;
+             returns specific error number only if no other error */
+          if (i_info == 0)
+            *info = -30;
+        }
       if (*pai == 0.0 && *pb == 0.0)
         *pei = 0.0;
       else
@@ -147,7 +147,6 @@ mexFunction(int nlhs, mxArray *plhs[],
       zhreshold = 1e-6;
     }
 
-
   /* keep a and b intact */
   memcpy(s, a, sizeof(double)*n1*n1);
   memcpy(t, b, sizeof(double)*n1*n1);
diff --git a/mex/sources/ms-sbvar/mex_top_level.cc b/mex/sources/ms-sbvar/mex_top_level.cc
index f4aff318198b1ba44ecc62a26a2449c95f060b05..9d982f327318e9c43a34a233da08d035a5822be5 100644
--- a/mex/sources/ms-sbvar/mex_top_level.cc
+++ b/mex/sources/ms-sbvar/mex_top_level.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -48,16 +48,16 @@ mexFunction(int nlhs, mxArray *plhs[],
   /*
    * Allocate memory
    */
-  maxnargs = (int)(mxGetN(prhs[0])/2+1);
-  argument = (char *)mxCalloc(mxGetN(prhs[0])+1, sizeof(char));
-  args = (char **)mxCalloc(maxnargs, sizeof(char *));
-  if (argument==NULL || args==NULL)
+  maxnargs = (int) (mxGetN(prhs[0])/2+1);
+  argument = (char *) mxCalloc(mxGetN(prhs[0])+1, sizeof(char));
+  args = (char **) mxCalloc(maxnargs, sizeof(char *));
+  if (argument == NULL || args == NULL)
     DYN_MEX_FUNC_ERR_MSG_TXT("Error in MS-SBVAR MEX file: could not allocate memory. (1)");
 
   /*
    * Create argument string from prhs and parse to create args / nargs
    */
-  if (!(args[nargs] = (char *)mxCalloc(strlen(mainarg)+1, sizeof(char))))
+  if (!(args[nargs] = (char *) mxCalloc(strlen(mainarg)+1, sizeof(char))))
     DYN_MEX_FUNC_ERR_MSG_TXT("Error in MS-SBVAR MEX file: could not allocate memory. (2)");
 
   strncpy(args[nargs++], mainarg, strlen(mainarg));
@@ -66,9 +66,9 @@ mexFunction(int nlhs, mxArray *plhs[],
     DYN_MEX_FUNC_ERR_MSG_TXT("Error in MS-SBVAR MEX file: error using mxGetString.\n");
 
   beginarg = &argument[0];
-  while((n=strcspn(beginarg, " ")))
+  while ((n = strcspn(beginarg, " ")))
     {
-      if (!(args[nargs] = (char *)mxCalloc(n+1, sizeof(char))))
+      if (!(args[nargs] = (char *) mxCalloc(n+1, sizeof(char))))
         DYN_MEX_FUNC_ERR_MSG_TXT("Error in MS-SBVAR MEX file: could not allocate memory. (3)");
 
       strncpy(args[nargs++], beginarg, n);
@@ -91,7 +91,7 @@ mexFunction(int nlhs, mxArray *plhs[],
   /*
    * free memory
    */
-  for (n=0; n<nargs; n++)
+  for (n = 0; n < nargs; n++)
     mxFree(args[n]);
   mxFree(args);
 
diff --git a/mex/sources/ms-sbvar/mex_write_to_matlab.c b/mex/sources/ms-sbvar/mex_write_to_matlab.c
index 7f188786d278017b172d949736130441b2a21064..1d14ffe3eb606949c1cf5642488557a0168e20ac 100644
--- a/mex/sources/ms-sbvar/mex_write_to_matlab.c
+++ b/mex/sources/ms-sbvar/mex_write_to_matlab.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 Dynare Team
+ * Copyright (C) 2011-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -31,9 +31,9 @@ mex_write_to_matlab_matfile(double *data, int rows, int cols, const char *varnam
   if (matfile == NULL)
     mexErrMsgTxt("Error encountered in mex when opening a .mat file");
 
-  if (matPutVariable(matfile, varname, toWrite) != 0 ||
-      ferror(matGetFp(matfile)) > 0 ||
-      feof(matGetFp(matfile)) > 0)
+  if (matPutVariable(matfile, varname, toWrite) != 0
+      || ferror(matGetFp(matfile)) > 0
+      || feof(matGetFp(matfile)) > 0)
     mexErrMsgTxt("Error encountered in mex when writing a .mat file");
 
   if (matClose(matfile) != 0)
diff --git a/mex/sources/ms-sbvar/modify_for_mex.h b/mex/sources/ms-sbvar/modify_for_mex.h
index cb477633f84270ef2fe81ca52dce99231382ed0b..0689df90f92a4126e8adefbacadcf0035d45c35d 100644
--- a/mex/sources/ms-sbvar/modify_for_mex.h
+++ b/mex/sources/ms-sbvar/modify_for_mex.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -22,29 +22,29 @@
 
 #if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE)
 
-#include <dynmex.h>
-#include <dynblas.h>
-#include <dynlapack.h>
+# include <dynmex.h>
+# include <dynblas.h>
+# include <dynlapack.h>
 
-#define dw_malloc mxMalloc
-#define dw_calloc mxCalloc
-#define dw_realloc mxRealloc
-#define dw_free mxFree
-#define dw_exit msExit
+# define dw_malloc mxMalloc
+# define dw_calloc mxCalloc
+# define dw_realloc mxRealloc
+# define dw_free mxFree
+# define dw_exit msExit
 
 /* Handle Ctrl-C in Matlab/Octave */
-#ifdef MATLAB_MEX_FILE
+# ifdef MATLAB_MEX_FILE
 extern bool utIsInterruptPending();
-#else
-#include <octave/config.h>
-#include <octave/quit.h>
-#endif
+# else
+#  include <octave/config.h>
+#  include <octave/quit.h>
+# endif
 
 void msExit(int status);
 extern int constant_seed;
 
-/* Write Matlab Output 
-mxArray *globalMatlabStruct;*/
+/* Write Matlab Output
+   mxArray *globalMatlabStruct;*/
 void mex_write_to_matlab_matfile(double *, int, int, const char *, const char *);
 void mex_write_to_matlab_global_struct(double *, int, int, const char *);
 mxArray *getMxArray(double *, int, int);
diff --git a/mex/sources/qzcomplex/qzcomplex.cc b/mex/sources/qzcomplex/qzcomplex.cc
index 7b95ce76f463608881ebb7cab374a6dbd25110f8..74773fcdc59dbdb8e9a8e85aac8742570090882b 100644
--- a/mex/sources/qzcomplex/qzcomplex.cc
+++ b/mex/sources/qzcomplex/qzcomplex.cc
@@ -6,7 +6,7 @@
  */
 
 /*
- * Copyright (C) 2010-2016 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -25,15 +25,15 @@
  */
 
 #ifdef __MINGW32__
-#define __CROSS_COMPILATION__
+# define __CROSS_COMPILATION__
 #endif
 
 #ifdef __MINGW64__
-#define __CROSS_COMPILATION__
+# define __CROSS_COMPILATION__
 #endif
 
 #ifdef __CROSS_COMPILATION__
-#define M_PI 3.14159265358979323846
+# define M_PI 3.14159265358979323846
 #endif
 
 #include <octave/oct.h>
diff --git a/mex/sources/sobol/gaussian.hh b/mex/sources/sobol/gaussian.hh
index 4506117731ff409b5ef26adc9ca2e34ef8ea8f73..6dd00ca22feb60a61dabb71552fd73daa69f730c 100644
--- a/mex/sources/sobol/gaussian.hh
+++ b/mex/sources/sobol/gaussian.hh
@@ -1,8 +1,8 @@
 /* Generates gaussian random deviates from uniform random deviates.
-** 
-** Pseudo code of the algorithm is given at http://home.online.no/~pjacklam/notes/invnorm  
 **
-** Copyright (C) 2010-2016 Dynare Team
+** Pseudo code of the algorithm is given at http://home.online.no/~pjacklam/notes/invnorm
+**
+** Copyright (C) 2010-2017 Dynare Team
 **
 ** This file is part of Dynare.
 **
@@ -18,8 +18,8 @@
 **
 ** You should have received a copy of the GNU General Public License
 ** along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
-** 
-** AUTHOR(S): stephane DOT adjemian AT univ DASH lemans DOT fr  
+**
+** AUTHOR(S): stephane DOT adjemian AT univ DASH lemans DOT fr
 */
 
 #include <cstdlib>
@@ -41,58 +41,60 @@ using namespace std;
 #define DEBUG_OMP 0
 
 #ifdef __MINGW32__
-#define __CROSS_COMPILATION__
+# define __CROSS_COMPILATION__
 #endif
 
 #ifdef __MINGW64__
-#define __CROSS_COMPILATION__
+# define __CROSS_COMPILATION__
 #endif
 
 #ifdef __CROSS_COMPILATION__
-#define M_PI 3.14159265358979323846
+# define M_PI 3.14159265358979323846
 #endif
 
-template<typename T> T icdf( const T uniform )
+template<typename T>
+T
+icdf(const T uniform)
 /*
 **  This function invert the gaussian cumulative distribution function.
 **
 */
-{ 
-  static T A[6] = 
+{
+  static T A[6] =
     {
       -3.969683028665376e+01,
-       2.209460984245205e+02,
+      2.209460984245205e+02,
       -2.759285104469687e+02,
-       1.383577518672690e+02,
+      1.383577518672690e+02,
       -3.066479806614716e+01,
-       2.506628277459239e+00
+      2.506628277459239e+00
     };
-  static T B[5] = 
+  static T B[5] =
     {
       -5.447609879822406e+01,
-       1.615858368580409e+02,
+      1.615858368580409e+02,
       -1.556989798598866e+02,
-       6.680131188771972e+01,
+      6.680131188771972e+01,
       -1.328068155288572e+01
     };
-  static T C[6] = 
+  static T C[6] =
     {
       -7.784894002430293e-03,
       -3.223964580411365e-01,
       -2.400758277161838e+00,
       -2.549732539343734e+00,
-       4.374664141464968e+00,
-       2.938163982698783e+00
+      4.374664141464968e+00,
+      2.938163982698783e+00
     };
-  static T D[4] = 
+  static T D[4] =
     {
       7.784695709041462e-03,
       3.224671290700398e-01,
       2.445134137142996e+00,
       3.754408661907416e+00
     };
-  T gaussian = (T)0.0;
-  if ( (0<uniform)  && (uniform<lb) )
+  T gaussian = (T) 0.0;
+  if ((0 < uniform)  && (uniform < lb))
     {
       T tmp;
       tmp = sqrt(-2*log(uniform));
@@ -117,65 +119,71 @@ template<typename T> T icdf( const T uniform )
             }
         }
     }
-  if ( (0<uniform) && (uniform<1) )
+  if ((0 < uniform) && (uniform < 1))
     {
       T tmp, tmp_;
       tmp = .5*erfc(-gaussian/sqrt(2.0))-uniform;
       tmp_ = tmp*sqrt(2*M_PI)*exp(.5*gaussian*gaussian);
       gaussian = gaussian - tmp_/(1+.5*gaussian*tmp_);
     }
-  if ( uniform==0)
+  if (uniform == 0)
     {
       gaussian = -INFINITY;
     }
-  if ( uniform==1)
+  if (uniform == 1)
     {
       gaussian = INFINITY;
     }
- return(gaussian);
+  return (gaussian);
 }
 
-template<typename T> void icdfm( const int n, T *U)
-{ 
-  #if USE_OMP
-  #pragma omp parallel for num_threads(omp_get_num_threads())
-  #endif
-  for(int i=0; i<n; i++)
+template<typename T>
+void
+icdfm(const int n, T *U)
+{
+#if USE_OMP
+# pragma omp parallel for num_threads(omp_get_num_threads())
+#endif
+  for (int i = 0; i < n; i++)
     {
       U[i] = icdf(U[i]);
     }
   return;
 }
 
-template<typename T> void icdfmSigma( const int d, const int n, T *U, const double *LowerCholSigma)
-{ 
+template<typename T>
+void
+icdfmSigma(const int d, const int n, T *U, const double *LowerCholSigma)
+{
   double one = 1.0;
   double zero = 0.0;
   blas_int dd(d);
   blas_int nn(n);
   icdfm(n*d, U);
   double tmp[n*d];
-  dgemm("N","N",&dd,&nn,&dd,&one,LowerCholSigma,&dd,U,&dd,&zero,tmp,&dd);
-  memcpy(U,tmp,d*n*sizeof(double));
+  dgemm("N", "N", &dd, &nn, &dd, &one, LowerCholSigma, &dd, U, &dd, &zero, tmp, &dd);
+  memcpy(U, tmp, d*n*sizeof(double));
   return;
 }
 
-template<typename T> void usphere( const int d, const int n, T *U)
-{ 
+template<typename T>
+void
+usphere(const int d, const int n, T *U)
+{
   icdfm(n*d, U);
-  #if USE_OMP
-  #pragma omp parallel for num_threads(omp_get_num_threads())
-  #endif
-  for (int j=0; j<n; j++)// sequence index.
+#if USE_OMP
+# pragma omp parallel for num_threads(omp_get_num_threads())
+#endif
+  for (int j = 0; j < n; j++)// sequence index.
     {
       int k = j*d;
       double norm = 0.0;
-      for(int i=0; i<d; i++)// dimension index.
+      for (int i = 0; i < d; i++)// dimension index.
         {
           norm = norm + U[k+i]*U[k+i];
         }
       norm = sqrt(norm);
-      for(int i=0; i<d; i++)// dimension index.
+      for (int i = 0; i < d; i++)// dimension index.
         {
           U[k+i] = U[k+i]/norm;
         }
@@ -183,22 +191,24 @@ template<typename T> void usphere( const int d, const int n, T *U)
   return;
 }
 
-template<typename T> void usphereRadius( const int d, const int n, double radius, T *U)
-{ 
+template<typename T>
+void
+usphereRadius(const int d, const int n, double radius, T *U)
+{
   icdfm(n*d, U);
-  #if USE_OMP
-  #pragma omp parallel for num_threads(omp_get_num_threads())
-  #endif
-  for (int j=0; j<n; j++)// sequence index.
+#if USE_OMP
+# pragma omp parallel for num_threads(omp_get_num_threads())
+#endif
+  for (int j = 0; j < n; j++)// sequence index.
     {
       int k = j*d;
       double norm = 0.0;
-      for(int i=0; i<d; i++)// dimension index.
+      for (int i = 0; i < d; i++)// dimension index.
         {
           norm = norm + U[k+i]*U[k+i];
         }
       norm = sqrt(norm);
-      for(int i=0; i<d; i++)// dimension index.
+      for (int i = 0; i < d; i++)// dimension index.
         {
           U[k+i] = radius*U[k+i]/norm;
         }
diff --git a/mex/sources/sobol/initialize_v_array.hh b/mex/sources/sobol/initialize_v_array.hh
index ac6a09b6b495638337f752eec519f59e0329d101..ad172d7a552da456bcd378599e4820dcc265d07d 100644
--- a/mex/sources/sobol/initialize_v_array.hh
+++ b/mex/sources/sobol/initialize_v_array.hh
@@ -1,11 +1,13 @@
-template<typename T> int initialize_v_array (int dim_max, int log_max, T **v)
+template<typename T>
+int
+initialize_v_array(int dim_max, int log_max, T **v)
 /*
-** This function initializes the v array used in the sobol routine. 
+** This function initializes the v array used in the sobol routine.
 **
 ** Original files downloaded from http://people.sc.fsu.edu/~burkardt/cpp_src/sobol/ (version 17-Feb-2009 09:46)
 **
 ** Copyright (C) 2009 John Burkardt
-** Copyright (C) 2010-2011 Dynare Team
+** Copyright (C) 2010-2017 Dynare Team
 **
 ** This program is free software: you can redistribute it and/or modify
 ** it under the terms of the GNU Lesser General Public License as published by
@@ -19,10 +21,8 @@ template<typename T> int initialize_v_array (int dim_max, int log_max, T **v)
 **
 ** You should have received a copy of the GNU Lesser General Public License
 ** along with this program.  If not, see <http://www.gnu.org/licenses/>.
-**
-** AUTHOR(S): stephane DOT adjemian AT univ DASH lemans DOT fr
 */
 {
-  #include "initialize_v_array.inc"
+#include "initialize_v_array.inc"
   return 1;
 }
diff --git a/mex/sources/sobol/qmc_sequence.cc b/mex/sources/sobol/qmc_sequence.cc
index bd6ed4ddc580dab282e66384bd5114fcfa6bc24d..e99d8059457a8287676df14e3a6bc31f1f0d9ccd 100644
--- a/mex/sources/sobol/qmc_sequence.cc
+++ b/mex/sources/sobol/qmc_sequence.cc
@@ -1,7 +1,7 @@
 /*
 ** Computes Quasi Monte-Carlo sequence.
 **
-** Copyright (C) 2010-2012 Dynare Team
+** Copyright (C) 2010-2017 Dynare Team
 **
 ** This file is part of Dynare (can be used outside Dynare).
 **
@@ -17,8 +17,6 @@
 **
 ** You should have received a copy of the GNU General Public License
 ** along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
-**
-** AUTHOR(S): stephane DOT adjemian AT univ DASH lemans DOT fr
 **/
 
 #include <sstream>
@@ -32,9 +30,10 @@
 // the maximum dimension defined in sobol.ff (but undef at the end)
 #define DIM_MAX 1111
 
-void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
+void
+mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
 {
-  /* 
+  /*
   ** INPUTS:
   ** prhs[0]    [integer]    scalar, dimension.
   ** prhs[1]    [integer]    scalar, seed.
@@ -51,12 +50,12 @@ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
   ** plhs[0]    [double]     sequence_size*dimension array, the Sobol sequence.
   ** plhs[1]    [integer]    scalar, seed.
   ** plhs[2]    [integer]    zero in case of success, one in case of error
-  ** 
+  **
   */
   /*
   ** Check the number of input and output arguments.
   */
-  if ( !( (nrhs==5) | (nrhs==4) | (nrhs==3) )  )
+  if (!((nrhs == 5) | (nrhs == 4) | (nrhs == 3)))
     {
       DYN_MEX_FUNC_ERR_MSG_TXT("qmc_sequence:: Five, four or three input arguments are required!");
     }
@@ -67,40 +66,40 @@ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
   /*
   ** Test the first input argument and assign it to dimension.
   */
-  if (  !( mxIsNumeric(prhs[0]) ) )
+  if (!(mxIsNumeric(prhs[0])))
     {
       DYN_MEX_FUNC_ERR_MSG_TXT("qmc_sequence:: First input (dimension) has to be a positive integer!");
     }
-  int dimension = ( int ) mxGetScalar(prhs[0]);
+  int dimension = (int) mxGetScalar(prhs[0]);
   /*
   ** Test the second input argument and assign it to seed.
   */
-  if ( !( mxIsNumeric(prhs[1]) && mxIsClass(prhs[1],"int64") ) )
+  if (!(mxIsNumeric(prhs[1]) && mxIsClass(prhs[1], "int64")))
     {
       DYN_MEX_FUNC_ERR_MSG_TXT("qmc_sequence:: Second input (seed) has to be an integer [int64]!");
     }
-  int64_T seed = ( int64_T ) mxGetScalar( prhs[1] );
+  int64_T seed = (int64_T) mxGetScalar(prhs[1]);
   /*
   ** Test the third input argument and assign it to type (kind of QMC sequence).
   */
   int error_flag_3 = 0;
-  if (  !(mxIsNumeric(prhs[2])) )
+  if (!(mxIsNumeric(prhs[2])))
     {
       error_flag_3 = 1;
     }
-  int type = ( int ) mxGetScalar(prhs[2]);
-  if ( !(type==0 || type==1 || type==2) )
+  int type = (int) mxGetScalar(prhs[2]);
+  if (!(type == 0 || type == 1 || type == 2))
     {
       error_flag_3 = 1;
     }
-  if (error_flag_3==1)
+  if (error_flag_3 == 1)
     {
       DYN_MEX_FUNC_ERR_MSG_TXT("qmc_sequence:: Third input (type of QMC sequence) has to be an integer equal to 0, 1 or 2!");
     }
   /*
   ** Test dimension>=2 when type==2
   */
-  if ( (type==2) && (dimension<2) )
+  if ((type == 2) && (dimension < 2))
     {
       DYN_MEX_FUNC_ERR_MSG_TXT("qmc_sequence:: First input (dimension) has to be greater than 1 for a uniform QMC on an hypershere!");
     }
@@ -114,14 +113,14 @@ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
   /*
   ** Test the optional fourth input argument and assign it to sequence_size.
   */
-  if  ( ( nrhs>3 )  &&  !mxIsNumeric(prhs[3])  ) 
+  if  ((nrhs > 3)  &&  !mxIsNumeric(prhs[3]))
     {
       DYN_MEX_FUNC_ERR_MSG_TXT("qmc_sequence:: Fourth input (qmc sequence size) has to be a positive integer!");
     }
   int sequence_size;
-  if ( nrhs>3)
+  if (nrhs > 3)
     {
-      sequence_size = ( int ) mxGetScalar( prhs[3] );
+      sequence_size = (int) mxGetScalar(prhs[3]);
     }
   else
     {
@@ -130,53 +129,53 @@ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
   /*
   ** Test the optional fifth input argument and assign it to lower_and_upper_bounds.
   */
-  if  (  ( nrhs>4 )  &&  (type==0) && ( !( mxGetN(prhs[4])==2) )  )// Sequence of uniformly distributed numbers in an hypercube.
+  if  ((nrhs > 4)  &&  (type == 0) && (!(mxGetN(prhs[4]) == 2)))// Sequence of uniformly distributed numbers in an hypercube.
     {
       DYN_MEX_FUNC_ERR_MSG_TXT("qmc_sequence:: The fifth input argument must be an array with two columns!");
     }
-  if  ( (nrhs>4)   &&  (type==0) &&  ( !( (int)mxGetM(prhs[4])==dimension) ) )
+  if  ((nrhs > 4)   &&  (type == 0) &&  (!((int) mxGetM(prhs[4]) == dimension)))
     {
       DYN_MEX_FUNC_ERR_MSG_TXT("qmc_sequence:: The fourth input argument must be an array with a number of lines equal to dimension (first input argument)!");
     }
-  if  ( ( nrhs>4 )  &&  (type==1) && ( !( ((int)mxGetN(prhs[4])==dimension) && ((int)mxGetM(prhs[4])==dimension) ) ) )// Sequence of normally distributed numbers.
+  if  ((nrhs > 4)  &&  (type == 1) && (!(((int) mxGetN(prhs[4]) == dimension) && ((int) mxGetM(prhs[4]) == dimension))))// Sequence of normally distributed numbers.
     {
       DYN_MEX_FUNC_ERR_MSG_TXT("qmc_sequence:: The fifth input argument must be a squared matrix (whose dimension is given by the first input argument)!");
     }
-  if  ( ( nrhs>4 )  &&  (type==2) && ( !( (mxGetN(prhs[4])==1) && (mxGetM(prhs[4])==1) ) ) )// Sequence of uniformly distributed numbers on an hypershere.
+  if  ((nrhs > 4)  &&  (type == 2) && (!((mxGetN(prhs[4]) == 1) && (mxGetM(prhs[4]) == 1))))// Sequence of uniformly distributed numbers on an hypershere.
     {
       DYN_MEX_FUNC_ERR_MSG_TXT("qmc_sequence:: The fifth input argument must be a positive scalar!");
     }
   double *lower_bounds = NULL, *upper_bounds = NULL;
   int unit_hypercube_flag = 1;
-  if ( (type==0) && (nrhs>4) )
+  if ((type == 0) && (nrhs > 4))
     {
-      lower_bounds = (double *) mxCalloc(dimension,sizeof(double));
-      upper_bounds = (double *) mxCalloc(dimension,sizeof(double));
+      lower_bounds = (double *) mxCalloc(dimension, sizeof(double));
+      upper_bounds = (double *) mxCalloc(dimension, sizeof(double));
       double *tmp;
-      tmp = (double *) mxCalloc(dimension*2,sizeof(double));
-      memcpy(tmp,mxGetPr(prhs[4]),dimension*2*sizeof(double));
+      tmp = (double *) mxCalloc(dimension*2, sizeof(double));
+      memcpy(tmp, mxGetPr(prhs[4]), dimension*2*sizeof(double));
       lower_bounds = &tmp[0];
       upper_bounds = &tmp[dimension];
       unit_hypercube_flag = 0;
     }
   double *cholcov;
   int identity_covariance_matrix = 1;
-  if ( (type==1) && (nrhs>4) )
+  if ((type == 1) && (nrhs > 4))
     {
-      cholcov = (double *) mxCalloc(dimension*dimension,sizeof(double));
+      cholcov = (double *) mxCalloc(dimension*dimension, sizeof(double));
       double *tmp;
-      tmp = (double *) mxCalloc(dimension*dimension,sizeof(double));
-      memcpy(tmp,mxGetPr(prhs[4]),dimension*dimension*sizeof(double));
+      tmp = (double *) mxCalloc(dimension*dimension, sizeof(double));
+      memcpy(tmp, mxGetPr(prhs[4]), dimension*dimension*sizeof(double));
       cholcov = &tmp[0];
       identity_covariance_matrix = 0;
     }
   double radius = 1.0;
   int unit_radius = 1;
-  if ( (type==2) && (nrhs>4) )
+  if ((type == 2) && (nrhs > 4))
     {
       double *tmp;
-      tmp = (double *) mxCalloc(1,sizeof(double));
-      memcpy(tmp,mxGetPr(prhs[4]),sizeof(double));
+      tmp = (double *) mxCalloc(1, sizeof(double));
+      memcpy(tmp, mxGetPr(prhs[4]), sizeof(double));
       radius = tmp[0];
       unit_radius = 0;
     }
@@ -184,35 +183,35 @@ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
   ** Initialize outputs of the mex file.
   */
   double *qmc_draws;
-  plhs[0] = mxCreateDoubleMatrix(dimension,sequence_size,mxREAL);
+  plhs[0] = mxCreateDoubleMatrix(dimension, sequence_size, mxREAL);
   qmc_draws = mxGetPr(plhs[0]);
   int64_T seed_out;
 
-  if (sequence_size==1)
+  if (sequence_size == 1)
     {
-      next_sobol ( dimension, &seed, qmc_draws );
+      next_sobol(dimension, &seed, qmc_draws);
       seed_out = seed;
     }
   else
-    seed_out = sobol_block( dimension, sequence_size, seed, qmc_draws);
+    seed_out = sobol_block(dimension, sequence_size, seed, qmc_draws);
 
-  if (type==0 && unit_hypercube_flag==0)// Uniform QMC sequence in an hypercube.
-    expand_unit_hypercube( dimension, sequence_size, qmc_draws, lower_bounds, upper_bounds);
-  else if (type==1)// Normal QMC sequance in R^n.
+  if (type == 0 && unit_hypercube_flag == 0) // Uniform QMC sequence in an hypercube.
+    expand_unit_hypercube(dimension, sequence_size, qmc_draws, lower_bounds, upper_bounds);
+  else if (type == 1)// Normal QMC sequance in R^n.
     {
-      if (identity_covariance_matrix==1)
+      if (identity_covariance_matrix == 1)
         icdfm(dimension*sequence_size, qmc_draws);
       else
-        icdfmSigma(dimension,sequence_size, qmc_draws, cholcov);
+        icdfmSigma(dimension, sequence_size, qmc_draws, cholcov);
     }
-  else if (type==2)// Uniform QMC sequence on an hypershere.
+  else if (type == 2)// Uniform QMC sequence on an hypershere.
     {
-      if (unit_radius==1)
+      if (unit_radius == 1)
         usphere(dimension, sequence_size, qmc_draws);
       else
         usphereRadius(dimension, sequence_size, radius, qmc_draws);
     }
-  
+
   if (nlhs >= 2)
     {
       plhs[1] = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL);
diff --git a/mex/sources/sobol/sobol.hh b/mex/sources/sobol/sobol.hh
index 8dbb987855a515c4a62aee20805bdbfcc2939827..8926daca92e9b3de987b20c54eb70305a0862f92 100644
--- a/mex/sources/sobol/sobol.hh
+++ b/mex/sources/sobol/sobol.hh
@@ -1,9 +1,9 @@
 /* Quasi Monte Carlo sequences (à la Sobol).
-** 
+**
 ** Original files downloaded from http://people.sc.fsu.edu/~burkardt/cpp_src/sobol/ (version 17-Feb-2009 09:46)
 **
 ** Copyright (C) 2009 John Burkardt
-** Copyright (C) 2010-2011 Dynare Team
+** Copyright (C) 2010-2017 Dynare Team
 **
 ** This program is free software: you can redistribute it and/or modify
 ** it under the terms of the GNU Lesser General Public License as published by
@@ -17,8 +17,6 @@
 **
 ** You should have received a copy of the GNU Lesser General Public License
 ** along with this program.  If not, see <http://www.gnu.org/licenses/>.
-**
-** AUTHOR(S): stephane DOT adjemian AT univ DASH lemans DOT fr
 */
 
 #include <cstdlib>
@@ -33,8 +31,10 @@ using namespace std;
 
 #define DIM_MAX 1111
 
-template<typename T> int bit_hi1(T n)
-/*  
+template<typename T>
+int
+bit_hi1(T n)
+/*
 ** This function returns the position of the high 1 bit base 2 in an integer.
 **
 ** Example:
@@ -44,7 +44,7 @@ template<typename T> int bit_hi1(T n)
 **       0           0     0
 **       1           1     1
 **       2          10     2
-**       3          11     2 
+**       3          11     2
 **       4         100     3
 **       5         101     3
 **       6         110     3
@@ -63,7 +63,7 @@ template<typename T> int bit_hi1(T n)
 **    1024 10000000000    11
 **    1025 10000000001    11
 **
-**  
+**
 **  Original files downloaded from http://people.sc.fsu.edu/~burkardt/cpp_src/sobol/ (version 17-Feb-2009 09:46)
 **
 **    Input, int or long long, the integer to be measured.
@@ -72,16 +72,18 @@ template<typename T> int bit_hi1(T n)
 **    Output: the location of the high order bit.
 */
 {
-  int bit = 0 ;
-  while ( n > 0 )
-  {
-    bit++ ;
-    n = n/2 ;
-  }
-  return bit ;
+  int bit = 0;
+  while (n > 0)
+    {
+      bit++;
+      n = n/2;
+    }
+  return bit;
 }
 
-template<typename T> int bit_lo0 ( T n )
+template<typename T>
+int
+bit_lo0(T n)
 /*
 **  This function returns the position of the low 0 bit base 2 in an integer.
 **
@@ -92,7 +94,7 @@ template<typename T> int bit_lo0 ( T n )
 **       0           0     1
 **       1           1     2
 **       2          10     1
-**       3          11     3 
+**       3          11     3
 **       4         100     1
 **       5         101     2
 **       6         110     1
@@ -123,22 +125,23 @@ template<typename T> int bit_lo0 ( T n )
 */
 {
   int bit = 0;
-  while ( true )
-  {
-    bit++;
-    T n2 = n/2;
-    if ( n == 2*n2 )
+  while (true)
     {
-      break;
+      bit++;
+      T n2 = n/2;
+      if (n == 2*n2)
+        {
+          break;
+        }
+      n = n2;
     }
-    n = n2;
-  }
   return bit;
 }
 
- 
-template<typename T>  T ixor ( T i, T j )
-/*  
+template<typename T>
+T
+ixor(T i, T j)
+/*
 **  This function  calculates the exclusive OR of two integers.
 **
 **  Original files downloaded from http://people.sc.fsu.edu/~burkardt/cpp_src/sobol/ (version 17-Feb-2009 09:46)
@@ -150,25 +153,26 @@ template<typename T>  T ixor ( T i, T j )
 {
   T k = 0;
   T l = 1;
-  while ( i != 0 || j != 0 )
-  {
-    T i2 = i / 2;
-    T j2 = j / 2;
-    if ( 
-        ( ( i == 2 * i2 ) && ( j != 2 * j2 ) ) ||
-        ( ( i != 2 * i2 ) && ( j == 2 * j2 ) )  )
-      {
-        k = k + l;
-      }
-    i = i2;
-    j = j2;
-    l = 2 * l;
-  }
+  while (i != 0 || j != 0)
+    {
+      T i2 = i / 2;
+      T j2 = j / 2;
+      if (
+          ((i == 2 * i2) && (j != 2 * j2))
+          || ((i != 2 * i2) && (j == 2 * j2)))
+        {
+          k = k + l;
+        }
+      i = i2;
+      j = j2;
+      l = 2 * l;
+    }
   return k;
 }
 
-
-template<typename T1, typename T2> void next_sobol ( int dim_num, T1 *seed, T2 *quasi )
+template<typename T1, typename T2>
+void
+next_sobol(int dim_num, T1 *seed, T2 *quasi)
 /*
 **  This function generates a new quasirandom Sobol vector with each call.
 **
@@ -203,7 +207,7 @@ template<typename T1, typename T2> void next_sobol ( int dim_num, T1 *seed, T2 *
 **
 **    Bennett Fox,
 **    Algorithm 647:
-**    Implementation and Relative Efficiency of Quasirandom 
+**    Implementation and Relative Efficiency of Quasirandom
 **    Sequence Generators,
 **    ACM Transactions on Mathematical Software,
 **    Volume 12, Number 4, pages 362-376, 1986.
@@ -218,10 +222,10 @@ template<typename T1, typename T2> void next_sobol ( int dim_num, T1 *seed, T2 *
 **    USSR Computational Mathematics and Mathematical Physics,
 **    Volume 16, pages 236-242, 1977.
 **
-**    Ilya Sobol, YL Levitan, 
-**    The Production of Points Uniformly Distributed in a Multidimensional 
+**    Ilya Sobol, YL Levitan,
+**    The Production of Points Uniformly Distributed in a Multidimensional
 **    Cube (in Russian),
-**    Preprint IPM Akad. Nauk SSSR, 
+**    Preprint IPM Akad. Nauk SSSR,
 **    Number 40, Moscow 1976.
 **
 **  Parameters:
@@ -238,287 +242,288 @@ template<typename T1, typename T2> void next_sobol ( int dim_num, T1 *seed, T2 *
 **
 **    Output, double QUASI[DIM_NUM], the next quasirandom vector.
 */
-{ 
-  static T1 atmost ;
-  static int dim_num_save = 0 ;
-  int LOG_MAX = sizeof(T1)*8-2 ;
+{
+  static T1 atmost;
+  static int dim_num_save = 0;
+  int LOG_MAX = sizeof(T1)*8-2;
   bool includ[LOG_MAX];
   static bool initialized = false;
   static T1 lastq[DIM_MAX];
   static T1 maxcol;
   T1 l = 0;
   static T1 poly[DIM_MAX] =
-  {
-        1,    3,    7,   11,   13,   19,   25,   37,   59,   47,
-       61,   55,   41,   67,   97,   91,  109,  103,  115,  131,
+    {
+      1,    3,    7,   11,   13,   19,   25,   37,   59,   47,
+      61,   55,   41,   67,   97,   91,  109,  103,  115,  131,
       193,  137,  145,  143,  241,  157,  185,  167,  229,  171,
       213,  191,  253,  203,  211,  239,  247,  285,  369,  299,
       301,  333,  351,  355,  357,  361,  391,  397,  425,  451,
       463,  487,  501,  529,  539,  545,  557,  563,  601,  607,
-      617,  623,  631,  637,  647,  661,  675,  677,  687,  695, 
+      617,  623,  631,  637,  647,  661,  675,  677,  687,  695,
       701,  719,  721,  731,  757,  761,  787,  789,  799,  803,
       817,  827,  847,  859,  865,  875,  877,  883,  895,  901,
       911,  949,  953,  967,  971,  973,  981,  985,  995, 1001,
-     1019, 1033, 1051, 1063, 1069, 1125, 1135, 1153, 1163, 1221,
-     1239, 1255, 1267, 1279, 1293, 1305, 1315, 1329, 1341, 1347,
-     1367, 1387, 1413, 1423, 1431, 1441, 1479, 1509, 1527, 1531,
-     1555, 1557, 1573, 1591, 1603, 1615, 1627, 1657, 1663, 1673, 
-     1717, 1729, 1747, 1759, 1789, 1815, 1821, 1825, 1849, 1863,
-     1869, 1877, 1881, 1891, 1917, 1933, 1939, 1969, 2011, 2035,
-     2041, 2053, 2071, 2091, 2093, 2119, 2147, 2149, 2161, 2171,
-     2189, 2197, 2207, 2217, 2225, 2255, 2257, 2273, 2279, 2283,
-     2293, 2317, 2323, 2341, 2345, 2363, 2365, 2373, 2377, 2385,
-     2395, 2419, 2421, 2431, 2435, 2447, 2475, 2477, 2489, 2503, 
-     2521, 2533, 2551, 2561, 2567, 2579, 2581, 2601, 2633, 2657,
-     2669, 2681, 2687, 2693, 2705, 2717, 2727, 2731, 2739, 2741,
-     2773, 2783, 2793, 2799, 2801, 2811, 2819, 2825, 2833, 2867,
-     2879, 2881, 2891, 2905, 2911, 2917, 2927, 2941, 2951, 2955,
-     2963, 2965, 2991, 2999, 3005, 3017, 3035, 3037, 3047, 3053,
-     3083, 3085, 3097, 3103, 3159, 3169, 3179, 3187, 3205, 3209,
-     3223, 3227, 3229, 3251, 3263, 3271, 3277, 3283, 3285, 3299,
-     3305, 3319, 3331, 3343, 3357, 3367, 3373, 3393, 3399, 3413,
-     3417, 3427, 3439, 3441, 3475, 3487, 3497, 3515, 3517, 3529,
-     3543, 3547, 3553, 3559, 3573, 3589, 3613, 3617, 3623, 3627,
-     3635, 3641, 3655, 3659, 3669, 3679, 3697, 3707, 3709, 3713,
-     3731, 3743, 3747, 3771, 3791, 3805, 3827, 3833, 3851, 3865,
-     3889, 3895, 3933, 3947, 3949, 3957, 3971, 3985, 3991, 3995,
-     4007, 4013, 4021, 4045, 4051, 4069, 4073, 4179, 4201, 4219,
-     4221, 4249, 4305, 4331, 4359, 4383, 4387, 4411, 4431, 4439,
-     4449, 4459, 4485, 4531, 4569, 4575, 4621, 4663, 4669, 4711,
-     4723, 4735, 4793, 4801, 4811, 4879, 4893, 4897, 4921, 4927,
-     4941, 4977, 5017, 5027, 5033, 5127, 5169, 5175, 5199, 5213,
-     5223, 5237, 5287, 5293, 5331, 5391, 5405, 5453, 5523, 5573,
-     5591, 5597, 5611, 5641, 5703, 5717, 5721, 5797, 5821, 5909,
-     5913, 5955, 5957, 6005, 6025, 6061, 6067, 6079, 6081, 6231,
-     6237, 6289, 6295, 6329, 6383, 6427, 6453, 6465, 6501, 6523,
-     6539, 6577, 6589, 6601, 6607, 6631, 6683, 6699, 6707, 6761,
-     6795, 6865, 6881, 6901, 6923, 6931, 6943, 6999, 7057, 7079,
-     7103, 7105, 7123, 7173, 7185, 7191, 7207, 7245, 7303, 7327, 
-     7333, 7355, 7365, 7369, 7375, 7411, 7431, 7459, 7491, 7505, 
-     7515, 7541, 7557, 7561, 7701, 7705, 7727, 7749, 7761, 7783,
-     7795, 7823, 7907, 7953, 7963, 7975, 8049, 8089, 8123, 8125,
-     8137, 8219, 8231, 8245, 8275, 8293, 8303, 8331, 8333, 8351,
-     8357, 8367, 8379, 8381, 8387, 8393, 8417, 8435, 8461, 8469,
-     8489, 8495, 8507, 8515, 8551, 8555, 8569, 8585, 8599, 8605,
-     8639, 8641, 8647, 8653, 8671, 8675, 8689, 8699, 8729, 8741,
-     8759, 8765, 8771, 8795, 8797, 8825, 8831, 8841, 8855, 8859,
-     8883, 8895, 8909, 8943, 8951, 8955, 8965, 8999, 9003, 9031,
-     9045, 9049, 9071, 9073, 9085, 9095, 9101, 9109, 9123, 9129,
-     9137, 9143, 9147, 9185, 9197, 9209, 9227, 9235, 9247, 9253,
-     9257, 9277, 9297, 9303, 9313, 9325, 9343, 9347, 9371, 9373,
-     9397, 9407, 9409, 9415, 9419, 9443, 9481, 9495, 9501, 9505,
-     9517, 9529, 9555, 9557, 9571, 9585, 9591, 9607, 9611, 9621,
-     9625, 9631, 9647, 9661, 9669, 9679, 9687, 9707, 9731, 9733,
-     9745, 9773, 9791, 9803, 9811, 9817, 9833, 9847, 9851, 9863,
-     9875, 9881, 9905, 9911, 9917, 9923, 9963, 9973,10003,10025,
-    10043,10063,10071,10077,10091,10099,10105,10115,10129,10145,
-    10169,10183,10187,10207,10223,10225,10247,10265,10271,10275,
-    10289,10299,10301,10309,10343,10357,10373,10411,10413,10431,
-    10445,10453,10463,10467,10473,10491,10505,10511,10513,10523,
-    10539,10549,10559,10561,10571,10581,10615,10621,10625,10643,
-    10655,10671,10679,10685,10691,10711,10739,10741,10755,10767,
-    10781,10785,10803,10805,10829,10857,10863,10865,10875,10877,
-    10917,10921,10929,10949,10967,10971,10987,10995,11009,11029,
-    11043,11045,11055,11063,11075,11081,11117,11135,11141,11159,
-    11163,11181,11187,11225,11237,11261,11279,11297,11307,11309,
-    11327,11329,11341,11377,11403,11405,11413,11427,11439,11453,
-    11461,11473,11479,11489,11495,11499,11533,11545,11561,11567,
-    11575,11579,11589,11611,11623,11637,11657,11663,11687,11691,
-    11701,11747,11761,11773,11783,11795,11797,11817,11849,11855,
-    11867,11869,11873,11883,11919,11921,11927,11933,11947,11955,
-    11961,11999,12027,12029,12037,12041,12049,12055,12095,12097,
-    12107,12109,12121,12127,12133,12137,12181,12197,12207,12209,
-    12239,12253,12263,12269,12277,12287,12295,12309,12313,12335,
-    12361,12367,12391,12409,12415,12433,12449,12469,12479,12481,
-    12499,12505,12517,12527,12549,12559,12597,12615,12621,12639,
-    12643,12657,12667,12707,12713,12727,12741,12745,12763,12769,
-    12779,12781,12787,12799,12809,12815,12829,12839,12857,12875,
-    12883,12889,12901,12929,12947,12953,12959,12969,12983,12987,
-    12995,13015,13019,13031,13063,13077,13103,13137,13149,13173,
-    13207,13211,13227,13241,13249,13255,13269,13283,13285,13303,
-    13307,13321,13339,13351,13377,13389,13407,13417,13431,13435,
-    13447,13459,13465,13477,13501,13513,13531,13543,13561,13581,
-    13599,13605,13617,13623,13637,13647,13661,13677,13683,13695,
-    13725,13729,13753,13773,13781,13785,13795,13801,13807,13825,
-    13835,13855,13861,13871,13883,13897,13905,13915,13939,13941,
-    13969,13979,13981,13997,14027,14035,14037,14051,14063,14085,
-    14095,14107,14113,14125,14137,14145,14151,14163,14193,14199,
-    14219,14229,14233,14243,14277,14287,14289,14295,14301,14305,
-    14323,14339,14341,14359,14365,14375,14387,14411,14425,14441,
-    14449,14499,14513,14523,14537,14543,14561,14579,14585,14593,
-    14599,14603,14611,14641,14671,14695,14701,14723,14725,14743,
-    14753,14759,14765,14795,14797,14803,14831,14839,14845,14855,
-    14889,14895,14909,14929,14941,14945,14951,14963,14965,14985,
-    15033,15039,15053,15059,15061,15071,15077,15081,15099,15121,
-    15147,15149,15157,15167,15187,15193,15203,15205,15215,15217,
-    15223,15243,15257,15269,15273,15287,15291,15313,15335,15347,
-    15359,15373,15379,15381,15391,15395,15397,15419,15439,15453,
-    15469,15491,15503,15517,15527,15531,15545,15559,15593,15611,
-    15613,15619,15639,15643,15649,15661,15667,15669,15681,15693,
-    15717,15721,15741,15745,15765,15793,15799,15811,15825,15835,
-    15847,15851,15865,15877,15881,15887,15899,15915,15935,15937,
-    15955,15973,15977,16011,16035,16061,16069,16087,16093,16097,
-    16121,16141,16153,16159,16165,16183,16189,16195,16197,16201,
-    16209,16215,16225,16259,16265,16273,16299,16309,16355,16375,
-    16381 };
+      1019, 1033, 1051, 1063, 1069, 1125, 1135, 1153, 1163, 1221,
+      1239, 1255, 1267, 1279, 1293, 1305, 1315, 1329, 1341, 1347,
+      1367, 1387, 1413, 1423, 1431, 1441, 1479, 1509, 1527, 1531,
+      1555, 1557, 1573, 1591, 1603, 1615, 1627, 1657, 1663, 1673,
+      1717, 1729, 1747, 1759, 1789, 1815, 1821, 1825, 1849, 1863,
+      1869, 1877, 1881, 1891, 1917, 1933, 1939, 1969, 2011, 2035,
+      2041, 2053, 2071, 2091, 2093, 2119, 2147, 2149, 2161, 2171,
+      2189, 2197, 2207, 2217, 2225, 2255, 2257, 2273, 2279, 2283,
+      2293, 2317, 2323, 2341, 2345, 2363, 2365, 2373, 2377, 2385,
+      2395, 2419, 2421, 2431, 2435, 2447, 2475, 2477, 2489, 2503,
+      2521, 2533, 2551, 2561, 2567, 2579, 2581, 2601, 2633, 2657,
+      2669, 2681, 2687, 2693, 2705, 2717, 2727, 2731, 2739, 2741,
+      2773, 2783, 2793, 2799, 2801, 2811, 2819, 2825, 2833, 2867,
+      2879, 2881, 2891, 2905, 2911, 2917, 2927, 2941, 2951, 2955,
+      2963, 2965, 2991, 2999, 3005, 3017, 3035, 3037, 3047, 3053,
+      3083, 3085, 3097, 3103, 3159, 3169, 3179, 3187, 3205, 3209,
+      3223, 3227, 3229, 3251, 3263, 3271, 3277, 3283, 3285, 3299,
+      3305, 3319, 3331, 3343, 3357, 3367, 3373, 3393, 3399, 3413,
+      3417, 3427, 3439, 3441, 3475, 3487, 3497, 3515, 3517, 3529,
+      3543, 3547, 3553, 3559, 3573, 3589, 3613, 3617, 3623, 3627,
+      3635, 3641, 3655, 3659, 3669, 3679, 3697, 3707, 3709, 3713,
+      3731, 3743, 3747, 3771, 3791, 3805, 3827, 3833, 3851, 3865,
+      3889, 3895, 3933, 3947, 3949, 3957, 3971, 3985, 3991, 3995,
+      4007, 4013, 4021, 4045, 4051, 4069, 4073, 4179, 4201, 4219,
+      4221, 4249, 4305, 4331, 4359, 4383, 4387, 4411, 4431, 4439,
+      4449, 4459, 4485, 4531, 4569, 4575, 4621, 4663, 4669, 4711,
+      4723, 4735, 4793, 4801, 4811, 4879, 4893, 4897, 4921, 4927,
+      4941, 4977, 5017, 5027, 5033, 5127, 5169, 5175, 5199, 5213,
+      5223, 5237, 5287, 5293, 5331, 5391, 5405, 5453, 5523, 5573,
+      5591, 5597, 5611, 5641, 5703, 5717, 5721, 5797, 5821, 5909,
+      5913, 5955, 5957, 6005, 6025, 6061, 6067, 6079, 6081, 6231,
+      6237, 6289, 6295, 6329, 6383, 6427, 6453, 6465, 6501, 6523,
+      6539, 6577, 6589, 6601, 6607, 6631, 6683, 6699, 6707, 6761,
+      6795, 6865, 6881, 6901, 6923, 6931, 6943, 6999, 7057, 7079,
+      7103, 7105, 7123, 7173, 7185, 7191, 7207, 7245, 7303, 7327,
+      7333, 7355, 7365, 7369, 7375, 7411, 7431, 7459, 7491, 7505,
+      7515, 7541, 7557, 7561, 7701, 7705, 7727, 7749, 7761, 7783,
+      7795, 7823, 7907, 7953, 7963, 7975, 8049, 8089, 8123, 8125,
+      8137, 8219, 8231, 8245, 8275, 8293, 8303, 8331, 8333, 8351,
+      8357, 8367, 8379, 8381, 8387, 8393, 8417, 8435, 8461, 8469,
+      8489, 8495, 8507, 8515, 8551, 8555, 8569, 8585, 8599, 8605,
+      8639, 8641, 8647, 8653, 8671, 8675, 8689, 8699, 8729, 8741,
+      8759, 8765, 8771, 8795, 8797, 8825, 8831, 8841, 8855, 8859,
+      8883, 8895, 8909, 8943, 8951, 8955, 8965, 8999, 9003, 9031,
+      9045, 9049, 9071, 9073, 9085, 9095, 9101, 9109, 9123, 9129,
+      9137, 9143, 9147, 9185, 9197, 9209, 9227, 9235, 9247, 9253,
+      9257, 9277, 9297, 9303, 9313, 9325, 9343, 9347, 9371, 9373,
+      9397, 9407, 9409, 9415, 9419, 9443, 9481, 9495, 9501, 9505,
+      9517, 9529, 9555, 9557, 9571, 9585, 9591, 9607, 9611, 9621,
+      9625, 9631, 9647, 9661, 9669, 9679, 9687, 9707, 9731, 9733,
+      9745, 9773, 9791, 9803, 9811, 9817, 9833, 9847, 9851, 9863,
+      9875, 9881, 9905, 9911, 9917, 9923, 9963, 9973, 10003, 10025,
+      10043, 10063, 10071, 10077, 10091, 10099, 10105, 10115, 10129, 10145,
+      10169, 10183, 10187, 10207, 10223, 10225, 10247, 10265, 10271, 10275,
+      10289, 10299, 10301, 10309, 10343, 10357, 10373, 10411, 10413, 10431,
+      10445, 10453, 10463, 10467, 10473, 10491, 10505, 10511, 10513, 10523,
+      10539, 10549, 10559, 10561, 10571, 10581, 10615, 10621, 10625, 10643,
+      10655, 10671, 10679, 10685, 10691, 10711, 10739, 10741, 10755, 10767,
+      10781, 10785, 10803, 10805, 10829, 10857, 10863, 10865, 10875, 10877,
+      10917, 10921, 10929, 10949, 10967, 10971, 10987, 10995, 11009, 11029,
+      11043, 11045, 11055, 11063, 11075, 11081, 11117, 11135, 11141, 11159,
+      11163, 11181, 11187, 11225, 11237, 11261, 11279, 11297, 11307, 11309,
+      11327, 11329, 11341, 11377, 11403, 11405, 11413, 11427, 11439, 11453,
+      11461, 11473, 11479, 11489, 11495, 11499, 11533, 11545, 11561, 11567,
+      11575, 11579, 11589, 11611, 11623, 11637, 11657, 11663, 11687, 11691,
+      11701, 11747, 11761, 11773, 11783, 11795, 11797, 11817, 11849, 11855,
+      11867, 11869, 11873, 11883, 11919, 11921, 11927, 11933, 11947, 11955,
+      11961, 11999, 12027, 12029, 12037, 12041, 12049, 12055, 12095, 12097,
+      12107, 12109, 12121, 12127, 12133, 12137, 12181, 12197, 12207, 12209,
+      12239, 12253, 12263, 12269, 12277, 12287, 12295, 12309, 12313, 12335,
+      12361, 12367, 12391, 12409, 12415, 12433, 12449, 12469, 12479, 12481,
+      12499, 12505, 12517, 12527, 12549, 12559, 12597, 12615, 12621, 12639,
+      12643, 12657, 12667, 12707, 12713, 12727, 12741, 12745, 12763, 12769,
+      12779, 12781, 12787, 12799, 12809, 12815, 12829, 12839, 12857, 12875,
+      12883, 12889, 12901, 12929, 12947, 12953, 12959, 12969, 12983, 12987,
+      12995, 13015, 13019, 13031, 13063, 13077, 13103, 13137, 13149, 13173,
+      13207, 13211, 13227, 13241, 13249, 13255, 13269, 13283, 13285, 13303,
+      13307, 13321, 13339, 13351, 13377, 13389, 13407, 13417, 13431, 13435,
+      13447, 13459, 13465, 13477, 13501, 13513, 13531, 13543, 13561, 13581,
+      13599, 13605, 13617, 13623, 13637, 13647, 13661, 13677, 13683, 13695,
+      13725, 13729, 13753, 13773, 13781, 13785, 13795, 13801, 13807, 13825,
+      13835, 13855, 13861, 13871, 13883, 13897, 13905, 13915, 13939, 13941,
+      13969, 13979, 13981, 13997, 14027, 14035, 14037, 14051, 14063, 14085,
+      14095, 14107, 14113, 14125, 14137, 14145, 14151, 14163, 14193, 14199,
+      14219, 14229, 14233, 14243, 14277, 14287, 14289, 14295, 14301, 14305,
+      14323, 14339, 14341, 14359, 14365, 14375, 14387, 14411, 14425, 14441,
+      14449, 14499, 14513, 14523, 14537, 14543, 14561, 14579, 14585, 14593,
+      14599, 14603, 14611, 14641, 14671, 14695, 14701, 14723, 14725, 14743,
+      14753, 14759, 14765, 14795, 14797, 14803, 14831, 14839, 14845, 14855,
+      14889, 14895, 14909, 14929, 14941, 14945, 14951, 14963, 14965, 14985,
+      15033, 15039, 15053, 15059, 15061, 15071, 15077, 15081, 15099, 15121,
+      15147, 15149, 15157, 15167, 15187, 15193, 15203, 15205, 15215, 15217,
+      15223, 15243, 15257, 15269, 15273, 15287, 15291, 15313, 15335, 15347,
+      15359, 15373, 15379, 15381, 15391, 15395, 15397, 15419, 15439, 15453,
+      15469, 15491, 15503, 15517, 15527, 15531, 15545, 15559, 15593, 15611,
+      15613, 15619, 15639, 15643, 15649, 15661, 15667, 15669, 15681, 15693,
+      15717, 15721, 15741, 15745, 15765, 15793, 15799, 15811, 15825, 15835,
+      15847, 15851, 15865, 15877, 15881, 15887, 15899, 15915, 15935, 15937,
+      15955, 15973, 15977, 16011, 16035, 16061, 16069, 16087, 16093, 16097,
+      16121, 16141, 16153, 16159, 16165, 16183, 16189, 16195, 16197, 16201,
+      16209, 16215, 16225, 16259, 16265, 16273, 16299, 16309, 16355, 16375,
+      16381
+    };
   static T2 recipd;
-  static T1 seed_save = - 1;
-  static T1** v ;
-  if ( !initialized || dim_num != dim_num_save )
-  {
-    v = new T1 *[DIM_MAX] ;
-    for( int i = 0 ; i < DIM_MAX ; i++ )
-      v[i] = new T1[LOG_MAX];
-    initialized = true;
-    initialize_v_array(DIM_MAX, LOG_MAX, v);
-    /*
-    **  Check parameters.
-    */
-    if ( dim_num < 1 || DIM_MAX < dim_num )
+  static T1 seed_save = -1;
+  static T1 **v;
+  if (!initialized || dim_num != dim_num_save)
     {
-      cout << "\n";
-      cout << "NEXT_SOBOL - Fatal error!\n";
-      cout << "  The spatial dimension DIM_NUM should satisfy:\n";
-      cout << "    1 <= DIM_NUM <= " << DIM_MAX << "\n";
-      cout << "  But this input value is DIM_NUM = " << dim_num << "\n";
-      exit ( 1 );
+      v = new T1 *[DIM_MAX];
+      for (int i = 0; i < DIM_MAX; i++)
+        v[i] = new T1[LOG_MAX];
+      initialized = true;
+      initialize_v_array(DIM_MAX, LOG_MAX, v);
+      /*
+      **  Check parameters.
+      */
+      if (dim_num < 1 || DIM_MAX < dim_num)
+        {
+          cout << "\n";
+          cout << "NEXT_SOBOL - Fatal error!\n";
+          cout << "  The spatial dimension DIM_NUM should satisfy:\n";
+          cout << "    1 <= DIM_NUM <= " << DIM_MAX << "\n";
+          cout << "  But this input value is DIM_NUM = " << dim_num << "\n";
+          exit(1);
+        }
+      dim_num_save = dim_num;
+      /*
+      **  Set ATMOST = 2^LOG_MAX - 1.
+      */
+      atmost = (T1) 0;
+      for (int i = 1; i <= LOG_MAX; i++)
+        atmost = 2 * atmost + 1;
+      /*
+      **  Find the highest 1 bit in ATMOST (should be LOG_MAX).
+      */
+      maxcol = bit_hi1(atmost);
+      /*
+      **  Initialize row 1 of V.
+      */
+      for (T1 j = 0; j < maxcol; j++)
+        {
+          v[0][j] = (T1) 1;
+        }
+      /*
+      **  Initialize the remaining rows of V.
+      */
+      for (int i = 1; i < dim_num; i++)
+        {
+          /*
+          **  The bit pattern of the integer POLY(I) gives the form
+          **  of polynomial I.
+          **
+          **  Find the degree of polynomial I from binary encoding.
+          */
+          T1 j = poly[i];
+          T1 m = 0;
+          while (true)
+            {
+              j = j / 2;
+              if (j <= 0)
+                {
+                  break;
+                }
+              m = m + 1;
+            }
+          /*
+          **  We expand this bit pattern to separate components
+          **  of the logical array INCLUD.
+          */
+          j = poly[i];
+          for (T1 k = m-1; 0 <= k; k--)
+            {
+              T1 j2 = j / 2;
+              includ[k] = (j != (2 * j2));
+              j = j2;
+            }
+          /*
+          **  Calculate the remaining elements of row I as explained
+          **  in Bratley and Fox, section 2.
+          **
+          **  Some tricky indexing here.  Did I change it correctly?
+          */
+          for (j = m; j < maxcol; j++)
+            {
+              T1 newv = v[i][j-m];
+              l = 1;
+              for (T1 k = 0; k < m; k++)
+                {
+                  l = 2 * l;
+                  if (includ[k])
+                    {
+                      newv = (newv ^ (l * v[i][j-k-1]));
+                    }
+                }
+              v[i][j] = newv;
+            }
+        }
+      /*
+      **  Multiply columns of V by appropriate power of 2.
+      */
+      l = 1;
+      for (T1 j = maxcol - 2; 0 <= j; j--)
+        {
+          l = 2 * l;
+          for (int i = 0; i < dim_num; i++)
+            {
+              v[i][j] = v[i][j] * l;
+            }
+        }
+      /*
+      **  RECIPD is 1/(common denominator of the elements in V).
+      */
+      recipd = 1.0E+00 / ((T2) (2 * l));
     }
-    dim_num_save = dim_num;
-    /*
-    **  Set ATMOST = 2^LOG_MAX - 1.
-    */
-    atmost = (T1) 0;
-    for ( int i = 1; i <= LOG_MAX; i++ )
-      atmost = 2 * atmost + 1;
-    /*
-    **  Find the highest 1 bit in ATMOST (should be LOG_MAX).
-    */
-    maxcol = bit_hi1 ( atmost );
-    /*
-    **  Initialize row 1 of V.
-    */
-    for ( T1 j = 0; j < maxcol; j++ )
-      {
-        v[0][j] = (T1) 1;
-      }
-    /*
-    **  Initialize the remaining rows of V.
-    */
-    for ( int i = 1; i < dim_num; i++ )
-      {
-        /*
-        **  The bit pattern of the integer POLY(I) gives the form
-        **  of polynomial I.
-        **
-        **  Find the degree of polynomial I from binary encoding.
-        */
-        T1 j = poly[i];
-        T1 m = 0;
-        while ( true )
-          {
-            j = j / 2;
-            if ( j <= 0 )
-              {
-                break;
-              }
-            m = m + 1;
-          }
-        /*
-        **  We expand this bit pattern to separate components
-        **  of the logical array INCLUD.
-        */
-        j = poly[i];
-        for ( T1 k = m-1; 0 <= k; k-- )
-          {
-            T1 j2 = j / 2;
-            includ[k] = ( j != ( 2 * j2 ) );
-            j = j2;
-          }
-        /*
-        **  Calculate the remaining elements of row I as explained
-        **  in Bratley and Fox, section 2.
-        **
-        **  Some tricky indexing here.  Did I change it correctly?
-        */
-        for ( j = m; j < maxcol; j++ )
-          {
-            T1 newv = v[i][j-m];
-            l = 1;
-            for ( T1 k = 0; k < m; k++ )
-              {
-                l = 2 * l;
-                if ( includ[k] )
-                  {
-                    newv = ( newv ^ ( l * v[i][j-k-1] ) );
-                  }
-              }
-            v[i][j] = newv;
-          }
-      }
-    /*
-    **  Multiply columns of V by appropriate power of 2.
-    */
-    l = 1;
-    for ( T1 j = maxcol - 2; 0 <= j; j-- )
-      {
-        l = 2 * l;
-        for ( int i = 0; i < dim_num; i++ )
-          {
-            v[i][j] = v[i][j] * l;
-          }
-      }
-    /*
-    **  RECIPD is 1/(common denominator of the elements in V).
-    */
-    recipd = 1.0E+00 / ( ( T2 ) ( 2 * l ) );
-  }
-  if ( *seed < 0 )
-    *seed = 0 ;
-  
-  if ( *seed == 0 )
+  if (*seed < 0)
+    *seed = 0;
+
+  if (*seed == 0)
     {
       l = 1;
-      for ( int i = 0; i < dim_num; i++ )
+      for (int i = 0; i < dim_num; i++)
         {
           lastq[i] = 0;
         }
     }
-  else if ( *seed == seed_save + 1 )
+  else if (*seed == seed_save + 1)
     {
-      l = bit_lo0 ( *seed );
+      l = bit_lo0(*seed);
     }
-  else if ( *seed <= seed_save )
+  else if (*seed <= seed_save)
     {
       seed_save = 0;
       l = 1;
-      for ( int i = 0; i < dim_num; i++ )
+      for (int i = 0; i < dim_num; i++)
         lastq[i] = 0;
-      for ( T1 seed_temp = seed_save; seed_temp <= (*seed)-1; seed_temp++ )
+      for (T1 seed_temp = seed_save; seed_temp <= (*seed)-1; seed_temp++)
         {
-          l = bit_lo0 ( seed_temp );
-          for ( int i = 0; i < dim_num; i++ )
+          l = bit_lo0(seed_temp);
+          for (int i = 0; i < dim_num; i++)
             {
-              lastq[i] = ( lastq[i] ^ v[i][l-1] );
+              lastq[i] = (lastq[i] ^ v[i][l-1]);
             }
         }
-      l = bit_lo0 ( *seed );
+      l = bit_lo0(*seed);
     }
-  else if ( seed_save+1 < *seed )
+  else if (seed_save+1 < *seed)
     {
-      for ( T1 seed_temp = seed_save+1; seed_temp <= (*seed)-1; seed_temp++ )
+      for (T1 seed_temp = seed_save+1; seed_temp <= (*seed)-1; seed_temp++)
         {
-          l = bit_lo0 ( seed_temp );
-          for ( int i = 0; i < dim_num; i++ )
+          l = bit_lo0(seed_temp);
+          for (int i = 0; i < dim_num; i++)
             {
-              lastq[i] = ( lastq[i] ^ v[i][l-1] );
+              lastq[i] = (lastq[i] ^ v[i][l-1]);
             }
         }
-      l = bit_lo0 ( *seed );
+      l = bit_lo0(*seed);
     }
   /*
   **  Check that the user is not calling too many times!
   */
-  if ( maxcol < l )
+  if (maxcol < l)
     {
       cout << "\n";
       cout << "NEXT_SOBOL - Fatal error!\n";
@@ -526,49 +531,52 @@ template<typename T1, typename T2> void next_sobol ( int dim_num, T1 *seed, T2 *
       cout << "  SEED =   " << *seed  << "\n";
       cout << "  MAXCOL = " << maxcol << "\n";
       cout << "  L =      " << l << "\n";
-      exit ( 2 );
+      exit(2);
     }
   /*
   **  Calculate the new components of QUASI.
   **  The caret indicates the bitwise exclusive OR.
   */
-  for ( int i = 0; i < dim_num; i++ )
+  for (int i = 0; i < dim_num; i++)
     {
-      quasi[i] = ( ( T2 ) lastq[i] ) * recipd;
-      lastq[i] = ( lastq[i]^v[i][l-1] );
+      quasi[i] = ((T2) lastq[i]) * recipd;
+      lastq[i] = (lastq[i]^v[i][l-1]);
     }
   seed_save = *seed;
   *seed = *seed + 1;
   return;
 }
 
-template<typename T1, typename T2> T1 sobol_block( int dimension, int block_size, T1 seed, T2 *block )
+template<typename T1, typename T2>
+T1
+sobol_block(int dimension, int block_size, T1 seed, T2 *block)
 {
-  for ( int iter = 0 ; iter < block_size ; iter++ )
+  for (int iter = 0; iter < block_size; iter++)
     {
-      next_sobol ( dimension, &seed, &block[iter*dimension] );
+      next_sobol(dimension, &seed, &block[iter*dimension]);
     }
   return seed;
 }
 
-template<typename T> void expand_unit_hypercube( int dimension, int block_size, T *block, T *lower_bound, T* upper_bound )
+template<typename T>
+void
+expand_unit_hypercube(int dimension, int block_size, T *block, T *lower_bound, T *upper_bound)
 {
   T *hypercube_length = new T[dimension];
-  for(int dim = 0 ; dim < dimension ; dim++ )
+  for (int dim = 0; dim < dimension; dim++)
     {
-      hypercube_length[dim] = upper_bound[dim]-lower_bound[dim] ; 
+      hypercube_length[dim] = upper_bound[dim]-lower_bound[dim];
     }
   int base = 0;
-  for ( int sim = 0 ; sim < block_size ; sim++ )
+  for (int sim = 0; sim < block_size; sim++)
     {
-      for (int dim = 0 ; dim < dimension ; dim++ )
+      for (int dim = 0; dim < dimension; dim++)
         {
           block[base+dim] = lower_bound[dim] + hypercube_length[dim]*block[base+dim];
         }
-      base+= dimension;
+      base += dimension;
     }
   delete[] hypercube_length;
 }
 
-
 #undef DIM_MAX
diff --git a/others/C/dynare_driver.h b/others/C/dynare_driver.h
index 56091c7d7450b9c68f5dcd6ef59ae51b4946688a..14588c2cdf7a5249a8491df6c5f9cae68a1ca6e0 100644
--- a/others/C/dynare_driver.h
+++ b/others/C/dynare_driver.h
@@ -17,8 +17,9 @@
 #ifndef _DYNARE_C_DRIVER_H
 #define _DYNARE_C_DRIVER_H
 
-struct aux_vars_t {
+struct aux_vars_t
+{
   int endo_index, type, orig_index, orig_lead_lag;
-} ;
+};
 
 #endif // ! _DYNARE_C_DRIVER_H
diff --git a/others/cpp/dynare_cpp_driver.cc b/others/cpp/dynare_cpp_driver.cc
index f6701dd4bd37cfd8743dbf1ee8262c9bf13ca283..2beec52600a7bfd0d8130e736aebc81fe61165f0 100644
--- a/others/cpp/dynare_cpp_driver.cc
+++ b/others/cpp/dynare_cpp_driver.cc
@@ -39,7 +39,7 @@ DynareInfo::DynareInfo(map<string, int > exo_names_arg,
   exo_nbr = exo_names.size();
   exo_det_nbr = exo_det_names.size();
   param_nbr = param_names.size();
-  
+
   exo_names = exo_names_arg;
   exo_det_names = exo_det_names_arg;
   endo_names = endo_names_arg;
@@ -54,27 +54,27 @@ DynareInfo::DynareInfo(map<string, int > exo_names_arg,
 DynareInfo::~DynareInfo()
 {
   for (vector<MarkovSwitching *>::iterator it = markov_switching_vector.begin();
-       it < markov_switching_vector.end(); it++ )
+       it < markov_switching_vector.end(); it++)
     delete *it;
 
   for (vector<ModFilePrior *>::iterator it = prior_vector.begin();
-       it < prior_vector.end(); it++ )
+       it < prior_vector.end(); it++)
     delete *it;
 
   for (vector<ModFileStructuralInnovationPrior *>::iterator it = structural_innovation_prior_vector.begin();
-       it < structural_innovation_prior_vector.end(); it++ )
+       it < structural_innovation_prior_vector.end(); it++)
     delete *it;
 
   for (vector<ModFileMeasurementErrorPrior *>::iterator it = measurement_error_prior_vector.begin();
-       it < measurement_error_prior_vector.end(); it++ )
+       it < measurement_error_prior_vector.end(); it++)
     delete *it;
 
   for (vector<ModFileStructuralInnovationCorrPrior *>::iterator it = structural_innovation_corr_prior_vector.begin();
-       it < structural_innovation_corr_prior_vector.end(); it++ )
+       it < structural_innovation_corr_prior_vector.end(); it++)
     delete *it;
 
   for (vector<ModFileMeasurementErrorCorrPrior *>::iterator it = measurement_error_corr_prior_vector.begin();
-       it < measurement_error_corr_prior_vector.end(); it++ )
+       it < measurement_error_corr_prior_vector.end(); it++)
     delete *it;
 
   markov_switching_vector.clear();
diff --git a/others/cpp/dynare_cpp_driver.hh b/others/cpp/dynare_cpp_driver.hh
index 9e39ee96e5c06e13154cf414a19f1059da9cf633..afdbc21a2ffa8d23d53e45a69981171f19692cd3 100644
--- a/others/cpp/dynare_cpp_driver.hh
+++ b/others/cpp/dynare_cpp_driver.hh
@@ -25,11 +25,12 @@
 
 using namespace std;
 
-struct aux_vars_t {
+struct aux_vars_t
+{
   int endo_index, type, orig_index, orig_lead_lag;
-} ;
+};
 
-typedef map<pair<int, int >, double> restriction_map_t ;
+typedef map<pair<int, int >, double> restriction_map_t;
 
 class ValueNotSetException
 {
@@ -57,21 +58,49 @@ public:
                   const vector<double> duration_arg,
                   const restriction_map_t restriction_map_arg);
 
-  inline bool number_of_lags_has_val() const { return number_of_lags_was_passed; };
-  inline bool restriction_map_has_val() const { return !restriction_map.empty(); };
+  inline bool
+  number_of_lags_has_val() const
+  {
+    return number_of_lags_was_passed;
+  };
+  inline bool
+  restriction_map_has_val() const
+  {
+    return !restriction_map.empty();
+  };
 
-  inline int get_chain() const { return chain; };
-  inline int get_number_of_regimes() const { return number_of_regimes; };
+  inline int
+  get_chain() const
+  {
+    return chain;
+  };
+  inline int
+  get_number_of_regimes() const
+  {
+    return number_of_regimes;
+  };
   int get_number_of_lags() throw (ValueNotSetException);
-  inline vector<int> get_parameters() { return parameters; };
-  inline vector<double> get_duration() { return duration; };
+  inline vector<int>
+  get_parameters()
+  {
+    return parameters;
+  };
+  inline vector<double>
+  get_duration()
+  {
+    return duration;
+  };
   restriction_map_t get_restriction_map() throw (ValueNotSetException);
 };
 
 class BasicModFilePrior
 {
 private:
-  inline bool isnan(double x) const { return (x!=x); };
+  inline bool
+  isnan(double x) const
+  {
+    return (x != x);
+  };
 protected:
   const int index;
   const string shape;
@@ -86,14 +115,42 @@ protected:
                     const double variance_arg,
                     const vector <double> domain_arg);
 public:
-  inline bool mean_has_val() const { return !isnan(mean); };
-  inline bool mode_has_val() const { return !isnan(mode); };
-  inline bool stdev_has_val() const { return !isnan(stdev); };
-  inline bool variance_has_val() const { return !isnan(variance); };
-  inline bool domain_has_val() const { return (domain.size() == 2); };
-
-  inline int get_index() const { return index; };
-  inline string get_shape() const { return shape; };
+  inline bool
+  mean_has_val() const
+  {
+    return !isnan(mean);
+  };
+  inline bool
+  mode_has_val() const
+  {
+    return !isnan(mode);
+  };
+  inline bool
+  stdev_has_val() const
+  {
+    return !isnan(stdev);
+  };
+  inline bool
+  variance_has_val() const
+  {
+    return !isnan(variance);
+  };
+  inline bool
+  domain_has_val() const
+  {
+    return (domain.size() == 2);
+  };
+
+  inline int
+  get_index() const
+  {
+    return index;
+  };
+  inline string
+  get_shape() const
+  {
+    return shape;
+  };
   double get_mean() throw (ValueNotSetException);
   double get_mode() throw (ValueNotSetException);
   double get_stdev() throw (ValueNotSetException);
@@ -113,7 +170,7 @@ public:
                const vector <double> domain_arg);
 };
 
-class ModFileStructuralInnovationPrior: public BasicModFilePrior
+class ModFileStructuralInnovationPrior : public BasicModFilePrior
 {
 public:
   ModFileStructuralInnovationPrior(const int index_arg,
@@ -170,7 +227,11 @@ public:
 class BasicModFileOption
 {
 private:
-  inline bool isnan(double x) const { return (x!=x); };
+  inline bool
+  isnan(double x) const
+  {
+    return (x != x);
+  };
 protected:
   const int index;
   const double init;
@@ -178,8 +239,16 @@ protected:
   BasicModFileOption(const int index_arg,
                      const double init_arg);
 public:
-  inline int get_index() const { return index; };
-  inline double get_init() const { return init; };
+  inline int
+  get_index() const
+  {
+    return index;
+  };
+  inline double
+  get_init() const
+  {
+    return init;
+  };
 };
 
 class ModFileOption : public BasicModFileOption
@@ -189,7 +258,7 @@ public:
                 const double init_arg);
 };
 
-class ModFileStructuralInnovationOption: public BasicModFileOption
+class ModFileStructuralInnovationOption : public BasicModFileOption
 {
 public:
   ModFileStructuralInnovationOption(const int index_arg,
@@ -257,65 +326,269 @@ public:
              vector<int> varobs_arg,
              vector<int> NNZDerivatives_arg);
 
-  inline void addMarkovSwitching(MarkovSwitching *ms) { markov_switching_vector.push_back(ms); };
-
-  inline void addPrior(ModFilePrior *p) { prior_vector.push_back(p); };
-  inline void addStructuralInnovationPrior(ModFileStructuralInnovationPrior *sip) { structural_innovation_prior_vector.push_back(sip); };
-  inline void addMeasurementErrorPrior(ModFileMeasurementErrorPrior *mep) { measurement_error_prior_vector.push_back(mep); };
-  inline void addStructuralInnovationCorrPrior(ModFileStructuralInnovationCorrPrior *sicp) { structural_innovation_corr_prior_vector.push_back(sicp); };
-  inline void addMeasurementErrorCorrPrior(ModFileMeasurementErrorCorrPrior *mecp) { measurement_error_corr_prior_vector.push_back(mecp); };
-
-  inline void addOption(ModFileOption *o) { option_vector.push_back(o); };
-  inline void addStructuralInnovationOption(ModFileStructuralInnovationOption *sio) { structural_innovation_option_vector.push_back(sio); };
-  inline void addMeasurementErrorOption(ModFileMeasurementErrorOption *meo) { measurement_error_option_vector.push_back(meo); };
-  inline void addStructuralInnovationCorrOption(ModFileStructuralInnovationCorrOption *sico) { structural_innovation_corr_option_vector.push_back(sico); };
-  inline void addMeasurementErrorCorrOption(ModFileMeasurementErrorCorrOption *meco) { measurement_error_corr_option_vector.push_back(meco); };
-
-  inline bool markov_switching_has_val() { return !markov_switching_vector.empty(); };
-  inline bool prior_has_val() { return !prior_vector.empty(); };
-  inline bool structural_innovation_prior_has_val() { return !structural_innovation_prior_vector.empty(); };
-  inline bool measurement_error_prior_has_val() { return !measurement_error_prior_vector.empty(); };
-  inline bool structural_innovation_corr_prior_has_val() { return !structural_innovation_corr_prior_vector.empty(); };
-  inline bool measurement_error_corr_prior_has_val() { return !measurement_error_corr_prior_vector.empty(); };
-
-  inline bool option_has_val() { return !option_vector.empty(); };
-  inline bool structural_innovation_option_has_val() { return !structural_innovation_option_vector.empty(); };
-  inline bool measurement_error_option_has_val() { return !measurement_error_option_vector.empty(); };
-  inline bool structural_innovation_corr_option_has_val() { return !structural_innovation_corr_option_vector.empty(); };
-  inline bool measurement_error_corr_option_has_val() { return !measurement_error_corr_option_vector.empty(); };
-
-  inline vector<MarkovSwitching *>get_markov_switching() { return markov_switching_vector; };
-  inline vector<ModFilePrior *> get_prior() { return prior_vector; };
-  inline vector<ModFileStructuralInnovationPrior *> get_structural_innovation_prior() { return structural_innovation_prior_vector; };
-  inline vector<ModFileMeasurementErrorPrior *> get_measurement_error_prior() { return measurement_error_prior_vector; };
-  inline vector<ModFileStructuralInnovationCorrPrior *> get_structural_innovation_corr_prior() { return structural_innovation_corr_prior_vector; };
-  inline vector<ModFileMeasurementErrorCorrPrior *> get_measurement_error_corr_prior() { return measurement_error_corr_prior_vector; };
-
-  inline vector<ModFileOption *> get_option() { return option_vector; };
-  inline vector<ModFileStructuralInnovationOption *> get_structural_innovation_option() { return structural_innovation_option_vector; };
-  inline vector<ModFileMeasurementErrorOption *> get_measurement_error_option() { return measurement_error_option_vector; };
-  inline vector<ModFileStructuralInnovationCorrOption *> get_structural_innovation_corr_option() { return structural_innovation_corr_option_vector; };
-  inline vector<ModFileMeasurementErrorCorrOption *> get_measurement_error_corr_option() { return measurement_error_corr_option_vector; };
-
-  inline map<string, int > get_exo_names() { return exo_names; };
-  inline map<string, int > get_exo_det_names() { return exo_det_names; };
-  inline map<string, int > get_endo_names() { return endo_names; };
-  inline map<string, int > get_param_names() { return param_names; };
-  inline vector<double> get_params() { return params; };
-  inline double *get_params_data(void) { return params.data(); };
-  inline vector <aux_vars_t> get_aux_vars() { return aux_vars; };
-  inline vector <int> get_predetermined_variables() { return predetermined_variables; };
-  inline vector <int> get_varobs() { return varobs; };
-  inline vector<int> get_NNZDerivatives() { return NNZDerivatives; };
-
-  inline int get_endo_nbr(void) { return endo_nbr; };
-  inline int get_exo_nbr(void) { return exo_nbr; };
-  inline int get_exo_det_nbr(void) { return exo_det_nbr; };
-  inline int get_param_nbr(void) { return param_nbr; };
-  inline vector<size_t>  get_zeta_back(void) { return zeta_back; };
-  inline vector<size_t>  get_zeta_fwrd(void) { return zeta_fwrd; };
-  inline vector<size_t>  get_zeta_mixed(void) { return zeta_mixed; };
-  inline vector<size_t>  get_zeta_static(void) { return zeta_static; };
+  inline void
+  addMarkovSwitching(MarkovSwitching *ms)
+  {
+    markov_switching_vector.push_back(ms);
+  };
+
+  inline void
+  addPrior(ModFilePrior *p)
+  {
+    prior_vector.push_back(p);
+  };
+  inline void
+  addStructuralInnovationPrior(ModFileStructuralInnovationPrior *sip)
+  {
+    structural_innovation_prior_vector.push_back(sip);
+  };
+  inline void
+  addMeasurementErrorPrior(ModFileMeasurementErrorPrior *mep)
+  {
+    measurement_error_prior_vector.push_back(mep);
+  };
+  inline void
+  addStructuralInnovationCorrPrior(ModFileStructuralInnovationCorrPrior *sicp)
+  {
+    structural_innovation_corr_prior_vector.push_back(sicp);
+  };
+  inline void
+  addMeasurementErrorCorrPrior(ModFileMeasurementErrorCorrPrior *mecp)
+  {
+    measurement_error_corr_prior_vector.push_back(mecp);
+  };
+
+  inline void
+  addOption(ModFileOption *o)
+  {
+    option_vector.push_back(o);
+  };
+  inline void
+  addStructuralInnovationOption(ModFileStructuralInnovationOption *sio)
+  {
+    structural_innovation_option_vector.push_back(sio);
+  };
+  inline void
+  addMeasurementErrorOption(ModFileMeasurementErrorOption *meo)
+  {
+    measurement_error_option_vector.push_back(meo);
+  };
+  inline void
+  addStructuralInnovationCorrOption(ModFileStructuralInnovationCorrOption *sico)
+  {
+    structural_innovation_corr_option_vector.push_back(sico);
+  };
+  inline void
+  addMeasurementErrorCorrOption(ModFileMeasurementErrorCorrOption *meco)
+  {
+    measurement_error_corr_option_vector.push_back(meco);
+  };
+
+  inline bool
+  markov_switching_has_val()
+  {
+    return !markov_switching_vector.empty();
+  };
+  inline bool
+  prior_has_val()
+  {
+    return !prior_vector.empty();
+  };
+  inline bool
+  structural_innovation_prior_has_val()
+  {
+    return !structural_innovation_prior_vector.empty();
+  };
+  inline bool
+  measurement_error_prior_has_val()
+  {
+    return !measurement_error_prior_vector.empty();
+  };
+  inline bool
+  structural_innovation_corr_prior_has_val()
+  {
+    return !structural_innovation_corr_prior_vector.empty();
+  };
+  inline bool
+  measurement_error_corr_prior_has_val()
+  {
+    return !measurement_error_corr_prior_vector.empty();
+  };
+
+  inline bool
+  option_has_val()
+  {
+    return !option_vector.empty();
+  };
+  inline bool
+  structural_innovation_option_has_val()
+  {
+    return !structural_innovation_option_vector.empty();
+  };
+  inline bool
+  measurement_error_option_has_val()
+  {
+    return !measurement_error_option_vector.empty();
+  };
+  inline bool
+  structural_innovation_corr_option_has_val()
+  {
+    return !structural_innovation_corr_option_vector.empty();
+  };
+  inline bool
+  measurement_error_corr_option_has_val()
+  {
+    return !measurement_error_corr_option_vector.empty();
+  };
+
+  inline vector<MarkovSwitching *>
+  get_markov_switching()
+  {
+    return markov_switching_vector;
+  };
+  inline vector<ModFilePrior *>
+  get_prior()
+  {
+    return prior_vector;
+  };
+  inline vector<ModFileStructuralInnovationPrior *>
+  get_structural_innovation_prior()
+  {
+    return structural_innovation_prior_vector;
+  };
+  inline vector<ModFileMeasurementErrorPrior *>
+  get_measurement_error_prior()
+  {
+    return measurement_error_prior_vector;
+  };
+  inline vector<ModFileStructuralInnovationCorrPrior *>
+  get_structural_innovation_corr_prior()
+  {
+    return structural_innovation_corr_prior_vector;
+  };
+  inline vector<ModFileMeasurementErrorCorrPrior *>
+  get_measurement_error_corr_prior()
+  {
+    return measurement_error_corr_prior_vector;
+  };
+
+  inline vector<ModFileOption *>
+  get_option()
+  {
+    return option_vector;
+  };
+  inline vector<ModFileStructuralInnovationOption *>
+  get_structural_innovation_option()
+  {
+    return structural_innovation_option_vector;
+  };
+  inline vector<ModFileMeasurementErrorOption *>
+  get_measurement_error_option()
+  {
+    return measurement_error_option_vector;
+  };
+  inline vector<ModFileStructuralInnovationCorrOption *>
+  get_structural_innovation_corr_option()
+  {
+    return structural_innovation_corr_option_vector;
+  };
+  inline vector<ModFileMeasurementErrorCorrOption *>
+  get_measurement_error_corr_option()
+  {
+    return measurement_error_corr_option_vector;
+  };
+
+  inline map<string, int >
+  get_exo_names()
+  {
+    return exo_names;
+  };
+  inline map<string, int >
+  get_exo_det_names()
+  {
+    return exo_det_names;
+  };
+  inline map<string, int >
+  get_endo_names()
+  {
+    return endo_names;
+  };
+  inline map<string, int >
+  get_param_names()
+  {
+    return param_names;
+  };
+  inline vector<double>
+  get_params()
+  {
+    return params;
+  };
+  inline double *
+  get_params_data(void)
+  {
+    return params.data();
+  };
+  inline vector <aux_vars_t>
+  get_aux_vars()
+  {
+    return aux_vars;
+  };
+  inline vector <int>
+  get_predetermined_variables()
+  {
+    return predetermined_variables;
+  };
+  inline vector <int>
+  get_varobs()
+  {
+    return varobs;
+  };
+  inline vector<int>
+  get_NNZDerivatives()
+  {
+    return NNZDerivatives;
+  };
+
+  inline int
+  get_endo_nbr(void)
+  {
+    return endo_nbr;
+  };
+  inline int
+  get_exo_nbr(void)
+  {
+    return exo_nbr;
+  };
+  inline int
+  get_exo_det_nbr(void)
+  {
+    return exo_det_nbr;
+  };
+  inline int
+  get_param_nbr(void)
+  {
+    return param_nbr;
+  };
+  inline vector<size_t>
+  get_zeta_back(void)
+  {
+    return zeta_back;
+  };
+  inline vector<size_t>
+  get_zeta_fwrd(void)
+  {
+    return zeta_fwrd;
+  };
+  inline vector<size_t>
+  get_zeta_mixed(void)
+  {
+    return zeta_mixed;
+  };
+  inline vector<size_t>
+  get_zeta_static(void)
+  {
+    return zeta_static;
+  };
 
   string get_exo_name_by_index(int index) throw (ValueNotSetException);
   int get_exo_index_by_name(string name) throw (ValueNotSetException);
diff --git a/others/cpp/dynare_driver.c b/others/cpp/dynare_driver.c
index f6701dd4bd37cfd8743dbf1ee8262c9bf13ca283..2beec52600a7bfd0d8130e736aebc81fe61165f0 100644
--- a/others/cpp/dynare_driver.c
+++ b/others/cpp/dynare_driver.c
@@ -39,7 +39,7 @@ DynareInfo::DynareInfo(map<string, int > exo_names_arg,
   exo_nbr = exo_names.size();
   exo_det_nbr = exo_det_names.size();
   param_nbr = param_names.size();
-  
+
   exo_names = exo_names_arg;
   exo_det_names = exo_det_names_arg;
   endo_names = endo_names_arg;
@@ -54,27 +54,27 @@ DynareInfo::DynareInfo(map<string, int > exo_names_arg,
 DynareInfo::~DynareInfo()
 {
   for (vector<MarkovSwitching *>::iterator it = markov_switching_vector.begin();
-       it < markov_switching_vector.end(); it++ )
+       it < markov_switching_vector.end(); it++)
     delete *it;
 
   for (vector<ModFilePrior *>::iterator it = prior_vector.begin();
-       it < prior_vector.end(); it++ )
+       it < prior_vector.end(); it++)
     delete *it;
 
   for (vector<ModFileStructuralInnovationPrior *>::iterator it = structural_innovation_prior_vector.begin();
-       it < structural_innovation_prior_vector.end(); it++ )
+       it < structural_innovation_prior_vector.end(); it++)
     delete *it;
 
   for (vector<ModFileMeasurementErrorPrior *>::iterator it = measurement_error_prior_vector.begin();
-       it < measurement_error_prior_vector.end(); it++ )
+       it < measurement_error_prior_vector.end(); it++)
     delete *it;
 
   for (vector<ModFileStructuralInnovationCorrPrior *>::iterator it = structural_innovation_corr_prior_vector.begin();
-       it < structural_innovation_corr_prior_vector.end(); it++ )
+       it < structural_innovation_corr_prior_vector.end(); it++)
     delete *it;
 
   for (vector<ModFileMeasurementErrorCorrPrior *>::iterator it = measurement_error_corr_prior_vector.begin();
-       it < measurement_error_corr_prior_vector.end(); it++ )
+       it < measurement_error_corr_prior_vector.end(); it++)
     delete *it;
 
   markov_switching_vector.clear();
diff --git a/others/cpp/dynare_driver.h b/others/cpp/dynare_driver.h
index 581cdd6eae7f38d08155081a674516fbcee84b75..3dcb7acd9e0c94ff52943af5c8d24f9f79fd179f 100644
--- a/others/cpp/dynare_driver.h
+++ b/others/cpp/dynare_driver.h
@@ -25,11 +25,12 @@
 
 using namespace std;
 
-struct aux_vars_t {
+struct aux_vars_t
+{
   int endo_index, type, orig_index, orig_lead_lag;
-} ;
+};
 
-typedef map<pair<int, int >, double> restriction_map_t ;
+typedef map<pair<int, int >, double> restriction_map_t;
 
 class ValueNotSetException
 {
@@ -57,21 +58,49 @@ public:
                   const vector<double> duration_arg,
                   const restriction_map_t restriction_map_arg);
 
-  inline bool number_of_lags_has_val() const { return number_of_lags_was_passed; };
-  inline bool restriction_map_has_val() const { return !restriction_map.empty(); };
+  inline bool
+  number_of_lags_has_val() const
+  {
+    return number_of_lags_was_passed;
+  };
+  inline bool
+  restriction_map_has_val() const
+  {
+    return !restriction_map.empty();
+  };
 
-  inline int get_chain() const { return chain; };
-  inline int get_number_of_regimes() const { return number_of_regimes; };
+  inline int
+  get_chain() const
+  {
+    return chain;
+  };
+  inline int
+  get_number_of_regimes() const
+  {
+    return number_of_regimes;
+  };
   int get_number_of_lags() throw (ValueNotSetException);
-  inline vector<int> get_parameters() { return parameters; };
-  inline vector<double> get_duration() { return duration; };
+  inline vector<int>
+  get_parameters()
+  {
+    return parameters;
+  };
+  inline vector<double>
+  get_duration()
+  {
+    return duration;
+  };
   restriction_map_t get_restriction_map() throw (ValueNotSetException);
 };
 
 class BasicModFilePrior
 {
 private:
-  inline bool isnan(double x) const { return (x!=x); };
+  inline bool
+  isnan(double x) const
+  {
+    return (x != x);
+  };
 protected:
   const int index;
   const string shape;
@@ -86,14 +115,42 @@ protected:
                     const double variance_arg,
                     const vector <double> domain_arg);
 public:
-  inline bool mean_has_val() const { return !isnan(mean); };
-  inline bool mode_has_val() const { return !isnan(mode); };
-  inline bool stdev_has_val() const { return !isnan(stdev); };
-  inline bool variance_has_val() const { return !isnan(variance); };
-  inline bool domain_has_val() const { return (domain.size() == 2); };
-
-  inline int get_index() const { return index; };
-  inline string get_shape() const { return shape; };
+  inline bool
+  mean_has_val() const
+  {
+    return !isnan(mean);
+  };
+  inline bool
+  mode_has_val() const
+  {
+    return !isnan(mode);
+  };
+  inline bool
+  stdev_has_val() const
+  {
+    return !isnan(stdev);
+  };
+  inline bool
+  variance_has_val() const
+  {
+    return !isnan(variance);
+  };
+  inline bool
+  domain_has_val() const
+  {
+    return (domain.size() == 2);
+  };
+
+  inline int
+  get_index() const
+  {
+    return index;
+  };
+  inline string
+  get_shape() const
+  {
+    return shape;
+  };
   double get_mean() throw (ValueNotSetException);
   double get_mode() throw (ValueNotSetException);
   double get_stdev() throw (ValueNotSetException);
@@ -113,7 +170,7 @@ public:
                const vector <double> domain_arg);
 };
 
-class ModFileStructuralInnovationPrior: public BasicModFilePrior
+class ModFileStructuralInnovationPrior : public BasicModFilePrior
 {
 public:
   ModFileStructuralInnovationPrior(const int index_arg,
@@ -170,7 +227,11 @@ public:
 class BasicModFileOption
 {
 private:
-  inline bool isnan(double x) const { return (x!=x); };
+  inline bool
+  isnan(double x) const
+  {
+    return (x != x);
+  };
 protected:
   const int index;
   const double init;
@@ -178,8 +239,16 @@ protected:
   BasicModFileOption(const int index_arg,
                      const double init_arg);
 public:
-  inline int get_index() const { return index; };
-  inline double get_init() const { return init; };
+  inline int
+  get_index() const
+  {
+    return index;
+  };
+  inline double
+  get_init() const
+  {
+    return init;
+  };
 };
 
 class ModFileOption : public BasicModFileOption
@@ -189,7 +258,7 @@ public:
                 const double init_arg);
 };
 
-class ModFileStructuralInnovationOption: public BasicModFileOption
+class ModFileStructuralInnovationOption : public BasicModFileOption
 {
 public:
   ModFileStructuralInnovationOption(const int index_arg,
@@ -258,65 +327,269 @@ public:
              vector<int> NNZDerivatives_arg);
   ~DynareInfo();
 
-  inline void addMarkovSwitching(MarkovSwitching *ms) { markov_switching_vector.push_back(ms); };
-
-  inline void addPrior(ModFilePrior *p) { prior_vector.push_back(p); };
-  inline void addStructuralInnovationPrior(ModFileStructuralInnovationPrior *sip) { structural_innovation_prior_vector.push_back(sip); };
-  inline void addMeasurementErrorPrior(ModFileMeasurementErrorPrior *mep) { measurement_error_prior_vector.push_back(mep); };
-  inline void addStructuralInnovationCorrPrior(ModFileStructuralInnovationCorrPrior *sicp) { structural_innovation_corr_prior_vector.push_back(sicp); };
-  inline void addMeasurementErrorCorrPrior(ModFileMeasurementErrorCorrPrior *mecp) { measurement_error_corr_prior_vector.push_back(mecp); };
-
-  inline void addOption(ModFileOption *o) { option_vector.push_back(o); };
-  inline void addStructuralInnovationOption(ModFileStructuralInnovationOption *sio) { structural_innovation_option_vector.push_back(sio); };
-  inline void addMeasurementErrorOption(ModFileMeasurementErrorOption *meo) { measurement_error_option_vector.push_back(meo); };
-  inline void addStructuralInnovationCorrOption(ModFileStructuralInnovationCorrOption *sico) { structural_innovation_corr_option_vector.push_back(sico); };
-  inline void addMeasurementErrorCorrOption(ModFileMeasurementErrorCorrOption *meco) { measurement_error_corr_option_vector.push_back(meco); };
-
-  inline bool markov_switching_has_val() { return !markov_switching_vector.empty(); };
-  inline bool prior_has_val() { return !prior_vector.empty(); };
-  inline bool structural_innovation_prior_has_val() { return !structural_innovation_prior_vector.empty(); };
-  inline bool measurement_error_prior_has_val() { return !measurement_error_prior_vector.empty(); };
-  inline bool structural_innovation_corr_prior_has_val() { return !structural_innovation_corr_prior_vector.empty(); };
-  inline bool measurement_error_corr_prior_has_val() { return !measurement_error_corr_prior_vector.empty(); };
-
-  inline bool option_has_val() { return !option_vector.empty(); };
-  inline bool structural_innovation_option_has_val() { return !structural_innovation_option_vector.empty(); };
-  inline bool measurement_error_option_has_val() { return !measurement_error_option_vector.empty(); };
-  inline bool structural_innovation_corr_option_has_val() { return !structural_innovation_corr_option_vector.empty(); };
-  inline bool measurement_error_corr_option_has_val() { return !measurement_error_corr_option_vector.empty(); };
-
-  inline vector<MarkovSwitching *>get_markov_switching() { return markov_switching_vector; };
-  inline vector<ModFilePrior *> get_prior() { return prior_vector; };
-  inline vector<ModFileStructuralInnovationPrior *> get_structural_innovation_prior() { return structural_innovation_prior_vector; };
-  inline vector<ModFileMeasurementErrorPrior *> get_measurement_error_prior() { return measurement_error_prior_vector; };
-  inline vector<ModFileStructuralInnovationCorrPrior *> get_structural_innovation_corr_prior() { return structural_innovation_corr_prior_vector; };
-  inline vector<ModFileMeasurementErrorCorrPrior *> get_measurement_error_corr_prior() { return measurement_error_corr_prior_vector; };
-
-  inline vector<ModFileOption *> get_option() { return option_vector; };
-  inline vector<ModFileStructuralInnovationOption *> get_structural_innovation_option() { return structural_innovation_option_vector; };
-  inline vector<ModFileMeasurementErrorOption *> get_measurement_error_option() { return measurement_error_option_vector; };
-  inline vector<ModFileStructuralInnovationCorrOption *> get_structural_innovation_corr_option() { return structural_innovation_corr_option_vector; };
-  inline vector<ModFileMeasurementErrorCorrOption *> get_measurement_error_corr_option() { return measurement_error_corr_option_vector; };
-
-  inline map<string, int > get_exo_names() { return exo_names; };
-  inline map<string, int > get_exo_det_names() { return exo_det_names; };
-  inline map<string, int > get_endo_names() { return endo_names; };
-  inline map<string, int > get_param_names() { return param_names; };
-  inline vector<double> get_params() { return params; };
-  inline double *get_params_data(void) { return params.data(); };
-  inline vector <aux_vars_t> get_aux_vars() { return aux_vars; };
-  inline vector <int> get_predetermined_variables() { return predetermined_variables; };
-  inline vector <int> get_varobs() { return varobs; };
-  inline vector<int> get_NNZDerivatives() { return NNZDerivatives; };
-
-  inline int get_endo_nbr(void) { return endo_nbr; };
-  inline int get_exo_nbr(void) { return exo_nbr; };
-  inline int get_exo_det_nbr(void) { return exo_det_nbr; };
-  inline int get_param_nbr(void) { return param_nbr; };
-  inline vector<size_t>  get_zeta_back(void) { return zeta_back; };
-  inline vector<size_t>  get_zeta_fwrd(void) { return zeta_fwrd; };
-  inline vector<size_t>  get_zeta_mixed(void) { return zeta_mixed; };
-  inline vector<size_t>  get_zeta_static(void) { return zeta_static; };
+  inline void
+  addMarkovSwitching(MarkovSwitching *ms)
+  {
+    markov_switching_vector.push_back(ms);
+  };
+
+  inline void
+  addPrior(ModFilePrior *p)
+  {
+    prior_vector.push_back(p);
+  };
+  inline void
+  addStructuralInnovationPrior(ModFileStructuralInnovationPrior *sip)
+  {
+    structural_innovation_prior_vector.push_back(sip);
+  };
+  inline void
+  addMeasurementErrorPrior(ModFileMeasurementErrorPrior *mep)
+  {
+    measurement_error_prior_vector.push_back(mep);
+  };
+  inline void
+  addStructuralInnovationCorrPrior(ModFileStructuralInnovationCorrPrior *sicp)
+  {
+    structural_innovation_corr_prior_vector.push_back(sicp);
+  };
+  inline void
+  addMeasurementErrorCorrPrior(ModFileMeasurementErrorCorrPrior *mecp)
+  {
+    measurement_error_corr_prior_vector.push_back(mecp);
+  };
+
+  inline void
+  addOption(ModFileOption *o)
+  {
+    option_vector.push_back(o);
+  };
+  inline void
+  addStructuralInnovationOption(ModFileStructuralInnovationOption *sio)
+  {
+    structural_innovation_option_vector.push_back(sio);
+  };
+  inline void
+  addMeasurementErrorOption(ModFileMeasurementErrorOption *meo)
+  {
+    measurement_error_option_vector.push_back(meo);
+  };
+  inline void
+  addStructuralInnovationCorrOption(ModFileStructuralInnovationCorrOption *sico)
+  {
+    structural_innovation_corr_option_vector.push_back(sico);
+  };
+  inline void
+  addMeasurementErrorCorrOption(ModFileMeasurementErrorCorrOption *meco)
+  {
+    measurement_error_corr_option_vector.push_back(meco);
+  };
+
+  inline bool
+  markov_switching_has_val()
+  {
+    return !markov_switching_vector.empty();
+  };
+  inline bool
+  prior_has_val()
+  {
+    return !prior_vector.empty();
+  };
+  inline bool
+  structural_innovation_prior_has_val()
+  {
+    return !structural_innovation_prior_vector.empty();
+  };
+  inline bool
+  measurement_error_prior_has_val()
+  {
+    return !measurement_error_prior_vector.empty();
+  };
+  inline bool
+  structural_innovation_corr_prior_has_val()
+  {
+    return !structural_innovation_corr_prior_vector.empty();
+  };
+  inline bool
+  measurement_error_corr_prior_has_val()
+  {
+    return !measurement_error_corr_prior_vector.empty();
+  };
+
+  inline bool
+  option_has_val()
+  {
+    return !option_vector.empty();
+  };
+  inline bool
+  structural_innovation_option_has_val()
+  {
+    return !structural_innovation_option_vector.empty();
+  };
+  inline bool
+  measurement_error_option_has_val()
+  {
+    return !measurement_error_option_vector.empty();
+  };
+  inline bool
+  structural_innovation_corr_option_has_val()
+  {
+    return !structural_innovation_corr_option_vector.empty();
+  };
+  inline bool
+  measurement_error_corr_option_has_val()
+  {
+    return !measurement_error_corr_option_vector.empty();
+  };
+
+  inline vector<MarkovSwitching *>
+  get_markov_switching()
+  {
+    return markov_switching_vector;
+  };
+  inline vector<ModFilePrior *>
+  get_prior()
+  {
+    return prior_vector;
+  };
+  inline vector<ModFileStructuralInnovationPrior *>
+  get_structural_innovation_prior()
+  {
+    return structural_innovation_prior_vector;
+  };
+  inline vector<ModFileMeasurementErrorPrior *>
+  get_measurement_error_prior()
+  {
+    return measurement_error_prior_vector;
+  };
+  inline vector<ModFileStructuralInnovationCorrPrior *>
+  get_structural_innovation_corr_prior()
+  {
+    return structural_innovation_corr_prior_vector;
+  };
+  inline vector<ModFileMeasurementErrorCorrPrior *>
+  get_measurement_error_corr_prior()
+  {
+    return measurement_error_corr_prior_vector;
+  };
+
+  inline vector<ModFileOption *>
+  get_option()
+  {
+    return option_vector;
+  };
+  inline vector<ModFileStructuralInnovationOption *>
+  get_structural_innovation_option()
+  {
+    return structural_innovation_option_vector;
+  };
+  inline vector<ModFileMeasurementErrorOption *>
+  get_measurement_error_option()
+  {
+    return measurement_error_option_vector;
+  };
+  inline vector<ModFileStructuralInnovationCorrOption *>
+  get_structural_innovation_corr_option()
+  {
+    return structural_innovation_corr_option_vector;
+  };
+  inline vector<ModFileMeasurementErrorCorrOption *>
+  get_measurement_error_corr_option()
+  {
+    return measurement_error_corr_option_vector;
+  };
+
+  inline map<string, int >
+  get_exo_names()
+  {
+    return exo_names;
+  };
+  inline map<string, int >
+  get_exo_det_names()
+  {
+    return exo_det_names;
+  };
+  inline map<string, int >
+  get_endo_names()
+  {
+    return endo_names;
+  };
+  inline map<string, int >
+  get_param_names()
+  {
+    return param_names;
+  };
+  inline vector<double>
+  get_params()
+  {
+    return params;
+  };
+  inline double *
+  get_params_data(void)
+  {
+    return params.data();
+  };
+  inline vector <aux_vars_t>
+  get_aux_vars()
+  {
+    return aux_vars;
+  };
+  inline vector <int>
+  get_predetermined_variables()
+  {
+    return predetermined_variables;
+  };
+  inline vector <int>
+  get_varobs()
+  {
+    return varobs;
+  };
+  inline vector<int>
+  get_NNZDerivatives()
+  {
+    return NNZDerivatives;
+  };
+
+  inline int
+  get_endo_nbr(void)
+  {
+    return endo_nbr;
+  };
+  inline int
+  get_exo_nbr(void)
+  {
+    return exo_nbr;
+  };
+  inline int
+  get_exo_det_nbr(void)
+  {
+    return exo_det_nbr;
+  };
+  inline int
+  get_param_nbr(void)
+  {
+    return param_nbr;
+  };
+  inline vector<size_t>
+  get_zeta_back(void)
+  {
+    return zeta_back;
+  };
+  inline vector<size_t>
+  get_zeta_fwrd(void)
+  {
+    return zeta_fwrd;
+  };
+  inline vector<size_t>
+  get_zeta_mixed(void)
+  {
+    return zeta_mixed;
+  };
+  inline vector<size_t>
+  get_zeta_static(void)
+  {
+    return zeta_static;
+  };
 
   string get_exo_name_by_index(int index) throw (ValueNotSetException);
   int get_exo_index_by_name(string name) throw (ValueNotSetException);
diff --git a/others/cpp/ms_dsge_c_driver.cc b/others/cpp/ms_dsge_c_driver.cc
index 6815205312b12c870e39226bb1245a7febf50fb1..b1183a845505421ec184d2b588a8c574cbc82f0d 100644
--- a/others/cpp/ms_dsge_c_driver.cc
+++ b/others/cpp/ms_dsge_c_driver.cc
@@ -50,27 +50,27 @@ MsDsgeInfo::MsDsgeInfo(map<string, int > exo_names_arg,
 MsDsgeInfo::~MsDsgeInfo()
 {
   for (vector<MarkovSwitching *>::iterator it = markov_switching_vector.begin();
-       it < markov_switching_vector.end(); it++ )
+       it < markov_switching_vector.end(); it++)
     delete *it;
 
   for (vector<ModFilePrior *>::iterator it = prior_vector.begin();
-       it < prior_vector.end(); it++ )
+       it < prior_vector.end(); it++)
     delete *it;
 
   for (vector<ModFileStructuralInnovationPrior *>::iterator it = structural_innovation_prior_vector.begin();
-       it < structural_innovation_prior_vector.end(); it++ )
+       it < structural_innovation_prior_vector.end(); it++)
     delete *it;
 
   for (vector<ModFileMeasurementErrorPrior *>::iterator it = measurement_error_prior_vector.begin();
-       it < measurement_error_prior_vector.end(); it++ )
+       it < measurement_error_prior_vector.end(); it++)
     delete *it;
 
   for (vector<ModFileStructuralInnovationCorrPrior *>::iterator it = structural_innovation_corr_prior_vector.begin();
-       it < structural_innovation_corr_prior_vector.end(); it++ )
+       it < structural_innovation_corr_prior_vector.end(); it++)
     delete *it;
 
   for (vector<ModFileMeasurementErrorCorrPrior *>::iterator it = measurement_error_corr_prior_vector.begin();
-       it < measurement_error_corr_prior_vector.end(); it++ )
+       it < measurement_error_corr_prior_vector.end(); it++)
     delete *it;
 
   markov_switching_vector.clear();
diff --git a/others/cpp/ms_dsge_c_driver.hh b/others/cpp/ms_dsge_c_driver.hh
index 9e968b4b6cc08261e76c6cd6944d83b315220ffe..194cfa94dd446a55aefcd5fdcd43b2de83c2df8a 100644
--- a/others/cpp/ms_dsge_c_driver.hh
+++ b/others/cpp/ms_dsge_c_driver.hh
@@ -25,11 +25,12 @@
 
 using namespace std;
 
-struct aux_vars_t {
+struct aux_vars_t
+{
   int endo_index, type, orig_index, orig_lead_lag;
-} ;
+};
 
-typedef map<pair<int, int >, double> restriction_map_t ;
+typedef map<pair<int, int >, double> restriction_map_t;
 
 class ValueNotSetException
 {
@@ -57,21 +58,49 @@ public:
                   const vector<double> duration_arg,
                   const restriction_map_t restriction_map_arg);
 
-  inline bool number_of_lags_has_val() const { return number_of_lags_was_passed; };
-  inline bool restriction_map_has_val() const { return !restriction_map.empty(); };
+  inline bool
+  number_of_lags_has_val() const
+  {
+    return number_of_lags_was_passed;
+  };
+  inline bool
+  restriction_map_has_val() const
+  {
+    return !restriction_map.empty();
+  };
 
-  inline int get_chain() const { return chain; };
-  inline int get_number_of_regimes() const { return number_of_regimes; };
+  inline int
+  get_chain() const
+  {
+    return chain;
+  };
+  inline int
+  get_number_of_regimes() const
+  {
+    return number_of_regimes;
+  };
   int get_number_of_lags() throw (ValueNotSetException);
-  inline vector<int> get_parameters() { return parameters; };
-  inline vector<double> get_duration() { return duration; };
+  inline vector<int>
+  get_parameters()
+  {
+    return parameters;
+  };
+  inline vector<double>
+  get_duration()
+  {
+    return duration;
+  };
   restriction_map_t get_restriction_map() throw (ValueNotSetException);
 };
 
 class BasicModFilePrior
 {
 private:
-  inline bool isnan(double x) const { return (x!=x); };
+  inline bool
+  isnan(double x) const
+  {
+    return (x != x);
+  };
 protected:
   const int index;
   const string shape;
@@ -86,14 +115,42 @@ protected:
                     const double variance_arg,
                     const vector <double> domain_arg);
 public:
-  inline bool mean_has_val() const { return !isnan(mean); };
-  inline bool mode_has_val() const { return !isnan(mode); };
-  inline bool stdev_has_val() const { return !isnan(stdev); };
-  inline bool variance_has_val() const { return !isnan(variance); };
-  inline bool domain_has_val() const { return (domain.size() == 2); };
-
-  inline int get_index() const { return index; };
-  inline string get_shape() const { return shape; };
+  inline bool
+  mean_has_val() const
+  {
+    return !isnan(mean);
+  };
+  inline bool
+  mode_has_val() const
+  {
+    return !isnan(mode);
+  };
+  inline bool
+  stdev_has_val() const
+  {
+    return !isnan(stdev);
+  };
+  inline bool
+  variance_has_val() const
+  {
+    return !isnan(variance);
+  };
+  inline bool
+  domain_has_val() const
+  {
+    return (domain.size() == 2);
+  };
+
+  inline int
+  get_index() const
+  {
+    return index;
+  };
+  inline string
+  get_shape() const
+  {
+    return shape;
+  };
   double get_mean() throw (ValueNotSetException);
   double get_mode() throw (ValueNotSetException);
   double get_stdev() throw (ValueNotSetException);
@@ -113,7 +170,7 @@ public:
                const vector <double> domain_arg);
 };
 
-class ModFileStructuralInnovationPrior: public BasicModFilePrior
+class ModFileStructuralInnovationPrior : public BasicModFilePrior
 {
 public:
   ModFileStructuralInnovationPrior(const int index_arg,
@@ -170,7 +227,11 @@ public:
 class BasicModFileOption
 {
 private:
-  inline bool isnan(double x) const { return (x!=x); };
+  inline bool
+  isnan(double x) const
+  {
+    return (x != x);
+  };
 protected:
   const int index;
   const double init;
@@ -178,8 +239,16 @@ protected:
   BasicModFileOption(const int index_arg,
                      const double init_arg);
 public:
-  inline int get_index() const { return index; };
-  inline double get_init() const { return init; };
+  inline int
+  get_index() const
+  {
+    return index;
+  };
+  inline double
+  get_init() const
+  {
+    return init;
+  };
 };
 
 class ModFileOption : public BasicModFileOption
@@ -189,7 +258,7 @@ public:
                 const double init_arg);
 };
 
-class ModFileStructuralInnovationOption: public BasicModFileOption
+class ModFileStructuralInnovationOption : public BasicModFileOption
 {
 public:
   ModFileStructuralInnovationOption(const int index_arg,
@@ -242,7 +311,7 @@ private:
   vector<aux_vars_t> aux_vars;
   vector<int> predetermined_variables;
   vector<int> varobs;
-  vector<vector<int > >lead_lag_incidence;
+  vector<vector<int > > lead_lag_incidence;
   vector<double> NNZDerivatives;
 public:
   DynareInfo(map<string, int > exo_names_arg,
@@ -257,56 +326,228 @@ public:
              vector<double> NNZDerivatives_arg);
   ~DynareInfo();
 
-  inline void addMarkovSwitching(MarkovSwitching *ms) { markov_switching_vector.push_back(ms); };
-
-  inline void addPrior(ModFilePrior *p) { prior_vector.push_back(p); };
-  inline void addStructuralInnovationPrior(ModFileStructuralInnovationPrior *sip) { structural_innovation_prior_vector.push_back(sip); };
-  inline void addMeasurementErrorPrior(ModFileMeasurementErrorPrior *mep) { measurement_error_prior_vector.push_back(mep); };
-  inline void addStructuralInnovationCorrPrior(ModFileStructuralInnovationCorrPrior *sicp) { structural_innovation_corr_prior_vector.push_back(sicp); };
-  inline void addMeasurementErrorCorrPrior(ModFileMeasurementErrorCorrPrior *mecp) { measurement_error_corr_prior_vector.push_back(mecp); };
-
-  inline void addOption(ModFileOption *o) { option_vector.push_back(o); };
-  inline void addStructuralInnovationOption(ModFileStructuralInnovationOption *sio) { structural_innovation_option_vector.push_back(sio); };
-  inline void addMeasurementErrorOption(ModFileMeasurementErrorOption *meo) { measurement_error_option_vector.push_back(meo); };
-  inline void addStructuralInnovationCorrOption(ModFileStructuralInnovationCorrOption *sico) { structural_innovation_corr_option_vector.push_back(sico); };
-  inline void addMeasurementErrorCorrOption(ModFileMeasurementErrorCorrOption *meco) { measurement_error_corr_option_vector.push_back(meco); };
-
-  inline bool markov_switching_has_val() { return !markov_switching_vector.empty(); };
-  inline bool prior_has_val() { return !prior_vector.empty(); };
-  inline bool structural_innovation_prior_has_val() { return !structural_innovation_prior_vector.empty(); };
-  inline bool measurement_error_prior_has_val() { return !measurement_error_prior_vector.empty(); };
-  inline bool structural_innovation_corr_prior_has_val() { return !structural_innovation_corr_prior_vector.empty(); };
-  inline bool measurement_error_corr_prior_has_val() { return !measurement_error_corr_prior_vector.empty(); };
-
-  inline bool option_has_val() { return !option_vector.empty(); };
-  inline bool structural_innovation_option_has_val() { return !structural_innovation_option_vector.empty(); };
-  inline bool measurement_error_option_has_val() { return !measurement_error_option_vector.empty(); };
-  inline bool structural_innovation_corr_option_has_val() { return !structural_innovation_corr_option_vector.empty(); };
-  inline bool measurement_error_corr_option_has_val() { return !measurement_error_corr_option_vector.empty(); };
-
-  inline vector<MarkovSwitching *>get_markov_switching() { return markov_switching_vector; };
-  inline vector<ModFilePrior *> get_prior() { return prior_vector; };
-  inline vector<ModFileStructuralInnovationPrior *> get_structural_innovation_prior() { return structural_innovation_prior_vector; };
-  inline vector<ModFileMeasurementErrorPrior *> get_measurement_error_prior() { return measurement_error_prior_vector; };
-  inline vector<ModFileStructuralInnovationCorrPrior *> get_structural_innovation_corr_prior() { return structural_innovation_corr_prior_vector; };
-  inline vector<ModFileMeasurementErrorCorrPrior *> get_measurement_error_corr_prior() { return measurement_error_corr_prior_vector; };
-
-  inline vector<ModFileOption *> get_option() { return option_vector; };
-  inline vector<ModFileStructuralInnovationOption *> get_structural_innovation_option() { return structural_innovation_option_vector; };
-  inline vector<ModFileMeasurementErrorOption *> get_measurement_error_option() { return measurement_error_option_vector; };
-  inline vector<ModFileStructuralInnovationCorrOption *> get_structural_innovation_corr_option() { return structural_innovation_corr_option_vector; };
-  inline vector<ModFileMeasurementErrorCorrOption *> get_measurement_error_corr_option() { return measurement_error_corr_option_vector; };
-
-  inline map<string, int > get_exo_names() { return exo_names; };
-  inline map<string, int > get_exo_det_names() { return exo_det_names; };
-  inline map<string, int > get_endo_names() { return endo_names; };
-  inline map<string, int > get_param_names() { return param_names; };
-  inline map<int, double > get_params() { return params; };
-  inline vector <aux_vars_t> get_aux_vars() { return aux_vars; };
-  inline vector <int> get_predetermined_variables() { return predetermined_variables; };
-  inline vector <int> get_varobs() { return varobs; };
-  inline vector<vector<int > > get_lead_lag_incidence() { return lead_lag_incidence; };
-  inline vector<double> get_NNZDerivatives() { return NNZDerivatives; };
+  inline void
+  addMarkovSwitching(MarkovSwitching *ms)
+  {
+    markov_switching_vector.push_back(ms);
+  };
+
+  inline void
+  addPrior(ModFilePrior *p)
+  {
+    prior_vector.push_back(p);
+  };
+  inline void
+  addStructuralInnovationPrior(ModFileStructuralInnovationPrior *sip)
+  {
+    structural_innovation_prior_vector.push_back(sip);
+  };
+  inline void
+  addMeasurementErrorPrior(ModFileMeasurementErrorPrior *mep)
+  {
+    measurement_error_prior_vector.push_back(mep);
+  };
+  inline void
+  addStructuralInnovationCorrPrior(ModFileStructuralInnovationCorrPrior *sicp)
+  {
+    structural_innovation_corr_prior_vector.push_back(sicp);
+  };
+  inline void
+  addMeasurementErrorCorrPrior(ModFileMeasurementErrorCorrPrior *mecp)
+  {
+    measurement_error_corr_prior_vector.push_back(mecp);
+  };
+
+  inline void
+  addOption(ModFileOption *o)
+  {
+    option_vector.push_back(o);
+  };
+  inline void
+  addStructuralInnovationOption(ModFileStructuralInnovationOption *sio)
+  {
+    structural_innovation_option_vector.push_back(sio);
+  };
+  inline void
+  addMeasurementErrorOption(ModFileMeasurementErrorOption *meo)
+  {
+    measurement_error_option_vector.push_back(meo);
+  };
+  inline void
+  addStructuralInnovationCorrOption(ModFileStructuralInnovationCorrOption *sico)
+  {
+    structural_innovation_corr_option_vector.push_back(sico);
+  };
+  inline void
+  addMeasurementErrorCorrOption(ModFileMeasurementErrorCorrOption *meco)
+  {
+    measurement_error_corr_option_vector.push_back(meco);
+  };
+
+  inline bool
+  markov_switching_has_val()
+  {
+    return !markov_switching_vector.empty();
+  };
+  inline bool
+  prior_has_val()
+  {
+    return !prior_vector.empty();
+  };
+  inline bool
+  structural_innovation_prior_has_val()
+  {
+    return !structural_innovation_prior_vector.empty();
+  };
+  inline bool
+  measurement_error_prior_has_val()
+  {
+    return !measurement_error_prior_vector.empty();
+  };
+  inline bool
+  structural_innovation_corr_prior_has_val()
+  {
+    return !structural_innovation_corr_prior_vector.empty();
+  };
+  inline bool
+  measurement_error_corr_prior_has_val()
+  {
+    return !measurement_error_corr_prior_vector.empty();
+  };
+
+  inline bool
+  option_has_val()
+  {
+    return !option_vector.empty();
+  };
+  inline bool
+  structural_innovation_option_has_val()
+  {
+    return !structural_innovation_option_vector.empty();
+  };
+  inline bool
+  measurement_error_option_has_val()
+  {
+    return !measurement_error_option_vector.empty();
+  };
+  inline bool
+  structural_innovation_corr_option_has_val()
+  {
+    return !structural_innovation_corr_option_vector.empty();
+  };
+  inline bool
+  measurement_error_corr_option_has_val()
+  {
+    return !measurement_error_corr_option_vector.empty();
+  };
+
+  inline vector<MarkovSwitching *>
+  get_markov_switching()
+  {
+    return markov_switching_vector;
+  };
+  inline vector<ModFilePrior *>
+  get_prior()
+  {
+    return prior_vector;
+  };
+  inline vector<ModFileStructuralInnovationPrior *>
+  get_structural_innovation_prior()
+  {
+    return structural_innovation_prior_vector;
+  };
+  inline vector<ModFileMeasurementErrorPrior *>
+  get_measurement_error_prior()
+  {
+    return measurement_error_prior_vector;
+  };
+  inline vector<ModFileStructuralInnovationCorrPrior *>
+  get_structural_innovation_corr_prior()
+  {
+    return structural_innovation_corr_prior_vector;
+  };
+  inline vector<ModFileMeasurementErrorCorrPrior *>
+  get_measurement_error_corr_prior()
+  {
+    return measurement_error_corr_prior_vector;
+  };
+
+  inline vector<ModFileOption *>
+  get_option()
+  {
+    return option_vector;
+  };
+  inline vector<ModFileStructuralInnovationOption *>
+  get_structural_innovation_option()
+  {
+    return structural_innovation_option_vector;
+  };
+  inline vector<ModFileMeasurementErrorOption *>
+  get_measurement_error_option()
+  {
+    return measurement_error_option_vector;
+  };
+  inline vector<ModFileStructuralInnovationCorrOption *>
+  get_structural_innovation_corr_option()
+  {
+    return structural_innovation_corr_option_vector;
+  };
+  inline vector<ModFileMeasurementErrorCorrOption *>
+  get_measurement_error_corr_option()
+  {
+    return measurement_error_corr_option_vector;
+  };
+
+  inline map<string, int >
+  get_exo_names()
+  {
+    return exo_names;
+  };
+  inline map<string, int >
+  get_exo_det_names()
+  {
+    return exo_det_names;
+  };
+  inline map<string, int >
+  get_endo_names()
+  {
+    return endo_names;
+  };
+  inline map<string, int >
+  get_param_names()
+  {
+    return param_names;
+  };
+  inline map<int, double >
+  get_params()
+  {
+    return params;
+  };
+  inline vector <aux_vars_t>
+  get_aux_vars()
+  {
+    return aux_vars;
+  };
+  inline vector <int>
+  get_predetermined_variables()
+  {
+    return predetermined_variables;
+  };
+  inline vector <int>
+  get_varobs()
+  {
+    return varobs;
+  };
+  inline vector<vector<int > >
+  get_lead_lag_incidence()
+  {
+    return lead_lag_incidence;
+  };
+  inline vector<double>
+  get_NNZDerivatives()
+  {
+    return NNZDerivatives;
+  };
 
   string get_exo_name_by_index(int index) throw (ValueNotSetException);
   int get_exo_index_by_name(string name) throw (ValueNotSetException);
@@ -317,7 +558,7 @@ public:
   string get_param_name_by_index(int index) throw (ValueNotSetException);
   int get_param_index_by_name(string name) throw (ValueNotSetException);
   double get_param_value_by_index(int index) throw (ValueNotSetException);
-  vector<int >get_lead_lag_incidence_for_endo_var_by_index(int index) throw (ValueNotSetException);
+  vector<int > get_lead_lag_incidence_for_endo_var_by_index(int index) throw (ValueNotSetException);
 };
 
 #endif // ! _DYNARE_CPP_DRIVER_HH
diff --git a/others/cpp/tests/snes_1.cc b/others/cpp/tests/snes_1.cc
index a5ddda6b23abef3e25b107eb47dfc41f38a2b3ac..1f03026e099b6d15b7c70baeeba8554617995bfd 100644
--- a/others/cpp/tests/snes_1.cc
+++ b/others/cpp/tests/snes_1.cc
@@ -6,40 +6,44 @@
 #include "main_tao.h"
 
 DynareInfo *preprocessorOutput(void);
-PetscErrorCode FormFunction(SNES snes,Vec y,Vec f,void *ctx);
-PetscErrorCode FormJacobian(SNES snes,Vec y,Mat J, Mat B,void *ctx);
-PetscErrorCode Monitor(SNES,PetscInt,PetscReal,void*);
-PetscErrorCode PreCheck(SNESLineSearch,Vec,Vec,PetscBool*,void*);
-PetscErrorCode PostCheck(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*);
-PetscErrorCode PostSetSubKSP(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*);
-PetscErrorCode MatrixFreePreconditioner(PC,Vec,Vec);
+PetscErrorCode FormFunction(SNES snes, Vec y, Vec f, void *ctx);
+PetscErrorCode FormJacobian(SNES snes, Vec y, Mat J, Mat B, void *ctx);
+PetscErrorCode Monitor(SNES, PetscInt, PetscReal, void *);
+PetscErrorCode PreCheck(SNESLineSearch, Vec, Vec, PetscBool *, void *);
+PetscErrorCode PostCheck(SNESLineSearch, Vec, Vec, Vec, PetscBool *, PetscBool *, void *);
+PetscErrorCode PostSetSubKSP(SNESLineSearch, Vec, Vec, Vec, PetscBool *, PetscBool *, void *);
+PetscErrorCode MatrixFreePreconditioner(PC, Vec, Vec);
 
 static char  help[] = "Testing";
 
 /*
-   User-defined context for monitoring
+  User-defined context for monitoring
 */
-typedef struct {
+typedef struct
+{
   PetscViewer viewer;
 } MonitorCtx;
 
 /*
-   User-defined context for checking candidate iterates that are
-   determined by line search methods
+  User-defined context for checking candidate iterates that are
+  determined by line search methods
 */
-typedef struct {
+typedef struct
+{
   Vec            last_step;  /* previous iterate */
   PetscReal      tolerance;  /* tolerance for changes between successive iterates */
   AppCtx *user;
 } StepCheckCtx;
 
-typedef struct {
+typedef struct
+{
   PetscInt its0; /* num of prevous outer KSP iterations */
 } SetSubKSPCtx;
 
 #undef __FUNCT__
 #define __FUNCT__ "main"
-int main(int argc, char **argv)
+int
+main(int argc, char **argv)
 {
   DynareInfo model_info;
 
@@ -49,7 +53,7 @@ int main(int argc, char **argv)
   // Steady state
   double *steady_state = new double[endo_nbr];
   int info;
-  steadystate(NULL,params, steady_state, &info);
+  steadystate(NULL, params, steady_state, &info);
   vector<int> NNZDerivatives = model_info.get_NNZDerivatives();
   AppCtx         user;            /* user-defined work context */
   user.exogenous = new double[exo_nbr];
@@ -65,237 +69,245 @@ int main(int argc, char **argv)
   user.val_ptr = new double[NNZDerivatives[0]];
   user.initial_values = new double[user.endo_nbr];
   user.terminal_values = new double[user.endo_nbr];
-  for (int i=0; i < user.endo_nbr; ++i)
+  for (int i = 0; i < user.endo_nbr; ++i)
     {
       user.initial_values[i] = user.steady_state[i];
       user.terminal_values[i] = user.steady_state[i];
     }
   /* Initialize PETSc */
-  PetscInitialize(&argc, &argv, (char *)0, help);
+  PetscInitialize(&argc, &argv, (char *) 0, help);
   PetscErrorCode ierr;
   /* Get number of processors */
   PetscInt size;
-  ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);CHKERRQ(ierr);
+  ierr = MPI_Comm_size(PETSC_COMM_WORLD, &size); CHKERRQ(ierr);
   /* Set periods a multiple of processor nbr */
-  user.periods = size*ceil((double)user.periods/size);
+  user.periods = size*ceil((double) user.periods/size);
   user.nb_row_x = user.periods + 1;
   user.X = new double[user.nb_row_x*user.exo_nbr];
-  for(double* px=user.X; px < user.X+user.nb_row_x*user.exo_nbr; px++) *px = 0.0;
+  for (double *px = user.X; px < user.X+user.nb_row_x*user.exo_nbr; px++)
+    *px = 0.0;
   user.X[1] = 0.01;
   user.X[1+user.nb_row_x] = 0.01;
   std::cout << size << " " << user.periods << " " << std::endl;
   PetscInt N = user.periods*user.endo_nbr;
   /* Create DMA */
-  DMDACreate1d(PETSC_COMM_WORLD,DM_BOUNDARY_GHOSTED,N,1,user.endo_nbr,NULL,&user.da);
+  DMDACreate1d(PETSC_COMM_WORLD, DM_BOUNDARY_GHOSTED, N, 1, user.endo_nbr, NULL, &user.da);
 
-  /*     Allocate vector and Jacobian matrix  */\
+  /*     Allocate vector and Jacobian matrix  */ \
   Vec Y, R;
-  DMCreateGlobalVector(user.da,&Y);
-  VecDuplicate(Y,&R);
+  DMCreateGlobalVector(user.da, &Y);
+  VecDuplicate(Y, &R);
 
-  Mat J ;
-  ierr = MatCreate(PETSC_COMM_WORLD,&J);CHKERRQ(ierr);
-  ierr = MatSetSizes(J,PETSC_DECIDE,PETSC_DECIDE,N,N);CHKERRQ(ierr);
-  ierr = MatSetFromOptions(J);CHKERRQ(ierr);
-  ierr = MatSetUp(J);CHKERRQ(ierr);
+  Mat J;
+  ierr = MatCreate(PETSC_COMM_WORLD, &J); CHKERRQ(ierr);
+  ierr = MatSetSizes(J, PETSC_DECIDE, PETSC_DECIDE, N, N); CHKERRQ(ierr);
+  ierr = MatSetFromOptions(J); CHKERRQ(ierr);
+  ierr = MatSetUp(J); CHKERRQ(ierr);
 
   /*
-   Get local grid boundaries (for 1-dimensional DMDA):
-     xs, xm - starting grid index, width of local grid (no ghost points)
+    Get local grid boundaries (for 1-dimensional DMDA):
+    xs, xm - starting grid index, width of local grid (no ghost points)
   */
   PetscInt xs, xm, xsg, xmg;
-  DMDAGetCorners(user.da,&xs,NULL,NULL,&xm,NULL,NULL);
+  DMDAGetCorners(user.da, &xs, NULL, NULL, &xm, NULL, NULL);
   std::cout << xs << " " << xm << std::endl;
-  DMDAGetGhostCorners(user.da,&xsg,NULL,NULL,&xmg,NULL,NULL);
+  DMDAGetGhostCorners(user.da, &xsg, NULL, NULL, &xmg, NULL, NULL);
   std::cout << "ghost " << xsg << " " << xmg << std::endl;
   /*
     Get pointers to vector data
   */
   PetscScalar *YY;
-  DMDAVecGetArray(user.da,Y,&YY);
-  
+  DMDAVecGetArray(user.da, Y, &YY);
+
   /*
     Compute local vector entries
   */
-  for (int i=xs; i<xs+xm; i += user.endo_nbr)
-    for (int j=0; j < user.endo_nbr; j++)
+  for (int i = xs; i < xs+xm; i += user.endo_nbr)
+    for (int j = 0; j < user.endo_nbr; j++)
       YY[i+j] = steady_state[j];
   /*
     Restore vectors
   */
-  DMDAVecRestoreArray(user.da,Y,&YY);
+  DMDAVecRestoreArray(user.da, Y, &YY);
 
   SNES snes;
-  ierr = SNESCreate(PETSC_COMM_WORLD,&snes);CHKERRQ(ierr);
-  
+  ierr = SNESCreate(PETSC_COMM_WORLD, &snes); CHKERRQ(ierr);
+
   //  SNES snes;
   SNESLineSearch linesearch;          /* SNESLineSearch context */
   MonitorCtx     monP;                 /* monitoring context */
   StepCheckCtx   checkP;               /* step-checking context */
   SetSubKSPCtx   checkP1;
-  PetscBool      pre_check,post_check,post_setsubksp; /* flag indicating whether we're checking candidate iterates */
-  PetscReal      abstol,rtol,stol,norm;
-  PetscInt       its,maxit,maxf;
+  PetscBool      pre_check, post_check, post_setsubksp; /* flag indicating whether we're checking candidate iterates */
+  PetscReal      abstol, rtol, stol, norm;
+  PetscInt       its, maxit, maxf;
   PetscBool      flg;
-  
+
   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      Create nonlinear solver context
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
 
-  ierr = SNESCreate(PETSC_COMM_WORLD,&snes);CHKERRQ(ierr);
+  ierr = SNESCreate(PETSC_COMM_WORLD, &snes); CHKERRQ(ierr);
 
   /*
-     Set function evaluation routine and vector.  Whenever the nonlinear
-     solver needs to compute the nonlinear function, it will call this
-     routine.
-      - Note that the final routine argument is the user-defined
-        context that provides application-specific data for the
-        function evaluation routine.
+    Set function evaluation routine and vector.  Whenever the nonlinear
+    solver needs to compute the nonlinear function, it will call this
+    routine.
+    - Note that the final routine argument is the user-defined
+    context that provides application-specific data for the
+    function evaluation routine.
   */
-  ierr = SNESSetFunction(snes,R,FormFunction,&user);CHKERRQ(ierr);
+  ierr = SNESSetFunction(snes, R, FormFunction, &user); CHKERRQ(ierr);
 
   /*
-     Set Jacobian matrix data structure and default Jacobian evaluation
-     routine.  Whenever the nonlinear solver needs to compute the
-     Jacobian matrix, it will call this routine.
-      - Note that the final routine argument is the user-defined
-        context that provides application-specific data for the
-        Jacobian evaluation routine.
+    Set Jacobian matrix data structure and default Jacobian evaluation
+    routine.  Whenever the nonlinear solver needs to compute the
+    Jacobian matrix, it will call this routine.
+    - Note that the final routine argument is the user-defined
+    context that provides application-specific data for the
+    Jacobian evaluation routine.
   */
-  ierr = SNESSetJacobian(snes,J,J,FormJacobian,&user);CHKERRQ(ierr);
+  ierr = SNESSetJacobian(snes, J, J, FormJacobian, &user); CHKERRQ(ierr);
 
   /*
-     Optional allow user provided preconditioner
-   */
-  ierr = PetscOptionsHasName(NULL,NULL,"-user_precond",&flg);CHKERRQ(ierr);
-  if (flg) {
-    KSP ksp;
-    PC  pc;
-    ierr = SNESGetKSP(snes,&ksp);CHKERRQ(ierr);
-    ierr = KSPGetPC(ksp,&pc);CHKERRQ(ierr);
-    ierr = PCSetType(pc,PCSHELL);CHKERRQ(ierr);
-    ierr = PCShellSetApply(pc,MatrixFreePreconditioner);CHKERRQ(ierr);
-  }
+    Optional allow user provided preconditioner
+  */
+  ierr = PetscOptionsHasName(NULL, NULL, "-user_precond", &flg); CHKERRQ(ierr);
+  if (flg)
+    {
+      KSP ksp;
+      PC  pc;
+      ierr = SNESGetKSP(snes, &ksp); CHKERRQ(ierr);
+      ierr = KSPGetPC(ksp, &pc); CHKERRQ(ierr);
+      ierr = PCSetType(pc, PCSHELL); CHKERRQ(ierr);
+      ierr = PCShellSetApply(pc, MatrixFreePreconditioner); CHKERRQ(ierr);
+    }
 
   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      Customize nonlinear solver; set runtime options
-   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
+     - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
 
   /*
-     Set an optional user-defined monitoring routine
+    Set an optional user-defined monitoring routine
   */
-  ierr = PetscViewerDrawOpen(PETSC_COMM_WORLD,0,0,0,0,400,400,&monP.viewer);CHKERRQ(ierr);
-  ierr = SNESMonitorSet(snes,Monitor,&monP,0);CHKERRQ(ierr);
+  ierr = PetscViewerDrawOpen(PETSC_COMM_WORLD, 0, 0, 0, 0, 400, 400, &monP.viewer); CHKERRQ(ierr);
+  ierr = SNESMonitorSet(snes, Monitor, &monP, 0); CHKERRQ(ierr);
 
   /*
-     Set names for some vectors to facilitate monitoring (optional)
+    Set names for some vectors to facilitate monitoring (optional)
   */
-  ierr = PetscObjectSetName((PetscObject)Y,"Approximate Solution");CHKERRQ(ierr);
+  ierr = PetscObjectSetName((PetscObject) Y, "Approximate Solution"); CHKERRQ(ierr);
   //  ierr = PetscObjectSetName((PetscObject)U,"Exact Solution");CHKERRQ(ierr);
 
   /*
-     Set SNES/KSP/KSP/PC runtime options, e.g.,
-         -snes_view -snes_monitor -ksp_type <ksp> -pc_type <pc>
+    Set SNES/KSP/KSP/PC runtime options, e.g.,
+    -snes_view -snes_monitor -ksp_type <ksp> -pc_type <pc>
   */
   KSP ksp;
   PC pc;
-  ierr = SNESGetKSP(snes,&ksp);CHKERRQ(ierr);
-  ierr = KSPGetPC(ksp,&pc);CHKERRQ(ierr);
-  ierr = PCSetType(pc,PCLU);CHKERRQ(ierr);
+  ierr = SNESGetKSP(snes, &ksp); CHKERRQ(ierr);
+  ierr = KSPGetPC(ksp, &pc); CHKERRQ(ierr);
+  ierr = PCSetType(pc, PCLU); CHKERRQ(ierr);
   //  PetscOptionsSetValue(NULL,"-pc_type","lu");
-  ierr = SNESSetFromOptions(snes);CHKERRQ(ierr);
+  ierr = SNESSetFromOptions(snes); CHKERRQ(ierr);
 
   /*
-     Set an optional user-defined routine to check the validity of candidate
-     iterates that are determined by line search methods
+    Set an optional user-defined routine to check the validity of candidate
+    iterates that are determined by line search methods
   */
-  ierr = SNESGetLineSearch(snes, &linesearch);CHKERRQ(ierr);
-  ierr = PetscOptionsHasName(NULL,NULL,"-post_check_iterates",&post_check);CHKERRQ(ierr);
+  ierr = SNESGetLineSearch(snes, &linesearch); CHKERRQ(ierr);
+  ierr = PetscOptionsHasName(NULL, NULL, "-post_check_iterates", &post_check); CHKERRQ(ierr);
 
-  if (post_check) {
-    ierr = PetscPrintf(PETSC_COMM_WORLD,"Activating post step checking routine\n");CHKERRQ(ierr);
-    ierr = SNESLineSearchSetPostCheck(linesearch,PostCheck,&checkP);CHKERRQ(ierr);
-    ierr = VecDuplicate(Y,&(checkP.last_step));CHKERRQ(ierr);
+  if (post_check)
+    {
+      ierr = PetscPrintf(PETSC_COMM_WORLD, "Activating post step checking routine\n"); CHKERRQ(ierr);
+      ierr = SNESLineSearchSetPostCheck(linesearch, PostCheck, &checkP); CHKERRQ(ierr);
+      ierr = VecDuplicate(Y, &(checkP.last_step)); CHKERRQ(ierr);
 
-    checkP.tolerance = 1.0;
-    checkP.user      = &user;
+      checkP.tolerance = 1.0;
+      checkP.user      = &user;
 
-    ierr = PetscOptionsGetReal(NULL,NULL,"-check_tol",&checkP.tolerance,NULL);CHKERRQ(ierr);
-  }
+      ierr = PetscOptionsGetReal(NULL, NULL, "-check_tol", &checkP.tolerance, NULL); CHKERRQ(ierr);
+    }
 
-  ierr = PetscOptionsHasName(NULL,NULL,"-post_setsubksp",&post_setsubksp);CHKERRQ(ierr);
-  if (post_setsubksp) {
-    ierr = PetscPrintf(PETSC_COMM_WORLD,"Activating post setsubksp\n");CHKERRQ(ierr);
-    ierr = SNESLineSearchSetPostCheck(linesearch,PostSetSubKSP,&checkP1);CHKERRQ(ierr);
-  }
+  ierr = PetscOptionsHasName(NULL, NULL, "-post_setsubksp", &post_setsubksp); CHKERRQ(ierr);
+  if (post_setsubksp)
+    {
+      ierr = PetscPrintf(PETSC_COMM_WORLD, "Activating post setsubksp\n"); CHKERRQ(ierr);
+      ierr = SNESLineSearchSetPostCheck(linesearch, PostSetSubKSP, &checkP1); CHKERRQ(ierr);
+    }
 
-  ierr = PetscOptionsHasName(NULL,NULL,"-pre_check_iterates",&pre_check);CHKERRQ(ierr);
-  if (pre_check) {
-    ierr = PetscPrintf(PETSC_COMM_WORLD,"Activating pre step checking routine\n");CHKERRQ(ierr);
-    ierr = SNESLineSearchSetPreCheck(linesearch,PreCheck,&checkP);CHKERRQ(ierr);
-  }
+  ierr = PetscOptionsHasName(NULL, NULL, "-pre_check_iterates", &pre_check); CHKERRQ(ierr);
+  if (pre_check)
+    {
+      ierr = PetscPrintf(PETSC_COMM_WORLD, "Activating pre step checking routine\n"); CHKERRQ(ierr);
+      ierr = SNESLineSearchSetPreCheck(linesearch, PreCheck, &checkP); CHKERRQ(ierr);
+    }
 
   /*
-     Print parameters used for convergence testing (optional) ... just
-     to demonstrate this routine; this information is also printed with
-     the option -snes_view
+    Print parameters used for convergence testing (optional) ... just
+    to demonstrate this routine; this information is also printed with
+    the option -snes_view
   */
-  ierr = SNESGetTolerances(snes,&abstol,&rtol,&stol,&maxit,&maxf);CHKERRQ(ierr);
-  ierr = PetscPrintf(PETSC_COMM_WORLD,"atol=%g, rtol=%g, stol=%g, maxit=%D, maxf=%D\n",(double)abstol,(double)rtol,(double)stol,maxit,maxf);CHKERRQ(ierr);
+  ierr = SNESGetTolerances(snes, &abstol, &rtol, &stol, &maxit, &maxf); CHKERRQ(ierr);
+  ierr = PetscPrintf(PETSC_COMM_WORLD, "atol=%g, rtol=%g, stol=%g, maxit=%D, maxf=%D\n", (double) abstol, (double) rtol, (double) stol, maxit, maxf); CHKERRQ(ierr);
 
   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      Evaluate initial guess; then solve nonlinear system
-   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
+     - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
 
   /*
-     Note: The user should initialize the vector, x, with the initial guess
-     for the nonlinear solver prior to calling SNESSolve().  In particular,
-     to employ an initial guess of zero, the user should explicitly set
-     this vector to zero by calling VecSet().
+    Note: The user should initialize the vector, x, with the initial guess
+    for the nonlinear solver prior to calling SNESSolve().  In particular,
+    to employ an initial guess of zero, the user should explicitly set
+    this vector to zero by calling VecSet().
   */
-  ierr = SNESSolve(snes,NULL,Y);CHKERRQ(ierr);
-  ierr = SNESGetIterationNumber(snes,&its);CHKERRQ(ierr);
-  ierr = PetscPrintf(PETSC_COMM_WORLD,"Number of SNES iterations = %D\n",its);CHKERRQ(ierr);
+  ierr = SNESSolve(snes, NULL, Y); CHKERRQ(ierr);
+  ierr = SNESGetIterationNumber(snes, &its); CHKERRQ(ierr);
+  ierr = PetscPrintf(PETSC_COMM_WORLD, "Number of SNES iterations = %D\n", its); CHKERRQ(ierr);
 
   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      Check solution and clean up
-   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
+     - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
 
   /*
-     Free work space.  All PETSc objects should be destroyed when they
-     are no longer needed.
+    Free work space.  All PETSc objects should be destroyed when they
+    are no longer needed.
   */
-  ierr = PetscViewerDestroy(&monP.viewer);CHKERRQ(ierr);
-  if (post_check) {ierr = VecDestroy(&checkP.last_step);CHKERRQ(ierr);}
-  ierr = SNESDestroy(&snes);CHKERRQ(ierr);
-  ierr = DMDestroy(&user.da);CHKERRQ(ierr);
+  ierr = PetscViewerDestroy(&monP.viewer); CHKERRQ(ierr);
+  if (post_check)
+    {
+      ierr = VecDestroy(&checkP.last_step); CHKERRQ(ierr);
+    }
+  ierr = SNESDestroy(&snes); CHKERRQ(ierr);
+  ierr = DMDestroy(&user.da); CHKERRQ(ierr);
 
-  
-  ierr = MatDestroy(&J);CHKERRQ(ierr);
-  ierr = VecDestroy(&Y);CHKERRQ(ierr);
-  ierr = VecDestroy(&R);CHKERRQ(ierr);
-  ierr = PetscFinalize();CHKERRQ(ierr);
+  ierr = MatDestroy(&J); CHKERRQ(ierr);
+  ierr = VecDestroy(&Y); CHKERRQ(ierr);
+  ierr = VecDestroy(&R); CHKERRQ(ierr);
+  ierr = PetscFinalize(); CHKERRQ(ierr);
 
   PetscFunctionReturn(0);
 }
 
-PetscErrorCode FormFunction(SNES snes,Vec y,Vec f,void *ctx)
+PetscErrorCode
+FormFunction(SNES snes, Vec y, Vec f, void *ctx)
 {
-  AppCtx *user = (AppCtx*) ctx;
+  AppCtx *user = (AppCtx *) ctx;
   DM             da    = user->da;
-  PetscScalar    *yy,*ff;
-  PetscInt       M,ys,ym;
+  PetscScalar    *yy, *ff;
+  PetscInt       M, ys, ym;
   Vec            ylocal;
 
-  DMGetLocalVector(da,&ylocal);
+  DMGetLocalVector(da, &ylocal);
   /*
     Scatter ghost points to local vector, using the 2-step process
     DMGlobalToLocalBegin(), DMGlobalToLocalEnd().
     By placing code between these two statements, computations can
     be done while messages are in transition.
   */
-  DMGlobalToLocalBegin(da,y,INSERT_VALUES,ylocal);
-  DMGlobalToLocalEnd(da,y,INSERT_VALUES,ylocal);
+  DMGlobalToLocalBegin(da, y, INSERT_VALUES, ylocal);
+  DMGlobalToLocalEnd(da, y, INSERT_VALUES, ylocal);
 
   /*
     Get pointers to vector data.
@@ -303,15 +315,15 @@ PetscErrorCode FormFunction(SNES snes,Vec y,Vec f,void *ctx)
     NOT include ghost points.
     - Using DMDAVecGetArray() allows accessing the values using global ordering
   */
-  DMDAVecGetArray(da,ylocal,&yy);
-  DMDAVecGetArray(da,f,&ff);
+  DMDAVecGetArray(da, ylocal, &yy);
+  DMDAVecGetArray(da, f, &ff);
 
   /*
     Get local grid boundaries (for 1-dimensional DMDA):
     ys, ym  - starting grid index, width of local grid (no ghost points)
   */
-  DMDAGetCorners(da,&ys,NULL,NULL,&ym,NULL,NULL);
-  DMDAGetInfo(da,NULL,&M,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
+  DMDAGetCorners(da, &ys, NULL, NULL, &ym, NULL, NULL);
+  DMDAGetInfo(da, NULL, &M, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
 
   /*
     Set function values for boundary points; define local interior grid point range:
@@ -321,8 +333,10 @@ PetscErrorCode FormFunction(SNES snes,Vec y,Vec f,void *ctx)
   if (ys == 0) /* left boundary */
     {
       PetscReal *y1 = new PetscReal[3*user->endo_nbr];
-      for (int i=0; i < user->endo_nbr; ++i) y1[i] = user->initial_values[i];
-      for (int i=0; i < 2*user->endo_nbr; ++i) y1[i+user->endo_nbr] = yy[i];
+      for (int i = 0; i < user->endo_nbr; ++i)
+        y1[i] = user->initial_values[i];
+      for (int i = 0; i < 2*user->endo_nbr; ++i)
+        y1[i+user->endo_nbr] = yy[i];
       Residuals(y1, user->X, user->nb_row_x, user->params, user->steady_state, 1, ff);
       ys += user->endo_nbr;
       ym -= user->endo_nbr;
@@ -331,7 +345,7 @@ PetscErrorCode FormFunction(SNES snes,Vec y,Vec f,void *ctx)
   /*
     Compute function over locally owned part of the grid (interior points only)
   */
-  while ( (ym  >= user->endo_nbr) && (ys + 2*user->endo_nbr <= M) )
+  while ((ym  >= user->endo_nbr) && (ys + 2*user->endo_nbr <= M))
     {
       int it = ys/user->endo_nbr + 2;
       Residuals(yy+ys-user->endo_nbr, user->X, user->nb_row_x, user->params, user->steady_state, it, ff+ys);
@@ -339,42 +353,44 @@ PetscErrorCode FormFunction(SNES snes,Vec y,Vec f,void *ctx)
       ym -= user->endo_nbr;
     }
 
-  
-  if ( (ym >= user->endo_nbr) && (ys + 2*user->endo_nbr >= M) ) 
+  if ((ym >= user->endo_nbr) && (ys + 2*user->endo_nbr >= M))
     {
       int it = ys/user->endo_nbr + 1;
       PetscReal *y1 = new PetscReal[3*user->endo_nbr];
-      for (int i=0; i < 2*user->endo_nbr; ++i) y1[i] = yy[ys+i-user->endo_nbr];
-      for (int i=0; i < user->endo_nbr; ++i) y1[i+2*user->endo_nbr] = user->terminal_values[i];
+      for (int i = 0; i < 2*user->endo_nbr; ++i)
+        y1[i] = yy[ys+i-user->endo_nbr];
+      for (int i = 0; i < user->endo_nbr; ++i)
+        y1[i+2*user->endo_nbr] = user->terminal_values[i];
       Residuals(y1, user->X, user->nb_row_x, user->params, user->steady_state, it, ff+ys);
     }
 
   /*
     Restore vectors
   */
-  DMDAVecRestoreArray(da,ylocal,&yy);
-  DMDAVecRestoreArray(da,f,&ff);
-  DMRestoreLocalVector(da,&ylocal);
-  return(0);
+  DMDAVecRestoreArray(da, ylocal, &yy);
+  DMDAVecRestoreArray(da, f, &ff);
+  DMRestoreLocalVector(da, &ylocal);
+  return (0);
 }
 
-PetscErrorCode FormJacobian(SNES snes,Vec y,Mat J, Mat B,void *ctx)
+PetscErrorCode
+FormJacobian(SNES snes, Vec y, Mat J, Mat B, void *ctx)
 {
-  AppCtx *user = (AppCtx*) ctx;
+  AppCtx *user = (AppCtx *) ctx;
   DM             da    = user->da;
   PetscScalar    *yy;
-  PetscInt       M,ys,ym,ierr;
+  PetscInt       M, ys, ym, ierr;
   Vec            ylocal;
 
-  DMGetLocalVector(da,&ylocal);
+  DMGetLocalVector(da, &ylocal);
   /*
     Scatter ghost points to local vector, using the 2-step process
     DMGlobalToLocalBegin(), DMGlobalToLocalEnd().
     By placing code between these two statements, computations can
     be done while messages are in transition.
   */
-  DMGlobalToLocalBegin(da,y,INSERT_VALUES,ylocal);
-  DMGlobalToLocalEnd(da,y,INSERT_VALUES,ylocal);
+  DMGlobalToLocalBegin(da, y, INSERT_VALUES, ylocal);
+  DMGlobalToLocalEnd(da, y, INSERT_VALUES, ylocal);
 
   /*
     Get pointers to vector data.
@@ -382,14 +398,14 @@ PetscErrorCode FormJacobian(SNES snes,Vec y,Mat J, Mat B,void *ctx)
     NOT include ghost points.
     - Using DMDAVecGetArray() allows accessing the values using global ordering
   */
-  DMDAVecGetArray(da,ylocal,&yy);
+  DMDAVecGetArray(da, ylocal, &yy);
 
   /*
     Get local grid boundaries (for 1-dimensional DMDA):
     ys, ym  - starting grid index, width of local grid (no ghost points)
   */
-  DMDAGetCorners(da,&ys,NULL,NULL,&ym,NULL,NULL);
-  DMDAGetInfo(da,NULL,&M,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
+  DMDAGetCorners(da, &ys, NULL, NULL, &ym, NULL, NULL);
+  DMDAGetInfo(da, NULL, &M, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
 
   /*
     Set function values for boundary points; define local interior grid point range:
@@ -400,32 +416,34 @@ PetscErrorCode FormJacobian(SNES snes,Vec y,Mat J, Mat B,void *ctx)
   if (ys == 0) /* left boundary */
     {
       PetscReal *y1 = new PetscReal[3*user->endo_nbr];
-      for (int i=0; i < user->endo_nbr; ++i) y1[i] = user->initial_values[i];
-      for (int i=0; i < 2*user->endo_nbr; ++i) y1[i+user->endo_nbr] = yy[i];
+      for (int i = 0; i < user->endo_nbr; ++i)
+        y1[i] = user->initial_values[i];
+      for (int i = 0; i < 2*user->endo_nbr; ++i)
+        y1[i+user->endo_nbr] = yy[i];
       FirstDerivatives(y1, user->X, user->nb_row_x, user->params, user->steady_state, 1, NULL, user->row_ptr, user->col_ptr, user->val_ptr);
-      for (int* r=user->row_ptr; r < user->row_ptr+user->endo_nbr; r++)
-	{
-	  int first_col = 0;
-	  int ncol = 0;
-	  int *pc = user->col_ptr + *r;
-	  while(*(pc) < user->endo_nbr)
-	    {
-	      ++first_col;
-	      ++pc;
-	    }
-	  while(pc < ((user->col_ptr)+*(r+1)))
-	    {
-	      if (*pc < 3*(user->endo_nbr))
-		{
-		  ++ncol;
-		  *pc -= user->endo_nbr;
-		}
-	      ++pc;
-	    }
-	  ierr = MatSetValues(J,1,&row,ncol,user->col_ptr + *r + first_col,user->val_ptr + *r  + first_col,INSERT_VALUES);
-	  CHKERRQ(ierr);
-	  ++row;
-	}
+      for (int *r = user->row_ptr; r < user->row_ptr+user->endo_nbr; r++)
+        {
+          int first_col = 0;
+          int ncol = 0;
+          int *pc = user->col_ptr + *r;
+          while (*(pc) < user->endo_nbr)
+            {
+              ++first_col;
+              ++pc;
+            }
+          while (pc < ((user->col_ptr)+*(r+1)))
+            {
+              if (*pc < 3*(user->endo_nbr))
+                {
+                  ++ncol;
+                  *pc -= user->endo_nbr;
+                }
+              ++pc;
+            }
+          ierr = MatSetValues(J, 1, &row, ncol, user->col_ptr + *r + first_col, user->val_ptr + *r  + first_col, INSERT_VALUES);
+          CHKERRQ(ierr);
+          ++row;
+        }
       ys += user->endo_nbr;
       ym -= user->endo_nbr;
     }
@@ -433,88 +451,90 @@ PetscErrorCode FormJacobian(SNES snes,Vec y,Mat J, Mat B,void *ctx)
   /*
     Compute function over locally owned part of the grid (interior points only)
   */
-  while ( (ym  >= user->endo_nbr) && (ys + 2*user->endo_nbr <= M) )
+  while ((ym  >= user->endo_nbr) && (ys + 2*user->endo_nbr <= M))
     {
       int it = ys/user->endo_nbr + 2;
       FirstDerivatives(yy+ys-user->endo_nbr, user->X, user->nb_row_x, user->params, user->steady_state, it, NULL, user->row_ptr, user->col_ptr, user->val_ptr);
-      for (int* r=user->row_ptr; r < user->row_ptr+user->endo_nbr; r++)
-	{
-	  int ncol = 0;
-	  for(int *pc = user->col_ptr + *r; pc < user->col_ptr + *(r+1); ++pc)
-	    if(*pc < 3*user->endo_nbr)
-	      {
-		*pc += ys - user->endo_nbr;
-		++ncol;
-	      }
-	  ierr = MatSetValues(J,1,&row,ncol,user->col_ptr + *r,user->val_ptr + *r,INSERT_VALUES);
-	  CHKERRQ(ierr);
-	  ++row;
-	}
+      for (int *r = user->row_ptr; r < user->row_ptr+user->endo_nbr; r++)
+        {
+          int ncol = 0;
+          for (int *pc = user->col_ptr + *r; pc < user->col_ptr + *(r+1); ++pc)
+            if (*pc < 3*user->endo_nbr)
+              {
+                *pc += ys - user->endo_nbr;
+                ++ncol;
+              }
+          ierr = MatSetValues(J, 1, &row, ncol, user->col_ptr + *r, user->val_ptr + *r, INSERT_VALUES);
+          CHKERRQ(ierr);
+          ++row;
+        }
       ys += user->endo_nbr;
       ym -= user->endo_nbr;
     }
 
-  
-  if ( (ym >= user->endo_nbr) && (ys + 2*user->endo_nbr >= M) ) 
+  if ((ym >= user->endo_nbr) && (ys + 2*user->endo_nbr >= M))
     {
       int it = ys/user->endo_nbr + 1;
       PetscReal *y1 = new PetscReal[3*user->endo_nbr];
-      for (int i=0; i < 2*user->endo_nbr; ++i) y1[i] = yy[ys+i-user->endo_nbr];
-      for (int i=0; i < user->endo_nbr; ++i) y1[i+2*user->endo_nbr] = user->terminal_values[i];
+      for (int i = 0; i < 2*user->endo_nbr; ++i)
+        y1[i] = yy[ys+i-user->endo_nbr];
+      for (int i = 0; i < user->endo_nbr; ++i)
+        y1[i+2*user->endo_nbr] = user->terminal_values[i];
       FirstDerivatives(y1, user->X, user->nb_row_x, user->params, user->steady_state, it, NULL, user->row_ptr, user->col_ptr, user->val_ptr);
-      for (int* r=user->row_ptr; r < user->row_ptr+user->endo_nbr; r++)
-	{
-	  int *pc = user->col_ptr + *r;
-	  int ncol = 0;
-	  while((*pc < 2*user->endo_nbr) && (pc < user->col_ptr + *(r+1)))
-	    {
-	      ++ncol;
-	      *pc += ys - user->endo_nbr;
-	      ++pc;
-	    }
-	  ierr = MatSetValues(J,1,&row,ncol,user->col_ptr + *r,user->val_ptr + *r,INSERT_VALUES);
-	  CHKERRQ(ierr);
-	  ++row;
-	}
+      for (int *r = user->row_ptr; r < user->row_ptr+user->endo_nbr; r++)
+        {
+          int *pc = user->col_ptr + *r;
+          int ncol = 0;
+          while ((*pc < 2*user->endo_nbr) && (pc < user->col_ptr + *(r+1)))
+            {
+              ++ncol;
+              *pc += ys - user->endo_nbr;
+              ++pc;
+            }
+          ierr = MatSetValues(J, 1, &row, ncol, user->col_ptr + *r, user->val_ptr + *r, INSERT_VALUES);
+          CHKERRQ(ierr);
+          ++row;
+        }
     }
 
   /*
     Restore vectors
   */
-  ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
-  DMDAVecRestoreArray(da,ylocal,&yy);
-  DMRestoreLocalVector(da,&ylocal);
-  ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
-  return(0);
+  ierr = MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
+  DMDAVecRestoreArray(da, ylocal, &yy);
+  DMRestoreLocalVector(da, &ylocal);
+  ierr = MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
+  return (0);
 }
 
 #undef __FUNCT__
 #define __FUNCT__ "Monitor"
 /*
-   Monitor - Optional user-defined monitoring routine that views the
-   current iterate with an x-window plot. Set by SNESMonitorSet().
-
-   Input Parameters:
-   snes - the SNES context
-   its - iteration number
-   norm - 2-norm function value (may be estimated)
-   ctx - optional user-defined context for private data for the
-         monitor routine, as set by SNESMonitorSet()
-
-   Note:
-   See the manpage for PetscViewerDrawOpen() for useful runtime options,
-   such as -nox to deactivate all x-window output.
- */
-PetscErrorCode Monitor(SNES snes,PetscInt its,PetscReal fnorm,void *ctx)
+  Monitor - Optional user-defined monitoring routine that views the
+  current iterate with an x-window plot. Set by SNESMonitorSet().
+
+  Input Parameters:
+  snes - the SNES context
+  its - iteration number
+  norm - 2-norm function value (may be estimated)
+  ctx - optional user-defined context for private data for the
+  monitor routine, as set by SNESMonitorSet()
+
+  Note:
+  See the manpage for PetscViewerDrawOpen() for useful runtime options,
+  such as -nox to deactivate all x-window output.
+*/
+PetscErrorCode
+Monitor(SNES snes, PetscInt its, PetscReal fnorm, void *ctx)
 {
   PetscErrorCode ierr;
-  MonitorCtx     *monP = (MonitorCtx*) ctx;
+  MonitorCtx     *monP = (MonitorCtx *) ctx;
   Vec            x;
 
   PetscFunctionBeginUser;
-  ierr = PetscPrintf(PETSC_COMM_WORLD,"iter = %D,SNES Function norm %g\n",its,(double)fnorm);CHKERRQ(ierr);
-  ierr = SNESGetSolution(snes,&x);CHKERRQ(ierr);
-  ierr = VecView(x,monP->viewer);CHKERRQ(ierr);
+  ierr = PetscPrintf(PETSC_COMM_WORLD, "iter = %D,SNES Function norm %g\n", its, (double) fnorm); CHKERRQ(ierr);
+  ierr = SNESGetSolution(snes, &x); CHKERRQ(ierr);
+  ierr = VecView(x, monP->viewer); CHKERRQ(ierr);
   PetscFunctionReturn(0);
 }
 
@@ -522,19 +542,20 @@ PetscErrorCode Monitor(SNES snes,PetscInt its,PetscReal fnorm,void *ctx)
 #undef __FUNCT__
 #define __FUNCT__ "PreCheck"
 /*
-   PreCheck - Optional user-defined routine that checks the validity of
-   candidate steps of a line search method.  Set by SNESLineSearchSetPreCheck().
-
-   Input Parameters:
-   snes - the SNES context
-   xcurrent - current solution
-   y - search direction and length
-
-   Output Parameters:
-   y         - proposed step (search direction and length) (possibly changed)
-   changed_y - tells if the step has changed or not
- */
-PetscErrorCode PreCheck(SNESLineSearch linesearch,Vec xcurrent,Vec y, PetscBool *changed_y, void * ctx)
+  PreCheck - Optional user-defined routine that checks the validity of
+  candidate steps of a line search method.  Set by SNESLineSearchSetPreCheck().
+
+  Input Parameters:
+  snes - the SNES context
+  xcurrent - current solution
+  y - search direction and length
+
+  Output Parameters:
+  y         - proposed step (search direction and length) (possibly changed)
+  changed_y - tells if the step has changed or not
+*/
+PetscErrorCode
+PreCheck(SNESLineSearch linesearch, Vec xcurrent, Vec y, PetscBool *changed_y, void *ctx)
 {
   PetscFunctionBeginUser;
   *changed_y = PETSC_FALSE;
@@ -545,29 +566,30 @@ PetscErrorCode PreCheck(SNESLineSearch linesearch,Vec xcurrent,Vec y, PetscBool
 #undef __FUNCT__
 #define __FUNCT__ "PostCheck"
 /*
-   PostCheck - Optional user-defined routine that checks the validity of
-   candidate steps of a line search method.  Set by SNESLineSearchSetPostCheck().
-
-   Input Parameters:
-   snes - the SNES context
-   ctx  - optional user-defined context for private data for the
-          monitor routine, as set by SNESLineSearchSetPostCheck()
-   xcurrent - current solution
-   y - search direction and length
-   x    - the new candidate iterate
-
-   Output Parameters:
-   y    - proposed step (search direction and length) (possibly changed)
-   x    - current iterate (possibly modified)
-
- */
-PetscErrorCode PostCheck(SNESLineSearch linesearch,Vec xcurrent,Vec y,Vec x,PetscBool  *changed_y,PetscBool  *changed_x, void * ctx)
+  PostCheck - Optional user-defined routine that checks the validity of
+  candidate steps of a line search method.  Set by SNESLineSearchSetPostCheck().
+
+  Input Parameters:
+  snes - the SNES context
+  ctx  - optional user-defined context for private data for the
+  monitor routine, as set by SNESLineSearchSetPostCheck()
+  xcurrent - current solution
+  y - search direction and length
+  x    - the new candidate iterate
+
+  Output Parameters:
+  y    - proposed step (search direction and length) (possibly changed)
+  x    - current iterate (possibly modified)
+
+*/
+PetscErrorCode
+PostCheck(SNESLineSearch linesearch, Vec xcurrent, Vec y, Vec x, PetscBool  *changed_y, PetscBool  *changed_x, void *ctx)
 {
   PetscErrorCode ierr;
-  PetscInt       i,iter,xs,xm;
+  PetscInt       i, iter, xs, xm;
   StepCheckCtx   *check;
   AppCtx *user;
-  PetscScalar    *xa,*xa_last,tmp;
+  PetscScalar    *xa, *xa_last, tmp;
   PetscReal      rdiff;
   DM             da;
   SNES           snes;
@@ -576,116 +598,124 @@ PetscErrorCode PostCheck(SNESLineSearch linesearch,Vec xcurrent,Vec y,Vec x,Pets
   *changed_x = PETSC_FALSE;
   *changed_y = PETSC_FALSE;
 
-  ierr  = SNESLineSearchGetSNES(linesearch, &snes);CHKERRQ(ierr);
-  check = (StepCheckCtx*)ctx;
+  ierr  = SNESLineSearchGetSNES(linesearch, &snes); CHKERRQ(ierr);
+  check = (StepCheckCtx *) ctx;
   user  = check->user;
-  ierr  = SNESGetIterationNumber(snes,&iter);CHKERRQ(ierr);
-  ierr  = SNESLineSearchGetPreCheck(linesearch, NULL, (void**)&check);CHKERRQ(ierr);
+  ierr  = SNESGetIterationNumber(snes, &iter); CHKERRQ(ierr);
+  ierr  = SNESLineSearchGetPreCheck(linesearch, NULL, (void **) &check); CHKERRQ(ierr);
 
   /* iteration 1 indicates we are working on the second iteration */
-  if (iter > 0) {
-    da   = user->da;
-    ierr = PetscPrintf(PETSC_COMM_WORLD,"Checking candidate step at iteration %D with tolerance %g\n",iter,(double)check->tolerance);CHKERRQ(ierr);
-
-    /* Access local array data */
-    ierr = DMDAVecGetArray(da,check->last_step,&xa_last);CHKERRQ(ierr);
-    ierr = DMDAVecGetArray(da,x,&xa);CHKERRQ(ierr);
-    ierr = DMDAGetCorners(da,&xs,NULL,NULL,&xm,NULL,NULL);CHKERRQ(ierr);
-
-    /*
-       If we fail the user-defined check for validity of the candidate iterate,
-       then modify the iterate as we like.  (Note that the particular modification
-       below is intended simply to demonstrate how to manipulate this data, not
-       as a meaningful or appropriate choice.)
-    */
-    for (i=xs; i<xs+xm; i++) {
-      if (!PetscAbsScalar(xa[i])) rdiff = 2*check->tolerance;
-      else rdiff = PetscAbsScalar((xa[i] - xa_last[i])/xa[i]);
-      if (rdiff > check->tolerance) {
-        tmp        = xa[i];
-        xa[i]      = .5*(xa[i] + xa_last[i]);
-        *changed_x = PETSC_TRUE;
-        ierr       = PetscPrintf(PETSC_COMM_WORLD,"  Altering entry %D: x=%g, x_last=%g, diff=%g, x_new=%g\n",
-                                 i,(double)PetscAbsScalar(tmp),(double)PetscAbsScalar(xa_last[i]),(double)rdiff,(double)PetscAbsScalar(xa[i]));CHKERRQ(ierr);
-      }
+  if (iter > 0)
+    {
+      da   = user->da;
+      ierr = PetscPrintf(PETSC_COMM_WORLD, "Checking candidate step at iteration %D with tolerance %g\n", iter, (double) check->tolerance); CHKERRQ(ierr);
+
+      /* Access local array data */
+      ierr = DMDAVecGetArray(da, check->last_step, &xa_last); CHKERRQ(ierr);
+      ierr = DMDAVecGetArray(da, x, &xa); CHKERRQ(ierr);
+      ierr = DMDAGetCorners(da, &xs, NULL, NULL, &xm, NULL, NULL); CHKERRQ(ierr);
+
+      /*
+        If we fail the user-defined check for validity of the candidate iterate,
+        then modify the iterate as we like.  (Note that the particular modification
+        below is intended simply to demonstrate how to manipulate this data, not
+        as a meaningful or appropriate choice.)
+      */
+      for (i = xs; i < xs+xm; i++)
+        {
+          if (!PetscAbsScalar(xa[i]))
+            rdiff = 2*check->tolerance;
+          else
+            rdiff = PetscAbsScalar((xa[i] - xa_last[i])/xa[i]);
+          if (rdiff > check->tolerance)
+            {
+              tmp        = xa[i];
+              xa[i]      = .5*(xa[i] + xa_last[i]);
+              *changed_x = PETSC_TRUE;
+              ierr       = PetscPrintf(PETSC_COMM_WORLD, "  Altering entry %D: x=%g, x_last=%g, diff=%g, x_new=%g\n",
+                                       i, (double) PetscAbsScalar(tmp), (double) PetscAbsScalar(xa_last[i]), (double) rdiff, (double) PetscAbsScalar(xa[i])); CHKERRQ(ierr);
+            }
+        }
+      ierr = DMDAVecRestoreArray(da, check->last_step, &xa_last); CHKERRQ(ierr);
+      ierr = DMDAVecRestoreArray(da, x, &xa); CHKERRQ(ierr);
     }
-    ierr = DMDAVecRestoreArray(da,check->last_step,&xa_last);CHKERRQ(ierr);
-    ierr = DMDAVecRestoreArray(da,x,&xa);CHKERRQ(ierr);
-  }
-  ierr = VecCopy(x,check->last_step);CHKERRQ(ierr);
+  ierr = VecCopy(x, check->last_step); CHKERRQ(ierr);
   PetscFunctionReturn(0);
 }
 
-
 /* ------------------------------------------------------------------- */
 #undef __FUNCT__
 #define __FUNCT__ "PostSetSubKSP"
 /*
-   PostSetSubKSP - Optional user-defined routine that reset SubKSP options when hierarchical bjacobi PC is used
-   e.g,
-     mpiexec -n 8 ./ex3 -nox -n 10000 -ksp_type fgmres -pc_type bjacobi -pc_bjacobi_blocks 4 -sub_ksp_type gmres -sub_ksp_max_it 3 -post_setsubksp -sub_ksp_rtol 1.e-16
-   Set by SNESLineSearchSetPostCheck().
-
-   Input Parameters:
-   linesearch - the LineSearch context
-   xcurrent - current solution
-   y - search direction and length
-   x    - the new candidate iterate
-
-   Output Parameters:
-   y    - proposed step (search direction and length) (possibly changed)
-   x    - current iterate (possibly modified)
-
- */
-PetscErrorCode PostSetSubKSP(SNESLineSearch linesearch,Vec xcurrent,Vec y,Vec x,PetscBool  *changed_y,PetscBool  *changed_x, void * ctx)
+  PostSetSubKSP - Optional user-defined routine that reset SubKSP options when hierarchical bjacobi PC is used
+  e.g,
+  mpiexec -n 8 ./ex3 -nox -n 10000 -ksp_type fgmres -pc_type bjacobi -pc_bjacobi_blocks 4 -sub_ksp_type gmres -sub_ksp_max_it 3 -post_setsubksp -sub_ksp_rtol 1.e-16
+  Set by SNESLineSearchSetPostCheck().
+
+  Input Parameters:
+  linesearch - the LineSearch context
+  xcurrent - current solution
+  y - search direction and length
+  x    - the new candidate iterate
+
+  Output Parameters:
+  y    - proposed step (search direction and length) (possibly changed)
+  x    - current iterate (possibly modified)
+
+*/
+PetscErrorCode
+PostSetSubKSP(SNESLineSearch linesearch, Vec xcurrent, Vec y, Vec x, PetscBool  *changed_y, PetscBool  *changed_x, void *ctx)
 {
   PetscErrorCode ierr;
   SetSubKSPCtx   *check;
-  PetscInt       iter,its,sub_its,maxit;
-  KSP            ksp,sub_ksp,*sub_ksps;
+  PetscInt       iter, its, sub_its, maxit;
+  KSP            ksp, sub_ksp, *sub_ksps;
   PC             pc;
   PetscReal      ksp_ratio;
   SNES           snes;
 
   PetscFunctionBeginUser;
-  ierr    = SNESLineSearchGetSNES(linesearch, &snes);CHKERRQ(ierr);
-  check   = (SetSubKSPCtx*)ctx;
-  ierr    = SNESGetIterationNumber(snes,&iter);CHKERRQ(ierr);
-  ierr    = SNESGetKSP(snes,&ksp);CHKERRQ(ierr);
-  ierr    = KSPGetPC(ksp,&pc);CHKERRQ(ierr);
-  ierr    = PCBJacobiGetSubKSP(pc,NULL,NULL,&sub_ksps);CHKERRQ(ierr);
+  ierr    = SNESLineSearchGetSNES(linesearch, &snes); CHKERRQ(ierr);
+  check   = (SetSubKSPCtx *) ctx;
+  ierr    = SNESGetIterationNumber(snes, &iter); CHKERRQ(ierr);
+  ierr    = SNESGetKSP(snes, &ksp); CHKERRQ(ierr);
+  ierr    = KSPGetPC(ksp, &pc); CHKERRQ(ierr);
+  ierr    = PCBJacobiGetSubKSP(pc, NULL, NULL, &sub_ksps); CHKERRQ(ierr);
   sub_ksp = sub_ksps[0];
-  ierr    = KSPGetIterationNumber(ksp,&its);CHKERRQ(ierr);      /* outer KSP iteration number */
-  ierr    = KSPGetIterationNumber(sub_ksp,&sub_its);CHKERRQ(ierr); /* inner KSP iteration number */
-
-  if (iter) {
-    ierr      = PetscPrintf(PETSC_COMM_WORLD,"    ...PostCheck snes iteration %D, ksp_it %d %d, subksp_it %d\n",iter,check->its0,its,sub_its);CHKERRQ(ierr);
-    ksp_ratio = ((PetscReal)(its))/check->its0;
-    maxit     = (PetscInt)(ksp_ratio*sub_its + 0.5);
-    if (maxit < 2) maxit = 2;
-    ierr = KSPSetTolerances(sub_ksp,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT,maxit);CHKERRQ(ierr);
-    ierr = PetscPrintf(PETSC_COMM_WORLD,"    ...ksp_ratio %g, new maxit %d\n\n",ksp_ratio,maxit);CHKERRQ(ierr);
-  }
+  ierr    = KSPGetIterationNumber(ksp, &its); CHKERRQ(ierr);      /* outer KSP iteration number */
+  ierr    = KSPGetIterationNumber(sub_ksp, &sub_its); CHKERRQ(ierr); /* inner KSP iteration number */
+
+  if (iter)
+    {
+      ierr      = PetscPrintf(PETSC_COMM_WORLD, "    ...PostCheck snes iteration %D, ksp_it %d %d, subksp_it %d\n", iter, check->its0, its, sub_its); CHKERRQ(ierr);
+      ksp_ratio = ((PetscReal) (its))/check->its0;
+      maxit     = (PetscInt) (ksp_ratio*sub_its + 0.5);
+      if (maxit < 2)
+        maxit = 2;
+      ierr = KSPSetTolerances(sub_ksp, PETSC_DEFAULT, PETSC_DEFAULT, PETSC_DEFAULT, maxit); CHKERRQ(ierr);
+      ierr = PetscPrintf(PETSC_COMM_WORLD, "    ...ksp_ratio %g, new maxit %d\n\n", ksp_ratio, maxit); CHKERRQ(ierr);
+    }
   check->its0 = its; /* save current outer KSP iteration number */
   PetscFunctionReturn(0);
 }
 
 /* ------------------------------------------------------------------- */
 /*
-   MatrixFreePreconditioner - This routine demonstrates the use of a
-   user-provided preconditioner.  This code implements just the null
-   preconditioner, which of course is not recommended for general use.
+  MatrixFreePreconditioner - This routine demonstrates the use of a
+  user-provided preconditioner.  This code implements just the null
+  preconditioner, which of course is not recommended for general use.
 
-   Input Parameters:
-+  pc - preconditioner
--  x - input vector
+  Input Parameters:
+  +  pc - preconditioner
+  -  x - input vector
 
-   Output Parameter:
-.  y - preconditioned vector
+  Output Parameter:
+  .  y - preconditioned vector
 */
-PetscErrorCode MatrixFreePreconditioner(PC pc,Vec x,Vec y)
+PetscErrorCode
+MatrixFreePreconditioner(PC pc, Vec x, Vec y)
 {
   PetscErrorCode ierr;
-  ierr = VecCopy(x,y);CHKERRQ(ierr);
+  ierr = VecCopy(x, y); CHKERRQ(ierr);
   return 0;
 }
diff --git a/others/cpp/tests/test1.cc b/others/cpp/tests/test1.cc
index 9e2c1304d8d8770f6edf34a2ef6aacda15931026..b5d773ac2063744ef393486fb7ceae20590072aa 100644
--- a/others/cpp/tests/test1.cc
+++ b/others/cpp/tests/test1.cc
@@ -3,9 +3,9 @@
 #include "DecisionRules.hh"
 
 DynareInfo *preprocessorOutput(void);
-extern "C"{
-void steadystate(double const*, double const*, double *, int *);
-void FirstDerivatives(const double *y, double *x, int nb_row_x, double *params, double *steady_state, int it_, double *residual, double *g1, double *v2, double *v3);
+extern "C" {
+  void steadystate(double const *, double const *, double *, int *);
+  void FirstDerivatives(const double *y, double *x, int nb_row_x, double *params, double *steady_state, int it_, double *residual, double *g1, double *v2, double *v3);
 }
 main(int argc, char **argv)
 {
@@ -17,8 +17,8 @@ main(int argc, char **argv)
   // Steady state
   double *steady_state = new double[endo_nbr];
   int info;
-  steadystate(NULL,params, steady_state, &info);
-  for (int i=0; i < endo_nbr; ++i)
+  steadystate(NULL, params, steady_state, &info);
+  for (int i = 0; i < endo_nbr; ++i)
     std::cout << model_info.get_endo_name_by_index(i) << " " << steady_state[i] << "\n";
 
   // 1st order approximation
@@ -54,7 +54,7 @@ main(int argc, char **argv)
   std::cout << "g1[44] = " << jacob_data[44] << endl;
   MatrixView jacob_tmp(jacob_data, endo_nbr, jacobian_col_nbr, endo_nbr);
   std::cout << "g1[44] = " << jacob_data[44] << endl;
-  std::cout << "jacob_tmp(2,7) = "<< jacob_tmp(2,7) << endl;
+  std::cout << "jacob_tmp(2,7) = "<< jacob_tmp(2, 7) << endl;
 
   Matrix jacobian(endo_nbr, jacobian_col_nbr), g_y(endo_nbr, nback+nmixed), g_u(endo_nbr, exo_nbr);
   jacobian = jacob_tmp;
diff --git a/preprocessor/CodeInterpreter.hh b/preprocessor/CodeInterpreter.hh
index 6d47072027b7726706ddadb9e80759094940cc4c..8939950fce0610933e3872cbb82203b79e10d85d 100644
--- a/preprocessor/CodeInterpreter.hh
+++ b/preprocessor/CodeInterpreter.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2015 Dynare Team
+ * Copyright (C) 2007-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/preprocessor/ComputingTasks.cc b/preprocessor/ComputingTasks.cc
index d3f2d1c15326b5d8b98e3ee085aea27e771a8b35..5488b0905ae1af218cadbfc06dce8ab224998f24 100644
--- a/preprocessor/ComputingTasks.cc
+++ b/preprocessor/ComputingTasks.cc
@@ -2325,15 +2325,16 @@ IdentificationStatement::writeJsonOutput(ostream &output) const
   output << "}";
 }
 
-WriteLatexDynamicModelStatement::WriteLatexDynamicModelStatement(const DynamicModel &dynamic_model_arg) :
-  dynamic_model(dynamic_model_arg)
+WriteLatexDynamicModelStatement::WriteLatexDynamicModelStatement(const DynamicModel &dynamic_model_arg, bool write_equation_tags_arg) :
+  dynamic_model(dynamic_model_arg),
+  write_equation_tags(write_equation_tags_arg)
 {
 }
 
 void
 WriteLatexDynamicModelStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const
 {
-  dynamic_model.writeLatexFile(basename);
+  dynamic_model.writeLatexFile(basename, write_equation_tags);
 }
 
 void
@@ -2408,6 +2409,53 @@ ShockDecompositionStatement::writeJsonOutput(ostream &output) const
   output << "}";
 }
 
+RealtimeShockDecompositionStatement::RealtimeShockDecompositionStatement(const SymbolList &symbol_list_arg,
+                                                                         const OptionsList &options_list_arg) :
+  symbol_list(symbol_list_arg),
+  options_list(options_list_arg)
+{
+}
+
+void
+RealtimeShockDecompositionStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const
+{
+  options_list.writeOutput(output);
+  symbol_list.writeOutput("var_list_", output);
+  output << "oo_ = realtime_shock_decomposition(M_,oo_,options_,var_list_,bayestopt_,estim_params_);" << endl;
+}
+
+PlotShockDecompositionStatement::PlotShockDecompositionStatement(const SymbolList &symbol_list_arg,
+                                                                 const OptionsList &options_list_arg) :
+  symbol_list(symbol_list_arg),
+  options_list(options_list_arg)
+{
+}
+
+void
+PlotShockDecompositionStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const
+{
+  output << "options_ = set_default_plot_shock_decomposition_options(options_);" << endl;
+  options_list.writeOutput(output);
+  symbol_list.writeOutput("var_list_", output);
+  output << "plot_shock_decomposition(M_, oo_, options_, var_list_);" << endl;
+}
+
+InitialConditionDecompositionStatement::InitialConditionDecompositionStatement(const SymbolList &symbol_list_arg,
+                                                                               const OptionsList &options_list_arg) :
+  symbol_list(symbol_list_arg),
+  options_list(options_list_arg)
+{
+}
+
+void
+InitialConditionDecompositionStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const
+{
+  output << "options_ = set_default_initial_condition_decomposition_options(options_);" << endl;
+  options_list.writeOutput(output);
+  symbol_list.writeOutput("var_list_", output);
+  output << "initial_condition_decomposition(M_, oo_, options_, var_list_, bayestopt_, estim_params_);" << endl;
+}
+
 ConditionalForecastStatement::ConditionalForecastStatement(const OptionsList &options_list_arg) :
   options_list(options_list_arg)
 {
@@ -4300,7 +4348,7 @@ CalibSmootherStatement::writeOutput(ostream &output, const string &basename, boo
   symbol_list.writeOutput("var_list_", output);
   output << "options_.smoother = 1;" << endl;
   output << "options_.order = 1;" << endl;
-  output << "[oo_,options_,bayestopt_]=evaluate_smoother('calibration',var_list_,M_,oo_,options_,bayestopt_,estim_params_);" << endl;
+  output << "[oo_,M_,options_,bayestopt_]=evaluate_smoother('calibration',var_list_,M_,oo_,options_,bayestopt_,estim_params_);" << endl;
 }
 
 void
diff --git a/preprocessor/ComputingTasks.hh b/preprocessor/ComputingTasks.hh
index 43b374c267c1a397f9e6c3fa477c6bf60bedab82..a222950afe56ea4b1b74009c6e6f032099d715d7 100644
--- a/preprocessor/ComputingTasks.hh
+++ b/preprocessor/ComputingTasks.hh
@@ -598,8 +598,9 @@ class WriteLatexDynamicModelStatement : public Statement
 {
 private:
   const DynamicModel &dynamic_model;
+  const bool write_equation_tags;
 public:
-  WriteLatexDynamicModelStatement(const DynamicModel &dynamic_model_arg);
+  WriteLatexDynamicModelStatement(const DynamicModel &dynamic_model_arg, bool write_equation_tags_arg);
   virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const;
   virtual void writeJsonOutput(ostream &output) const;
 };
@@ -636,6 +637,39 @@ public:
   virtual void writeJsonOutput(ostream &output) const;
 };
 
+class RealtimeShockDecompositionStatement : public Statement
+{
+private:
+  const SymbolList symbol_list;
+  const OptionsList options_list;
+public:
+  RealtimeShockDecompositionStatement(const SymbolList &symbol_list_arg,
+                                      const OptionsList &options_list_arg);
+  virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const;
+};
+
+class PlotShockDecompositionStatement : public Statement
+{
+private:
+  const SymbolList symbol_list;
+  const OptionsList options_list;
+public:
+  PlotShockDecompositionStatement(const SymbolList &symbol_list_arg,
+                                  const OptionsList &options_list_arg);
+  virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const;
+};
+
+class InitialConditionDecompositionStatement : public Statement
+{
+private:
+  const SymbolList symbol_list;
+  const OptionsList options_list;
+public:
+  InitialConditionDecompositionStatement(const SymbolList &symbol_list_arg,
+                                         const OptionsList &options_list_arg);
+  virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const;
+};
+
 class ConditionalForecastStatement : public Statement
 {
 private:
diff --git a/preprocessor/ConfigFile.cc b/preprocessor/ConfigFile.cc
index 36a1faa7d164be55fe3668b09545d07f53b5d0d3..64d899e13735f08ee8398b695885edc4bde86fc7 100644
--- a/preprocessor/ConfigFile.cc
+++ b/preprocessor/ConfigFile.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2016 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/preprocessor/ConfigFile.hh b/preprocessor/ConfigFile.hh
index e054922f71d00d8d2bcdafffbf1f736100bd2d6c..e3d9143eb426d96801bb21f933a3780437d75e7c 100644
--- a/preprocessor/ConfigFile.hh
+++ b/preprocessor/ConfigFile.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2016 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/preprocessor/DataTree.hh b/preprocessor/DataTree.hh
index d7a1de5d831732f93241a421e9d382b03425903a..5efb57bdbf4353d830cd692128006db97e07aee7 100644
--- a/preprocessor/DataTree.hh
+++ b/preprocessor/DataTree.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2016 Dynare Team
+ * Copyright (C) 2003-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/preprocessor/DynamicModel.cc b/preprocessor/DynamicModel.cc
index 00820fa15070767fc639decbd589ebdadfb61c9f..663453429cb8367e88127c1222739d08d9d0d8ac 100644
--- a/preprocessor/DynamicModel.cc
+++ b/preprocessor/DynamicModel.cc
@@ -2002,6 +2002,7 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri
           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 evaluation of block " << block <<"']);\n";
+          mDynamicModelFile << "    oo_.deterministic_simulation.status = 0;\n";
           mDynamicModelFile << "    oo_.deterministic_simulation.error = 100;\n";
           mDynamicModelFile << "    varargout{1} = oo_;\n";
           mDynamicModelFile << "    return;\n";
@@ -2029,6 +2030,7 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri
           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 evaluation of block " << block <<"']);\n";
+          mDynamicModelFile << "    oo_.deterministic_simulation.status = 0;\n";
           mDynamicModelFile << "    oo_.deterministic_simulation.error = 100;\n";
           mDynamicModelFile << "    varargout{1} = oo_;\n";
           mDynamicModelFile << "    return;\n";
@@ -2060,6 +2062,7 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri
           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";
+          mDynamicModelFile << "    oo_.deterministic_simulation.status = 0;\n";
           mDynamicModelFile << "    oo_.deterministic_simulation.error = 100;\n";
           mDynamicModelFile << "    varargout{1} = oo_;\n";
           mDynamicModelFile << "    return;\n";
@@ -2092,6 +2095,7 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri
           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";
+          mDynamicModelFile << "    oo_.deterministic_simulation.status = 0;\n";
           mDynamicModelFile << "    oo_.deterministic_simulation.error = 100;\n";
           mDynamicModelFile << "    varargout{1} = oo_;\n";
           mDynamicModelFile << "    return;\n";
@@ -2124,6 +2128,7 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri
           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";
+          mDynamicModelFile << "    oo_.deterministic_simulation.status = 0;\n";
           mDynamicModelFile << "    oo_.deterministic_simulation.error = 100;\n";
           mDynamicModelFile << "    varargout{1} = oo_;\n";
           mDynamicModelFile << "    return;\n";
@@ -4097,11 +4102,11 @@ DynamicModel::testTrendDerivativesEqualToZero(const eval_context_t &eval_context
                     double nearZero = testeq->getDerivative(endogit->second)->eval(eval_context); // eval d F / d Trend d Endog
                     if (fabs(nearZero) > ZERO_BAND)
                       {
-                        cerr << "ERROR: trends not compatible with balanced growth path; the second-order cross partial of equation " << eq + 1 << " (line "
+                        cerr << "WARNING: trends not compatible with balanced growth path; the second-order cross partial of equation " << eq + 1 << " (line "
                              << equations_lineno[eq] << ") w.r.t. trend variable "
                              << symbol_table.getName(it->first.first) << " and endogenous variable "
                              << symbol_table.getName(endogit->first.first) << " is not null. " << endl;
-                        exit(EXIT_FAILURE);
+                        // Changed to warning. See discussion in #1389
                       }
                   }
             }
@@ -4371,9 +4376,9 @@ DynamicModel::writeChainRuleDerivative(ostream &output, int eqr, int varr, int l
 }
 
 void
-DynamicModel::writeLatexFile(const string &basename) const
+DynamicModel::writeLatexFile(const string &basename, const bool write_equation_tags) const
 {
-  writeLatexModelFile(basename + "_dynamic", oLatexDynamicModel);
+  writeLatexModelFile(basename + "_dynamic", oLatexDynamicModel, write_equation_tags);
 }
 
 void
diff --git a/preprocessor/DynamicModel.hh b/preprocessor/DynamicModel.hh
index 4e4b64538735b2fde76c7d15022fc293865d1b3a..270359430ec93dbb3bad61633e91f41e5acca3fa 100644
--- a/preprocessor/DynamicModel.hh
+++ b/preprocessor/DynamicModel.hh
@@ -290,7 +290,7 @@ public:
   size_t dynamicOnlyEquationsNbr() const;
 
   //! Writes LaTeX file with the equations of the dynamic model
-  void writeLatexFile(const string &basename) const;
+  void writeLatexFile(const string &basename, const bool write_equation_tags) const;
 
   //! Writes LaTeX file with the equations of the dynamic model (for the original model)
   void writeLatexOriginalFile(const string &basename) const;
diff --git a/preprocessor/DynareBison.yy b/preprocessor/DynareBison.yy
index 7f6d28834cf00bdd53b0441e342ba073a6e0d147..c82b7025b3ae1c64f1389d4b51a051b334a89704 100644
--- a/preprocessor/DynareBison.yy
+++ b/preprocessor/DynareBison.yy
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2016 Dynare Team
+ * Copyright (C) 2003-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -86,12 +86,12 @@ class ParsingDriver;
 
 %token AIM_SOLVER ANALYTIC_DERIVATION ANALYTIC_DERIVATION_MODE AR AUTOCORR POSTERIOR_SAMPLING_METHOD
 %token BAYESIAN_IRF BETA_PDF BLOCK USE_CALIBRATION SILENT_OPTIMIZER
-%token BVAR_DENSITY BVAR_FORECAST NODECOMPOSITION DR_DISPLAY_TOL HUGE_NUMBER
-%token BVAR_PRIOR_DECAY BVAR_PRIOR_FLAT BVAR_PRIOR_LAMBDA
-%token BVAR_PRIOR_MU BVAR_PRIOR_OMEGA BVAR_PRIOR_TAU BVAR_PRIOR_TRAIN
-%token BVAR_REPLIC BYTECODE ALL_VALUES_REQUIRED PROPOSAL_DISTRIBUTION
+%token BVAR_DENSITY BVAR_FORECAST NODECOMPOSITION DR_DISPLAY_TOL HUGE_NUMBER FIG_NAME WRITE_XLS
+%token BVAR_PRIOR_DECAY BVAR_PRIOR_FLAT BVAR_PRIOR_LAMBDA INTERACTIVE SCREEN_SHOCKS STEADYSTATE
+%token BVAR_PRIOR_MU BVAR_PRIOR_OMEGA BVAR_PRIOR_TAU BVAR_PRIOR_TRAIN DETAIL_PLOT TYPE
+%token BVAR_REPLIC BYTECODE ALL_VALUES_REQUIRED PROPOSAL_DISTRIBUTION REALTIME VINTAGE
 %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 INITIAL_CONDITION_DECOMPOSITION
 %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 DIRNAME FILTER_STEP_AHEAD FILTERED_VARS FIRST_OBS LAST_OBS SET_TIME OSR_PARAMS_BOUNDS KEEP_KALMAN_ALGO_IF_SINGULARITY_IS_DETECTED
@@ -103,17 +103,17 @@ 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 FAST_KALMAN_FILTER KALMAN_ALGO KALMAN_TOL DIFFUSE_KALMAN_TOL SUBSAMPLES OPTIONS TOLF TOLX
+%token FAST_KALMAN_FILTER KALMAN_ALGO KALMAN_TOL DIFFUSE_KALMAN_TOL SUBSAMPLES OPTIONS TOLF TOLX PLOT_INIT_DATE PLOT_END_DATE
 %token LAPLACE LIK_ALGO LIK_INIT LINEAR LOAD_IDENT_FILES LOAD_MH_FILE LOAD_RESULTS_AFTER_LOAD_MH LOAD_PARAMS_AND_STEADY_STATE LOGLINEAR LOGDATA LYAPUNOV LINEAR_APPROXIMATION
 %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 CONTEMPORANEOUS_CORRELATION DIFFUSE_FILTER SUB_DRAWS TAPER_STEPS GEWEKE_INTERVAL RAFTERY_LEWIS_QRS RAFTERY_LEWIS_DIAGNOSTICS MCMC_JUMPING_COVARIANCE MOMENT_CALIBRATION
 %token NUMBER_OF_PARTICLES RESAMPLING SYSTEMATIC GENERIC RESAMPLING_THRESHOLD RESAMPLING_METHOD KITAGAWA STRATIFIED SMOOTH
-%token CPF_WEIGHTS AMISANOTRISTANI MURRAYJONESPARSLOW
-%token FILTER_ALGORITHM PROPOSAL_APPROXIMATION CUBATURE UNSCENTED MONTECARLO DISTRIBUTION_APPROXIMATION
+%token CPF_WEIGHTS AMISANOTRISTANI MURRAYJONESPARSLOW WRITE_EQUATION_TAGS
+%token NONLINEAR_FILTER_INITIALIZATION FILTER_ALGORITHM PROPOSAL_APPROXIMATION CUBATURE UNSCENTED MONTECARLO DISTRIBUTION_APPROXIMATION
 %token <string_val> NAME
-%token USE_PENALIZED_OBJECTIVE_FOR_HESSIAN
+%token USE_PENALIZED_OBJECTIVE_FOR_HESSIAN INIT_STATE RESCALE_PREDICTION_ERROR_COVARIANCE
 %token NAN_CONSTANT NO_STATIC NOBS NOCONSTANT NODISPLAY NOCORR NODIAGNOSTIC NOFUNCTIONS NO_HOMOTOPY
 %token NOGRAPH POSTERIOR_NOGRAPH POSTERIOR_GRAPH NOMOMENTS NOPRINT NORMAL_PDF SAVE_DRAWS
 %token OBSERVATION_TRENDS OPTIM OPTIM_WEIGHTS ORDER OSR OSR_PARAMS MAX_DIM_COVA_GROUP ADVANCED OUTFILE OUTVARS OVERWRITE
@@ -125,13 +125,13 @@ class ParsingDriver;
 %token RELATIVE_IRF REPLIC SIMUL_REPLIC RPLOT SAVE_PARAMS_AND_STEADY_STATE PARAMETER_UNCERTAINTY
 %token SHOCKS SHOCK_DECOMPOSITION SHOCK_GROUPS USE_SHOCK_GROUPS SIGMA_E SIMUL SIMUL_ALGO SIMUL_SEED ENDOGENOUS_TERMINAL_PERIOD
 %token SMOOTHER SMOOTHER2HISTVAL SQUARE_ROOT_SOLVER STACK_SOLVE_ALGO STEADY_STATE_MODEL SOLVE_ALGO SOLVER_PERIODS ROBUST_LIN_SOLVE
-%token STDERR STEADY STOCH_SIMUL SURPRISE SYLVESTER SYLVESTER_FIXED_POINT_TOL REGIMES REGIME
+%token STDERR STEADY STOCH_SIMUL SURPRISE SYLVESTER SYLVESTER_FIXED_POINT_TOL REGIMES REGIME REALTIME_SHOCK_DECOMPOSITION
 %token TEX RAMSEY_MODEL RAMSEY_POLICY RAMSEY_CONSTRAINTS PLANNER_DISCOUNT DISCRETIONARY_POLICY DISCRETIONARY_TOL
 %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 VALUES VAR VAREXO VAREXO_DET VAROBS PREDETERMINED_VARIABLES PLOT_SHOCK_DECOMPOSITION
 %token WRITE_LATEX_DYNAMIC_MODEL WRITE_LATEX_STATIC_MODEL WRITE_LATEX_ORIGINAL_MODEL
-%token XLS_SHEET XLS_RANGE LMMCP OCCBIN BANDPASS_FILTER COLORMAP
+%token XLS_SHEET XLS_RANGE LMMCP OCCBIN BANDPASS_FILTER COLORMAP QOQ YOY AOA
 %left COMMA
 %left EQUAL_EQUAL EXCLAMATION_EQUAL
 %left LESS GREATER LESS_EQUAL GREATER_EQUAL
@@ -143,7 +143,7 @@ class ParsingDriver;
 %token ASINH ACOSH ATANH SQRT NORMCDF NORMPDF STEADY_STATE EXPECTATION
 /* GSA analysis */
 %token DYNARE_SENSITIVITY MORRIS STAB REDFORM PPRIOR PRIOR_RANGE PPOST ILPTAU MORRIS_NLIV
-%token MORRIS_NTRA NSAM LOAD_REDFORM LOAD_RMSE LOAD_STAB ALPHA2_STAB KSSTAT LOGTRANS_REDFORM THRESHOLD_REDFORM
+%token MORRIS_NTRA NSAM LOAD_REDFORM LOAD_RMSE LOAD_STAB ALPHA2_STAB LOGTRANS_REDFORM THRESHOLD_REDFORM
 %token KSSTAT_REDFORM ALPHA2_REDFORM NAMENDO NAMLAGENDO NAMEXO RMSE LIK_ONLY VAR_RMSE PFILT_RMSE ISTART_RMSE
 %token ALPHA_RMSE ALPHA2_RMSE
 /* end of GSA analysis*/
@@ -171,7 +171,7 @@ class ParsingDriver;
 %token ADAPTIVE_MH_DRAWS THINNING_FACTOR COEFFICIENTS_PRIOR_HYPERPARAMETERS
 %token CONVERGENCE_STARTING_VALUE CONVERGENCE_ENDING_VALUE CONVERGENCE_INCREMENT_VALUE
 %token MAX_ITERATIONS_STARTING_VALUE MAX_ITERATIONS_INCREMENT_VALUE MAX_BLOCK_ITERATIONS
-%token MAX_REPEATED_OPTIMIZATION_RUNS FUNCTION_CONVERGENCE_CRITERION
+%token MAX_REPEATED_OPTIMIZATION_RUNS FUNCTION_CONVERGENCE_CRITERION SAVE_REALTIME
 %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
@@ -261,6 +261,9 @@ statement : parameters
           | write_latex_static_model
           | write_latex_original_model
           | shock_decomposition
+          | realtime_shock_decomposition
+          | plot_shock_decomposition
+          | initial_condition_decomposition
           | conditional_forecast
           | conditional_forecast_paths
           | plot_conditional_forecast
@@ -1815,6 +1818,7 @@ estimation_options : o_datafile
 		   | o_resampling_threshold
 		   | o_resampling_method
 		   | o_filter_algorithm
+                   | o_nonlinear_filter_initialization
                    | o_cpf_weights
 		   | o_proposal_approximation
 		   | o_distribution_approximation
@@ -1827,6 +1831,7 @@ estimation_options : o_datafile
                    | o_posterior_sampler_options
                    | o_keep_kalman_algo_if_singularity_is_detected
                    | o_use_penalized_objective_for_hessian
+                   | o_rescale_prediction_error_covariance
                    ;
 
 list_optim_option : QUOTED_STRING COMMA QUOTED_STRING
@@ -2107,7 +2112,9 @@ ramsey_policy_options : stoch_simul_primary_options
                       ;
 
 write_latex_dynamic_model : WRITE_LATEX_DYNAMIC_MODEL ';'
-                            { driver.write_latex_dynamic_model(); }
+                            { driver.write_latex_dynamic_model(false); }
+                          | WRITE_LATEX_DYNAMIC_MODEL '(' WRITE_EQUATION_TAGS ')' ';'
+                            { driver.write_latex_dynamic_model(true); }
                           ;
 
 write_latex_static_model : WRITE_LATEX_STATIC_MODEL ';'
@@ -2128,6 +2135,36 @@ shock_decomposition : SHOCK_DECOMPOSITION ';'
                       { driver.shock_decomposition(); }
                     ;
 
+realtime_shock_decomposition : REALTIME_SHOCK_DECOMPOSITION ';'
+                               {driver.realtime_shock_decomposition(); }
+                             | REALTIME_SHOCK_DECOMPOSITION '(' realtime_shock_decomposition_options_list ')' ';'
+                               { driver.realtime_shock_decomposition(); }
+                             | REALTIME_SHOCK_DECOMPOSITION symbol_list ';'
+                               { driver.realtime_shock_decomposition(); }
+                             | REALTIME_SHOCK_DECOMPOSITION '(' realtime_shock_decomposition_options_list ')' symbol_list ';'
+                               { driver.realtime_shock_decomposition(); }
+                             ;
+
+plot_shock_decomposition : PLOT_SHOCK_DECOMPOSITION ';'
+                           {driver.plot_shock_decomposition(); }
+                         | PLOT_SHOCK_DECOMPOSITION '(' plot_shock_decomposition_options_list ')' ';'
+                           { driver.plot_shock_decomposition(); }
+                         | PLOT_SHOCK_DECOMPOSITION symbol_list ';'
+                           { driver.plot_shock_decomposition(); }
+                         | PLOT_SHOCK_DECOMPOSITION '(' plot_shock_decomposition_options_list ')' symbol_list ';'
+                           { driver.plot_shock_decomposition(); }
+                         ;
+
+initial_condition_decomposition : INITIAL_CONDITION_DECOMPOSITION ';'
+                                  {driver.initial_condition_decomposition(); }
+                                | INITIAL_CONDITION_DECOMPOSITION '(' initial_condition_decomposition_options_list ')' ';'
+                                  { driver.initial_condition_decomposition(); }
+                                | INITIAL_CONDITION_DECOMPOSITION symbol_list ';'
+                                  { driver.initial_condition_decomposition(); }
+                                | INITIAL_CONDITION_DECOMPOSITION '(' initial_condition_decomposition_options_list ')' symbol_list ';'
+                                  { driver.initial_condition_decomposition(); }
+                                ;
+
 bvar_prior_option : o_bvar_prior_tau
                   | o_bvar_prior_decay
                   | o_bvar_prior_lambda
@@ -2444,7 +2481,6 @@ dynare_sensitivity_option : o_gsa_identification
                           | o_gsa_load_rmse
                           | o_gsa_load_stab
                           | o_gsa_alpha2_stab
-                          | o_gsa_ksstat
                           | o_gsa_logtrans_redform
                           | o_gsa_ksstat_redform
                           | o_gsa_alpha2_redform
@@ -2494,8 +2530,58 @@ shock_decomposition_option : o_parameter_set
                            | o_shock_decomposition_nograph
                            | o_first_obs
                            | o_nobs
+                           | o_init_state
                            ;
 
+realtime_shock_decomposition_options_list : realtime_shock_decomposition_option COMMA realtime_shock_decomposition_options_list
+                                         | realtime_shock_decomposition_option
+                                         ;
+
+realtime_shock_decomposition_option : o_parameter_set
+                                    | o_datafile
+                                    | o_first_obs
+                                    | o_nobs
+                                    | o_use_shock_groups
+                                    | o_colormap
+                                    | o_shock_decomposition_nograph
+                                    | o_shock_decomposition_presample
+                                    | o_shock_decomposition_forecast
+                                    | o_save_realtime
+                                    ;
+
+plot_shock_decomposition_options_list : plot_shock_decomposition_option COMMA plot_shock_decomposition_options_list
+                                      | plot_shock_decomposition_option
+                                      ;
+
+plot_shock_decomposition_option : o_psd_use_shock_groups
+                                | o_psd_colormap
+                                | o_psd_nodisplay
+                                | o_psd_graph_format
+                                | o_psd_detail_plot
+                                | o_psd_interactive
+                                | o_psd_screen_shocks
+                                | o_psd_steadystate
+                                | o_psd_type
+                                | o_psd_fig_name
+                                | o_psd_write_xls
+                                | o_psd_realtime
+                                | o_psd_vintage
+                                | o_psd_plot_init_date
+                                | o_psd_plot_end_date
+                                ;
+
+initial_condition_decomposition_options_list : initial_condition_decomposition_option COMMA initial_condition_decomposition_options_list
+                                             | initial_condition_decomposition_option
+                                             ;
+
+initial_condition_decomposition_option : o_icd_type
+                                       | o_icd_detail_plot
+                                       | o_icd_steadystate
+                                       | o_icd_write_xls
+                                       | o_icd_plot_init_date
+                                       | o_icd_plot_end_date
+                                       ;
+
 homotopy_setup: HOMOTOPY_SETUP ';' homotopy_list END ';'
                { driver.end_homotopy();};
 
@@ -2832,12 +2918,22 @@ o_posterior_nograph : POSTERIOR_NOGRAPH
             { driver.option_num("no_graph.posterior", "0"); }
           ;
 o_shock_decomposition_nograph : NOGRAPH { driver.option_num("no_graph.shock_decomposition", "1"); }
+o_init_state : INIT_STATE EQUAL INT_NUMBER { driver.option_num("shock_decomp.init_state", $3); };
+o_shock_decomposition_presample : PRESAMPLE EQUAL INT_NUMBER { driver.option_num("shock_decomp.presample", $3); };
+o_shock_decomposition_forecast : FORECAST EQUAL INT_NUMBER { driver.option_num("shock_decomp.forecast", $3); };
+o_save_realtime : SAVE_REALTIME EQUAL vec_int { driver.option_vec_int("shock_decomp.save_realtime", $3); };
 o_nodisplay : NODISPLAY { driver.option_num("nodisplay","1"); };
+o_psd_nodisplay : NODISPLAY { driver.option_num("plot_shock_decomp.nodisplay","1"); };
 o_graph_format : GRAPH_FORMAT EQUAL allowed_graph_formats
                  { driver.process_graph_format_option(); }
                | GRAPH_FORMAT EQUAL '(' list_allowed_graph_formats ')'
                  { driver.process_graph_format_option(); }
                ;
+o_psd_graph_format : GRAPH_FORMAT EQUAL allowed_graph_formats
+                     { driver.plot_shock_decomp_process_graph_format_option(); }
+                   | GRAPH_FORMAT EQUAL '(' list_allowed_graph_formats ')'
+                     { driver.plot_shock_decomp_process_graph_format_option(); }
+                   ;
 allowed_graph_formats : EPS
                         { driver.add_graph_format("eps"); }
                       | FIG
@@ -2943,7 +3039,35 @@ o_dr : DR EQUAL CYCLE_REDUCTION {driver.option_num("dr_cycle_reduction", "1"); }
 o_dr_cycle_reduction_tol : DR_CYCLE_REDUCTION_TOL EQUAL non_negative_number {driver.option_num("dr_cycle_reduction_tol",$3);};
 o_dr_logarithmic_reduction_tol : DR_LOGARITHMIC_REDUCTION_TOL EQUAL non_negative_number {driver.option_num("dr_logarithmic_reduction_tol",$3);};
 o_dr_logarithmic_reduction_maxiter : DR_LOGARITHMIC_REDUCTION_MAXITER EQUAL INT_NUMBER {driver.option_num("dr_logarithmic_reduction_maxiter",$3);};
-
+o_psd_detail_plot : DETAIL_PLOT { driver.option_num("plot_shock_decomp.detail_plot", "1"); };
+o_icd_detail_plot : DETAIL_PLOT { driver.option_num("initial_condition_decomp.detail_plot", "1"); };
+o_psd_interactive : INTERACTIVE { driver.option_num("plot_shock_decomp.interactive", "1"); };
+o_psd_screen_shocks : SCREEN_SHOCKS { driver.option_num("plot_shock_decomp.screen_shocks", "1"); };
+o_psd_steadystate : STEADYSTATE { driver.option_num("plot_shock_decomp.steadystate", "1"); };
+o_icd_steadystate : STEADYSTATE { driver.option_num("initial_condition_decomp.steadystate", "1"); };
+o_psd_fig_name : FIG_NAME EQUAL filename { driver.option_str("plot_shock_decomp.fig_name", $3); };
+o_psd_type : TYPE EQUAL QOQ
+             { driver.option_str("plot_shock_decomp.type", "qoq"); }
+           | TYPE EQUAL YOY
+             { driver.option_str("plot_shock_decomp.type", "qoq"); }
+           | TYPE EQUAL AOA
+             { driver.option_str("plot_shock_decomp.type", "qoq"); }
+           ;
+o_icd_type : TYPE EQUAL QOQ
+             { driver.option_str("initial_condition_decomp.type", "qoq"); }
+           | TYPE EQUAL YOY
+             { driver.option_str("initial_condition_decomp.type", "qoq"); }
+           | TYPE EQUAL AOA
+             { driver.option_str("initial_condition_decomp.type", "qoq"); }
+           ;
+o_icd_plot_init_date : PLOT_INIT_DATE EQUAL date_expr { driver.option_date("initial_condition_decomp.plot_init_date", $3); } ;
+o_icd_plot_end_date : PLOT_END_DATE EQUAL date_expr { driver.option_date("initial_condition_decomp.plot_end_date", $3); } ;
+o_psd_plot_init_date : PLOT_INIT_DATE EQUAL date_expr { driver.option_date("plot_shock_decomp.plot_init_date", $3); } ;
+o_psd_plot_end_date : PLOT_END_DATE EQUAL date_expr { driver.option_date("plot_shock_decomp.plot_end_date", $3); } ;
+o_icd_write_xls : WRITE_XLS { driver.option_num("initial_condition_decomp.write_xls", "1"); };
+o_psd_write_xls : WRITE_XLS { driver.option_num("plot_shock_decomp.write_xls", "1"); };
+o_psd_realtime : REALTIME EQUAL INT_NUMBER { driver.option_num("plot_shock_decomp.realtime", $3); };
+o_psd_vintage : VINTAGE EQUAL INT_NUMBER { driver.option_num("plot_shock_decomp.vintage", $3); };
 o_bvar_prior_tau : BVAR_PRIOR_TAU EQUAL signed_number { driver.option_num("bvar_prior_tau", $3); };
 o_bvar_prior_decay : BVAR_PRIOR_DECAY EQUAL non_negative_number { driver.option_num("bvar_prior_decay", $3); };
 o_bvar_prior_lambda : BVAR_PRIOR_LAMBDA EQUAL signed_number { driver.option_num("bvar_prior_lambda", $3); };
@@ -2964,6 +3088,7 @@ o_resampling_method : RESAMPLING_METHOD EQUAL KITAGAWA {driver.option_num("parti
 o_cpf_weights : CPF_WEIGHTS EQUAL AMISANOTRISTANI {driver.option_num("particle.cpf_weights_method.amisanotristani", "1"); driver.option_num("particle.cpf_weights_method.murrayjonesparslow", "0"); }
               | CPF_WEIGHTS EQUAL MURRAYJONESPARSLOW {driver.option_num("particle.cpf_weights_method.amisanotristani", "0"); driver.option_num("particle.cpf_weights_method.murrayjonesparslow", "1"); };
 o_filter_algorithm : FILTER_ALGORITHM EQUAL symbol { driver.option_str("particle.filter_algorithm", $3); };
+o_nonlinear_filter_initialization : NONLINEAR_FILTER_INITIALIZATION EQUAL INT_NUMBER { driver.option_num("particle.initialization", $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");} ;
@@ -2987,7 +3112,6 @@ o_gsa_load_redform : LOAD_REDFORM EQUAL INT_NUMBER { driver.option_num("load_red
 o_gsa_load_rmse : LOAD_RMSE EQUAL INT_NUMBER { driver.option_num("load_rmse", $3); };
 o_gsa_load_stab : LOAD_STAB EQUAL INT_NUMBER { driver.option_num("load_stab", $3); };
 o_gsa_alpha2_stab : ALPHA2_STAB EQUAL non_negative_number { driver.option_num("alpha2_stab", $3); };
-o_gsa_ksstat : KSSTAT EQUAL non_negative_number { driver.option_num("ksstat", $3); };
 o_gsa_logtrans_redform : LOGTRANS_REDFORM EQUAL INT_NUMBER { driver.option_num("logtrans_redform", $3); };
 o_gsa_threshold_redform : THRESHOLD_REDFORM EQUAL vec_value_w_inf { driver.option_num("threshold_redform",$3); };
 o_gsa_ksstat_redform : KSSTAT_REDFORM EQUAL non_negative_number { driver.option_num("ksstat_redform", $3); };
@@ -3234,6 +3358,7 @@ o_mcmc_jumping_covariance : MCMC_JUMPING_COVARIANCE EQUAL HESSIAN
                           | MCMC_JUMPING_COVARIANCE EQUAL filename
                             { driver.option_str("MCMC_jumping_covariance", $3); }
                           ;
+o_rescale_prediction_error_covariance : RESCALE_PREDICTION_ERROR_COVARIANCE { driver.option_num("rescale_prediction_error_covariance", "true"); };
 o_use_penalized_objective_for_hessian : USE_PENALIZED_OBJECTIVE_FOR_HESSIAN { driver.option_num("hessian.use_penalized_objective","true"); };
 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); };
@@ -3253,7 +3378,11 @@ o_sampling_draws : SAMPLING_DRAWS EQUAL INT_NUMBER { driver.option_num("sampling
 o_use_shock_groups : USE_SHOCK_GROUPS { driver.option_str("use_shock_groups","default"); }
                    | USE_SHOCK_GROUPS EQUAL symbol { driver.option_str("use_shock_groups", $3); }
                    ;
-o_colormap : COLORMAP EQUAL symbol { driver.option_num("colormap",$3); };
+o_psd_use_shock_groups : USE_SHOCK_GROUPS { driver.option_str("plot_shock_decomp.use_shock_groups","default"); }
+                       | USE_SHOCK_GROUPS EQUAL symbol { driver.option_str("plot_shock_decomp.use_shock_groups", $3); }
+                       ;
+o_colormap : COLORMAP EQUAL symbol { driver.option_num("plot_shock_decomp.colormap",$3); };
+o_psd_colormap : COLORMAP EQUAL symbol { driver.option_num("plot_shock_decomp.colormap",$3); };
 
 range : symbol ':' symbol
         {
diff --git a/preprocessor/DynareFlex.ll b/preprocessor/DynareFlex.ll
index e1e0aa4c5c30ff65bbf1fd7ed6c8bd7517fdcf7f..9553fab4519afeb0d9a7731ab8ff21ae9210344e 100644
--- a/preprocessor/DynareFlex.ll
+++ b/preprocessor/DynareFlex.ll
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2016 Dynare Team
+ * Copyright (C) 2003-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -150,6 +150,9 @@ 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>histval_file {BEGIN DYNARE_STATEMENT; return token::HISTVAL_FILE;}
 <INITIAL>forecast {BEGIN DYNARE_STATEMENT; return token::FORECAST;}
 <INITIAL>shock_decomposition {BEGIN DYNARE_STATEMENT; return token::SHOCK_DECOMPOSITION;}
+<INITIAL>realtime_shock_decomposition {BEGIN DYNARE_STATEMENT; return token::REALTIME_SHOCK_DECOMPOSITION;}
+<INITIAL>plot_shock_decomposition {BEGIN DYNARE_STATEMENT; return token::PLOT_SHOCK_DECOMPOSITION;}
+<INITIAL>initial_condition_decomposition {BEGIN DYNARE_STATEMENT; return token::INITIAL_CONDITION_DECOMPOSITION;}
 <INITIAL>sbvar {BEGIN DYNARE_STATEMENT; return token::SBVAR;}
 <INITIAL>ms_estimation {BEGIN DYNARE_STATEMENT; return token::MS_ESTIMATION;}
 <INITIAL>ms_simulation {BEGIN DYNARE_STATEMENT; return token::MS_SIMULATION;}
@@ -373,6 +376,8 @@ 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>indxscalesstates {return token::INDXSCALESSTATES;}
 <DYNARE_STATEMENT>fixed_point {return token::FIXED_POINT;}
 <DYNARE_STATEMENT>doubling {return token::DOUBLING;}
+<DYNARE_STATEMENT>plot_init_date {return token::PLOT_INIT_DATE;}
+<DYNARE_STATEMENT>plot_end_date {return token::PLOT_END_DATE;}
 <DYNARE_STATEMENT>square_root_solver {return token::SQUARE_ROOT_SOLVER;}
 <DYNARE_STATEMENT>cycle_reduction {return token::CYCLE_REDUCTION;}
 <DYNARE_STATEMENT>logarithmic_reduction {return token::LOGARITHMIC_REDUCTION;}
@@ -393,6 +398,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>amisanotristani {return token::AMISANOTRISTANI;}
 <DYNARE_STATEMENT>murrayjonesparslow {return token::MURRAYJONESPARSLOW;}
 <DYNARE_STATEMENT>filter_algorithm {return token::FILTER_ALGORITHM;}
+<DYNARE_STATEMENT>nonlinear_filter_initialization {return token::NONLINEAR_FILTER_INITIALIZATION;}
 <DYNARE_STATEMENT>proposal_approximation {return token::PROPOSAL_APPROXIMATION;}
 <DYNARE_STATEMENT>cubature {return token::CUBATURE;}
 <DYNARE_STATEMENT>unscented {return token::UNSCENTED;}
@@ -400,6 +406,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>distribution_approximation {return token::DISTRIBUTION_APPROXIMATION;}
 <DYNARE_STATEMENT>proposal_distribution {return token::PROPOSAL_DISTRIBUTION;}
 <DYNARE_STATEMENT>no_posterior_kernel_density {return token::NO_POSTERIOR_KERNEL_DENSITY;}
+<DYNARE_STATEMENT>rescale_prediction_error_covariance {return token::RESCALE_PREDICTION_ERROR_COVARIANCE;}
 <DYNARE_STATEMENT>use_penalized_objective_for_hessian {return token::USE_PENALIZED_OBJECTIVE_FOR_HESSIAN;}
 
 <DYNARE_STATEMENT>alpha {
@@ -459,6 +466,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
   yylval->string_val = new string(yytext);
   return token::ABAND;
 }
+<DYNARE_STATEMENT>write_equation_tags {return token::WRITE_EQUATION_TAGS;}
 <DYNARE_STATEMENT>indxap {return token::INDXAP;}
 <DYNARE_STATEMENT>apband {return token::APBAND;}
 <DYNARE_STATEMENT>indximf {return token::INDXIMF;}
@@ -570,6 +578,20 @@ 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>controlled_varexo {return token::CONTROLLED_VAREXO; }
 <DYNARE_STATEMENT>parameter_set {return token::PARAMETER_SET; }
+<DYNARE_STATEMENT>init_state {return token::INIT_STATE; }
+<DYNARE_STATEMENT>save_realtime {return token::SAVE_REALTIME;}
+<DYNARE_STATEMENT>detail_plot {return token::DETAIL_PLOT;}
+<DYNARE_STATEMENT>interactive {return token::INTERACTIVE;}
+<DYNARE_STATEMENT>screen_shocks {return token::SCREEN_SHOCKS;}
+<DYNARE_STATEMENT>steadystate {return token::STEADYSTATE;}
+<DYNARE_STATEMENT>type {return token::TYPE;}
+<DYNARE_STATEMENT>qoq {return token::QOQ; }
+<DYNARE_STATEMENT>yoy {return token::YOY; }
+<DYNARE_STATEMENT>aoa {return token::AOA; }
+<DYNARE_STATEMENT>fig_name {return token::FIG_NAME;}
+<DYNARE_STATEMENT>write_xls {return token::WRITE_XLS;}
+<DYNARE_STATEMENT>realtime {return token::REALTIME;}
+<DYNARE_STATEMENT>vintage {return token::VINTAGE;}
 <DYNARE_STATEMENT>prior_mode {return token::PRIOR_MODE; }
 <DYNARE_STATEMENT>prior_mean {return token::PRIOR_MEAN; }
 <DYNARE_STATEMENT>posterior_mode {return token::POSTERIOR_MODE; }
@@ -779,7 +801,6 @@ 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>load_rmse {return token::LOAD_RMSE;}
 <DYNARE_STATEMENT>load_stab {return token::LOAD_STAB;}
 <DYNARE_STATEMENT>alpha2_stab {return token::ALPHA2_STAB;}
-<DYNARE_STATEMENT>ksstat {return token::KSSTAT;}
 <DYNARE_STATEMENT>logtrans_redform {return token::LOGTRANS_REDFORM;}
 <DYNARE_STATEMENT>threshold_redform {return token::THRESHOLD_REDFORM;}
 <DYNARE_STATEMENT>ksstat_redform {return token::KSSTAT_REDFORM;}
diff --git a/preprocessor/ExternalFunctionsTable.cc b/preprocessor/ExternalFunctionsTable.cc
index 8554d8304c24ba25b62e37b29554823881efa8ca..eb4ab00cbc0164be60d7c99b5ccee5e8fde9f9c1 100644
--- a/preprocessor/ExternalFunctionsTable.cc
+++ b/preprocessor/ExternalFunctionsTable.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2015 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/preprocessor/ExternalFunctionsTable.hh b/preprocessor/ExternalFunctionsTable.hh
index aa4b02cdfa7f08f232f325cb575224b875a9525a..42d18391e727a5b8c5c8b9b116cf82ceaad9a907 100644
--- a/preprocessor/ExternalFunctionsTable.hh
+++ b/preprocessor/ExternalFunctionsTable.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2015 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/preprocessor/MinimumFeedbackSet.cc b/preprocessor/MinimumFeedbackSet.cc
index a84a994aba5dcef4da1674b99039310617ddbb90..d91391c5870d1580c116e0fa130076908e7d6f20 100644
--- a/preprocessor/MinimumFeedbackSet.cc
+++ b/preprocessor/MinimumFeedbackSet.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2012 Dynare Team
+ * Copyright (C) 2009-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/preprocessor/ModFile.cc b/preprocessor/ModFile.cc
index e0462b6b0ee136fbe2553dc5b7a7ef842c883473..a7c5c0b2645e0d2a872f04bf676aecaaf75dc6d7 100644
--- a/preprocessor/ModFile.cc
+++ b/preprocessor/ModFile.cc
@@ -144,7 +144,7 @@ ModFile::checkPass(bool nostrict)
   if ((mod_file_struct.ramsey_model_present || mod_file_struct.ramsey_policy_present)
       && mod_file_struct.discretionary_policy_present)
     {
-      cerr << "ERROR: You cannot use the discretionary_policy command when you use either rasmey_model or ramsey_policy and vice versa" << endl;
+      cerr << "ERROR: You cannot use the discretionary_policy command when you use either ramsey_model or ramsey_policy and vice versa" << endl;
       exit(EXIT_FAILURE);
     }
 
@@ -277,6 +277,19 @@ ModFile::checkPass(bool nostrict)
           || dynamic_model.isBinaryOpUsed(oDifferent)))
     warnings << "WARNING: you are using a function (max, min, abs, sign) or an operator (<, >, <=, >=, ==, !=) which is unsuitable for a stochastic context; see the reference manual, section about \"Expressions\", for more details." << endl;
 
+  if (linear
+      && (dynamic_model.isUnaryOpUsed(oSign)
+          || dynamic_model.isUnaryOpUsed(oAbs)
+          || dynamic_model.isBinaryOpUsed(oMax)
+          || dynamic_model.isBinaryOpUsed(oMin)
+          || dynamic_model.isBinaryOpUsed(oGreater)
+          || dynamic_model.isBinaryOpUsed(oLess)
+          || dynamic_model.isBinaryOpUsed(oGreaterEqual)
+          || dynamic_model.isBinaryOpUsed(oLessEqual)
+          || dynamic_model.isBinaryOpUsed(oEqualEqual)
+          || dynamic_model.isBinaryOpUsed(oDifferent)))
+    warnings << "WARNING: you have declared your model 'linear' but you are using a function (max, min, abs, sign) or an operator (<, >, <=, >=, ==, !=) which potentially makes it non-linear." << endl;
+
   // Test if some estimated parameters are used within the values of shocks
   // statements (see issue #469)
   set<int> parameters_intersect;
diff --git a/preprocessor/ModelTree.cc b/preprocessor/ModelTree.cc
index ecfb7fee0711865854c0c0402764ecca3e6bda52..2282f292d1b442a724637c7123598477d5e6d853 100644
--- a/preprocessor/ModelTree.cc
+++ b/preprocessor/ModelTree.cc
@@ -232,7 +232,7 @@ ModelTree::computeNonSingularNormalization(jacob_map_t &contemporaneous_jacobian
 void
 ModelTree::computeNormalizedEquations(multimap<int, int> &endo2eqs) const
 {
-  for (int i = 0; i < equations.size(); i++)
+  for (size_t i = 0; i < equations.size(); i++)
     {
       VariableNode *lhs = dynamic_cast<VariableNode *>(equations[i]->get_arg1());
       if (lhs == NULL)
@@ -247,7 +247,7 @@ ModelTree::computeNormalizedEquations(multimap<int, int> &endo2eqs) const
       if (endo.find(make_pair(symbol_table.getTypeSpecificID(symb_id), 0)) != endo.end())
         continue;
 
-      endo2eqs.insert(make_pair(symbol_table.getTypeSpecificID(symb_id), i));
+      endo2eqs.insert(make_pair(symbol_table.getTypeSpecificID(symb_id), (int) i));
       cout << "Endogenous " << symbol_table.getName(symb_id) << " normalized in equation " << (i+1) << endl;
     }
 }
@@ -1631,7 +1631,7 @@ ModelTree::Write_Inf_To_Bin_File(const string &basename,
 }
 
 void
-ModelTree::writeLatexModelFile(const string &basename, ExprNodeOutputType output_type) const
+ModelTree::writeLatexModelFile(const string &basename, ExprNodeOutputType output_type, const bool write_equation_tags) const
 {
   ofstream output, content_output;
   string filename = basename + ".tex";
@@ -1675,8 +1675,31 @@ ModelTree::writeLatexModelFile(const string &basename, ExprNodeOutputType output
 
   for (int eq = 0; eq < (int) equations.size(); eq++)
     {
-      content_output << "\\begin{dmath}" << endl
-                     << "% Equation " << eq+1 << endl;
+      content_output << "% Equation " << eq + 1 << endl;
+      bool wrote_eq_tag = false;
+      if (write_equation_tags)
+        {
+          for (vector<pair<int, pair<string, string> > >::const_iterator iteqt = equation_tags.begin();
+               iteqt != equation_tags.end(); iteqt++)
+            if (iteqt->first == eq)
+              {
+                if (!wrote_eq_tag)
+                  content_output << "\\noindent[";
+                else
+                  content_output << ", ";
+
+                content_output << iteqt->second.first;
+
+                if (iteqt->second.second.empty())
+                  content_output << "= `" << iteqt->second.second << "'";
+
+                wrote_eq_tag = true;
+              }
+        }
+      if (wrote_eq_tag)
+        content_output << "]";
+
+      content_output << "\\begin{dmath}" << endl;
       // Here it is necessary to cast to superclass ExprNode, otherwise the overloaded writeOutput() method is not found
       dynamic_cast<ExprNode *>(equations[eq])->writeOutput(content_output, output_type);
       content_output << endl << "\\end{dmath}" << endl;
@@ -1746,7 +1769,7 @@ ModelTree::addNonstationaryVariables(vector<int> nonstationary_vars, bool log_de
 void
 ModelTree::initializeVariablesAndEquations()
 {
-  for (int j = 0; j < equations.size(); j++)
+  for (size_t j = 0; j < equations.size(); j++)
     {
       equation_reordered.push_back(j);
       variable_reordered.push_back(j);
diff --git a/preprocessor/ModelTree.hh b/preprocessor/ModelTree.hh
index 8a9a6877d24679fe751684afab59e14ce53dbf6d..24db008abc4b05dcddfb974a23020f503f166343 100644
--- a/preprocessor/ModelTree.hh
+++ b/preprocessor/ModelTree.hh
@@ -200,7 +200,7 @@ protected:
   void compileModelEquations(ostream &code_file, unsigned int &instruction_number, const temporary_terms_t &tt, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic) const;
 
   //! Writes LaTeX model file
-  void writeLatexModelFile(const string &basename, ExprNodeOutputType output_type) const;
+  void writeLatexModelFile(const string &basename, ExprNodeOutputType output_type, const bool write_equation_tags = false) const;
 
   //! Sparse matrix of double to store the values of the Jacobian
   /*! First index is equation number, second index is endogenous type specific ID */
diff --git a/preprocessor/NumericalInitialization.cc b/preprocessor/NumericalInitialization.cc
index 59ef96ad7273837c0e1284ed57e2ba348668a358..843026517243ddd088d32a72024f8cf9f1cda271 100644
--- a/preprocessor/NumericalInitialization.cc
+++ b/preprocessor/NumericalInitialization.cc
@@ -245,12 +245,12 @@ InitValStatement::writeJsonOutput(ostream &output) const
 void
 InitValStatement::writeOutputPostInit(ostream &output) const
 {
-  output << "if M_.exo_nbr > 0;" << endl
-         << "\too_.exo_simul = [ones(M_.maximum_lag,1)*oo_.exo_steady_state'];" << endl
-         <<"end;" << endl
-         << "if M_.exo_det_nbr > 0;" << endl
-         << "\too_.exo_det_simul = [ones(M_.maximum_lag,1)*oo_.exo_det_steady_state'];" << endl
-         <<"end;" << endl;
+  output << "if M_.exo_nbr > 0" << endl
+         << "\too_.exo_simul = ones(M_.maximum_lag,1)*oo_.exo_steady_state';" << endl
+         <<"end" << endl
+         << "if M_.exo_det_nbr > 0" << endl
+         << "\too_.exo_det_simul = ones(M_.maximum_lag,1)*oo_.exo_det_steady_state';" << endl
+         <<"end" << endl;
 }
 
 EndValStatement::EndValStatement(const init_values_t &init_values_arg,
@@ -319,8 +319,6 @@ HistValStatement::HistValStatement(const hist_values_t &hist_values_arg,
 void
 HistValStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings)
 {
-  mod_file_struct.histval_present = true;
-
   if (all_values_required)
     {
       set<int> unused_endo = symbol_table.getEndogenous();
diff --git a/preprocessor/ParsingDriver.cc b/preprocessor/ParsingDriver.cc
index 2fbab28f505b399005024be54148ab3a2bcbce7e..f8b1e88146154350963f737bb1b5a5d83950b410 100644
--- a/preprocessor/ParsingDriver.cc
+++ b/preprocessor/ParsingDriver.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2016 Dynare Team
+ * Copyright (C) 2003-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -1962,9 +1962,9 @@ ParsingDriver::discretionary_policy()
 }
 
 void
-ParsingDriver::write_latex_dynamic_model()
+ParsingDriver::write_latex_dynamic_model(bool write_equation_tags)
 {
-  mod_file->addStatement(new WriteLatexDynamicModelStatement(mod_file->dynamic_model));
+  mod_file->addStatement(new WriteLatexDynamicModelStatement(mod_file->dynamic_model, write_equation_tags));
 }
 
 void
@@ -2124,6 +2124,30 @@ ParsingDriver::shock_decomposition()
   options_list.clear();
 }
 
+void
+ParsingDriver::realtime_shock_decomposition()
+{
+  mod_file->addStatement(new RealtimeShockDecompositionStatement(symbol_list, options_list));
+  symbol_list.clear();
+  options_list.clear();
+}
+
+void
+ParsingDriver::plot_shock_decomposition()
+{
+  mod_file->addStatement(new PlotShockDecompositionStatement(symbol_list, options_list));
+  symbol_list.clear();
+  options_list.clear();
+}
+
+void
+ParsingDriver::initial_condition_decomposition()
+{
+  mod_file->addStatement(new InitialConditionDecompositionStatement(symbol_list, options_list));
+  symbol_list.clear();
+  options_list.clear();
+}
+
 void
 ParsingDriver::conditional_forecast()
 {
@@ -2216,7 +2240,7 @@ ParsingDriver::declare_and_init_model_local_variable(string *name, expr_t rhs)
       // It can have already been declared in a steady_state_model block, check that it is indeed a ModelLocalVariable
       symb_id = mod_file->symbol_table.getID(*name);
       if (mod_file->symbol_table.getType(symb_id) != eModelLocalVariable)
-        error(*name + " has wrong type, you cannot use it within as left-hand side of a pound ('#') expression");
+        error(*name + " has wrong type or was already used on the right-hand side. You cannot use it on the left-hand side of a pound ('#') expression");
     }
 
   try
@@ -2806,6 +2830,13 @@ ParsingDriver::process_graph_format_option()
   graph_formats.clear();
 }
 
+void
+ParsingDriver::plot_shock_decomp_process_graph_format_option()
+{
+  options_list.symbol_list_options["plot_shock_decomp.graph_format"] = graph_formats;
+  graph_formats.clear();
+}
+
 void
 ParsingDriver::model_diagnostics()
 {
diff --git a/preprocessor/ParsingDriver.hh b/preprocessor/ParsingDriver.hh
index ad9a75e38121b4d92928a12db48cd9d4fd08784d..f6f04f8a06d0465944fd6e7d462930d729aa1da7 100644
--- a/preprocessor/ParsingDriver.hh
+++ b/preprocessor/ParsingDriver.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2016 Dynare Team
+ * Copyright (C) 2003-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -561,7 +561,7 @@ public:
   //! Discretionary policy statement
   void discretionary_policy();
   //! Adds a write_latex_dynamic_model statement
-  void write_latex_dynamic_model();
+  void write_latex_dynamic_model(bool write_equation_tags);
   //! Adds a write_latex_static_model statement
   void write_latex_static_model();
   //! Adds a write_latex_original_model statement
@@ -592,6 +592,12 @@ public:
   void markov_switching();
   //! Shock decomposition
   void shock_decomposition();
+  //! Realtime Shock decomposition
+  void realtime_shock_decomposition();
+  //! Plot Shock decomposition
+  void plot_shock_decomposition();
+  //! Initial Condition decomposition
+  void initial_condition_decomposition();
   //! Conditional forecast statement
   void conditional_forecast();
   //! Conditional forecast paths block
@@ -722,6 +728,8 @@ public:
   void add_graph_format(const string &name);
   //! Add the graph_format option to the OptionsList structure
   void process_graph_format_option();
+  //! Add the graph_format option to the plot_shock_decomp substructure of the OptionsList structure
+  void plot_shock_decomp_process_graph_format_option();
   //! Model diagnostics
   void model_diagnostics();
   //! Processing the parallel_local_files option
diff --git a/preprocessor/Statement.cc b/preprocessor/Statement.cc
index e3e54b3b3e4626730ef5f77fe88ebba34ecb8190..14bffcc3bcc197f264062525060dc86605a370b3 100644
--- a/preprocessor/Statement.cc
+++ b/preprocessor/Statement.cc
@@ -40,7 +40,6 @@ ModFileStructure::ModFileStructure() :
   identification_present(false),
   estimation_analytic_derivation(false),
   partial_information(false),
-  histval_present(false),
   k_order_solver(false),
   calibrated_measurement_errors(false),
   dsge_prior_weight_in_estimated_params(false),
diff --git a/preprocessor/Statement.hh b/preprocessor/Statement.hh
index ceb819574f79553a23f639976a16c8135b27bf53..7c80f5d5bb80979381d8dc8eed98e9a4cef3dd28 100644
--- a/preprocessor/Statement.hh
+++ b/preprocessor/Statement.hh
@@ -72,9 +72,6 @@ public:
   bool estimation_analytic_derivation;
   //! Whether the option partial_information is given to stoch_simul/estimation/osr/ramsey_policy
   bool partial_information;
-  //! Whether a histval bloc is present
-  /*! Used for the workaround for trac ticket #157 */
-  bool histval_present;
   //! Whether the "k_order_solver" option is used (explictly, or implicitly if order >= 3)
   bool k_order_solver;
   //! Whether there is a calibrated measurement error
diff --git a/preprocessor/SteadyStateModel.cc b/preprocessor/SteadyStateModel.cc
index 5fc9dc1de01da099628361f47fe6b6a58fa68adf..0a6e1536d0c49e329a1004518550b1e7e409bdf6 100644
--- a/preprocessor/SteadyStateModel.cc
+++ b/preprocessor/SteadyStateModel.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2016 Dynare Team
+ * Copyright (C) 2010-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/preprocessor/WarningConsolidation.cc b/preprocessor/WarningConsolidation.cc
index f026dea8f3bf7375b93b2a0878a0cc6558c665b3..f1c24f4ad19ef623d606a6d39ac81492e30c38ae 100644
--- a/preprocessor/WarningConsolidation.cc
+++ b/preprocessor/WarningConsolidation.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012-2013 Dynare Team
+ * Copyright (C) 2012-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/preprocessor/WarningConsolidation.hh b/preprocessor/WarningConsolidation.hh
index 582af0f43fea7b9c8c890d7bdac1aa955cd39d66..ece47995e582d5fd930c059700d61197994051b0 100644
--- a/preprocessor/WarningConsolidation.hh
+++ b/preprocessor/WarningConsolidation.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012-2013 Dynare Team
+ * Copyright (C) 2012-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/preprocessor/macro/MacroDriver.cc b/preprocessor/macro/MacroDriver.cc
index c5193cc6bb2d18f5d9421d5e9c304f1c8572accb..71d53b9cbaf0da6373d662f5ea3d926651906893 100644
--- a/preprocessor/macro/MacroDriver.cc
+++ b/preprocessor/macro/MacroDriver.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008-2015 Dynare Team
+ * Copyright (C) 2008-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/preprocessor/macro/MacroDriver.hh b/preprocessor/macro/MacroDriver.hh
index 7b828b0286d8383cfbda5d7cc5ef700a21656d80..773a99dcfda7355cc7d6df6aec15a82a0c30d6b7 100644
--- a/preprocessor/macro/MacroDriver.hh
+++ b/preprocessor/macro/MacroDriver.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008-2015 Dynare Team
+ * Copyright (C) 2008-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/preprocessor/macro/MacroValue.cc b/preprocessor/macro/MacroValue.cc
index 3dfab32331afdf9c654f44acb364443584ec6438..b20beb5db8d00392f2a8192a17fd2f76c7b48af7 100644
--- a/preprocessor/macro/MacroValue.cc
+++ b/preprocessor/macro/MacroValue.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008-2013 Dynare Team
+ * Copyright (C) 2008-2014 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/preprocessor/macro/MacroValue.hh b/preprocessor/macro/MacroValue.hh
index 64f0cdef73a6310f50642606ebdc6376f78f33e3..1097841d9831f9e0c37b5c5e116c6bce691dfbe9 100644
--- a/preprocessor/macro/MacroValue.hh
+++ b/preprocessor/macro/MacroValue.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008-2016 Dynare Team
+ * Copyright (C) 2008-2017 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/scripts/fix-copyright-years b/scripts/fix-copyright-years
index 86eceb7bdd63e7d24da38443e4454dec312f12af..d6f883e275027793b7fe52a86036dae1139078bd 100755
--- a/scripts/fix-copyright-years
+++ b/scripts/fix-copyright-years
@@ -14,7 +14,7 @@
 # Note that the script does not understand some unusual copyright notices: it
 # will display a message in that case.
 
-LAST_UPDATE_COMMIT=61485ab809d9a33484abf6136f05abd84da2be1b
+LAST_UPDATE_COMMIT=1bf81c9f5a79757c23356f16fe015ae4f10bebde
 
 if [ -z "$1" ]; then
     echo "Give a filename in argument"
diff --git a/scripts/indent-c++.el b/scripts/indent-c++.el
index 17ab26ba54b11c97927abbe718dc2868bc741e4f..ffbfaf68d19ff102a849e4d324f1eecb646acdea 100644
--- a/scripts/indent-c++.el
+++ b/scripts/indent-c++.el
@@ -1,5 +1,6 @@
 (c++-mode)
 (setq indent-tabs-mode nil)
 (indent-region (point-min) (point-max))
-(set-buffer-file-coding-system 'unix)
+(set-buffer-file-coding-system 'utf-8-unix)
+(delete-trailing-whitespace)
 (save-buffer)
diff --git a/scripts/indent-matlab.el b/scripts/indent-matlab.el
index 76861b258056e241b7eefe6cfa8f050931d077e5..a0ef3ae76bf58b70017547d9d52c561d8f8accfa 100644
--- a/scripts/indent-matlab.el
+++ b/scripts/indent-matlab.el
@@ -3,5 +3,6 @@
 (setq matlab-indent-function-body nil)
 (untabify (point-min) (point-max))
 (indent-region (point-min) (point-max))
-(set-buffer-file-coding-system 'unix)
+(set-buffer-file-coding-system 'utf-8-unix)
+(delete-trailing-whitespace)
 (save-buffer)
diff --git a/tests/Makefile.am b/tests/Makefile.am
index b857b28f5bf261765d12e5da7bc216ab835d24cc..a4e8ab8768ef382e140212a52d15f0d7246f9187 100644
--- a/tests/Makefile.am
+++ b/tests/Makefile.am
@@ -12,6 +12,8 @@ MODFILES = \
 	observation_trends_and_prefiltering/MCMC/Trend_loglin_prefilt_first_obs_MC.mod \
 	observation_trends_and_prefiltering/MCMC/Trend_prefilter_MC.mod \
 	observation_trends_and_prefiltering/MCMC/Trend_prefilter_first_obs_MC.mod \
+	dates/dseries_interact.mod \
+	dates/fs2000.mod \
 	estimation/slice/fs2000_slice.mod \
 	optimizers/fs2000_9.mod \
 	optimizers/fs2000_10.mod \
@@ -26,6 +28,7 @@ MODFILES = \
 	estimation/fs2000_MCMC_jumping_covariance.mod \
 	ms-sbvar/test_ms_variances_repeated_runs.mod \
 	fs2000/fs2000.mod \
+	ls2003/ls2003_hessian_zero.mod \
 	ep/rbc.mod \
 	estimation/fs2000_with_weibull_prior.mod \
 	estimation/fs2000_initialize_from_calib.mod	\
@@ -247,7 +250,7 @@ MODFILES = \
 	stochastic-backward-models/solow_cd_with_steadystate.mod \
 	stochastic-backward-models/backward_linear.mod \
 	deterministic_simulations/purely_forward/ar1.mod \
-        deterministic_simulations/purely_forward/nk.mod \
+	deterministic_simulations/purely_forward/nk.mod \
 	deterministic_simulations/purely_backward/ar1.mod \
 	deterministic_simulations/rbc_det1.mod \
 	deterministic_simulations/rbc_det2.mod \
@@ -272,9 +275,9 @@ MODFILES = \
 	deterministic_simulations/multiple_lead_lags/AR2.mod \
 	deterministic_simulations/multiple_lead_lags/AR2_forward.mod \
 	deterministic_simulations/multiple_lead_lags/ramst_augmented_histval.mod \
-        deterministic_simulations/rbc_det.mod \
-        deterministic_simulations/rbc_det_stack_solve_algo_7.mod \
-        lmmcp/rbc.mod \
+	deterministic_simulations/rbc_det.mod \
+	deterministic_simulations/rbc_det_stack_solve_algo_7.mod \
+	lmmcp/rbc.mod \
 	lmmcp/sw_lmmcp.mod \
 	lmmcp/sw_newton.mod \
 	trend_var/fs2000_nonstationary.mod \
@@ -286,6 +289,7 @@ MODFILES = \
 	shock_decomposition/fs2000_est.mod \
 	shock_decomposition/fs2000_est_varlist.mod \
 	shock_decomposition/fs2000_cal_groups.mod \
+	shock_decomposition/ls2003_plot.mod \
 	stochastic_purely_forward/stochastic_purely_forward.mod \
 	stochastic_purely_forward/stochastic_purely_forward_with_static.mod \
 	forecast/Hansen_exo_det_forecast.mod \
@@ -297,9 +301,12 @@ MODFILES = \
 	gradient/fs2000_numgrad_5.mod \
 	filter_step_ahead/fs2000_filter_step_ahead_bayesian.mod \
 	filter_step_ahead/fs2000_filter_step_ahead_ML.mod \
+	loglinear/example4_exp.mod \
 	loglinear/example4_loglinear.mod \
 	loglinear/example4_loglinear_lagged_exogenous.mod \
 	loglinear/example4_loglinear_lagged_exogenous_a.mod \
+	loglinear/example4_exp_histval.mod \
+	loglinear/example4_loglinear_histval.mod \
 	smoother2histval/fs2000_simul.mod \
 	smoother2histval/fs2000_smooth.mod \
 	smoother2histval/fs2000_smooth_stoch_simul.mod \
@@ -334,6 +341,10 @@ MODFILES = \
 	observation_trends_and_prefiltering/calib_smoother/Tr_prefil_f_obs_loglin_cal_smoother.mod \
 	observation_trends_and_prefiltering/ML/Trend_no_prefilter_selected_var.mod
 
+PARTICLEFILES = \
+	particle/dsge_base2.mod \
+	particle/dsge_unit_root.mod
+
 
 XFAIL_MODFILES = ramst_xfail.mod \
 	estim_param_in_shock_value_xfail.mod \
@@ -462,9 +473,14 @@ deterministic_simulations/multiple_lead_lags/sim_lead_lag.o.trs: deterministic_s
 deterministic_simulations/multiple_lead_lags/ramst_augmented_histval.m.trs: ramst.m.trs 
 deterministic_simulations/multiple_lead_lags/ramst_augmented_histval.o.trs: ramst.o.trs
 
+loglinear/example4_loglinear.m.trs: loglinear/example4_exp.m.trs
+loglinear/example4_loglinear.o.trs: loglinear/example4_exp.o.trs
 loglinear/example4_loglinear_lagged_exogenous_a.m.trs: loglinear/example4_loglinear_lagged_exogenous.m.trs 
 loglinear/example4_loglinear_lagged_exogenous_a.o.trs: loglinear/example4_loglinear_lagged_exogenous.o.trs 
 
+loglinear/example4_loglinear_histval.m.trs: loglinear/example4_exp_histval.m.trs
+loglinear/example4_loglinear_histval.o.trs: loglinear/example4_exp_histval.o.trs
+
 observation_trends_and_prefiltering/ML/Trend_loglinear_no_prefilter_first_obs.m.trs: observation_trends_and_prefiltering/ML/Trend_loglinear_no_prefilter.m.trs
 observation_trends_and_prefiltering/ML/Trend_loglinear_no_prefilter_first_obs.o.trs: observation_trends_and_prefiltering/ML/Trend_loglinear_no_prefilter.o.trs
 observation_trends_and_prefiltering/ML/Trend_loglinear_no_prefilter.m.trs: observation_trends_and_prefiltering/ML/Trend_no_prefilter.m.trs
@@ -625,6 +641,10 @@ lmmcp: m/lmmcp o/lmmcp
 m/lmmcp: $(patsubst %.mod, %.m.trs, $(filter lmmcp/%.mod, $(MODFILES)))
 o/lmmcp: $(patsubst %.mod, %.o.trs, $(filter lmmcp/%.mod, $(MODFILES)))
 
+loglinear: m/loglinear o/loglinear
+m/loglinear: $(patsubst %.mod, %.m.trs, $(filter loglinear/%.mod, $(MODFILES)))
+o/loglinear: $(patsubst %.mod, %.o.trs, $(filter loglinear/%.mod, $(MODFILES)))
+
 gsa: m/gsa o/gsa
 m/gsa: $(patsubst %.mod, %.m.trs, $(filter gsa/%.mod, $(MODFILES)))
 o/gsa: $(patsubst %.mod, %.o.trs, $(filter gsa/%.mod, $(MODFILES)))
@@ -681,6 +701,10 @@ gradient: m/gradient o/gradient
 m/gradient: $(patsubst %.mod, %.m.trs, $(filter gradient/%.mod, $(MODFILES)))
 o/gradient: $(patsubst %.mod, %.o.trs, $(filter gradient/%.mod, $(MODFILES)))
 
+particle: m/particle o/particle
+m/particle: $(patsubst %.mod, %.m.trs, $(PARTICLEFILES))
+o/particle: $(patsubst %.mod, %.o.trs, $(PARTICLEFILES))
+
 # 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
@@ -697,12 +721,11 @@ 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 \
+	load_octave_packages.m \
 	$(MODFILES) \
 	$(XFAIL_MODFILES) \
 	$(MFILES) \
@@ -731,6 +754,7 @@ EXTRA_DIST = \
 	AIM/fsdat.m \
 	block_bytecode/run_ls2003.m \
 	bvar_a_la_sims/bvar_sample.m \
+	dates/fsdat_simul.m \
 	external_function/extFunDeriv.m \
 	external_function/extFunNoDerivs.m \
 	external_function/extFunWithFirstAndSecondDerivs.m \
@@ -779,7 +803,6 @@ EXTRA_DIST = \
 	decision_rules/third_order/comparison_policy_functions_dynare_mathematica.m \
 	shock_decomposition/example1_calib_shock_decomp_data.mat \
 	shock_decomposition/fsdat_simul.m \
-	loglinear/results_exp.mat \
 	smoother2histval/fsdat_simul.m \
 	optimal_policy/Ramsey/find_c.m \
 	optimal_policy/Ramsey/oo_ramsey_policy_initval.mat \
@@ -833,7 +856,7 @@ check-octave: $(O_XFAIL_TRS_FILES) $(O_TRS_FILES)
 	@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 || \
-	printf ":test-result: FAIL\n:number-tests: 1\n:number-failed-tests: 1\n:list-of-failed-tests: $*.mod\n:cputime: 0.0\n" > $*.m.trs
+	printf ":test-result: FAIL\n:number-tests: 1\n:number-failed-tests: 1\n:list-of-failed-tests: $*.mod\n:elapsed-time: 0.0\n" > $*.m.trs
 	@if grep -q ":test-result: PASS" $*.m.trs; then \
 	echo "`tput bold``tput setaf 2`MATLAB: $(PWD)/$* PASSED!`tput sgr0`" ; \
 	else \
@@ -853,7 +876,7 @@ check-octave: $(O_XFAIL_TRS_FILES) $(O_TRS_FILES)
 	@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 --path "$*.mod" run_test_octave.m > $*.o.log 2>&1 || \
-	printf ":test-result: FAIL\n:number-tests: 1\n:number-failed-tests: 1\n:list-of-failed-tests: $*.mod\n:cputime: 0.0\n" > $*.o.trs
+	printf ":test-result: FAIL\n:number-tests: 1\n:number-failed-tests: 1\n:list-of-failed-tests: $*.mod\n:elapsed-time: 0.0\n" > $*.o.trs
 	@if grep -q ":test-result: PASS" $*.o.trs; then \
 	echo "`tput bold``tput setaf 2`OCTAVE: $(PWD)/$* PASSED!`tput sgr0`" ; \
 	else \
@@ -938,6 +961,8 @@ clean-local:
 
 	rm -rf ramsey_objective
 
+	rm -f ep/*.c
+
 	rm -f fs2000_ssfile_steadystate.m
 
 	rm -f $(shell find -name '*~')
@@ -967,6 +992,8 @@ clean-local:
 
 	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
 
+	rm -f loglinear/results_exp_histval.mat loglinear/results_exp.mat
+
 	find . -name "*.tex" -type f -delete
 	find . -name "*.aux" -type f -delete
 	find . -name "*.log" -type f -delete
diff --git a/tests/TeX/fs2000_corr_ME.mod b/tests/TeX/fs2000_corr_ME.mod
index dfb933ee1a08664ac7f0489df4c19c5a45323d03..c226ef835860c6d7f2d5e7698a41e7f8b02506a2 100644
--- a/tests/TeX/fs2000_corr_ME.mod
+++ b/tests/TeX/fs2000_corr_ME.mod
@@ -71,7 +71,9 @@ del = 0.02;
 options_.TeX=1;
 
 model;
+[name='technology growth: $\Delta A_{t}$', eq='\#1']
 dA = exp(gam+e_a);
+[name='money supply rule']
 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;
@@ -82,8 +84,11 @@ 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);
+[name='Production function']
 y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a));
+[name='observed output growth']
 gy_obs = dA*y/y(-1);
+[name='observed inflation']
 gp_obs = (P/P(-1))*m(-1)/dA;
 end;
 
@@ -134,7 +139,7 @@ stoch_simul(order=1,irf=20,graph_format=eps,periods=0,contemporaneous_correlatio
 
 write_latex_original_model;
 write_latex_static_model;
-write_latex_dynamic_model;
+write_latex_dynamic_model(write_equation_tags);
 write_latex_parameter_table;
 write_latex_definitions;
 
diff --git a/tests/bvar_a_la_sims/bvar_standalone.mod b/tests/bvar_a_la_sims/bvar_standalone.mod
index f3b2cbf185c1e0fdb0c8b6fa29c33b390eb33eb9..ae34ff959175e2c46f79e3933be4d67f51e17693 100644
--- a/tests/bvar_a_la_sims/bvar_standalone.mod
+++ b/tests/bvar_a_la_sims/bvar_standalone.mod
@@ -2,9 +2,9 @@ var dx dy;
 varobs dx dy;
 
 bvar_density(datafile = bvar_sample, first_obs = 20, bvar_prior_flat,
-             bvar_prior_train = 10) 8;
+             bvar_prior_train = 10) 2;
 
-bvar_forecast(forecast = 10, bvar_replic = 10000, nobs = 200) 8;
+bvar_forecast(forecast = 2, bvar_replic = 1000, nobs = 200) 2;
 
-bvar_irf(8,'Cholesky');
-bvar_irf(8,'SquareRoot');
\ No newline at end of file
+bvar_irf(2,'Cholesky');
+bvar_irf(2,'SquareRoot');
\ No newline at end of file
diff --git a/tests/dates/dseries_interact.mod b/tests/dates/dseries_interact.mod
new file mode 100644
index 0000000000000000000000000000000000000000..068d070b25ac81eafec3212a12efd551a1f045d3
--- /dev/null
+++ b/tests/dates/dseries_interact.mod
@@ -0,0 +1,57 @@
+%% Mod-file tests interaction between estimation and shock_decomposition when dseries is used or not
+var hh nn log_nn;
+varexo eps_a;
+parameters alfa nbar lambda betta rho_a std_a nn_init;
+
+nn_init = -0.1;
+alfa = 0.05;
+lambda = 0.054;
+betta = 0.99;
+nbar = 1;
+rho_a = 0;
+std_a = 1;
+
+
+model(linear);
+
+hh = - alfa * nn + betta * ( hh(+1) + 0  *  eps_a(+1) ) + eps_a;
+
+log_nn = log_nn(-1) + hh * lambda / (1-lambda);
+
+log_nn = ln(nbar) + nn;
+
+end;
+
+steady_state_model;
+log_nn = log(nbar);
+nn = 0;
+hh = 0;
+end;
+
+shocks;
+var eps_a; stderr 1;
+end;
+
+estimated_params;
+alfa, beta_pdf,   0.1, 0.05; 
+std_a,   inv_gamma_pdf, 0.05, 1;
+end;
+
+varobs log_nn;
+
+if ~isoctave() && ~matlab_ver_less_than('8.4')
+   websave('data_uav.xlsx','http://www.dynare.org/Datasets/data_uav.xlsx', weboptions('Timeout', 30))
+else
+   urlwrite('http://www.dynare.org/Datasets/data_uav.xlsx','data_uav.xlsx')
+end
+
+%reading Excel sheet from column A on creates quarterly dseries starting in
+%1950
+estimation(first_obs=2,datafile=data_uav, xls_sheet=Tabelle1, xls_range=a1:b54, mh_replic=2, mh_nblocks=1, mh_jscale=1.1, mh_drop=0.8, plot_priors=0, smoother) log_nn nn hh ;
+shock_decomposition( parameter_set=posterior_median ) nn hh;
+
+%reading Excel sheet from column B on creates annual dseries starting with 1
+estimation(first_obs=2,datafile=data_uav, xls_sheet=Tabelle1, xls_range=b1:b54, mh_replic=2, mh_nblocks=1, mh_jscale=1.1, mh_drop=0.8, plot_priors=0, smoother) log_nn nn hh ;
+shock_decomposition( parameter_set=posterior_median ) nn hh;
+
+delete('data_uav.xlsx')
diff --git a/tests/dates/fs2000.mod b/tests/dates/fs2000.mod
index 897f78b5f8c445102fdba5d50358d3b909339c17..957b4b745fb7b990bd44822b8e919536cded980f 100644
--- a/tests/dates/fs2000.mod
+++ b/tests/dates/fs2000.mod
@@ -1,12 +1,8 @@
-// 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;
 
-set_time(1950Q1);
-
 alp = 0.33;
 bet = 0.99;
 gam = 0.003;
@@ -79,19 +75,18 @@ stderr e_a, inv_gamma_pdf, 0.035449, inf;
 stderr e_m, inv_gamma_pdf, 0.008862, inf;
 end;
 
+// List the observed variables.
 varobs gp_obs gy_obs;
 
-options_.solve_tolf = 1e-12;
+// Instantiate a dseries object from an m file. Note that the dseries object has more than two variables. 
+ts = dseries('fsdat_simul.m');
 
-//data(file=fsdat_simul, first_obs=1950Q3, last_obs=1998Q1);
+// Load directly the dseries object as data for the estimation. The declared observed variables must be in the dseries object ts. 
+data(series=ts, first_obs=1950Q3, last_obs=2000Q3);
 
-ts = dseries('fsdat_simul.m');
-rr = 1950Q3:(1950Q1+ts.nobs);
-nn = length(rr);
-ds = ts(rr);
-ds.save('fsdat_simul2','m');
+// Print the first date of the sample.
+disp('First date is $1950Q3')  // disp('First date is 1950Q3'), without the $ symbol,  would trigger an error because of the substitution of 1950Q3 by dates('1950Q3')
 
-estimation(order=1,datafile=fsdat_simul2,loglinear,mh_replic=0);
+// Run the estimation. Note that we do not have a datafile option, because of the data command used above.
+estimation(order=1, loglinear, mh_replic=0);
 
-disp('First date is $1950Q3')
-// disp('Last date is 2000Q1') // This line would trigger an error because of the substitution of 2000Q1 by dates('2000Q1')
diff --git a/tests/deterministic_simulations/homotopy.mod b/tests/deterministic_simulations/homotopy.mod
index cd17a513e1c07ce5a288bb5991a7addc05fb8116..f6b3081dd641e2801a90fd728558fc0d71b3b65b 100644
--- a/tests/deterministic_simulations/homotopy.mod
+++ b/tests/deterministic_simulations/homotopy.mod
@@ -46,4 +46,8 @@ steady;
 
 simul(periods=200);
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 plot(Simulated_time_series.Capital(1Q1:25Q4));
diff --git a/tests/deterministic_simulations/homotopy_histval.mod b/tests/deterministic_simulations/homotopy_histval.mod
index 6fbc5e96f49bab6ed98f461ac6d800b5a17ed242..394081c56b3754ea8a9d3f0fb5c8760ab769912d 100644
--- a/tests/deterministic_simulations/homotopy_histval.mod
+++ b/tests/deterministic_simulations/homotopy_histval.mod
@@ -53,6 +53,10 @@ end;
 
 simul(periods=200);
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 plot(Simulated_time_series.Capital(1Q1:25Q4));
 
 if max(abs(oo_.endo_simul(:,1)-M_.endo_histval))>1e-6
diff --git a/tests/deterministic_simulations/initialization.mod b/tests/deterministic_simulations/initialization.mod
index 3523cfc225578f9d90054fffe05501ef7d173362..057618526f0efb2e4ce85d3e2cb957df0a594cab 100644
--- a/tests/deterministic_simulations/initialization.mod
+++ b/tests/deterministic_simulations/initialization.mod
@@ -18,5 +18,10 @@ check;
 
 %% DETERMINISTIC SIMULATION
 simul(periods = 40, stack_solve_algo=0, maxit=100);
+
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 dsample 40;
 rplot x;
\ No newline at end of file
diff --git a/tests/deterministic_simulations/lbj/rbc.mod b/tests/deterministic_simulations/lbj/rbc.mod
index 3395c6cc8ebbe67919d6a114967bb2d872ca634a..8d31197e714a36948784d386e4274530450abedf 100644
--- a/tests/deterministic_simulations/lbj/rbc.mod
+++ b/tests/deterministic_simulations/lbj/rbc.mod
@@ -73,11 +73,19 @@ end;
 perfect_foresight_setup(periods=400);
 perfect_foresight_solver(stack_solve_algo=0);
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 oo0 = oo_;
 
 perfect_foresight_setup(periods=400);
 perfect_foresight_solver(stack_solve_algo=6);
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 oo6 = oo_;
 
 maxabsdiff = max(max(abs(oo0.endo_simul-oo6.endo_simul)));
diff --git a/tests/deterministic_simulations/linear_approximation/sw.mod b/tests/deterministic_simulations/linear_approximation/sw.mod
index 218d4f203f95b337683a4d81261ee75e026c3862..0ef745d6aff2520ff853708f15b368d079f470bc 100644
--- a/tests/deterministic_simulations/linear_approximation/sw.mod
+++ b/tests/deterministic_simulations/linear_approximation/sw.mod
@@ -117,9 +117,15 @@ check;
 
 simul(periods=300);
 endo_simul_0 = oo_.endo_simul;
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
 
 simul(linear_approximation,periods=300);
 endo_simul_1 = oo_.endo_simul;
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
 
 if max(abs(endo_simul_0(:)-endo_simul_1(:)))>.01*options_.dynatol.f
     error('Something is wrong!')
diff --git a/tests/deterministic_simulations/lola_solve_one_boundary.mod b/tests/deterministic_simulations/lola_solve_one_boundary.mod
index bb200110b5142c98885236a1d95ad70f06195601..707d2f8b12ec5a638b5e2fd754e0652281c2ba4d 100644
--- a/tests/deterministic_simulations/lola_solve_one_boundary.mod
+++ b/tests/deterministic_simulations/lola_solve_one_boundary.mod
@@ -980,4 +980,8 @@ end;
 
 simul(periods=125,maxit=100);
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 delete('lola_data.mat')
diff --git a/tests/deterministic_simulations/multiple_lead_lags/AR2.mod b/tests/deterministic_simulations/multiple_lead_lags/AR2.mod
index c13db02e2926998f843afee05b34557aacbcec33..3a773488130af676ba1ab292f93d6425cd50ab5c 100644
--- a/tests/deterministic_simulations/multiple_lead_lags/AR2.mod
+++ b/tests/deterministic_simulations/multiple_lead_lags/AR2.mod
@@ -30,6 +30,10 @@ check;
 options_.solve_tolf=1e-12;
 simul(periods=100);
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 // Display the path of consumption and capital
 rplot y_backward;
 
diff --git a/tests/deterministic_simulations/multiple_lead_lags/AR2_forward.mod b/tests/deterministic_simulations/multiple_lead_lags/AR2_forward.mod
index cdeb8bb8fa307f2f8da825245bd52147752189ae..8e6b3f083934754bee9133e6514603e37bc07c04 100644
--- a/tests/deterministic_simulations/multiple_lead_lags/AR2_forward.mod
+++ b/tests/deterministic_simulations/multiple_lead_lags/AR2_forward.mod
@@ -32,6 +32,10 @@ check;
 options_.solve_tolf=1e-12;
 simul(periods=100);
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 // Display the path of consumption and capital
 rplot y_backward;
 
diff --git a/tests/deterministic_simulations/multiple_lead_lags/ramst_augmented_histval.mod b/tests/deterministic_simulations/multiple_lead_lags/ramst_augmented_histval.mod
index 9b417917a587b6b30d31c35753379dd252e3c87e..52aa9de85c5fd67b173169ae61e061328e0dd3d4 100644
--- a/tests/deterministic_simulations/multiple_lead_lags/ramst_augmented_histval.mod
+++ b/tests/deterministic_simulations/multiple_lead_lags/ramst_augmented_histval.mod
@@ -54,6 +54,10 @@ end;
 // Deterministic simulation of the model for 200 periods
 simul(periods=200);
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 junk=zeros(1,options_.periods+M_.maximum_lag);
 junk(1)=2;
 junk(2)=1;
diff --git a/tests/deterministic_simulations/multiple_lead_lags/sim_base.mod b/tests/deterministic_simulations/multiple_lead_lags/sim_base.mod
index 27c3b41cc222d47c0989bca5ebacc6249d054787..c54c3b4727ae5a4ad54f2347946226ace1b51d86 100644
--- a/tests/deterministic_simulations/multiple_lead_lags/sim_base.mod
+++ b/tests/deterministic_simulations/multiple_lead_lags/sim_base.mod
@@ -27,4 +27,8 @@ periods 2;
 values 0.9;
 end;
 
-simul(periods=200,maxit=100);
\ No newline at end of file
+simul(periods=200,maxit=100);
+
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
\ No newline at end of file
diff --git a/tests/deterministic_simulations/multiple_lead_lags/sim_endo_lead_lag.mod b/tests/deterministic_simulations/multiple_lead_lags/sim_endo_lead_lag.mod
index b85b0b5c1d997576b5e1ae810350e75f6840ae48..490c2882c4f7149a2db838ab3a21d6943e43b5c4 100644
--- a/tests/deterministic_simulations/multiple_lead_lags/sim_endo_lead_lag.mod
+++ b/tests/deterministic_simulations/multiple_lead_lags/sim_endo_lead_lag.mod
@@ -39,6 +39,11 @@ values 0.9;
 end;
 
 simul(periods=200,maxit=100);
+
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 base_results=load('sim_base_results.mat');
 if max(abs(base_results.oo_.endo_simul(strmatch('c',base_results.M_.endo_names,'exact'),1+base_results.M_.maximum_endo_lag:end-base_results.M_.maximum_endo_lead) -...
     oo_.endo_simul(strmatch('c',M_.endo_names,'exact'),1+M_.maximum_endo_lag:end-M_.maximum_endo_lead)))>1e-8 || ...
diff --git a/tests/deterministic_simulations/multiple_lead_lags/sim_endo_lead_lag_aux_vars.mod b/tests/deterministic_simulations/multiple_lead_lags/sim_endo_lead_lag_aux_vars.mod
index 6f6b4f56079d0ea28a613491ea5963ee25f821ec..9c5a26f4da46dc46430e78e1ce99011dcda40a8b 100644
--- a/tests/deterministic_simulations/multiple_lead_lags/sim_endo_lead_lag_aux_vars.mod
+++ b/tests/deterministic_simulations/multiple_lead_lags/sim_endo_lead_lag_aux_vars.mod
@@ -42,6 +42,11 @@ values 0.9;
 end;
 
 simul(periods=200,maxit=100);
+
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 base_results=load('sim_base_results.mat');
 if max(abs(base_results.oo_.endo_simul(strmatch('c',base_results.M_.endo_names,'exact'),1+base_results.M_.maximum_endo_lag:end-base_results.M_.maximum_endo_lead) -...
     oo_.endo_simul(strmatch('c',M_.endo_names,'exact'),1+M_.maximum_endo_lag:end-M_.maximum_endo_lead)))>1e-8 || ...
diff --git a/tests/deterministic_simulations/multiple_lead_lags/sim_exo_lead_lag.mod b/tests/deterministic_simulations/multiple_lead_lags/sim_exo_lead_lag.mod
index 2a73f207461f42f94289d2e5ebd7f4d820363fc2..0df5a01f1312dbad8f642cc2497f737c60ddaa9c 100644
--- a/tests/deterministic_simulations/multiple_lead_lags/sim_exo_lead_lag.mod
+++ b/tests/deterministic_simulations/multiple_lead_lags/sim_exo_lead_lag.mod
@@ -37,6 +37,11 @@ values 0.9;
 end;
 
 simul(periods=200,maxit=100);
+
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 base_results=load('sim_base_results.mat');
 if max(abs(base_results.oo_.endo_simul(strmatch('c',base_results.M_.endo_names,'exact'),1+base_results.M_.maximum_endo_lag:end-base_results.M_.maximum_endo_lead) -...
     oo_.endo_simul(strmatch('c',M_.endo_names,'exact'),1+M_.maximum_lag:end-M_.maximum_lead)))>1e-8 || ...
diff --git a/tests/deterministic_simulations/multiple_lead_lags/sim_exo_lead_lag_aux_vars.mod b/tests/deterministic_simulations/multiple_lead_lags/sim_exo_lead_lag_aux_vars.mod
index c0d60e072d739806f709b0d5baf55138630a7a82..0cf9342aeb96c0fec215b2e98a8f5e2baf43d7b1 100644
--- a/tests/deterministic_simulations/multiple_lead_lags/sim_exo_lead_lag_aux_vars.mod
+++ b/tests/deterministic_simulations/multiple_lead_lags/sim_exo_lead_lag_aux_vars.mod
@@ -42,6 +42,11 @@ values 0.9;
 end;
 
 simul(periods=200,maxit=100);
+
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 base_results=load('sim_base_results.mat');
 if max(abs(base_results.oo_.endo_simul(strmatch('c',base_results.M_.endo_names,'exact'),1+base_results.M_.maximum_endo_lag:end-base_results.M_.maximum_endo_lead) -...
     oo_.endo_simul(strmatch('c',M_.endo_names,'exact'),1+M_.maximum_endo_lag:end-M_.maximum_endo_lead)))>1e-8 || ...
diff --git a/tests/deterministic_simulations/multiple_lead_lags/sim_lead_lag.mod b/tests/deterministic_simulations/multiple_lead_lags/sim_lead_lag.mod
index 9fe8de65b8d1f29f4de57761e4587bc36db4fb83..406f6645917e4e8a87e55157eac3287de8cb1bcb 100644
--- a/tests/deterministic_simulations/multiple_lead_lags/sim_lead_lag.mod
+++ b/tests/deterministic_simulations/multiple_lead_lags/sim_lead_lag.mod
@@ -41,6 +41,11 @@ values 0.9;
 end;
 
 simul(periods=200,maxit=100);
+
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 base_results=load('sim_base_results.mat');
 if max(abs(base_results.oo_.endo_simul(strmatch('c',base_results.M_.endo_names,'exact'),1+base_results.M_.maximum_endo_lag:end-base_results.M_.maximum_endo_lead) -...
     oo_.endo_simul(strmatch('c',M_.endo_names,'exact'),1+M_.maximum_lag:end-M_.maximum_lead)))>1e-8 || ...
diff --git a/tests/deterministic_simulations/multiple_lead_lags/sim_lead_lag_aux_vars.mod b/tests/deterministic_simulations/multiple_lead_lags/sim_lead_lag_aux_vars.mod
index e8c11d073152ab0c1834c41d0b29b11620f3a63c..a09c0d0e646a2ef00ebc299e3c3292de44af1390 100644
--- a/tests/deterministic_simulations/multiple_lead_lags/sim_lead_lag_aux_vars.mod
+++ b/tests/deterministic_simulations/multiple_lead_lags/sim_lead_lag_aux_vars.mod
@@ -52,6 +52,11 @@ values 0.9;
 end;
 
 simul(periods=200,maxit=100);
+
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 base_results=load('sim_base_results.mat');
 if max(abs(base_results.oo_.endo_simul(strmatch('c',base_results.M_.endo_names,'exact'),1+base_results.M_.maximum_endo_lag:end-base_results.M_.maximum_endo_lead) -...
     oo_.endo_simul(strmatch('c',M_.endo_names,'exact'),1+M_.maximum_endo_lag:end-M_.maximum_endo_lead)))>1e-8 || ...
diff --git a/tests/deterministic_simulations/purely_backward/ar1.mod b/tests/deterministic_simulations/purely_backward/ar1.mod
index c4ea3299d8330a058b1b017d1f2be570da8257e9..1eb5dc5a4469d4e65d3560714ca17af377f4a3d1 100644
--- a/tests/deterministic_simulations/purely_backward/ar1.mod
+++ b/tests/deterministic_simulations/purely_backward/ar1.mod
@@ -27,6 +27,10 @@ end;
 
 simul(periods=10);
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 if max(abs(y-[1; exp(cumprod([1; rho*ones(9, 1)]))]))>options_.dynatol.x
     error('Wrong solution!')
 end
diff --git a/tests/deterministic_simulations/purely_forward/ar1.mod b/tests/deterministic_simulations/purely_forward/ar1.mod
index 0942e8466acdfa616e64b6991dfc0678f2f4892c..4c7f8ee045861219c94d95cd9a5e726a7dffe554 100644
--- a/tests/deterministic_simulations/purely_forward/ar1.mod
+++ b/tests/deterministic_simulations/purely_forward/ar1.mod
@@ -24,6 +24,10 @@ end;
 
 simul(periods=5);
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 expected_y = ones(1, 6);
 expected_y(2) = exp(-1);
 expected_y(1) = sqrt(exp(-1))*exp(1);
diff --git a/tests/deterministic_simulations/purely_forward/nk.mod b/tests/deterministic_simulations/purely_forward/nk.mod
index 5d5dcfa8b04815d2d7f1654b4295d052199cd9e4..15295ff01c100eeb009059065593142564269d2c 100644
--- a/tests/deterministic_simulations/purely_forward/nk.mod
+++ b/tests/deterministic_simulations/purely_forward/nk.mod
@@ -37,6 +37,10 @@ end;
 
 simul(periods=5);
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 % Initialize the analytical solution for the endogenous variables.
 expected_y = zeros(1, 6);
 expected_pi = zeros(1, 6);
diff --git a/tests/deterministic_simulations/rbc_det.mod b/tests/deterministic_simulations/rbc_det.mod
index 77388ac6f86e296d6faa40382c6f14b85ea78ad5..71fdbd59f9e81d5b4ce2aba8f0a96c9d3c43e5fa 100644
--- a/tests/deterministic_simulations/rbc_det.mod
+++ b/tests/deterministic_simulations/rbc_det.mod
@@ -74,5 +74,9 @@ perfect_foresight_setup(periods=200);
 
 perfect_foresight_solver;
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 rplot Consumption;
 rplot Capital;
\ No newline at end of file
diff --git a/tests/deterministic_simulations/rbc_det1.mod b/tests/deterministic_simulations/rbc_det1.mod
index a5fe6f5b3e857705bdb54261f38e0063c032979b..0458074b21f03b72585ed5bd8d145145242c16c5 100644
--- a/tests/deterministic_simulations/rbc_det1.mod
+++ b/tests/deterministic_simulations/rbc_det1.mod
@@ -71,5 +71,9 @@ end;
 
 simul(periods=20);
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 rplot Consumption;
 rplot Capital;
\ No newline at end of file
diff --git a/tests/deterministic_simulations/rbc_det2.mod b/tests/deterministic_simulations/rbc_det2.mod
index 7c34d592ff669dccf43a78c86c9be51a06976da4..55eab92c7c549204723b3161c74b39f2c2b7d5f3 100644
--- a/tests/deterministic_simulations/rbc_det2.mod
+++ b/tests/deterministic_simulations/rbc_det2.mod
@@ -71,5 +71,9 @@ end;
 
 simul(periods=300);
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 rplot Consumption;
 rplot Capital;
\ No newline at end of file
diff --git a/tests/deterministic_simulations/rbc_det3.mod b/tests/deterministic_simulations/rbc_det3.mod
index be9f5ff3ecaf69ee3029e028cc6b9cf308aaad64..f805b607d8e540df3763af95da7efb8d91908294 100644
--- a/tests/deterministic_simulations/rbc_det3.mod
+++ b/tests/deterministic_simulations/rbc_det3.mod
@@ -71,5 +71,9 @@ end;
 
 simul(periods=300);
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 rplot Consumption;
 rplot Capital;
\ No newline at end of file
diff --git a/tests/deterministic_simulations/rbc_det4.mod b/tests/deterministic_simulations/rbc_det4.mod
index cdee86dd5b81ac171f043e800dde1380236592ad..82542bb31622837f895179bcbe11609e7777d770 100644
--- a/tests/deterministic_simulations/rbc_det4.mod
+++ b/tests/deterministic_simulations/rbc_det4.mod
@@ -74,5 +74,9 @@ steady;
 
 simul(periods=300);
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 rplot Consumption;
 rplot Capital;
\ No newline at end of file
diff --git a/tests/deterministic_simulations/rbc_det5.mod b/tests/deterministic_simulations/rbc_det5.mod
index 7fcd4d0b67bc88b217deb5936c67cf69fa6032e0..ffeadf10a4495bdf66a654074ac15c80ecf0ace2 100644
--- a/tests/deterministic_simulations/rbc_det5.mod
+++ b/tests/deterministic_simulations/rbc_det5.mod
@@ -80,5 +80,9 @@ end;
 
 simul(periods=300);
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 rplot Consumption;
 rplot Capital;
\ No newline at end of file
diff --git a/tests/deterministic_simulations/rbc_det6.mod b/tests/deterministic_simulations/rbc_det6.mod
index 0bbb1008c5ba7617d558ab30c724f824827ab252..ad1ff2870dd666eaf76ef901eb0ac74ac652847c 100644
--- a/tests/deterministic_simulations/rbc_det6.mod
+++ b/tests/deterministic_simulations/rbc_det6.mod
@@ -72,12 +72,20 @@ end;
 simul(periods=500);
 fff = oo_.endo_simul;
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 simul(periods=500, endogenous_terminal_period);
 ggg = oo_.endo_simul;
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 t1 = abs(fff-ggg);
 t2 = max(max(t1));
 
 if t2>1e-5
-    error('sim1::endogenous_terminal_period: round off error is greater than 1e-5!')
+    error('Perfect foresight simulation with endogenous terminal period failed! Round off error is greater than 1e-5')
 end
diff --git a/tests/deterministic_simulations/rbc_det_exo_lag_2a.mod b/tests/deterministic_simulations/rbc_det_exo_lag_2a.mod
index b831cfdda7d82e059daad123bcb658de0c930aca..a0505dcd3d2b2a46514d9783082ef3a6270ba30d 100644
--- a/tests/deterministic_simulations/rbc_det_exo_lag_2a.mod
+++ b/tests/deterministic_simulations/rbc_det_exo_lag_2a.mod
@@ -71,5 +71,9 @@ end;
 
 simul(periods=300);
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 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
index d59a8e61333bf1271388448c760f5fac1f26912e..fb687f4c63300e5fd0379d7d3e48c4253aeca5e4 100644
--- a/tests/deterministic_simulations/rbc_det_exo_lag_2b.mod
+++ b/tests/deterministic_simulations/rbc_det_exo_lag_2b.mod
@@ -72,6 +72,10 @@ end;
 
 simul(periods=300);
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 rplot Consumption;
 rplot Capital;
 
diff --git a/tests/deterministic_simulations/rbc_det_exo_lag_2c.mod b/tests/deterministic_simulations/rbc_det_exo_lag_2c.mod
index fd702410904fcc8722cd14b30f503c9d851d214d..c6c8cbd88ed042d3b94f15ef4570a4bb3d89ef89 100644
--- a/tests/deterministic_simulations/rbc_det_exo_lag_2c.mod
+++ b/tests/deterministic_simulations/rbc_det_exo_lag_2c.mod
@@ -72,6 +72,10 @@ end;
 
 simul(periods=300);
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 rplot Consumption;
 rplot Capital;
 
diff --git a/tests/deterministic_simulations/rbc_det_stack_solve_algo_7.mod b/tests/deterministic_simulations/rbc_det_stack_solve_algo_7.mod
index c1e015dc39c240a402a9196a3b267b4b970df483..a4c829ffb37d6102c2ff238544b60c863d9a43d1 100644
--- a/tests/deterministic_simulations/rbc_det_stack_solve_algo_7.mod
+++ b/tests/deterministic_simulations/rbc_det_stack_solve_algo_7.mod
@@ -74,6 +74,10 @@ perfect_foresight_setup(periods=200);
 
 perfect_foresight_solver(stack_solve_algo=7,solve_algo=1);
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 rplot Consumption;
 rplot Capital;
 
@@ -91,6 +95,10 @@ options_.dynatol.f=1e-10;
 perfect_foresight_setup(periods=200);
 perfect_foresight_solver(stack_solve_algo=7,solve_algo=@{solve_algo_iter});
 
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
 rplot Consumption;
 rplot Capital;
 
diff --git a/tests/ep/rbc_mc.mod b/tests/ep/rbc_mc.mod
index d16e4835237d4109b4ba0b978ed7431e74e2909c..5f30d6ce5e92d64016472bdd5e712929e3de3eaf 100644
--- a/tests/ep/rbc_mc.mod
+++ b/tests/ep/rbc_mc.mod
@@ -72,4 +72,4 @@ end;
 
 steady(nocheck);
 
-Simulations = extended_path_mc([], 10, 5, [], options_, M_, oo_);
\ No newline at end of file
+Simulations = extended_path_mc([], 2, 2, [], options_, M_, oo_);
\ No newline at end of file
diff --git a/tests/gsa/ls2003.mod b/tests/gsa/ls2003.mod
index 2905f6de2fc8a7e2f85b717a2a4be1db0fc9c3ec..c93a7ff22d28dafc3962a53abc99df91b5bc7021 100644
--- a/tests/gsa/ls2003.mod
+++ b/tests/gsa/ls2003.mod
@@ -216,6 +216,7 @@ disp('Press ENTER to continue'); pause(5);
 
 dynare_sensitivity(nodisplay, stab=0, // no need for stability analysis since the posterior sample is surely OK
 datafile='data_ca1.m',first_obs=8,nobs=79,prefilter=1,
+alpha2_rmse=0, // no correlation analysis
 rmse=1,ppost=1,Nsam=512);
 
 collect_latex_files;
diff --git a/tests/gsa/morris/nk_est.mod b/tests/gsa/morris/nk_est.mod
index eb994ba01e86e6e00b096894791e5f787948c92c..fd502b4f93b5bc08c3375e05e808c9617fb721ab 100644
--- a/tests/gsa/morris/nk_est.mod
+++ b/tests/gsa/morris/nk_est.mod
@@ -55,7 +55,7 @@ stderr eps_A,0.02,0.000000000001,100,INV_GAMMA2_PDF,0.2,inf;
 stderr eps_P,0.03,0.000000000001,100,INV_GAMMA2_PDF,0.2,inf;
 end;
 estimation(order=1,prior_trunc=0,plot_priors =0, datafile=nk_est_data,conf_sig =.95,smoother,moments_varendo,filtered_vars,mode_check,mode_compute=4,mh_replic=5000,mh_jscale=1.5,mh_nblocks=1,bayesian_irf) y pi l dy pic;
-dynare_sensitivity (pprior=0,ppost=1,datafile=nk_est_data,rmse=1, nsam = 2000, lik_only = 0, morris = 2,var_rmse=(dy pic)) ;
-dynare_sensitivity (pprior=0,ppost=1,datafile=nk_est_data,rmse=1, nsam = 2000, lik_only = 0, morris = 1,var_rmse=(dy pic)) ;
+dynare_sensitivity (datafile=nk_est_data,rmse=0, nsam = 2000, lik_only = 0, morris = 2,var_rmse=(dy pic)) ;
+dynare_sensitivity (datafile=nk_est_data,rmse=0, nsam = 2000, lik_only = 0, morris = 1,var_rmse=(dy pic)) ;
 
 
diff --git a/tests/kalman_filter_smoother/check_variable_dimensions/fs2000_ML.mod b/tests/kalman_filter_smoother/check_variable_dimensions/fs2000_ML.mod
index 6b396682cbff9ebe9ecf695fa6b12d143494c478..b333d7ff0773dd523b5e33ef114999a94e353251 100644
--- a/tests/kalman_filter_smoother/check_variable_dimensions/fs2000_ML.mod
+++ b/tests/kalman_filter_smoother/check_variable_dimensions/fs2000_ML.mod
@@ -116,7 +116,7 @@ corr e_m, e_a, 0;
 stderr gp_obs, 0.01;
 end;
 options_.prior_trunc=0;
-estimation(order=1,datafile='../fsdat_simul', nobs=192, loglinear, forecast=8,smoother,filtered_vars,filter_step_ahead=[1,2,4],filter_decomposition,selected_variables_only)  m P c e W R k d y gy_obs;
+estimation(order=1,datafile='../fsdat_simul', nobs=192, loglinear, forecast=8,smoother,filter_covariance,filtered_vars,filter_step_ahead=[1,2,4],filter_decomposition,selected_variables_only)  m P c e W R k d y gy_obs;
 
 
 if size(oo_.FilteredVariablesKStepAhead,3)~=(options_.nobs+max(options_.filter_step_ahead)) || ...
@@ -124,8 +124,8 @@ if size(oo_.FilteredVariablesKStepAhead,3)~=(options_.nobs+max(options_.filter_s
     error('FilteredVariablesKStepAhead has the wrong length')    
 end
 
-if size(oo_.FilteredVariablesKStepAheadVariances,4)~=(options_.nobs+max(options_.filter_step_ahead)) || ...
-        size(oo_.FilteredVariablesKStepAheadVariances,1)~=(length(options_.filter_step_ahead))
+if options_.filter_covariance && (size(oo_.FilteredVariablesKStepAheadVariances,4)~=(options_.nobs+max(options_.filter_step_ahead)) || ...
+        size(oo_.FilteredVariablesKStepAheadVariances,1)~=(length(options_.filter_step_ahead)))
     error('FilteredVariablesKStepAhead has the wrong length')    
 end
 
diff --git a/tests/kalman_filter_smoother/test_compute_Pinf_Pstar.mod b/tests/kalman_filter_smoother/test_compute_Pinf_Pstar.mod
index 036b62442e13a3849be1204029d5ea31f673ce7f..e2551ef2ca8388ab4c0651d47d67ff54ac2d007b 100644
--- a/tests/kalman_filter_smoother/test_compute_Pinf_Pstar.mod
+++ b/tests/kalman_filter_smoother/test_compute_Pinf_Pstar.mod
@@ -103,9 +103,9 @@ k = reshape(1:M_.endo_nbr,3,round(M_.endo_nbr/3));
 kc = k(1,:);
 kr = k(2:3,:);
 
-if norm(Pinf(kr(:),kc)) > 1e-15
+if norm(Pinf(kr(:),kc)) > 1e-14
    error('Pinf isn''t correct')
 end
-if norm(Pinf(kr(:),kc)) > 1e-15
+if norm(Pinf(kr(:),kc)) > 1e-14
    error('Pstar isn''t correct')
 end
diff --git a/tests/loglinear/example4_exp.mod b/tests/loglinear/example4_exp.mod
index e53b68db74ef537f524ce8f6c98486b29af87119..4fd4811bf4613303f67b3bf9459ee03fcf524508 100644
--- a/tests/loglinear/example4_exp.mod
+++ b/tests/loglinear/example4_exp.mod
@@ -64,5 +64,19 @@ var e, u = phi*0.009*0.009;
 end;
 
 stoch_simul(order=1);
+forecast;
+conditional_forecast_paths;
+var a;
+periods  1  2  ;
+values   0.01 -0.02;
+var b;
+periods 1 2;
+values  0.05 0;
+end;
+
+conditional_forecast(parameter_set=calibration, controlled_varexo=(u,e));
+
 oo_exp=oo_;
-save results_exp.mat oo_exp
+load('conditional_forecasts.mat')
+conditional_forecasts_exp=forecasts;
+save results_exp.mat oo_exp conditional_forecasts_exp
\ No newline at end of file
diff --git a/tests/loglinear/example4_exp_histval.mod b/tests/loglinear/example4_exp_histval.mod
new file mode 100644
index 0000000000000000000000000000000000000000..e07a0a6fbf094754f29a7c9687b0555bce5667c3
--- /dev/null
+++ b/tests/loglinear/example4_exp_histval.mod
@@ -0,0 +1,92 @@
+/*
+ * Example 1 from F. Collard (2001): "Stochastic simulations with DYNARE:
+ * A practical guide" (see "guide.pdf" in the documentation directory).
+ */
+
+/*
+ * Copyright (C) 2001-2016 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 y, c, k, a, h, b;
+varexo e, u;
+
+parameters beta, rho, alpha, delta, theta, psi, tau;
+
+alpha = 0.36;
+rho   = 0.95;
+tau   = 0.025;
+beta  = 0.99;
+delta = 0.025;
+psi   = 0;
+theta = 2.95;
+
+phi   = 0.1;
+
+model;
+exp(c)*theta*exp(h)^(1+psi)=(1-alpha)*exp(y);
+exp(k) = beta*(((exp(b)*exp(c))/(exp(b(+1))*exp(c(+1))))
+    *(exp(b(+1))*alpha*exp(y(+1))+(1-delta)*exp(k)));
+exp(y) = exp(a)*(exp(k(-1))^alpha)*(exp(h)^(1-alpha));
+exp(k) = exp(b)*(exp(y)-exp(c))+(1-delta)*exp(k(-1));
+a = rho*a(-1)+tau*b(-1) + e;
+b = tau*a(-1)+rho*b(-1) + u;
+end;
+
+initval;
+y = log(1.08068253095672);
+c = log(0.80359242014163);
+h = log(0.29175631001732);
+k = log(11.08360443260358);
+a = 0;
+b = 0;
+end;
+resid(1);
+shocks;
+var e; stderr 0.009;
+var u; stderr 0.009;
+var e, u = phi*0.009*0.009;
+end;
+
+histval;
+k(0) = log(11.08);
+a(0) = log(1.2);
+b(0) = log(1);
+end;
+
+stoch_simul(order=1,periods=1000);
+forecast;
+
+forecast;
+conditional_forecast_paths;
+var a;
+periods  1  2  ;
+values   0.01 -0.02;
+var b;
+periods 1 2;
+values  0.05 0;
+end;
+
+conditional_forecast(parameter_set=calibration, controlled_varexo=(u,e));
+
+oo_exp=oo_;
+load('conditional_forecasts.mat')
+conditional_forecasts_exp=forecasts;
+
+oo_exp=oo_;
+save results_exp_histval.mat oo_exp conditional_forecasts_exp
diff --git a/tests/loglinear/example4_loglinear.mod b/tests/loglinear/example4_loglinear.mod
index 482a39e7ebac1d7747d8c3456e905eb3afe54cd5..81f4583a424a77e98d2e12529ab62624146c5d84 100644
--- a/tests/loglinear/example4_loglinear.mod
+++ b/tests/loglinear/example4_loglinear.mod
@@ -64,6 +64,18 @@ var e, u = phi*0.009*0.009;
 end;
 
 stoch_simul(loglinear,order=1);
+forecast;
+
+conditional_forecast_paths;
+var a;
+periods  1  2  ;
+values   0.01 -0.02;
+var b;
+periods 1 2;
+values  0.05 0;
+end;
+
+conditional_forecast(parameter_set=calibration, controlled_varexo=(u,e));
 
 load results_exp;
 if max(max(abs(oo_.dr.ghx-oo_exp.dr.ghx)))>1e-10
@@ -99,6 +111,22 @@ for ii=1:length(oo_.autocorr)
     error('Option loglinear wrong, moments not equal')
     end
 end
+
+if max(max(abs(struct2array(oo_.forecast.Mean)-struct2array(oo_exp.forecast.Mean))))>1e-10 || ...
+    max(max(abs(struct2array(oo_.forecast.HPDinf)-struct2array(oo_exp.forecast.HPDinf))))>1e-10 || ...
+    max(max(abs(struct2array(oo_.forecast.HPDsup)-struct2array(oo_exp.forecast.HPDsup))))>1e-10
+    error('Option loglinear wrong, forecast not equal')
+end
+
+load('conditional_forecasts.mat')
+
+if max(max(abs(struct2array(forecasts.cond.Mean)-struct2array(conditional_forecasts_exp.cond.Mean))))>1e-10 || ...
+    max(max(abs(struct2array(forecasts.cond.ci)-struct2array(conditional_forecasts_exp.cond.ci))))>1e-10 || ...
+    max(max(abs(struct2array(forecasts.uncond.Mean)-struct2array(conditional_forecasts_exp.uncond.Mean))))>1e-10 || ...
+    max(max(abs(struct2array(forecasts.uncond.ci)-struct2array(conditional_forecasts_exp.uncond.ci))))>1e-10 
+    error('Option loglinear wrong, conditional forecast not equal')
+end
+
 stoch_simul(loglinear,order=1,periods=100000);
 if abs(mean(y)-0.0776)>0.02
     error('Simulations are wrong')
diff --git a/tests/loglinear/example4_loglinear_histval.mod b/tests/loglinear/example4_loglinear_histval.mod
new file mode 100644
index 0000000000000000000000000000000000000000..752baa8bc3cd100baad229aa497b6c2b0cc70db1
--- /dev/null
+++ b/tests/loglinear/example4_loglinear_histval.mod
@@ -0,0 +1,124 @@
+/*
+ * Example 1 from F. Collard (2001): "Stochastic simulations with DYNARE:
+ * A practical guide" (see "guide.pdf" in the documentation directory).
+ */
+
+/*
+ * Copyright (C) 2001-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 y, c, k, a, h, b;
+varexo e, u;
+
+parameters beta, rho, alpha, delta, theta, psi, tau;
+
+alpha = 0.36;
+rho   = 0.95;
+tau   = 0.025;
+beta  = 0.99;
+delta = 0.025;
+psi   = 0;
+theta = 2.95;
+
+phi   = 0.1;
+
+model;
+c*theta*h^(1+psi)=(1-alpha)*y;
+k = beta*(((b*c)/(b(+1)*c(+1)))
+    *(b(+1)*alpha*y(+1)+(1-delta)*k));
+y = a*(k(-1)^alpha)*(h^(1-alpha));
+k = b*(y-c)+(1-delta)*k(-1);
+log(a) = rho*log(a(-1))+tau*log(b(-1)) + e;
+log(b) = tau*log(a(-1))+rho*log(b(-1)) + u;
+end;
+
+initval;
+y = 1.08068253095672;
+c = 0.80359242014163;
+h = 0.29175631001732;
+k = 11.08360443260358;
+a = 1;
+b = 1;
+end;
+
+resid(1);
+shocks;
+var e; stderr 0.009;
+var u; stderr 0.009;
+var e, u = phi*0.009*0.009;
+end;
+
+histval;
+k(0) = 11.08;
+a(0) = 1.2;
+b(0) = 1;
+end;
+
+stoch_simul(loglinear,order=1,periods=1000);
+forecast;
+
+load results_exp_histval;
+if max(max(abs(oo_.dr.ghx-oo_exp.dr.ghx)))>1e-10
+    error('Option loglinear wrong, ghx not equal')
+end
+if max(max(abs(oo_.dr.ghu-oo_exp.dr.ghu)))>1e-10
+    error('Option loglinear wrong, ghu not equal')
+end
+if max(max(abs(oo_.irfs.y_e-oo_exp.irfs.y_e)))>1e-10
+    error('Option loglinear wrong, IRFs not equal')
+end
+if max(max(abs(oo_.irfs.y_u-oo_exp.irfs.y_u)))>1e-10
+    error('Option loglinear wrong, ghu not equal')
+end
+if max(max(abs(oo_.mean-oo_exp.mean)))>1e-10
+    error('Option loglinear wrong, mean not equal')
+end
+if max(max(abs(oo_.dr.ys-oo_exp.dr.ys)))>1e-10
+    error('Option loglinear wrong, ys not equal')
+end
+if max(max(abs(oo_.steady_state-oo_exp.steady_state)))>1e-10
+    error('Option loglinear wrong, steady_state not equal')
+end
+
+if max(max(abs(struct2array(oo_.forecast.Mean)-struct2array(oo_exp.forecast.Mean))))>1e-10 || ...
+    max(max(abs(struct2array(oo_.forecast.HPDinf)-struct2array(oo_exp.forecast.HPDinf))))>1e-10 || ...
+    max(max(abs(struct2array(oo_.forecast.HPDsup)-struct2array(oo_exp.forecast.HPDsup))))>1e-10
+    error('Option loglinear wrong, forecast not equal')
+end
+
+conditional_forecast_paths;
+var a;
+periods  1  2  ;
+values   0.01 -0.02;
+var b;
+periods 1 2;
+values  0.05 0;
+end;
+
+conditional_forecast(parameter_set=calibration, controlled_varexo=(u,e));
+
+
+load('conditional_forecasts.mat')
+
+if max(max(abs(struct2array(forecasts.cond.Mean)-struct2array(conditional_forecasts_exp.cond.Mean))))>1e-10 || ...
+    max(max(abs(struct2array(forecasts.cond.ci)-struct2array(conditional_forecasts_exp.cond.ci))))>1e-10 || ...
+    max(max(abs(struct2array(forecasts.uncond.Mean)-struct2array(conditional_forecasts_exp.uncond.Mean))))>1e-10 || ...
+    max(max(abs(struct2array(forecasts.uncond.ci)-struct2array(conditional_forecasts_exp.uncond.ci))))>1e-10 
+    error('Option loglinear wrong, conditional forecast not equal')
+end
diff --git a/tests/loglinear/results_exp.mat b/tests/loglinear/results_exp.mat
deleted file mode 100644
index fad6d3f8f1d8ff6a74544ef4c6b7783094ffcc13..0000000000000000000000000000000000000000
Binary files a/tests/loglinear/results_exp.mat and /dev/null differ
diff --git a/tests/ls2003/ls2003_hessian_zero.mod b/tests/ls2003/ls2003_hessian_zero.mod
new file mode 100644
index 0000000000000000000000000000000000000000..7476b5b3d6dfb5e7295b0134ab00b0d9d0040d40
--- /dev/null
+++ b/tests/ls2003/ls2003_hessian_zero.mod
@@ -0,0 +1,44 @@
+//test whether Dynare correctly reverts to linear approximation if 0 Hessian is detected
+
+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;
+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;
+
+stoch_simul(order=2);
\ No newline at end of file
diff --git a/tests/observation_trends_and_prefiltering/ML/Trend_no_prefilter_selected_var.mod b/tests/observation_trends_and_prefiltering/ML/Trend_no_prefilter_selected_var.mod
index d785da2abae289a580a958ab74b51b0665dc0206..b64d27fddc0079b964991b4916eed0458978f205 100644
--- a/tests/observation_trends_and_prefiltering/ML/Trend_no_prefilter_selected_var.mod
+++ b/tests/observation_trends_and_prefiltering/ML/Trend_no_prefilter_selected_var.mod
@@ -68,7 +68,7 @@ generate_trend_stationary_AR1;
 estimation(order=1,datafile='AR1_trend_data_with_constant',mh_replic=0,
         mode_compute=4,first_obs=1,nobs=1000,
         filtered_vars, filter_step_ahead = [1,2,4],        
-        diffuse_filter,smoother,forecast=0,prefilter=0,filter_decomposition) P_obs Y_obs junk2;
+        diffuse_filter,filter_covariance,smoother,forecast=0,prefilter=0,filter_decomposition) P_obs Y_obs junk2;
 
 %Test selected_variables_only option
 oo_all_variables=oo_;
@@ -85,7 +85,7 @@ set_dynare_seed('default');
 estimation(order=1,datafile='AR1_trend_data_with_constant',mh_replic=0,
         mode_compute=4,first_obs=1,nobs=1000,
         filtered_vars, filter_step_ahead = [1,2,4],        
-        diffuse_filter,smoother,forecast=0,prefilter=0,filter_decomposition,selected_variables_only) P_obs Y_obs junk2;
+        diffuse_filter,smoother,forecast=0,filter_covariance,prefilter=0,filter_decomposition,selected_variables_only) P_obs Y_obs junk2;
 
 % do checks
         
@@ -118,7 +118,7 @@ if max(max(max(abs(oo_.FilteredVariablesKStepAhead-oo_all_variables.FilteredVari
     error('FilteredVariablesKStepAhead is wrong')
 end
 
-if max(max(max(max(abs(oo_.FilteredVariablesKStepAheadVariances-oo_all_variables.FilteredVariablesKStepAheadVariances(:,[Y_pos;P_pos;junk2_pos],[Y_pos;P_pos;junk2_pos],:))))))>1e-8
+if options_.filter_covariance && max(max(max(max(abs(oo_.FilteredVariablesKStepAheadVariances-oo_all_variables.FilteredVariablesKStepAheadVariances(:,[Y_pos;P_pos;junk2_pos],[Y_pos;P_pos;junk2_pos],:))))))>1e-8
     error('FilteredVariablesKStepAheadVariances is wrong')
 end
 
diff --git a/tests/optimizers/fs2000_6.mod b/tests/optimizers/fs2000_6.mod
index 3a3fe275c247bb3616c72c4d2ef8d3b7f6d14c5a..21738c869306b3e319c65adcde82eeb524dd6b88 100644
--- a/tests/optimizers/fs2000_6.mod
+++ b/tests/optimizers/fs2000_6.mod
@@ -1,6 +1,6 @@
 @#include "fs2000.common.inc"
 
-estimation(mode_compute=6,order=1, datafile='../fs2000/fsdat_simul', nobs=192, mh_replic=0, optim=('nclimb-mh', 10, 'ncov-mh', 5000, 'nscale-mh', 10000));
+estimation(mode_compute=6,order=1, datafile='../fs2000/fsdat_simul', nobs=192, mh_replic=0, optim=('nclimb-mh', 10, 'ncov-mh', 1000, 'nscale-mh', 5000));
 
 // test the mode file generated with mode_compute=6
 estimation(order=1,datafile='../fs2000/fsdat_simul',nobs=192,loglinear,mode_compute=0,mode_file=fs2000_6_mode,mh_replic=10,
diff --git a/tests/particle/dsge_base2.mod b/tests/particle/dsge_base2.mod
index 2b1f264104abb85faef8e39428ef2d52eca1af90..b7d4cb1b5f419ce2743bdfa68eab4cc2dc33bbd2 100644
--- a/tests/particle/dsge_base2.mod
+++ b/tests/particle/dsge_base2.mod
@@ -1,27 +1,51 @@
-// This file deals with the resolution and estimation of a basic DSGE model with
-//employment for comparison with the benchmark in Gauss which solves with
-//the same particular filter but global methodology.
-//
-// Juin 2015
-
 // DGP
+@#ifndef RISKY_CALIBRATION
 @#define RISKY_CALIBRATION = 0
+@#endif
+@#ifndef EXTREME_CALIBRATION
 @#define EXTREME_CALIBRATION = 1
+@#endif
+@#ifndef BENCHMARK_CALIBRATION
 @#define BENCHMARK_CALIBRATION = 0
+@#endif
 
 // ALGORITHM
-@#define LINEAR_KALMAN = 1
+@#ifndef LINEAR_KALMAN
+@#define LINEAR_KALMAN = 0
+@#endif
+@#ifndef ALGO_SIR
 @#define ALGO_SIR = 0
+@#endif
+@#ifndef ALGO_SISmoothR
 @#define ALGO_SISmoothR = 0
+@#endif
+@#ifndef ALGO_APF
 @#define ALGO_APF = 0
+@#endif
+@#ifndef ALGO_GPF
 @#define ALGO_GPF = 0
+@#endif
+@#ifndef ALGO_GCF
 @#define ALGO_GCF = 0
-@#define ALGO_GUF = 0
+@#endif
+@#ifndef ALGO_GUF
+@#define ALGO_GUF = 1
+@#endif
+@#ifndef ALGO_GMPF
 @#define ALGO_GMPF = 0
+@#endif
+@#ifndef ALGO_GMCF
 @#define ALGO_GMCF = 0
+@#endif
+@#ifndef ALGO_ONLINE_1
 @#define ALGO_ONLINE_1 = 0
+@#endif
+@#ifndef ALGO_ONLINE_2
 @#define ALGO_ONLINE_2 = 0
-
+@#endif
+@#ifndef MCMC
+@#define MCMC = 0
+@#endif
 
 var k A c l i y;
 varexo e_a;
@@ -164,7 +188,9 @@ options_.mode_check.number_of_points = 250;
   estimation(order=1,number_of_particles=1000,mode_compute=11);
 @#endif
 
-options_.mh_nblck = 10 ;
-options_.posterior_sampling_method = 'RWGMH';
-options_.rwgmh_scale_shock = (1e-5)*[10 10 1 1 10 10 10 1000 10 10] ;
-estimation(order=1,mh_replic=5000,mode_compute=0,mode_file=dsge_base2_mode);
+@#if MCMC
+  options_.mh_nblck = 10 ;
+  options_.posterior_sampling_method = 'RWGMH';
+  options_.rwgmh_scale_shock = (1e-5)*[10 10 1 1 10 10 10 1000 10 10] ;
+  estimation(order=1,mh_replic=5000,mode_compute=0,mode_file=dsge_base2_mode);
+@#endif
\ No newline at end of file
diff --git a/tests/particle/dsge_unit_root.mod b/tests/particle/dsge_unit_root.mod
new file mode 100644
index 0000000000000000000000000000000000000000..a0f1a4f8521287ddfb986f4e58a2a1f8738b4b4b
--- /dev/null
+++ b/tests/particle/dsge_unit_root.mod
@@ -0,0 +1,221 @@
+// DGP
+@#ifndef RISKY_CALIBRATION 
+@#define RISKY_CALIBRATION = 0
+@#endif
+@#ifndef EXTREME_CALIBRATION
+@#define EXTREME_CALIBRATION = 1
+@#endif
+@#ifndef BENCHMARK_CALIBRATION
+@#define BENCHMARK_CALIBRATION = 0
+@#endif
+
+// ALGORITHM
+@#ifndef LINEAR_KALMAN
+@#define LINEAR_KALMAN = 0
+@#endif
+@#ifndef ALGO_SIR
+@#define ALGO_SIR = 0
+@#endif
+@#ifndef ALGO_SISmoothR
+@#define ALGO_SISmoothR = 0
+@#endif
+@#ifndef ALGO_APF
+@#define ALGO_APF = 0
+@#endif
+@#ifndef ALGO_GPF
+@#define ALGO_GPF = 0
+@#endif
+@#ifndef ALGO_GCF
+@#define ALGO_GCF = 0
+@#endif
+@#ifndef ALGO_GUF
+@#define ALGO_GUF = 1
+@#endif
+@#ifndef ALGO_GMPF
+@#define ALGO_GMPF = 0
+@#endif
+@#ifndef ALGO_GMCF
+@#define ALGO_GMCF = 0
+@#endif
+@#ifndef ALGO_ONLINE_1
+@#define ALGO_ONLINE_1 = 0
+@#endif
+@#ifndef ALGO_ONLINE_2
+@#define ALGO_ONLINE_2 = 0
+@#endif
+@#ifndef MCMC
+@#define MCMC = 0
+@#endif
+
+var k A c l i y;
+varexo e_a;
+
+parameters alp bet tet tau delt rho ;
+alp = 0.4;
+bet = 0.99;
+tet = 0.357 ;
+tau =  50 ;
+delt = 0.02;
+rho = 1.0;
+
+model;
+c = ((1 - alp)*tet/(1-tet))*A*(1-l)*((k(-1)/l)^alp) ;
+y = A*(k(-1)^alp)*(l^(1-alp)) ;
+i = y-c ;
+k = (1-delt)*k(-1) + i ;
+log(A) = rho*log(A(-1)) + e_a ;
+(((c^(tet))*((1-l)^(1-tet)))^(1-tau))/c - bet*((((c(+1)^(tet))*((1-l(+1))^(1-tet)))^(1-tau))/c(+1))*(1 -delt+alp*(A(1)*(k^alp)*(l(1)^(1-alp)))/k)=0 ;
+end;
+
+shocks;
+var e_a; stderr 0.035;
+end;
+
+steady(nocheck);
+
+
+stoch_simul(periods=5000, irf=0, noprint);
+
+@#if EXTREME_CALIBRATION
+    verbatim;
+    y = y + randn(size(y))*.0175;
+    l = l + randn(size(l))*.00312;
+    i = i + randn(size(i))*.00465;
+    end;
+    ds = dseries([y, l, i, c, A], 1900Q1, {'y'; 'l'; 'i'; 'c'; 'A'});
+@#endif 
+
+@#if RISKY_CALIBRATION
+    verbatim;
+    y = y + randn(size(y))*.00158;
+    l = l + randn(size(l))*.0011;
+    i = i + randn(size(i))*.000866;
+    end;
+    ds = dseries([y, l, i, c, A], 1900Q1, {'y'; 'l'; 'i'; 'c'; 'A'});
+@#endif
+
+@#if BENCHMARK_CALIBRATION
+    // TODO: This section is to be completed (measurement are missing)
+    ds = dseries([y, l, i, c, A], 1900Q1, {'y'; 'l'; 'i'; 'c'; 'A'});
+@#endif
+
+estimated_params;
+alp, uniform_pdf,,, 0.0001, 0.99;
+bet, uniform_pdf,,, 0.0001, 0.99999;
+tet, uniform_pdf,,, 0.0001, .999;
+tau, uniform_pdf,,, 0.0001, 100;
+delt, uniform_pdf,,, 0.0001, 0.05;
+stderr e_a, uniform_pdf,,, 0.00001, 0.1;
+stderr y, uniform_pdf,,, 0.00001, 0.1;
+stderr l, uniform_pdf,,, 0.00001, 0.1;
+stderr i, uniform_pdf,,, 0.00001, 0.1;
+end;
+
+@#if RISKY_CALIBRATION
+  estimated_params_init;
+  alp, 0.4;
+  bet, 0.99;
+  tet, 0.357;
+  tau, 50;
+  delt, 0.02;
+  stderr e_a, .035;
+  stderr y, .00158;
+  stderr l, .0011;
+  stderr i, .000866;
+  end;
+@#endif
+
+@#if EXTREME_CALIBRATION
+  estimated_params_init;
+  alp, 0.4;
+  bet, 0.99;
+  tet, 0.357;
+  tau, 50;
+  delt, 0.02;
+  stderr e_a, .035;
+  stderr y, .0175;
+  stderr l, .00312;
+  stderr i, .00465;
+  end;
+@#endif
+
+varobs y l i ;
+
+options_.mode_check.neighbourhood_size = .01 ;
+options_.mode_check.number_of_points = 250;
+
+//options_.particle.initialization = 3;
+
+@#if EXTREME_CALIBRATION
+  data(series=ds, nobs=200, first_obs=1973Q1);
+@#endif 
+
+@#if RISKY_CALIBRATION
+    data(series=ds, nobs=200, first_obs=1973Q1);
+@#endif
+
+@#if BENCHMARK_CALIBRATION
+    data(series=ds, nobs = 200, first_obs=1973Q1);
+@#endif
+
+
+@#if LINEAR_KALMAN
+%  estimation(nograph,order=1,mode_compute=8,mh_replic=0,mode_check);
+@#endif
+
+@#if ALGO_SIR
+  estimation(order=2,nonlinear_filter_initialization=3,nograph,number_of_particles=1000,mh_replic=0,mode_compute=8,mode_check);
+@#endif
+
+@#if ALGO_SISmoothR
+  estimation(order=2,nonlinear_filter_initialization=3,nograph,number_of_particles=1000,resampling_method=smooth,mode_compute=8,mh_replic=0);
+  estimation(order=2,nonlinear_filter_initialization=3,nograph,number_of_particles=1000,resampling_method=smooth,mode_compute=8,mode_file=dsge_unit_root_mode,mh_replic=0);
+  estimation(order=2,nonlinear_filter_initialization=3,nograph,number_of_particles=1000,resampling_method=smooth,mode_compute=4,mode_file=dsge_unit_root_mode,mh_replic=0,mode_check);
+@#endif
+
+@#if ALGO_APF
+  estimation(order=2,nonlinear_filter_initialization=3,nograph,filter_algorithm=apf,number_of_particles=1000,mh_replic=0,mode_compute=8,mode_check);
+@#endif
+
+@#if ALGO_GPF
+  estimation(order=2,nonlinear_filter_initialization=3,nograph,filter_algorithm=gf,distribution_approximation=montecarlo,number_of_particles=1000,mh_replic=0,mode_compute=8);
+  estimation(order=2,nonlinear_filter_initialization=3,nograph,filter_algorithm=gf,distribution_approximation=montecarlo,number_of_particles=1000,mode_file=dsge_unit_root_mode,mh_replic=0,mode_compute=4,mode_check);
+@#endif
+
+@#if ALGO_GCF
+  estimation(order=2,nonlinear_filter_initialization=3,nograph,filter_algorithm=gf,mh_replic=0,mode_compute=8);
+  estimation(order=2,nonlinear_filter_initialization=3,nograph,filter_algorithm=gf,mh_replic=0,mode_compute=4,mode_file=dsge_unit_root_mode,mode_check);
+@#endif
+
+@#if ALGO_GUF
+  estimation(order=2,nonlinear_filter_initialization=3,nograph,filter_algorithm=gf,proposal_approximation=unscented,distribution_approximation=unscented,mh_replic=0,mode_compute=4);
+  estimation(order=2,nonlinear_filter_initialization=3,nograph,filter_algorithm=gf,proposal_approximation=unscented,distribution_approximation=unscented,mode_file=dsge_unit_root_mode,mh_replic=0,mode_compute=8,mode_check);
+@#endif
+
+@#if ALGO_GMPF
+  estimation(nograph,order=2,nonlinear_filter_initialization=3,filter_algorithm=gmf,distribution_approximation=montecarlo,number_of_particles=1000,mh_replic=0,mode_compute=8);
+  estimation(nograph,order=2,nonlinear_filter_initialization=3,filter_algorithm=gmf,distribution_approximation=montecarlo,number_of_particles=1000,mh_replic=0,mode_file=dsge_unit_root_mode,mode_compute=8);
+  estimation(nograph,order=2,nonlinear_filter_initialization=3,filter_algorithm=gmf,distribution_approximation=montecarlo,number_of_particles=1000,mh_replic=0,mode_file=dsge_unit_root_mode,mode_compute=4,mode_check);
+@#endif
+
+@#if ALGO_GMCF
+  estimation(nograph,order=2,nonlinear_filter_initialization=3,filter_algorithm=gmf,mh_replic=0,mode_compute=8);
+  estimation(nograph,order=2,nonlinear_filter_initialization=3,filter_algorithm=gmf,mh_replic=0,mode_compute=4,mode_file=dsge_unit_root_mode,mode_check);
+@#endif
+
+@#if ALGO_ONLINE_2
+  options_.particle.liu_west_delta = 0.9 ;
+  estimation(order=2,number_of_particles=1000,mode_compute=11);
+@#endif
+
+@#if ALGO_ONLINE_1
+  options_.particle.liu_west_delta = 0.9 ;
+  estimation(order=1,number_of_particles=1000,mode_compute=11);
+@#endif
+
+@#if MCMC
+  options_.mh_nblck = 10 ;
+  options_.posterior_sampling_method = 'RWGMH';
+  options_.rwgmh_scale_shock = (1e-5)*[10 10 1 1 10 10 10 1000 10 10] ;
+  estimation(order=1,mh_replic=5000,mode_compute=0,mode_file=dsge_base2_mode);
+@#endif
\ No newline at end of file
diff --git a/tests/read_trs_files.sh b/tests/read_trs_files.sh
index e805cb150201cca70cef189ed3309a8c46bdeb5b..cdd866d557f8deca901041abd49d70d9771fdd68 100755
--- a/tests/read_trs_files.sh
+++ b/tests/read_trs_files.sh
@@ -22,7 +22,7 @@ for file in $1 ; do
     done
   fi
 
-  time=`grep cputime $file | cut -d: -f3`
+  time=`grep elapsed-time $file | cut -d: -f3`
   tosort=`echo $tosort\| $file ' - ' $time:`
 done
 ((passed=$total-$failed));
@@ -42,7 +42,7 @@ for file in $2 ; do
     done
   fi
 
-  time=`grep cputime $file | cut -d: -f3`
+  time=`grep elapsed-time $file | cut -d: -f3`
   tosort=`echo $tosort\| $file ' - ' $time:`
 done
 ((xfailed=$total_xfail-$xpassed));
diff --git a/tests/reporting/AnnualTable.m b/tests/reporting/AnnualTable.m
index fb78267f2f37fe3342e4a78f3ddd4e01f16946cc..304cc3fe9809124ff16c4f0e222b014866093299 100644
--- a/tests/reporting/AnnualTable.m
+++ b/tests/reporting/AnnualTable.m
@@ -1,5 +1,5 @@
 function rep = AnnualTable(rep, db_a, dc_a, seriesRootName, arange)
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2014 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/tests/reporting/CountryGraphPage.m b/tests/reporting/CountryGraphPage.m
index d67bb28a1817449028275d9e1fe1553f6abeacf5..c3b03d188ea56133ab63de18e069ecc05e0938ac 100644
--- a/tests/reporting/CountryGraphPage.m
+++ b/tests/reporting/CountryGraphPage.m
@@ -1,5 +1,5 @@
 function rep = CountryGraphPage(rep, countryAbbr, db_q, dc_q, prange, srange)
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2013-2014 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/tests/reporting/CountryTablePage.m b/tests/reporting/CountryTablePage.m
index 309d69c9cb847084462b4e5f2968c6173608a1f1..bf0087587939da500f616a3654a74564cc219ec9 100644
--- a/tests/reporting/CountryTablePage.m
+++ b/tests/reporting/CountryTablePage.m
@@ -1,5 +1,5 @@
 function rep = CountryTablePage(rep, countryAbbr, countryName, db_q, dc_q, db_a, dc_a, trange, vline_after)
-% Copyright (C) 2013-2014 Dynare Team
+% Copyright (C) 2013-2016 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/tests/reporting/runDynareReport.m b/tests/reporting/runDynareReport.m
index eab6eb234d551a29057a627b23b0ff1a809994c2..3d779c7ecac651eebbf426d4afbba552f31af6d4 100644
--- a/tests/reporting/runDynareReport.m
+++ b/tests/reporting/runDynareReport.m
@@ -1,5 +1,5 @@
 function runDynareReport(dc_a, dc_q, db_a, db_q)
-% Copyright (C) 2013-2014 Dynare Team
+% Copyright (C) 2013-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/tests/run_all_unitary_tests.m b/tests/run_all_unitary_tests.m
index 34ab08a211f96d3248e54b920fbdaed1afc92135..49ddb307cde2390f8680765e55c4d16088f66709 100644
--- a/tests/run_all_unitary_tests.m
+++ b/tests/run_all_unitary_tests.m
@@ -1,4 +1,4 @@
-% Copyright (C) 2013-2016 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -82,7 +82,7 @@ else
   fprintf(fid,':number-tests: %d\n', counter);
   fprintf(fid,':number-failed-tests: 0\n');
 end
-fprintf(fid,':cputime: %f\n',0.0);
+fprintf(fid,':elapsed-time: %f\n',0.0);
 fclose(fid);
 if ~isoctave
     exit
diff --git a/tests/run_block_byte_tests_matlab.m b/tests/run_block_byte_tests_matlab.m
index 530d2f7a8c87b98aac7fce7e6ccde2b49aa2425e..b3e017c56e48b43cfa9bcdeb2218f34e5bc71661 100644
--- a/tests/run_block_byte_tests_matlab.m
+++ b/tests/run_block_byte_tests_matlab.m
@@ -1,4 +1,4 @@
-% Copyright (C) 2011-2013 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -38,7 +38,7 @@ failedBlock = {};
 num_block_tests = 0;
 cd([top_test_dir filesep 'block_bytecode']);
 has_optimization_toolbox = user_has_matlab_license('optimization_toolbox');
-cput = cputime;
+tic;
 for blockFlag = 0:1
     for bytecodeFlag = 0:1
         default_solve_algo = 2;
@@ -129,7 +129,7 @@ for blockFlag = 0:1
         end
     end
 end
-ecput = cputime - cput;
+ecput = toc;
 delete('wsMat.mat')
 cd(getenv('TOP_TEST_DIR'));
 fid = fopen('run_block_byte_tests_matlab.m.trs', 'w+');
@@ -143,6 +143,6 @@ else
   fprintf(fid,':number-tests: %d\n', num_block_tests);
   fprintf(fid,':number-failed-tests: 0\n');
 end
-fprintf(fid,':cputime: %f\n', ecput);
+fprintf(fid,':elapsed-time: %f\n', ecput);
 fclose(fid);
 exit;
diff --git a/tests/run_block_byte_tests_octave.m b/tests/run_block_byte_tests_octave.m
index a915e9752679ab5ecd43b82679d16ea94d4a974f..be1acf56461219d90af1fb15c9b1dd3af0a3f864 100644
--- a/tests/run_block_byte_tests_octave.m
+++ b/tests/run_block_byte_tests_octave.m
@@ -1,4 +1,4 @@
-## Copyright (C) 2009-2013 Dynare Team
+## Copyright (C) 2009-2017 Dynare Team
 ##
 ## This file is part of Dynare.
 ##
@@ -40,7 +40,7 @@ putenv("GNUTERM", "dumb")
 failedBlock = {};
 num_block_tests = 0;
 cd([top_test_dir filesep 'block_bytecode']);
-cput = cputime;
+tic;
 for blockFlag = 0:1
     for bytecodeFlag = 0:1
         ## Recall that solve_algo=7 and stack_solve_algo=2 are not supported
@@ -131,7 +131,7 @@ for blockFlag = 0:1
         endfor
     endfor
 endfor
-ecput = cputime - cput;
+ecput = toc;
 delete('wsOct');
 cd(getenv('TOP_TEST_DIR'));
 fid = fopen('run_block_byte_tests_octave.o.trs', 'w+');
@@ -145,7 +145,7 @@ else
   fprintf(fid,':number-tests: %d\n', num_block_tests);
   fprintf(fid,':number-failed-tests: 0\n');
 end
-fprintf(fid,':cputime: %f\n', ecput);
+fprintf(fid,':elapsed-time: %f\n', ecput);
 fclose(fid);
 ## Local variables:
 ## mode: Octave
diff --git a/tests/run_reporting_test_matlab.m b/tests/run_reporting_test_matlab.m
index e5729c7321ea03b46ad306762bc7808022f1ff5c..00b3356e77f79d83031534c3fa43bf5e091a8f94 100644
--- a/tests/run_reporting_test_matlab.m
+++ b/tests/run_reporting_test_matlab.m
@@ -1,4 +1,4 @@
-% Copyright (C) 2013-2016 Dynare Team
+% Copyright (C) 2013-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -54,6 +54,6 @@ else
   fprintf(fid,':number-failed-tests: 0\n');
   fprintf(fid,':list-of-passed-tests: run_reporting_test_matlab.m\n');
 end
-fprintf(fid,':cputime: %f\n',0.0);
+fprintf(fid,':elapsed-time: %f\n',0.0);
 fclose(fid);
 exit;
diff --git a/tests/run_reporting_test_octave.m b/tests/run_reporting_test_octave.m
index 43c6067fcfe62d372876e2369d153762a7e3b333..a992b9a4689fb6f0c85db77563ff1868d1baf60c 100644
--- a/tests/run_reporting_test_octave.m
+++ b/tests/run_reporting_test_octave.m
@@ -1,4 +1,4 @@
-## Copyright (C) 2013-2016 Dynare Team
+## Copyright (C) 2013-2017 Dynare Team
 ##
 ## This file is part of Dynare.
 ##
@@ -60,7 +60,7 @@ else
   fprintf(fid,':number-failed-tests: 0\n');
   fprintf(fid,':list-of-passed-tests: run_reporting_test_octave.m\n');
 end
-fprintf(fid,':cputime: %f\n',0.0);
+fprintf(fid,':elapsed-time: %f\n',0.0);
 fclose(fid);
 
 ## Local variables:
diff --git a/tests/run_test_matlab.m b/tests/run_test_matlab.m
index 191087c692c3feec8d24ca8d10070c42b8bd4787..7727032f7e6cea54bd948223268876427e786bcf 100644
--- a/tests/run_test_matlab.m
+++ b/tests/run_test_matlab.m
@@ -1,4 +1,4 @@
-% Copyright (C) 2011-2012 Dynare Team
+% Copyright (C) 2011-2017 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -32,7 +32,7 @@ cd(directory);
 disp('');
 disp(['***  TESTING: ' modfile ' ***']);
 
-cput = cputime;
+tic;
 save(['wsMat' testfile '.mat']);
 try
   dynare([testfile ext], 'console')
@@ -45,7 +45,7 @@ top_test_dir = getenv('TOP_TEST_DIR');
 [modfile, name] = strtok(getenv('FILESTEM'));
 [directory, testfile, ext] = fileparts([top_test_dir '/' modfile]);
 load(['wsMat' testfile '.mat']);
-ecput = cputime - cput;
+ecput = toc;
 delete(['wsMat' testfile '.mat']);
 
 cd(top_test_dir);
@@ -67,7 +67,7 @@ else
   fprintf(fid,':number-failed-tests: 0\n');
   fprintf(fid,':list-of-passed-tests: %s\n', [name '.mod']);
 end
-fprintf(fid,':cputime: %f\n', ecput);
+fprintf(fid,':elapsed-time: %f\n', ecput);
 fclose(fid);
 warning off
 exit
diff --git a/tests/run_test_octave.m b/tests/run_test_octave.m
index cc834e31c2e942896757c0be607fd93e58d9c654..4a7854dda29d628ae4f9d9bbcd3686744220d6e3 100644
--- a/tests/run_test_octave.m
+++ b/tests/run_test_octave.m
@@ -1,4 +1,4 @@
-## Copyright (C) 2009-2016 Dynare Team
+## Copyright (C) 2009-2017 Dynare Team
 ##
 ## This file is part of Dynare.
 ##
@@ -25,7 +25,6 @@ load_octave_packages
 
 top_test_dir = getenv('TOP_TEST_DIR');
 addpath(top_test_dir);
-addpath('.'); % workaround for bug in Octave 4.2.0-rc2: https://savannah.gnu.org/bugs/?49334
 addpath([top_test_dir filesep '..' filesep 'matlab']);
 
 ## Test Dynare Version
@@ -44,7 +43,7 @@ cd(directory);
 
 printf("\n***  TESTING: %s ***\n", name);
 
-cput = cputime;
+tic;
 save(['wsOct' testfile '.mat']);
 try
   dynare([testfile ext])
@@ -57,7 +56,7 @@ top_test_dir = getenv('TOP_TEST_DIR');
 name = getenv("FILESTEM");
 [directory, testfile, ext] = fileparts([top_test_dir '/' name]);
 load(['wsOct' testfile '.mat']);
-ecput = cputime - cput;
+ecput = toc;
 delete(['wsOct' testfile '.mat']);
 
 cd(top_test_dir);
@@ -73,7 +72,7 @@ else
   fprintf(fid,':number-failed-tests: 0\n');
   fprintf(fid,':list-of-passed-tests: %s\n', [name '.mod']);
 end
-fprintf(fid,':cputime: %f\n', ecput);
+fprintf(fid,':elapsed-time: %f\n', ecput);
 fclose(fid);
 
 ## Local variables:
diff --git a/tests/shock_decomposition/ls2003_plot.mod b/tests/shock_decomposition/ls2003_plot.mod
new file mode 100644
index 0000000000000000000000000000000000000000..7faa00d0c7cf0eacffce430361ff11be6033bda1
--- /dev/null
+++ b/tests/shock_decomposition/ls2003_plot.mod
@@ -0,0 +1,135 @@
+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;
+
+options_.TeX=1;
+estimation(datafile='../ls2003/data_ca1',first_obs=8,nobs=79,mh_nblocks=10,prefilter=1,mh_jscale=0.5,mh_replic=0);
+close all
+
+shock_groups(name=trade);
+supply = e_A ;
+trade = e_q ;
+monetary = e_R ;
+end;
+
+shock_groups(name=row);
+supply = e_A ;
+'RoW shocks' = e_q e_ys e_pies  ;
+monetary = e_R ;
+end;
+options_.initial_date=dates('1989Q4'); % date arbitrarily set for testing purposes
+shock_decomposition(use_shock_groups=trade) y_obs R_obs pie_obs dq de;
+
+// various tests for plot_shock_decompositions
+// standard plot [using trade group defined before]
+plot_shock_decomposition;
+
+// test datailed, custom name and yoy plots
+plot_shock_decomposition(detail_plot, fig_name = MR, type = yoy);
+
+
+close all,
+
+
+// testing realtime decomposition
+// first compute realtime decompositions [pre-processor not yet available]
+realtime_shock_decomposition(forecast=8, save_realtime=[5 9 13 17 21 25 29 33 37 41 45 49 53 57 61 65 69 73 77]);
+
+//realtime pooled
+plot_shock_decomposition(realtime = 1);
+
+//conditional pooled
+plot_shock_decomposition(realtime = 2);
+
+// conditional 8-step ahead decomposition, given 1989q4
+plot_shock_decomposition(detail_plot, realtime = 2, vintage = 29);
+
+close all,
+
+//forecast pooled
+plot_shock_decomposition(realtime = 3);
+
+// forecast 8-step ahead decomposition, given 1989q4
+plot_shock_decomposition(detail_plot, realtime = 3, vintage = 29);
+
+close all,
+
+// now I test annualized variables
+options_.plot_shock_decomp.q2a=1;
+options_.plot_shock_decomp.islog=1;
+plot_shock_decomposition(detail_plot, type = aoa) y;
+
+plot_shock_decomposition(realtime = 1) y;
+plot_shock_decomposition(realtime = 1, vintage = 29) y;
+plot_shock_decomposition(realtime = 2, vintage = 29) y;
+plot_shock_decomposition(realtime = 3, vintage = 29) y;
+
+close all
+
+//test uimenu for groups
+plot_shock_decomposition(detail_plot, interactive, use_shock_groups = row, type = qoq);
+plot_shock_decomposition(detail_plot, interactive, realtime = 3, vintage = 29);
+
+collect_latex_files;
+if system(['pdflatex -halt-on-error -interaction=batchmode ' M_.fname '_TeX_binder.tex'])
+    error('TeX-File did not compile.')
+end
diff --git a/tests/stochastic-backward-models/solow_cd_with_steadystate.mod b/tests/stochastic-backward-models/solow_cd_with_steadystate.mod
index 90dfb7400847c1612c426848dc1163da007a3521..500cc137ca796a3a200f0a08d99dc08d335d0610 100644
--- a/tests/stochastic-backward-models/solow_cd_with_steadystate.mod
+++ b/tests/stochastic-backward-models/solow_cd_with_steadystate.mod
@@ -53,15 +53,15 @@ T = 5*floor(log(precision)/log(max(rho_x, rho_n)));
 oo_ = simul_backward_model(M_.endo_histval, T, options_, M_, oo_, zeros(T+1,2));
 
 if abs(oo_.endo_simul(1,end)-LongRunEfficiency)>1e-10
-    error('Wrong long run level!')
+   error('Wrong long run level!')
 end
 
 if abs(oo_.endo_simul(3,end)-LongRunPopulation)>1e-10
-    error('Wrong long run level!')
+   error('Wrong long run level!')
 end
 
 IntensiveCapitalStock = oo_.endo_simul(6,1:end)./(oo_.endo_simul(1,1:end).*oo_.endo_simul(3,1:end));
 
-if abs(IntensiveCapitalStock-LongRunIntensiveCapitalStock)>1e-6
-    error('Wrong long run level!')
+if abs(IntensiveCapitalStock(end)-LongRunIntensiveCapitalStock>1e-10)
+   error('Wrong long run level!')
 end
diff --git a/windows/README.txt b/windows/README.txt
index 02ee18ecf5201755c039cf2715c72c2e538277a9..56d8a6aa45a5b238d16d696582a6538df64148b8 100644
--- a/windows/README.txt
+++ b/windows/README.txt
@@ -57,7 +57,7 @@ Using Dynare with Octave
 Dynare also works on top of GNU Octave, a free clone of MATLAB (R) (see
 <http://www.octave.org>).
 
-This version of Dynare is compiled for Octave 3.6 (MinGW), and may not work
+This version of Dynare is compiled for Octave 4.2.1 (MinGW, 32bit and 64bit), and may not work
 with other versions of Octave. The recommended version of Octave can be
 downloaded at:
 
diff --git a/windows/dynare.nsi b/windows/dynare.nsi
index c72bc4c0fd6fa788ce7c25915b82421b1f927b99..60b575149cee7dfa901b794146c8176faef3cbe7 100644
--- a/windows/dynare.nsi
+++ b/windows/dynare.nsi
@@ -54,7 +54,7 @@ Section "Dynare core (preprocessor and M-files)"
  SectionIn RO
 !insertmacro DETERMINE_CONTEXT
  SetOutPath $INSTDIR
- File README.txt ..\NEWS mexopts-win32.bat mexopts-win64.bat ..\license.txt
+ File README.txt ..\NEWS mexopts-win32.bat mexopts-win64.bat ..\license.txt ..\VERSION
 
  SetOutPath $INSTDIR\matlab
  File /r ..\matlab\*.m
@@ -98,21 +98,30 @@ 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 9.1 (R2009a to R2016b)"
- SetOutPath $INSTDIR\mex\matlab\win64-7.8-9.1
- File ..\mex\matlab\win64-7.8-9.1\*.mexw64
+Section "MEX files for MATLAB 64-bit, version 7.8 to 9.2 (R2009a to R2017a)"
+ SetOutPath $INSTDIR\mex\matlab\win64-7.8-9.2
+ File ..\mex\matlab\win64-7.8-9.2\*.mexw64
 SectionEnd
 
 SectionGroupEnd
 
-Section "MEX files for Octave 3.6 (MinGW)"
+SectionGroup "MEX files for OCTAVE"
+
+Section "MEX files for Octave 4.2.1 (MinGW, 64bit)"
  SetOutPath $INSTDIR\mex\octave
  File ..\mex\octave\*.mex ..\mex\octave\*.oct
 SectionEnd
 
+Section "MEX files for Octave 4.2.1 (MinGW, 32bit)"
+ SetOutPath $INSTDIR\mex\octave32
+ File ..\mex\octave32\*.mex ..\mex\octave32\*.oct
+SectionEnd
+
+SectionGroupEnd
+
 Section "Dynare++ (standalone executable)"
  SetOutPath $INSTDIR\dynare++
- File ..\dynare++\src\dynare++.exe ..\dynare++\extern\matlab\dynare_simul.m
+ File ..\dynare++\src\dynare++.exe ..\dynare++\extern\matlab\dynare_simul.m ..\dynare++\*.dll
 SectionEnd
 
 Section "Documentation and examples (Dynare and Dynare++)"