diff --git a/tags/v_3.062/doc/DynareKalman.TeX b/tags/v_3.062/doc/DynareKalman.TeX
new file mode 100644
index 0000000000000000000000000000000000000000..82729c4c65801089425b5b05d2ec11ab460acf08
--- /dev/null
+++ b/tags/v_3.062/doc/DynareKalman.TeX
@@ -0,0 +1,196 @@
+% ----------------------------------------------------------------
+% AMS-LaTeX Paper ************************************************
+% **** -----------------------------------------------------------
+\documentclass{amsart}
+\usepackage{graphicx}
+% ----------------------------------------------------------------
+\vfuzz2pt % Don't report over-full v-boxes if over-edge is small
+\hfuzz2pt % Don't report over-full h-boxes if over-edge is small
+% THEOREMS -------------------------------------------------------
+\newtheorem{thm}{Theorem}[section]
+\newtheorem{cor}[thm]{Corollary}
+\newtheorem{lem}[thm]{Lemma}
+\newtheorem{prop}[thm]{Proposition}
+\theoremstyle{definition}
+\newtheorem{defn}[thm]{Definition}
+\theoremstyle{remark}
+\newtheorem{rem}[thm]{Remark}
+\numberwithin{equation}{section}
+% MATH -----------------------------------------------------------
+\newcommand{\norm}[1]{\left\Vert#1\right\Vert}
+\newcommand{\abs}[1]{\left\vert#1\right\vert}
+\newcommand{\set}[1]{\left\{#1\right\}}
+\newcommand{\Real}{\mathbb R}
+\newcommand{\eps}{\varepsilon}
+\newcommand{\To}{\longrightarrow}
+\newcommand{\BX}{\mathbf{B}(X)}
+\newcommand{\A}{\mathcal{A}}
+% ----------------------------------------------------------------
+\begin{document}
+
+\title{Kalman filtering and smoothing in Dynare}%
+% ----------------------------------------------------------------
+\maketitle
+% ----------------------------------------------------------------
+
+\section*{Introduction}
+
+\noindent \textbf{``Filtering and Smoothing of State Vector for
+Diffuse State Space Models''}, S.J. Koopman and J. Durbin (2003,
+in \textit{Journal of Time Series Analysis}, vol. 24(1), pp.
+85-98).\newline
+
+\noindent \textbf{``Fast Filtering and Smoothing for Multivariate
+State Space Models''}, S.J. Koopman and J. Durbin (2000, in
+\textit{Journal of Time Series Analysis}, vol. 21(3), pp.
+282-296).\newline
+
+
+\bigskip
+
+\noindent \textsc{The State-Space Model}\footnote{Note that in
+Dynare, matrices $T$, $Z$, $R$, $H$ and $Q$ are assumed to be time
+invariant.}:
+
+\[y_t =   Z\alpha_t + \varepsilon_t\]
+\[\alpha_{t+1} = T \alpha_t + R\eta_t\]
+with:
+\[\alpha_1 = a + A\delta + R_0\eta_0\]
+
+\noindent $m\times q$ matrix $A$ and $m\times(m-q)$ matrix $R_0$
+are selection matrices (their columns constitue all the columns of
+the $m\times m$ identity matrix) so that $A'R_0 = 0$ and
+$A'\alpha_1 = \delta$. We assume that the vector $\delta$ is
+distributed as a $\mathcal{N}(0,\kappa I_q)$ for a given  $\kappa
+> 0$. So that the expectation of $\alpha_1$ is a and its variance
+is $P$, with
+
+\[ P = \kappa P_{\infty} + P_{\star}\]
+\[           P_{\infty} = A A'\]
+\[ P_{\star}  = R_0 Q_0 R_0'\]
+
+\noindent $P_{\infty}$ is a $m\times m$ diagonal matrix with $q$
+ones and $m-q$ zeros. and where: $y_t$ is a $pp\times 1$ vector,
+$\alpha_t$ is a $mm\times 1$ vector, $\varepsilon_t$ is a
+$pp\times 1$ multivariate random variable (iid
+$\mathcal{N}(0,H)$), $\eta_t$ is a $rr\times 1$ multivariate
+random variable (iid $\mathcal{N}(0,Q)$), $a_1$ is a $mm\times 1$
+vector, $Z_t$ is a $pp\times mm$ matrix, $T$ is a $mm \times mm$
+matrix, $H$ is a $pp\times pp$ matrix, $R$ is a $mm\times rr$
+matrix, $Q$ is a $rr\times rr$ matrix and $P_1$ is a $mm\times mm$
+matrix. \newline
+
+\section{Filtering}
+
+\noindent The filtering equations are given by:
+\begin{equation}
+\begin{split}
+v_t &= y_t - Z  a_t\\
+F_t &= Z P_t Z' + H\\
+K_t &= P_t Z' F_t^{-1}\\
+a_{t+1} &= T (a_t + K_t v_t)\\
+P_{t+1} &= T (P_t - P_tZ'K') T' + R Q R'\\
+\end{split}
+\end{equation}
+$\{F_t\}$ and $\{v_t\}$ are used to evaluate the likelihood. A
+potentially faster algorithm (unfortunately not with matlab) is to
+consider a univariate approach to the multivariate Kalman filter
+(the covariance matrix associated to the measurement errors has to
+be diagonal: $H=diag(\sigma_1^2,\dots,\sigma_{pp}^2)$). Let $Z_i$
+be line $i$ of the selection matrix $Z$. The univariate algorithm
+is as follows :
+\begin{equation}
+\begin{split}
+v_{t,i} &= y_{t,i} - Z_i  a_t^{(i)}\\
+F_t^{(i)} &= Z_i P_t^{(i)} Z_i' + \sigma_{i}^2\\
+K_t^{(i)} &= P_t^{(i)} Z_i'\\
+a_{t}^{(i+1)} &= a_t^{(i)} + K_t^{(i)} v_{t,i} / F_t^{(i)}\\
+P_{t}^{(i+1)} &= P_{t}^{(i)} - K_{t}^{(i)} \left.K_t^{(i)}\right.' / F_t^{(i)}\\
+a_{t+1}^{(1)} &= T a_t^{(pp)}\\
+P_{t+1}^{(1)} &= T P_t^{(pp)} T' + R Q R'\\
+\end{split}
+\end{equation}
+when $F_t^{(i)}$ is equal to zero we simply have
+$a_{t}^{(i+1)}=a_{t}^{(i)}$ and $P_{t}^{(i+1)}=P_{t}^{(i)}$. The
+log-likelihood is evaluated as follows:
+\begin{equation}
+\mathcal{L}_T = const -\frac{1}{2}\sum_{i=1}^{pp}\sum_{t=1}^n \log
+F_{t}^{(i)} + v_{t,i}^2 / F_{t}^{(i)}
+\end{equation}
+
+\bigskip
+
+\noindent The diffuse filtering equations are given by:
+\begin{equation}
+\begin{split}
+v_t &= y_t - Z  a_t\\
+F_{\infty,t} &= Z P_{\infty,t} Z' + H\\
+K_{\infty,t} &= P_{\infty,t} Z' F_{\infty,t}^{-1}\\
+F_{\ast,t} &= Z P_{\ast,t} Z' + H\\
+K_{\ast,t} &= \left(P_{\ast,t} Z' - K_{\infty,t}F_{\ast,t}\right)F_{\infty,t}^{-1}\\
+P_{\ast,t+1} &= T (P_{\ast,t}-P_{\ast,t}Z'K_{\infty,t}' - P_{\infty,t}Z'K_{\ast,t}') T' + R Q R'\\
+P_{\infty,t+1} &= T(P_{\infty,t}-P_{\infty,t}Z'K_{\infty,t}')T'\\
+a_{t+1} &= T (a_t + K_{\infty,t} v_t)\\
+\end{split}
+\end{equation}
+When the condition $rank(P_{\infty,t+1})=0$ is satisfied we set
+$d=t$ and go back to the standard Kalman filtering equations. Here
+$F_{\infty,t}$ is assumed to be a full rank matrix. If this is not
+the case we switch to another algorithm. If $F_{\infty,t}=0$:
+\begin{equation}
+\begin{split}
+v_t &= y_t - Z  a_t\\
+F_{\ast,t} &= Z P_{\ast,t} Z' + H\\
+K_{\ast,t} &= P_{\ast,t} Z'F_{\infty,t}^{-1}\\
+P_{\ast,t+1} &= T (P_{\ast,t}-P_{\ast,t}Z'K_{\ast,t}') T' + R Q R'\\
+P_{\infty,t+1} &= TP_{\infty,t}T'\\
+a_{t+1} &= T (a_t + K_{\ast,t} v_t)\\
+L_t &= T(I - K_t Z)\\
+\end{split}
+\end{equation}
+otherwise, we consider a diffuse version of the univariate
+approach described above.
+
+\section{Smoothing}
+
+\noindent The smoothing equations are given by:
+\begin{equation}
+\begin{split}
+r_{t-1} &= Z' F_t^{-1}v_t + L_t' r_t\\
+\widehat{\alpha}_t &= a_t + P_t r_{t-1} \\
+\widehat{\eta}_t &= Q R r_t\\
+\widehat{\varepsilon}_t &= H \left(F_t^{-1}v_t-K_t'r_t\right)\\
+\end{split}
+\end{equation}
+initializing with $r_n = 0$ and with $L_t = T-K_tZ$. The diffuse
+smoothing equations are given by :
+\begin{equation}
+\begin{split}
+r_{t-1}^{(0)} &= L_{\infty,t}r_{t}^{(0)}\\
+r_{t-1}^{(1)} &= Z' F_{\infty,t}^{-1}v_t - K_{\ast,t}'r_{t}^{(0)}+ L_{\infty,t}' r_t^{(1)}\\
+\widehat{\alpha}_t &= a_t + P_{\ast,t} r_{t-1}^{(0)} + P_{\infty,t}r_{t-1}^{(1)}\\
+\widehat{\eta}_t &= Q R r_t^{(0)}\\
+\widehat{\varepsilon}_t &= -H K_{\infty,t}'r_t^{(0)}\\
+\end{split}
+\end{equation}
+for $t = d,d-1,...,1$, where $d$ is such that $P_{\infty,d+1}=0$.
+This backward recurrence is initialized with $r_{d}^{(0)}=r_{d}$,
+obtained from the non diffuse Kalman smoother, and
+$r_{d}^{(1)}=0$. $L_{\infty,t} = T-K_{\infty,t}Z$.\newline
+
+
+\noindent A univariate smoothing algorithm has to be coded... In
+the smoothing part the matrix $F_t$ (or $F_{\infty,t}$) is assumed
+to be full rank...
+
+
+
+
+
+% ----------------------------------------------------------------
+%\bibliographystyle{amsplain}
+%\bibliography{}
+\end{document}
+% ----------------------------------------------------------------
+
+
diff --git a/tags/v_3.062/doc/bibmad.sty b/tags/v_3.062/doc/bibmad.sty
new file mode 100644
index 0000000000000000000000000000000000000000..d25236e0691a56a7a750565c83dd26edcb0e8c8a
--- /dev/null
+++ b/tags/v_3.062/doc/bibmad.sty
@@ -0,0 +1,105 @@
+\message{harvard bibliography,}
+
+\def\@hiteml[#1]#2#3#4{\item[]\if@filesw%
+      { \def\protect##1{\string ##1\space}\immediate%
+\write\@auxout{\string\harvardcite{#4}{#2}{#1}{#3}}}\fi%
+\protect\hspace*{-\labelwidth}\protect\hspace*{-\labelsep}\ignorespaces}
+
+\def\@hitem#1#2#3{\item[]\if@filesw%
+      { \def\protect##1{\string ##1\space}\immediate%
+\write\@auxout{\string\harvardcite{#3}{#1}{#1}{#2}}}\fi%
+\protect\hspace*{-\labelwidth}\protect\hspace*{-\labelsep}\ignorespaces}
+
+\def\harvarditem{\@ifnextchar [{\@hiteml}{\@hitem}}
+
+\def\harvardcite#1#2#3#4{
+  \global\@namedef{bhf@#1}{#2}
+  \global\@namedef{bha@#1}{#3}
+  \global\@namedef{bhy@#1}{#4}\global\@namedef{b@#1}{\csname bhf@#1\endcsname}
+}
+
+\def\citeasnoun{\@ifnextchar [{\@tempswatrue\@citex}{\@tempswafalse\@citex[]}}
+\def\cite{\@ifnextchar [{\@tempswatrue\@citexasnoun}
+                           {\@tempswafalse\@citexasnoun[]}
+}
+\def\citeyear{\@ifnextchar [{\@tempswatrue\@citexyear}
+                           {\@tempswafalse\@citexyear[]}
+}
+\def\citename{\@ifnextchar [{\@tempswatrue\@citexname}
+                           {\@tempswafalse\@citexname[]}
+}
+
+% \def\@enamedef#1{\expandafter\edef\csname #1\endcsname}
+% Previous line should be replaced by the following to prevent
+% problems with the NFSS. Solution by Bernd Raichle.
+\def\@enamedef#1{\expandafter\def\csname #1\expandafter\endcsname\expandafter}
+
+\def\@citex[#1]#2{\if@filesw\immediate\write\@auxout{\string\citation{#2}}\fi
+  \def\@citea{}\@cite{\@for\@citeb:=#2\do
+    {\@citea\def\@citea{\@hisep\penalty\@m\ }\@ifundefined
+       {b@\@citeb}{{\bf ?}\@warning
+       {Citation `\@citeb' on page \thepage \space undefined}}%
+{{\csname b@\@citeb\endcsname\@hysep\csname bhy@\@citeb\endcsname}%
+\global\@enamedef{b@\@citeb}{\csname bha@\@citeb\endcsname}}%
+}}{#1}}
+
+\def\@citexasnoun[#1]#2{%
+\if@filesw\immediate\write\@auxout{\string\citation{#2}}\fi%
+\@citeasnoun{{\@ifundefined%
+{b@#2}%
+{[{\bf ?}\@warning{Citation `#2' on page \thepage \space undefined}}%
+{{\csname b@#2\endcsname\ [\csname bhy@#2\endcsname}%
+\global\@namedef{b@#2}{\csname bha@#2\endcsname}}%
+}}{#1}}
+
+\def\@citexname[#1]#2{%
+\if@filesw\immediate\write\@auxout{\string\citation{#2}}\fi%
+\@citename{{\@ifundefined%
+{b@#2}%
+{{\bf ?}\@warning{Citation `#2' on page \thepage \space undefined}}%
+{{\csname bhf@#2\endcsname}}%
+}}{#1}}
+
+\def\@citexyear[#1]#2{\if@filesw\immediate\write\@auxout{\string\citation{#2}}\fi
+  \def\@citeayear{}\@cite{\@for\@citebyear:=#2\do
+    {\@citeayear\def\@citeayear{\@hisep\penalty\@m\ }\@ifundefined
+       {b@\@citebyear}{{\bf ?}\@warning
+       {Citation `\@citebyear' on page \thepage \space undefined}}%
+{{\csname bhy@\@citebyear\endcsname}%
+}%
+}}{#1}}
+
+\gdef\hysep@agsm{\ }\gdef\hisep@agsm{,}%
+\gdef\hysep@dcu{, }\gdef\hisep@dcu{;}%
+\let\@hysep\hysep@agsm \let\@hisep\hisep@agsm
+\def\citationstyle#1{%
+\global\@namedef{@hysep}{\csname hysep@#1\endcsname}%
+\global\@namedef{@hisep}{\csname hisep@#1\endcsname}}
+ 
+%DEFAULT DEFINITIONS
+\def\@cite#1#2{({#1\if@tempswa , #2\fi})}
+\def\@citeasnoun#1#2{{#1\if@tempswa , #2\fi]}}
+\def\@citename#1#2{{#1\if@tempswa \ (#2)\fi}}
+
+% CHANGE \end{document} - to handle double definitions
+\def\enddocument{\@checkend{document}\clearpage\begingroup
+\if@filesw \immediate\closeout\@mainaux
+\def\global\@namedef##1##2{}\def\newlabel{\@testdef r}%
+\def\bibcite{\@testdef b}%
+\def\harvardcite{\@testbibh}\@tempswafalse \makeatletter\input \jobname.aux
+\if@tempswa \@warning{Label(s) may have changed.  Rerun to get
+cross-references right}\fi\fi\endgroup\deadcycles\z@\@@end}
+ 
+\def\@testbibh #1#2#3{
+  \def\@tempa{#2}\expandafter
+  \ifx \csname bhf@#1\endcsname \@tempa 
+     \def\@tempa{#3}\expandafter
+     \ifx \csname bha@#1\endcsname \@tempa
+     \else \@tempswatrue
+     \fi
+  \else
+     \@tempswatrue
+  \fi
+}
+ 
+%
\ No newline at end of file
diff --git a/tags/v_3.062/doc/dynare.xsl b/tags/v_3.062/doc/dynare.xsl
new file mode 100644
index 0000000000000000000000000000000000000000..337666d1dfd694c53e48d124caa0bb9ad528420d
--- /dev/null
+++ b/tags/v_3.062/doc/dynare.xsl
@@ -0,0 +1,23 @@
+<?xml version='1.0'?>
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
+                xmlns:fo="http://www.w3.org/1999/XSL/Format"
+                xmlns:doc="http://nwalsh.com/xsl/documentation/1.0"
+                exclude-result-prefixes="doc"
+                version='1.0'>
+
+<!-- It is important to use indent="no" here, otherwise verbatim -->
+<!-- environments get broken by indented tags...at least when the -->
+<!-- callout extension is used...at least with some processors -->
+
+<xsl:param name="generate.index">1</xsl:param>
+<xsl:param name="refentry.generate.name">0</xsl:param>
+<xsl:param name="refentry.generate.title">1</xsl:param>
+<xsl:param name="section.autolabel" select="1"></xsl:param>
+<xsl:param name="biblioentry.item.separator">, </xsl:param>
+
+<xsl:attribute-set name="section.level1.properties">
+  <xsl:attribute name="break-before">page</xsl:attribute>
+</xsl:attribute-set>
+
+
+</xsl:stylesheet>
diff --git a/tags/v_3.062/doc/dynare_fo.xsl b/tags/v_3.062/doc/dynare_fo.xsl
new file mode 100644
index 0000000000000000000000000000000000000000..ce5e367b50b357f7ef363b6a1f6604fbabfd96d4
--- /dev/null
+++ b/tags/v_3.062/doc/dynare_fo.xsl
@@ -0,0 +1,28 @@
+<?xml version='1.0'?>
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
+                xmlns:fo="http://www.w3.org/1999/XSL/Format"
+                xmlns:doc="http://nwalsh.com/xsl/documentation/1.0"
+                exclude-result-prefixes="doc"
+                version='1.0'>
+
+<!-- It is important to use indent="no" here, otherwise verbatim -->
+<!-- environments get broken by indented tags...at least when the -->
+<!-- callout extension is used...at least with some processors -->
+<xsl:import href="e:/docbook-xsl-1.66.1/fo/docbook.xsl"/>
+<xsl:import href="dynare.xsl"/>
+
+<xsl:import href="dynare_lists.xsl"/>
+
+<xsl:param name="passivetex.extensions">1</xsl:param>
+<xsl:attribute-set name="list.item.spacing">
+  <xsl:attribute name="line-height">0em</xsl:attribute>
+</xsl:attribute-set>
+<xsl:attribute-set name="compact.list.item.spacing">
+  <xsl:attribute name="space-before.optimum">0em</xsl:attribute>
+  <xsl:attribute name="space-before.minimum">0em</xsl:attribute>
+  <xsl:attribute name="space-before.maximum">0em</xsl:attribute>
+  <xsl:attribute name="line-height">0em</xsl:attribute>
+</xsl:attribute-set>
+ 
+
+</xsl:stylesheet>
diff --git a/tags/v_3.062/doc/dynare_fo_fop.xsl b/tags/v_3.062/doc/dynare_fo_fop.xsl
new file mode 100644
index 0000000000000000000000000000000000000000..b99170fe54e5a274fcb7bdf3c5ff1b8489f84eb3
--- /dev/null
+++ b/tags/v_3.062/doc/dynare_fo_fop.xsl
@@ -0,0 +1,115 @@
+<?xml version='1.0'?>
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
+                xmlns:fo="http://www.w3.org/1999/XSL/Format"
+                xmlns:doc="http://nwalsh.com/xsl/documentation/1.0"
+                exclude-result-prefixes="doc"
+                version='1.0'>
+
+<!-- It is important to use indent="no" here, otherwise verbatim -->
+<!-- environments get broken by indented tags...at least when the -->
+<!-- callout extension is used...at least with some processors -->
+<!-- <xsl:import href="c:/cygwin/usr/share/docbook-xsl/fo/docbook.xsl"/> -->
+<xsl:import href="e:/docbook-xsl-1.65.1/fo/docbook.xsl"/>
+
+<xsl:param name="use.extensions">1</xsl:param>
+<xsl:param name="fop.extensions">1</xsl:param>
+<xsl:param name="refentry.generate.name">0</xsl:param>
+<xsl:param name="refentry.generate.title">1</xsl:param>
+<xsl:template match="refsynopsisdiv">
+  <fo:block font-weight="bold" font-size="16pt" font-family="sans-serif">
+    <xsl:call-template name="gentext">
+                  <xsl:with-param name="key" select="'RefSynopsisDiv'"/>
+    </xsl:call-template>
+  </fo:block>
+    <xsl:apply-templates/>
+</xsl:template>
+
+<xsl:template match="refnamediv">
+  <xsl:variable name="section.level">
+    <xsl:call-template name="refentry.level">
+      <xsl:with-param name="node" select="ancestor::refentry"/>
+    </xsl:call-template>
+  </xsl:variable>
+
+  <xsl:variable name="reftitle">
+    <xsl:choose>
+      <xsl:when test="$refentry.generate.name != 0">
+        <xsl:call-template name="gentext">
+          <xsl:with-param name="key" select="'RefName'"/>
+        </xsl:call-template>
+      </xsl:when>
+      <xsl:when test="$refentry.generate.title != 0">
+        <xsl:choose>
+          <xsl:when test="../refmeta/refentrytitle">
+            <xsl:apply-templates select="../refmeta/refentrytitle"/>
+          </xsl:when>
+          <xsl:otherwise>
+            <xsl:apply-templates select="refname[1]"/>
+          </xsl:otherwise>
+        </xsl:choose>
+      </xsl:when>
+    </xsl:choose>
+  </xsl:variable>
+
+  <!-- xsl:use-attribute-sets takes only a Qname, not a variable -->
+  <fo:block>
+    <xsl:choose>
+      <xsl:when test="$section.level = 1">
+        <fo:block xsl:use-attribute-sets="refentry.title.properties">
+          <fo:block xsl:use-attribute-sets="section.title.level1.properties">
+            <xsl:value-of select="$reftitle"/>
+          </fo:block>
+        </fo:block>
+      </xsl:when>
+      <xsl:when test="$section.level = 2">
+        <fo:block xsl:use-attribute-sets="refentry.title.properties">
+          <fo:block xsl:use-attribute-sets="section.title.level2.properties">
+            <xsl:value-of select="$reftitle"/>
+          </fo:block>
+        </fo:block>
+      </xsl:when>
+      <xsl:when test="$section.level = 3">
+        <fo:block xsl:use-attribute-sets="refentry.title.properties">
+          <fo:block xsl:use-attribute-sets="section.title.level3.properties">
+            <xsl:value-of select="$reftitle"/>
+          </fo:block>
+        </fo:block>
+      </xsl:when>
+      <xsl:when test="$section.level = 4">
+        <fo:block xsl:use-attribute-sets="refentry.title.properties">
+          <fo:block xsl:use-attribute-sets="section.title.level4.properties">
+            <xsl:value-of select="$reftitle"/>
+          </fo:block>
+        </fo:block>
+      </xsl:when>
+      <xsl:when test="$section.level = 5">
+        <fo:block xsl:use-attribute-sets="refentry.title.properties">
+          <fo:block xsl:use-attribute-sets="section.title.level5.properties">
+            <xsl:value-of select="$reftitle"/>
+          </fo:block>
+        </fo:block>
+      </xsl:when>
+      <xsl:otherwise>
+        <fo:block xsl:use-attribute-sets="refentry.title.properties">
+          <fo:block xsl:use-attribute-sets="section.title.level6.properties">
+            <xsl:value-of select="$reftitle"/>
+          </fo:block>
+        </fo:block>
+      </xsl:otherwise>
+    </xsl:choose>
+
+    <fo:block space-after="1em">
+      <xsl:choose>
+        <xsl:when test="../refmeta/refentrytitle">
+          <xsl:apply-templates select="../refmeta/refentrytitle"/>
+        </xsl:when>
+        <xsl:otherwise>
+          <xsl:apply-templates select="refname[1]"/>
+        </xsl:otherwise>
+      </xsl:choose>
+      <xsl:apply-templates select="refpurpose"/>
+    </fo:block>
+  </fo:block>
+  
+</xsl:template>
+</xsl:stylesheet>
diff --git a/tags/v_3.062/doc/dynare_html.xsl b/tags/v_3.062/doc/dynare_html.xsl
new file mode 100644
index 0000000000000000000000000000000000000000..ef41a4c7c0b9283ec0771f08159d7b26f18836b8
--- /dev/null
+++ b/tags/v_3.062/doc/dynare_html.xsl
@@ -0,0 +1,15 @@
+<?xml version='1.0'?>
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
+                xmlns:fo="http://www.w3.org/1999/XSL/Format"
+                xmlns:doc="http://nwalsh.com/xsl/documentation/1.0"
+                exclude-result-prefixes="doc"
+                version='1.0'>
+
+<!-- It is important to use indent="no" here, otherwise verbatim -->
+<!-- environments get broken by indented tags...at least when the -->
+<!-- callout extension is used...at least with some processors -->
+<xsl:import href="c:/cygwin/usr/share/docbook-xsl/html/chunk.xsl"/>
+
+<xsl:import href="dynare.xsl"/>
+
+</xsl:stylesheet>
diff --git a/tags/v_3.062/doc/dynare_lists.xsl b/tags/v_3.062/doc/dynare_lists.xsl
new file mode 100644
index 0000000000000000000000000000000000000000..99f421b4e9c9e7bc9672d2ca42a97f8bd7dff9cd
--- /dev/null
+++ b/tags/v_3.062/doc/dynare_lists.xsl
@@ -0,0 +1,1169 @@
+<?xml version='1.0'?>
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
+                xmlns:fo="http://www.w3.org/1999/XSL/Format"
+                version='1.0'>
+
+<!-- ********************************************************************
+     $Id: dynare_lists.xsl,v 1.1 2005/01/09 13:00:17 michel Exp $
+     ********************************************************************
+
+     This file is part of the XSL DocBook Stylesheet distribution.
+     See ../README or http://nwalsh.com/docbook/xsl/ for copyright
+     and other information.
+
+     ******************************************************************** -->
+
+<!-- ==================================================================== -->
+
+<xsl:template match="itemizedlist">
+  <xsl:variable name="id">
+    <xsl:call-template name="object.id"/>
+  </xsl:variable>
+
+  <xsl:variable name="label-width">
+    <xsl:call-template name="dbfo-attribute">
+      <xsl:with-param name="pis"
+                      select="processing-instruction('dbfo')"/>
+      <xsl:with-param name="attribute" select="'label-width'"/>
+    </xsl:call-template>
+  </xsl:variable>
+
+  <xsl:if test="title">
+    <xsl:apply-templates select="title" mode="list.title.mode"/>
+  </xsl:if>
+
+  <!-- Preserve order of PIs and comments -->
+  <xsl:apply-templates 
+      select="*[not(self::listitem
+                or self::title
+                or self::titleabbrev)]
+              |comment()[not(preceding-sibling::listitem)]
+              |processing-instruction()[not(preceding-sibling::listitem)]"/>
+
+  <xsl:variable name="content">
+    <xsl:apply-templates 
+          select="listitem
+                  |comment()[preceding-sibling::listitem]
+                  |processing-instruction()[preceding-sibling::listitem]"/>
+  </xsl:variable>
+
+  <!-- nested lists don't add extra list-block spacing -->
+  <xsl:choose>
+    <xsl:when test="ancestor::listitem">
+      <fo:list-block id="{$id}" 
+                     provisional-label-separation="0.2em">
+        <xsl:attribute name="provisional-distance-between-starts">
+          <xsl:choose>
+            <xsl:when test="$label-width != ''">
+              <xsl:value-of select="$label-width"/>
+            </xsl:when>
+            <xsl:otherwise>1.5em</xsl:otherwise>
+          </xsl:choose>
+        </xsl:attribute>
+        <xsl:copy-of select="$content"/>
+      </fo:list-block>
+    </xsl:when>
+    <xsl:otherwise>
+      <fo:list-block id="{$id}" xsl:use-attribute-sets="list.block.spacing"
+                     provisional-label-separation="0.2em">
+        <xsl:attribute name="provisional-distance-between-starts">
+          <xsl:choose>
+            <xsl:when test="$label-width != ''">
+              <xsl:value-of select="$label-width"/>
+            </xsl:when>
+            <xsl:otherwise>1.5em</xsl:otherwise>
+          </xsl:choose>
+        </xsl:attribute>
+        <xsl:copy-of select="$content"/>
+      </fo:list-block>
+    </xsl:otherwise>
+  </xsl:choose>
+
+</xsl:template>
+
+<xsl:template match="itemizedlist/title|orderedlist/title">
+  <!--nop-->
+</xsl:template>
+
+<xsl:template match="variablelist/title" mode="vl.as.list">
+  <!--nop-->
+</xsl:template>
+
+<xsl:template match="variablelist/title" mode="vl.as.blocks">
+  <!--nop-->
+</xsl:template>
+
+<xsl:template match="itemizedlist/titleabbrev|orderedlist/titleabbrev">
+  <!--nop-->
+</xsl:template>
+
+<xsl:template match="procedure/titleabbrev">
+  <!--nop-->
+</xsl:template>
+
+<xsl:template match="variablelist/titleabbrev" mode="vl.as.list">
+  <!--nop-->
+</xsl:template>
+
+<xsl:template match="variablelist/titleabbrev" mode="vl.as.blocks">
+  <!--nop-->
+</xsl:template>
+
+<xsl:template match="itemizedlist/listitem">
+  <xsl:variable name="id"><xsl:call-template name="object.id"/></xsl:variable>
+
+  <xsl:variable name="itemsymbol">
+    <xsl:call-template name="list.itemsymbol">
+      <xsl:with-param name="node" select="parent::itemizedlist"/>
+    </xsl:call-template>
+  </xsl:variable>
+
+  <xsl:variable name="item.contents">
+    <fo:list-item-label end-indent="label-end()">
+      <fo:block>
+        <xsl:choose>
+          <xsl:when test="$itemsymbol='disc'">&#x2022;</xsl:when>
+          <xsl:when test="$itemsymbol='bullet'">&#x2022;</xsl:when>
+          <!-- why do these symbols not work? -->
+          <!--
+          <xsl:when test="$itemsymbol='circle'">&#x2218;</xsl:when>
+          <xsl:when test="$itemsymbol='round'">&#x2218;</xsl:when>
+          <xsl:when test="$itemsymbol='square'">&#x2610;</xsl:when>
+          <xsl:when test="$itemsymbol='box'">&#x2610;</xsl:when>
+          -->
+          <xsl:otherwise>&#x2022;</xsl:otherwise>
+        </xsl:choose>
+      </fo:block>
+    </fo:list-item-label>
+    <fo:list-item-body start-indent="body-start()">
+      <!-- fo:block -->
+	<xsl:apply-templates/>
+      <!-- /fo:block -->
+    </fo:list-item-body>
+  </xsl:variable>
+
+  <xsl:choose>
+    <xsl:when test="parent::*/@spacing = 'compact'">
+      <fo:list-item id="{$id}" xsl:use-attribute-sets="compact.list.item.spacing">
+        <xsl:copy-of select="$item.contents"/>
+      </fo:list-item>
+    </xsl:when>
+    <xsl:otherwise>
+      <fo:list-item id="{$id}" xsl:use-attribute-sets="list.item.spacing">
+        <xsl:copy-of select="$item.contents"/>
+      </fo:list-item>
+    </xsl:otherwise>
+  </xsl:choose>
+</xsl:template>
+
+<xsl:template match="orderedlist">
+  <xsl:variable name="id">
+    <xsl:call-template name="object.id"/>
+  </xsl:variable>
+
+  <xsl:variable name="label-width">
+    <xsl:call-template name="dbfo-attribute">
+      <xsl:with-param name="pis"
+                      select="processing-instruction('dbfo')"/>
+      <xsl:with-param name="attribute" select="'label-width'"/>
+    </xsl:call-template>
+  </xsl:variable>
+
+  <xsl:if test="title">
+    <xsl:apply-templates select="title" mode="list.title.mode"/>
+  </xsl:if>
+
+  <!-- Preserve order of PIs and comments -->
+  <xsl:apply-templates 
+      select="*[not(self::listitem
+                or self::title
+                or self::titleabbrev)]
+              |comment()[not(preceding-sibling::listitem)]
+              |processing-instruction()[not(preceding-sibling::listitem)]"/>
+
+  <xsl:variable name="content">
+    <xsl:apply-templates 
+          select="listitem
+                  |comment()[preceding-sibling::listitem]
+                  |processing-instruction()[preceding-sibling::listitem]"/>
+  </xsl:variable>
+
+  <!-- nested lists don't add extra list-block spacing -->
+  <xsl:choose>
+    <xsl:when test="ancestor::listitem">
+      <fo:list-block id="{$id}" 
+                     provisional-label-separation="0.2em">
+        <xsl:attribute name="provisional-distance-between-starts">
+          <xsl:choose>
+            <xsl:when test="$label-width != ''">
+              <xsl:value-of select="$label-width"/>
+            </xsl:when>
+            <xsl:otherwise>2em</xsl:otherwise>
+          </xsl:choose>
+        </xsl:attribute>
+        <xsl:copy-of select="$content"/>
+      </fo:list-block>
+    </xsl:when>
+    <xsl:otherwise>
+      <fo:list-block id="{$id}" xsl:use-attribute-sets="list.block.spacing"
+                     provisional-label-separation="0.2em">
+        <xsl:attribute name="provisional-distance-between-starts">
+          <xsl:choose>
+            <xsl:when test="$label-width != ''">
+              <xsl:value-of select="$label-width"/>
+            </xsl:when>
+            <xsl:otherwise>2em</xsl:otherwise>
+          </xsl:choose>
+        </xsl:attribute>
+        <xsl:copy-of select="$content"/>
+      </fo:list-block>
+    </xsl:otherwise>
+  </xsl:choose>
+</xsl:template>
+
+<xsl:template match="orderedlist/listitem" mode="item-number">
+  <xsl:variable name="numeration">
+    <xsl:call-template name="list.numeration">
+      <xsl:with-param name="node" select="parent::orderedlist"/>
+    </xsl:call-template>
+  </xsl:variable>
+
+  <xsl:variable name="type">
+    <xsl:choose>
+      <xsl:when test="$numeration='arabic'">1.</xsl:when>
+      <xsl:when test="$numeration='loweralpha'">a.</xsl:when>
+      <xsl:when test="$numeration='lowerroman'">i.</xsl:when>
+      <xsl:when test="$numeration='upperalpha'">A.</xsl:when>
+      <xsl:when test="$numeration='upperroman'">I.</xsl:when>
+      <!-- What!? This should never happen -->
+      <xsl:otherwise>
+        <xsl:message>
+          <xsl:text>Unexpected numeration: </xsl:text>
+          <xsl:value-of select="$numeration"/>
+        </xsl:message>
+        <xsl:value-of select="1."/>
+      </xsl:otherwise>
+    </xsl:choose>
+  </xsl:variable>
+
+  <xsl:variable name="item-number">
+    <xsl:call-template name="orderedlist-item-number"/>
+  </xsl:variable>
+
+  <xsl:if test="parent::orderedlist/@inheritnum='inherit'
+                and ancestor::listitem[parent::orderedlist]">
+    <xsl:apply-templates select="ancestor::listitem[parent::orderedlist][1]"
+                         mode="item-number"/>
+  </xsl:if>
+
+  <xsl:number value="$item-number" format="{$type}"/>
+</xsl:template>
+
+<xsl:template match="orderedlist/listitem">
+  <xsl:variable name="id"><xsl:call-template name="object.id"/></xsl:variable>
+
+  <xsl:variable name="item.contents">
+    <fo:list-item-label end-indent="label-end()">
+      <fo:block>
+        <xsl:apply-templates select="." mode="item-number"/>
+      </fo:block>
+    </fo:list-item-label>
+    <fo:list-item-body start-indent="body-start()">
+      <fo:block>
+	<xsl:apply-templates/>
+      </fo:block>
+    </fo:list-item-body>
+  </xsl:variable>
+
+  <xsl:choose>
+    <xsl:when test="parent::*/@spacing = 'compact'">
+      <fo:list-item id="{$id}" xsl:use-attribute-sets="compact.list.item.spacing">
+        <xsl:copy-of select="$item.contents"/>
+      </fo:list-item>
+    </xsl:when>
+    <xsl:otherwise>
+      <fo:list-item id="{$id}" xsl:use-attribute-sets="list.item.spacing">
+        <xsl:copy-of select="$item.contents"/>
+      </fo:list-item>
+    </xsl:otherwise>
+  </xsl:choose>
+</xsl:template>
+
+<xsl:template match="listitem/*[1][local-name()='para' or 
+                                   local-name()='simpara' or 
+                                   local-name()='formalpara']
+                     |step/*[1][local-name()='para' or 
+                                   local-name()='simpara' or 
+                                   local-name()='formalpara']
+                     |callout/*[1][local-name()='para' or 
+                                   local-name()='simpara' or 
+                                   local-name()='formalpara']"
+              priority="2">
+  <fo:block>
+    <xsl:call-template name="anchor"/>
+    <xsl:apply-templates/>
+  </fo:block>
+</xsl:template>
+
+<xsl:template match="variablelist">
+  <xsl:variable name="presentation">
+    <xsl:call-template name="dbfo-attribute">
+      <xsl:with-param name="pis"
+                      select="processing-instruction('dbfo')"/>
+      <xsl:with-param name="attribute" select="'list-presentation'"/>
+    </xsl:call-template>
+  </xsl:variable>
+
+  <xsl:choose>
+    <xsl:when test="$presentation = 'list'">
+      <xsl:apply-templates select="." mode="vl.as.list"/>
+    </xsl:when>
+    <xsl:when test="$presentation = 'blocks'">
+      <xsl:apply-templates select="." mode="vl.as.blocks"/>
+    </xsl:when>
+    <xsl:when test="$variablelist.as.blocks != 0">
+      <xsl:apply-templates select="." mode="vl.as.blocks"/>
+    </xsl:when>
+    <xsl:otherwise>
+      <xsl:apply-templates select="." mode="vl.as.list"/>
+    </xsl:otherwise>
+  </xsl:choose>
+</xsl:template>
+
+<xsl:template match="variablelist" mode="vl.as.list">
+  <xsl:variable name="id">
+    <xsl:call-template name="object.id"/>
+  </xsl:variable>
+
+  <xsl:variable name="term-width">
+    <xsl:call-template name="dbfo-attribute">
+      <xsl:with-param name="pis"
+                      select="processing-instruction('dbfo')"/>
+      <xsl:with-param name="attribute" select="'term-width'"/>
+    </xsl:call-template>
+  </xsl:variable>
+
+  <xsl:variable name="termlength">
+    <xsl:choose>
+      <xsl:when test="$term-width != ''">
+        <xsl:value-of select="$term-width"/>
+      </xsl:when>
+      <xsl:when test="@termlength">
+        <xsl:variable name="termlength.is.number">
+          <xsl:value-of select="@termlength + 0"/>
+        </xsl:variable>
+        <xsl:choose>
+          <xsl:when test="$termlength.is.number = 'NaN'">
+            <!-- if the term length isn't just a number, assume it's a measurement -->
+            <xsl:value-of select="@termlength"/>
+          </xsl:when>
+          <xsl:otherwise>
+            <xsl:value-of select="@termlength"/>
+            <xsl:text>em * 0.60</xsl:text>
+          </xsl:otherwise>
+        </xsl:choose>
+      </xsl:when>
+      <xsl:otherwise>
+        <xsl:call-template name="longest.term">
+          <xsl:with-param name="terms" select="varlistentry/term"/>
+          <xsl:with-param name="maxlength" select="$variablelist.max.termlength"/>
+        </xsl:call-template>
+        <xsl:text>em * 0.60</xsl:text>
+      </xsl:otherwise>
+    </xsl:choose>
+  </xsl:variable>
+
+<!--
+  <xsl:message>
+    <xsl:text>term width: </xsl:text>
+    <xsl:value-of select="$termlength"/>
+  </xsl:message>
+-->
+
+  <xsl:variable name="label-separation">1em</xsl:variable>
+
+  <xsl:if test="title">
+    <xsl:apply-templates select="title" mode="list.title.mode"/>
+  </xsl:if>
+
+  <!-- Preserve order of PIs and comments -->
+  <xsl:apply-templates 
+    select="*[not(self::varlistentry
+              or self::title
+              or self::titleabbrev)]
+            |comment()[not(preceding-sibling::varlistentry)]
+            |processing-instruction()[not(preceding-sibling::varlistentry)]"/>
+
+  <xsl:variable name="content">
+    <xsl:apply-templates mode="vl.as.list"
+      select="varlistentry
+              |comment()[preceding-sibling::varlistentry]
+              |processing-instruction()[preceding-sibling::varlistentry]"/>
+  </xsl:variable>
+
+  <!-- nested lists don't add extra list-block spacing -->
+  <xsl:choose>
+    <xsl:when test="ancestor::listitem">
+      <fo:list-block id="{$id}"
+                     provisional-distance-between-starts=
+                        "{$termlength}+{$label-separation}"
+                     provisional-label-separation="{$label-separation}">
+        <xsl:copy-of select="$content"/>
+      </fo:list-block>
+    </xsl:when>
+    <xsl:otherwise>
+      <fo:list-block id="{$id}"
+                     provisional-distance-between-starts=
+                        "{$termlength}+{$label-separation}"
+                     provisional-label-separation="{$label-separation}"
+                     xsl:use-attribute-sets="list.block.spacing">
+        <xsl:copy-of select="$content"/>
+      </fo:list-block>
+    </xsl:otherwise>
+  </xsl:choose>
+</xsl:template>
+
+<xsl:template name="longest.term">
+  <xsl:param name="longest" select="0"/>
+  <xsl:param name="terms" select="."/>
+  <xsl:param name="maxlength" select="-1"/>
+
+  <xsl:choose>
+    <xsl:when test="$longest &gt; $maxlength and $maxlength &gt; 0">
+      <xsl:value-of select="$maxlength"/>
+    </xsl:when>
+    <xsl:when test="not($terms)">
+      <xsl:value-of select="$longest"/>
+    </xsl:when>
+    <xsl:when test="string-length($terms[1]/node()[not(indexterm)]) &gt; $longest">
+      <xsl:call-template name="longest.term">
+        <xsl:with-param name="longest" 
+	    select="string-length($terms[1]/node()[not(indexterm)])"/>
+        <xsl:with-param name="maxlength" select="$maxlength"/>
+        <xsl:with-param name="terms" select="$terms[position() &gt; 1]"/>
+      </xsl:call-template>
+    </xsl:when>
+    <xsl:otherwise>
+      <xsl:call-template name="longest.term">
+        <xsl:with-param name="longest" select="$longest"/>
+        <xsl:with-param name="maxlength" select="$maxlength"/>
+        <xsl:with-param name="terms" select="$terms[position() &gt; 1]"/>
+      </xsl:call-template>
+    </xsl:otherwise>
+  </xsl:choose>
+</xsl:template>
+
+<xsl:template match="varlistentry" mode="vl.as.list">
+  <xsl:variable name="id"><xsl:call-template name="object.id"/></xsl:variable>
+  <fo:list-item id="{$id}" xsl:use-attribute-sets="list.item.spacing">
+    <fo:list-item-label end-indent="label-end()" text-align="start">
+      <fo:block>
+        <xsl:apply-templates select="term"/>
+      </fo:block>
+    </fo:list-item-label>
+    <fo:list-item-body start-indent="body-start()">
+      <fo:block>
+	<xsl:apply-templates select="listitem"/>
+      </fo:block>
+    </fo:list-item-body>
+  </fo:list-item>
+</xsl:template>
+
+<xsl:template match="variablelist" mode="vl.as.blocks">
+  <xsl:variable name="id">
+    <xsl:call-template name="object.id"/>
+  </xsl:variable>
+
+  <!-- termlength is irrelevant -->
+
+  <xsl:if test="title">
+    <xsl:apply-templates select="title" mode="list.title.mode"/>
+  </xsl:if>
+
+  <!-- Preserve order of PIs and comments -->
+  <xsl:apply-templates 
+    select="*[not(self::varlistentry
+              or self::title
+              or self::titleabbrev)]
+            |comment()[not(preceding-sibling::varlistentry)]
+            |processing-instruction()[not(preceding-sibling::varlistentry)]"/>
+
+  <xsl:variable name="content">
+    <xsl:apply-templates mode="vl.as.blocks"
+      select="varlistentry
+              |comment()[preceding-sibling::varlistentry]
+              |processing-instruction()[preceding-sibling::varlistentry]"/>
+  </xsl:variable>
+
+  <!-- nested lists don't add extra list-block spacing -->
+  <xsl:choose>
+    <xsl:when test="ancestor::listitem">
+      <fo:block id="{$id}">
+        <xsl:copy-of select="$content"/>
+      </fo:block>
+    </xsl:when>
+    <xsl:otherwise>
+      <fo:block id="{$id}" xsl:use-attribute-sets="list.block.spacing">
+        <xsl:copy-of select="$content"/>
+      </fo:block>
+    </xsl:otherwise>
+  </xsl:choose>
+</xsl:template>
+
+<xsl:template match="varlistentry" mode="vl.as.blocks">
+  <xsl:variable name="id"><xsl:call-template name="object.id"/></xsl:variable>
+
+  <fo:block id="{$id}" xsl:use-attribute-sets="list.item.spacing"  
+      keep-together.within-column="always" 
+      keep-with-next.within-column="always">
+    <xsl:apply-templates select="term"/>
+  </fo:block>
+
+  <fo:block margin-left="0.25in">
+    <xsl:apply-templates select="listitem"/>
+  </fo:block>
+</xsl:template>
+
+<xsl:template match="varlistentry/term">
+  <fo:inline><xsl:apply-templates/>, </fo:inline>
+</xsl:template>
+
+<xsl:template match="varlistentry/term[position()=last()]" priority="2">
+  <fo:inline><xsl:apply-templates/></fo:inline>
+</xsl:template>
+
+<xsl:template match="varlistentry/listitem">
+  <xsl:apply-templates/>
+</xsl:template>
+
+<!-- ==================================================================== -->
+
+<xsl:template match="title" mode="list.title.mode">
+  <xsl:call-template name="formal.object.heading">
+    <xsl:with-param name="object" select=".."/>
+  </xsl:call-template>
+</xsl:template>
+
+<!-- ==================================================================== -->
+
+<xsl:template match="simplelist">
+  <!-- with no type specified, the default is 'vert' -->
+  <fo:table xsl:use-attribute-sets="normal.para.spacing">
+    <xsl:call-template name="simplelist.table.columns">
+      <xsl:with-param name="cols">
+        <xsl:choose>
+          <xsl:when test="@columns">
+            <xsl:value-of select="@columns"/>
+          </xsl:when>
+          <xsl:otherwise>1</xsl:otherwise>
+        </xsl:choose>
+      </xsl:with-param>
+    </xsl:call-template>
+    <fo:table-body>
+      <xsl:call-template name="simplelist.vert">
+        <xsl:with-param name="cols">
+          <xsl:choose>
+            <xsl:when test="@columns">
+              <xsl:value-of select="@columns"/>
+            </xsl:when>
+            <xsl:otherwise>1</xsl:otherwise>
+          </xsl:choose>
+        </xsl:with-param>
+      </xsl:call-template>
+    </fo:table-body>
+  </fo:table>
+</xsl:template>
+
+<xsl:template match="simplelist[@type='inline']">
+  <fo:inline><xsl:apply-templates/></fo:inline>
+</xsl:template>
+
+<xsl:template match="simplelist[@type='horiz']">
+
+  <xsl:variable name="explicit.table.width">
+    <xsl:call-template name="dbfo-attribute">
+      <xsl:with-param name="pis"
+                      select="processing-instruction('dbfo')"/>
+      <xsl:with-param name="attribute" select="'list-width'"/>
+    </xsl:call-template>
+  </xsl:variable>
+
+  <xsl:variable name="table.width">
+    <xsl:choose>
+      <xsl:when test="$explicit.table.width != ''">
+        <xsl:value-of select="$explicit.table.width"/>
+      </xsl:when>
+      <xsl:when test="$default.table.width = ''">
+        <xsl:text>100%</xsl:text>
+      </xsl:when>
+      <xsl:otherwise>
+        <xsl:value-of select="$default.table.width"/>
+      </xsl:otherwise>
+    </xsl:choose>
+  </xsl:variable>
+
+  <fo:table xsl:use-attribute-sets="normal.para.spacing">
+    <xsl:choose>
+      <xsl:when test="$axf.extensions != 0">
+        <xsl:attribute name="table-layout">auto</xsl:attribute>
+	<xsl:if test="$explicit.table.width != ''">
+          <xsl:attribute name="width"><xsl:value-of 
+	                     select="$explicit.table.width"/></xsl:attribute>
+        </xsl:if>
+      </xsl:when>
+      <xsl:otherwise>
+        <xsl:attribute name="table-layout">fixed</xsl:attribute>
+        <xsl:attribute name="width"><xsl:value-of 
+	                              select="$table.width"/></xsl:attribute>
+      </xsl:otherwise>
+    </xsl:choose>
+    <xsl:call-template name="simplelist.table.columns">
+      <xsl:with-param name="cols">
+        <xsl:choose>
+          <xsl:when test="@columns">
+            <xsl:value-of select="@columns"/>
+          </xsl:when>
+          <xsl:otherwise>1</xsl:otherwise>
+        </xsl:choose>
+      </xsl:with-param>
+    </xsl:call-template>
+    <fo:table-body>
+      <xsl:call-template name="simplelist.horiz">
+        <xsl:with-param name="cols">
+          <xsl:choose>
+            <xsl:when test="@columns">
+              <xsl:value-of select="@columns"/>
+            </xsl:when>
+            <xsl:otherwise>1</xsl:otherwise>
+          </xsl:choose>
+        </xsl:with-param>
+      </xsl:call-template>
+    </fo:table-body>
+  </fo:table>
+</xsl:template>
+
+<xsl:template match="simplelist[@type='vert']">
+  <fo:table xsl:use-attribute-sets="normal.para.spacing">
+    <xsl:call-template name="simplelist.table.columns">
+      <xsl:with-param name="cols">
+        <xsl:choose>
+          <xsl:when test="@columns">
+            <xsl:value-of select="@columns"/>
+          </xsl:when>
+          <xsl:otherwise>1</xsl:otherwise>
+        </xsl:choose>
+      </xsl:with-param>
+    </xsl:call-template>
+    <fo:table-body>
+      <xsl:call-template name="simplelist.vert">
+        <xsl:with-param name="cols">
+          <xsl:choose>
+            <xsl:when test="@columns">
+              <xsl:value-of select="@columns"/>
+            </xsl:when>
+            <xsl:otherwise>1</xsl:otherwise>
+          </xsl:choose>
+        </xsl:with-param>
+      </xsl:call-template>
+    </fo:table-body>
+  </fo:table>
+</xsl:template>
+
+<xsl:template name="simplelist.table.columns">
+  <xsl:param name="cols" select="1"/>
+  <xsl:param name="curcol" select="1"/>
+  <fo:table-column column-number="{$curcol}"
+                   column-width="proportional-column-width(1)"/>
+  <xsl:if test="$curcol &lt; $cols">
+    <xsl:call-template name="simplelist.table.columns">
+      <xsl:with-param name="cols" select="$cols"/>
+      <xsl:with-param name="curcol" select="$curcol + 1"/>
+    </xsl:call-template>
+  </xsl:if>
+</xsl:template>
+
+<xsl:template name="simplelist.horiz">
+  <xsl:param name="cols">1</xsl:param>
+  <xsl:param name="cell">1</xsl:param>
+  <xsl:param name="members" select="./member"/>
+
+  <xsl:if test="$cell &lt;= count($members)">
+    <fo:table-row>
+      <xsl:call-template name="simplelist.horiz.row">
+        <xsl:with-param name="cols" select="$cols"/>
+        <xsl:with-param name="cell" select="$cell"/>
+        <xsl:with-param name="members" select="$members"/>
+      </xsl:call-template>
+   </fo:table-row>
+    <xsl:call-template name="simplelist.horiz">
+      <xsl:with-param name="cols" select="$cols"/>
+      <xsl:with-param name="cell" select="$cell + $cols"/>
+      <xsl:with-param name="members" select="$members"/>
+    </xsl:call-template>
+  </xsl:if>
+</xsl:template>
+
+<xsl:template name="simplelist.horiz.row">
+  <xsl:param name="cols">1</xsl:param>
+  <xsl:param name="cell">1</xsl:param>
+  <xsl:param name="members" select="./member"/>
+  <xsl:param name="curcol">1</xsl:param>
+
+  <xsl:if test="$curcol &lt;= $cols">
+    <fo:table-cell>
+      <fo:block>
+        <xsl:if test="$members[position()=$cell]">
+          <xsl:apply-templates select="$members[position()=$cell]"/>
+        </xsl:if>
+      </fo:block>
+    </fo:table-cell>
+    <xsl:call-template name="simplelist.horiz.row">
+      <xsl:with-param name="cols" select="$cols"/>
+      <xsl:with-param name="cell" select="$cell+1"/>
+      <xsl:with-param name="members" select="$members"/>
+      <xsl:with-param name="curcol" select="$curcol+1"/>
+    </xsl:call-template>
+  </xsl:if>
+</xsl:template>
+
+<xsl:template name="simplelist.vert">
+  <xsl:param name="cols">1</xsl:param>
+  <xsl:param name="cell">1</xsl:param>
+  <xsl:param name="members" select="./member"/>
+  <xsl:param name="rows"
+             select="floor((count($members)+$cols - 1) div $cols)"/>
+
+  <xsl:if test="$cell &lt;= $rows">
+    <fo:table-row>
+      <xsl:call-template name="simplelist.vert.row">
+        <xsl:with-param name="cols" select="$cols"/>
+        <xsl:with-param name="rows" select="$rows"/>
+        <xsl:with-param name="cell" select="$cell"/>
+        <xsl:with-param name="members" select="$members"/>
+      </xsl:call-template>
+   </fo:table-row>
+    <xsl:call-template name="simplelist.vert">
+      <xsl:with-param name="cols" select="$cols"/>
+      <xsl:with-param name="cell" select="$cell+1"/>
+      <xsl:with-param name="members" select="$members"/>
+      <xsl:with-param name="rows" select="$rows"/>
+    </xsl:call-template>
+  </xsl:if>
+</xsl:template>
+
+<xsl:template name="simplelist.vert.row">
+  <xsl:param name="cols">1</xsl:param>
+  <xsl:param name="rows">1</xsl:param>
+  <xsl:param name="cell">1</xsl:param>
+  <xsl:param name="members" select="./member"/>
+  <xsl:param name="curcol">1</xsl:param>
+
+  <xsl:if test="$curcol &lt;= $cols">
+    <fo:table-cell>
+      <fo:block>
+        <xsl:if test="$members[position()=$cell]">
+          <xsl:apply-templates select="$members[position()=$cell]"/>
+        </xsl:if>
+      </fo:block>
+    </fo:table-cell>
+    <xsl:call-template name="simplelist.vert.row">
+      <xsl:with-param name="cols" select="$cols"/>
+      <xsl:with-param name="rows" select="$rows"/>
+      <xsl:with-param name="cell" select="$cell+$rows"/>
+      <xsl:with-param name="members" select="$members"/>
+      <xsl:with-param name="curcol" select="$curcol+1"/>
+    </xsl:call-template>
+  </xsl:if>
+</xsl:template>
+
+<xsl:template match="member">
+  <xsl:apply-templates/>
+</xsl:template>
+
+<xsl:template match="simplelist[@type='inline']/member">
+  <xsl:apply-templates/>
+  <xsl:text>, </xsl:text>
+</xsl:template>
+
+<xsl:template match="simplelist[@type='inline']/member[position()=last()]"
+              priority="2">
+  <xsl:apply-templates/>
+</xsl:template>
+
+<!-- ==================================================================== -->
+
+<xsl:template match="procedure">
+  <xsl:variable name="id">
+    <xsl:call-template name="object.id"/>
+  </xsl:variable>
+
+  <xsl:variable name="param.placement"
+                select="substring-after(normalize-space($formal.title.placement),
+                                        concat(local-name(.), ' '))"/>
+
+  <xsl:variable name="placement">
+    <xsl:choose>
+      <xsl:when test="contains($param.placement, ' ')">
+        <xsl:value-of select="substring-before($param.placement, ' ')"/>
+      </xsl:when>
+      <xsl:when test="$param.placement = ''">before</xsl:when>
+      <xsl:otherwise>
+        <xsl:value-of select="$param.placement"/>
+      </xsl:otherwise>
+    </xsl:choose>
+  </xsl:variable>
+
+  <!-- Preserve order of PIs and comments -->
+  <xsl:variable name="preamble"
+        select="*[not(self::step
+                  or self::title
+                  or self::titleabbrev)]
+                |comment()[not(preceding-sibling::step)]
+                |processing-instruction()[not(preceding-sibling::step)]"/>
+
+  <xsl:variable name="steps" 
+                select="step
+                        |comment()[preceding-sibling::step]
+                        |processing-instruction()[preceding-sibling::step]"/>
+
+  <fo:block id="{$id}" xsl:use-attribute-sets="list.block.spacing">
+    <xsl:if test="./title and $placement = 'before'">
+      <!-- n.b. gentext code tests for $formal.procedures and may make an "informal" -->
+      <!-- heading even though we called formal.object.heading. odd but true. -->
+      <xsl:call-template name="formal.object.heading"/>
+    </xsl:if>
+
+    <xsl:apply-templates select="$preamble"/>
+
+    <fo:list-block xsl:use-attribute-sets="list.block.spacing"
+                   provisional-distance-between-starts="2em"
+                   provisional-label-separation="0.2em">
+      <xsl:apply-templates select="$steps"/>
+    </fo:list-block>
+
+    <xsl:if test="./title and $placement != 'before'">
+      <!-- n.b. gentext code tests for $formal.procedures and may make an "informal" -->
+      <!-- heading even though we called formal.object.heading. odd but true. -->
+      <xsl:call-template name="formal.object.heading"/>
+    </xsl:if>
+  </fo:block>
+</xsl:template>
+
+<xsl:template match="procedure/title">
+</xsl:template>
+
+<xsl:template match="substeps">
+  <fo:list-block xsl:use-attribute-sets="list.block.spacing"
+                 provisional-distance-between-starts="2em"
+                 provisional-label-separation="0.2em">
+    <xsl:apply-templates/>
+  </fo:list-block>
+</xsl:template>
+
+<xsl:template match="procedure/step|substeps/step">
+  <xsl:variable name="id">
+    <xsl:call-template name="object.id"/>
+  </xsl:variable>
+
+  <fo:list-item xsl:use-attribute-sets="list.item.spacing">
+    <fo:list-item-label end-indent="label-end()">
+      <fo:block id="{$id}">
+        <!-- dwc: fix for one step procedures. Use a bullet if there's no step 2 -->
+        <xsl:choose>
+          <xsl:when test="count(../step) = 1">
+            <xsl:text>&#x2022;</xsl:text>
+          </xsl:when>
+          <xsl:otherwise>
+            <xsl:apply-templates select="." mode="number">
+              <xsl:with-param name="recursive" select="0"/>
+            </xsl:apply-templates>.
+          </xsl:otherwise>
+        </xsl:choose>
+      </fo:block>
+    </fo:list-item-label>
+    <fo:list-item-body start-indent="body-start()">
+      <fo:block>
+	<xsl:apply-templates/>
+      </fo:block>
+    </fo:list-item-body>
+  </fo:list-item>
+</xsl:template>
+
+<xsl:template match="stepalternatives">
+  <fo:list-block provisional-distance-between-starts="2em"
+		 provisional-label-separation="0.2em">
+    <xsl:apply-templates select="step"/>
+  </fo:list-block>
+</xsl:template>
+
+<xsl:template match="stepalternatives/step">
+  <xsl:variable name="id">
+    <xsl:call-template name="object.id"/>
+  </xsl:variable>
+
+  <fo:list-item xsl:use-attribute-sets="list.item.spacing">
+    <fo:list-item-label end-indent="label-end()">
+      <fo:block id="{$id}">
+	<xsl:text>&#x2022;</xsl:text>
+      </fo:block>
+    </fo:list-item-label>
+    <fo:list-item-body start-indent="body-start()">
+      <fo:block>
+	<xsl:apply-templates/>
+      </fo:block>
+    </fo:list-item-body>
+  </fo:list-item>
+</xsl:template>
+
+<xsl:template match="step/title">
+  <fo:block font-weight="bold"
+            keep-together.within-column="always" 
+            keep-with-next.within-column="always">
+    <xsl:apply-templates/>
+  </fo:block>
+</xsl:template>
+
+<!-- ==================================================================== -->
+
+<xsl:template match="segmentedlist">
+  <xsl:variable name="presentation">
+    <xsl:call-template name="pi-attribute">
+      <xsl:with-param name="pis"
+                      select="processing-instruction('dbfo')"/>
+      <xsl:with-param name="attribute" select="'list-presentation'"/>
+    </xsl:call-template>
+  </xsl:variable>
+
+  <xsl:variable name="id">
+    <xsl:call-template name="object.id"/>
+  </xsl:variable>
+
+  <xsl:choose>
+    <xsl:when test="$presentation = 'table'">
+      <fo:block id="{$id}">
+        <xsl:apply-templates select="." mode="seglist-table"/>
+      </fo:block>
+    </xsl:when>
+    <xsl:when test="$presentation = 'list'">
+      <fo:block id="{$id}">
+        <xsl:apply-templates/>
+      </fo:block>
+    </xsl:when>
+    <xsl:when test="$segmentedlist.as.table != 0">
+      <fo:block id="{$id}">
+        <xsl:apply-templates select="." mode="seglist-table"/>
+      </fo:block>
+    </xsl:when>
+    <xsl:otherwise>
+      <fo:block id="{$id}">
+        <xsl:apply-templates/>
+      </fo:block>
+    </xsl:otherwise>
+  </xsl:choose>
+</xsl:template>
+
+<xsl:template match="segmentedlist/title">
+  <xsl:apply-templates select="." mode="list.title.mode" />
+</xsl:template>
+
+<xsl:template match="segtitle">
+</xsl:template>
+
+<xsl:template match="segtitle" mode="segtitle-in-seg">
+  <xsl:apply-templates/>
+</xsl:template>
+
+<xsl:template match="seglistitem">
+  <xsl:variable name="id">
+    <xsl:call-template name="object.id"/>
+  </xsl:variable>
+  <fo:block id="{$id}">
+    <xsl:apply-templates/>
+  </fo:block>
+</xsl:template>
+
+<xsl:template match="seg">
+  <xsl:variable name="segnum" select="count(preceding-sibling::seg)+1"/>
+  <xsl:variable name="seglist" select="ancestor::segmentedlist"/>
+  <xsl:variable name="segtitles" select="$seglist/segtitle"/>
+
+  <!--
+     Note: segtitle is only going to be the right thing in a well formed
+     SegmentedList.  If there are too many Segs or too few SegTitles,
+     you'll get something odd...maybe an error
+  -->
+
+  <fo:block>
+    <fo:inline font-weight="bold">
+      <xsl:apply-templates select="$segtitles[$segnum=position()]"
+                           mode="segtitle-in-seg"/>
+      <xsl:text>: </xsl:text>
+    </fo:inline>
+    <xsl:apply-templates/>
+  </fo:block>
+</xsl:template>
+
+<xsl:template match="segmentedlist" mode="seglist-table">
+  <xsl:apply-templates select="title" mode="list.title.mode" />
+  <fo:table>
+    <fo:table-column column-number="1" column-width="proportional-column-width(1)"/>
+    <fo:table-column column-number="2" column-width="proportional-column-width(1)"/>
+    <fo:table-header>
+      <fo:table-row>
+        <xsl:apply-templates select="segtitle" mode="seglist-table"/>
+      </fo:table-row>
+    </fo:table-header>
+    <fo:table-body>
+      <xsl:apply-templates select="seglistitem" mode="seglist-table"/>
+    </fo:table-body>
+  </fo:table>
+</xsl:template>
+
+<xsl:template match="segtitle" mode="seglist-table">
+  <fo:table-cell>
+    <fo:block>
+      <xsl:apply-templates/>
+    </fo:block>
+  </fo:table-cell>
+</xsl:template>
+
+<xsl:template match="seglistitem" mode="seglist-table">
+  <xsl:variable name="id">
+    <xsl:call-template name="object.id"/>
+  </xsl:variable>
+  <fo:table-row id="{$id}">
+    <xsl:apply-templates mode="seglist-table"/>
+  </fo:table-row>
+</xsl:template>
+
+<xsl:template match="seg" mode="seglist-table">
+  <fo:table-cell>
+    <fo:block>
+      <xsl:apply-templates/>
+    </fo:block>
+  </fo:table-cell>
+</xsl:template>
+
+<!-- ==================================================================== -->
+
+<xsl:template match="calloutlist">
+  <xsl:variable name="id">
+  <xsl:call-template name="object.id"/>
+  </xsl:variable>
+
+  <fo:block id="{$id}">
+    <xsl:if test="title">
+      <xsl:apply-templates select="title" mode="list.title.mode"/>
+    </xsl:if>
+
+    <!-- Preserve order of PIs and comments -->
+    <xsl:apply-templates 
+         select="*[not(self::callout or self::title or self::titleabbrev)]
+                   |comment()[not(preceding-sibling::callout)]
+		   |processing-instruction()[not(preceding-sibling::callout)]"/>
+
+    <fo:list-block space-before.optimum="1em"
+                   space-before.minimum="0.8em"
+                   space-before.maximum="1.2em"
+                   provisional-distance-between-starts="2.2em"
+                   provisional-label-separation="0.2em">
+      <xsl:apply-templates select="callout
+			        |comment()[preceding-sibling::calllout]
+				|processing-instruction()[preceding-sibling::callout]"/>
+    </fo:list-block>
+  </fo:block>
+</xsl:template>
+
+<xsl:template match="calloutlist/title">
+</xsl:template>
+
+<xsl:template match="callout">
+  <xsl:variable name="id"><xsl:call-template name="object.id"/></xsl:variable>
+  <fo:list-item id="{$id}">
+    <fo:list-item-label end-indent="label-end()">
+      <fo:block>
+        <xsl:call-template name="callout.arearefs">
+          <xsl:with-param name="arearefs" select="@arearefs"/>
+        </xsl:call-template>
+      </fo:block>
+    </fo:list-item-label>
+    <fo:list-item-body start-indent="body-start()">
+      <fo:block>
+	<xsl:apply-templates/>
+      </fo:block>
+    </fo:list-item-body>
+  </fo:list-item>
+</xsl:template>
+
+<xsl:template name="callout.arearefs">
+  <xsl:param name="arearefs"></xsl:param>
+  <xsl:if test="$arearefs!=''">
+    <xsl:choose>
+      <xsl:when test="substring-before($arearefs,' ')=''">
+        <xsl:call-template name="callout.arearef">
+          <xsl:with-param name="arearef" select="$arearefs"/>
+        </xsl:call-template>
+      </xsl:when>
+      <xsl:otherwise>
+        <xsl:call-template name="callout.arearef">
+          <xsl:with-param name="arearef"
+                          select="substring-before($arearefs,' ')"/>
+        </xsl:call-template>
+      </xsl:otherwise>
+    </xsl:choose>
+    <xsl:call-template name="callout.arearefs">
+      <xsl:with-param name="arearefs"
+                      select="substring-after($arearefs,' ')"/>
+    </xsl:call-template>
+  </xsl:if>
+</xsl:template>
+
+<xsl:template name="callout.arearef">
+  <xsl:param name="arearef"></xsl:param>
+  <xsl:variable name="targets" select="key('id',$arearef)"/>
+  <xsl:variable name="target" select="$targets[1]"/>
+
+  <xsl:choose>
+    <xsl:when test="count($target)=0">
+      <xsl:value-of select="$arearef"/>
+      <xsl:text>: ???</xsl:text>
+    </xsl:when>
+    <xsl:when test="local-name($target)='co'">
+      <xsl:apply-templates select="$target" mode="callout-bug"/>
+    </xsl:when>
+    <xsl:when test="local-name($target)='areaset'">
+      <xsl:call-template name="callout-bug">
+        <xsl:with-param name="conum">
+          <xsl:apply-templates select="$target" mode="conumber"/>
+        </xsl:with-param>
+      </xsl:call-template>
+    </xsl:when>
+    <xsl:when test="local-name($target)='area'">
+      <xsl:choose>
+        <xsl:when test="$target/parent::areaset">
+          <xsl:call-template name="callout-bug">
+            <xsl:with-param name="conum">
+              <xsl:apply-templates select="$target/parent::areaset"
+                                   mode="conumber"/>
+            </xsl:with-param>
+          </xsl:call-template>
+        </xsl:when>
+        <xsl:otherwise>
+          <xsl:call-template name="callout-bug">
+            <xsl:with-param name="conum">
+              <xsl:apply-templates select="$target" mode="conumber"/>
+            </xsl:with-param>
+          </xsl:call-template>
+        </xsl:otherwise>
+      </xsl:choose>
+    </xsl:when>
+    <xsl:otherwise>
+      <xsl:text>???</xsl:text>
+    </xsl:otherwise>
+  </xsl:choose>
+</xsl:template>
+
+<!-- ==================================================================== -->
+
+</xsl:stylesheet>
+
diff --git a/tags/v_3.062/doc/guide.bbl b/tags/v_3.062/doc/guide.bbl
new file mode 100644
index 0000000000000000000000000000000000000000..cdfc64ca0ae0ad4776726bef85c5615c06639996
--- /dev/null
+++ b/tags/v_3.062/doc/guide.bbl
@@ -0,0 +1,16 @@
+\ifx\undefined\bysame
+\newcommand{\bysame}{\leavevmode\hbox to\leftmargin{\hrulefill\,\,}}
+\fi
+\begin{thebibliography}{xx}
+
+\harvarditem[Collard and Juillard]{Collard and Juillard}{2001}{COLL/JUIL/01a}
+{ Collard, F. and M.~Juillard}, Accuracy of stochastic perturbation methods:
+  The case of asset pricing models, {\it Journal of Economic Dynamics and
+  Control}, 2001, {\it 25}, 979--999.
+
+\harvarditem[Schmitt-Grohe and Uribe]{Schmitt-Grohe and Uribe}{2002}{SGU/02}
+{ Schmitt-Grohe, S. and M.~Uribe}, {\it Solving Dynamic General Equilibrium
+  Models Using a Second-Order Approximation to the Policy Function}, technical
+  working paper, Rutgers Univsersity 2002.
+
+\end{thebibliography}
diff --git a/tags/v_3.062/doc/guide.blg b/tags/v_3.062/doc/guide.blg
new file mode 100644
index 0000000000000000000000000000000000000000..54ae1ee8a253a7d597bb57b70049f5ab738e83a6
--- /dev/null
+++ b/tags/v_3.062/doc/guide.blg
@@ -0,0 +1,9 @@
+This is BibTeX, Version 0.99cThe top-level auxiliary file: guide.aux
+The style file: Usmad.bst
+Database file #1: michel.bib
+I was expecting a `,' or a `}'---line 248 of file michel.bib
+ : 
+ : journal = "Computational Economics",
+(Error may have been on previous line)
+I'm skipping whatever remains of this entry
+(There was 1 error message)
diff --git a/tags/v_3.062/doc/guide.tex b/tags/v_3.062/doc/guide.tex
new file mode 100644
index 0000000000000000000000000000000000000000..4aa2c09f54bb044cd533db729afdb49e889a3f43
--- /dev/null
+++ b/tags/v_3.062/doc/guide.tex
@@ -0,0 +1,346 @@
+\documentclass[11pt,a4paper]{article}
+\usepackage{bibmad,graphicx,latexsym,amssymb,times}
+\usepackage[cp850]{inputenc}
+
+\begin{document}
+\title{Stochastic simulations with {\sc Dynare}. A practical guide.}
+\author{Fabrice Collard (GREMAQ, University of Toulouse)\\Adapted for Dynare 2.5.2\\ by Michel Juillard (CEPREMAP and University Paris 8)}
+\date{First draft: February 2001\hspace{10mm}This draft: January 2003.}
+\maketitle
+This document describes a model involving both endogenous and exogenous state variable. We first describe the theoretical model, before showing how the perturbation method is implemented in {\sc Dynare} (MATLAB version). 
+
+\section{A theoretical model} 
+We consider an economy that consists of a large number of dynastic households and a large number of firms. Firms are producing a homogeneous final product that can be either consumed or invested by means of capital and labor services. Firms own their capital stock and hire labor supplied by the households. Households own the firms. In each and every period three perfectly competitive markets open --- the markets for consumption goods, labor services, and financial capital in the form of firms' shares. 
+Household preferences are characterized by the lifetime utility function:
+\begin{equation}
+  E_t\sum_{\tau=t}^{\infty}{\beta^\star}^{\tau-t} \left(\log(c_t)-\theta\frac{h_t^{1+\psi}}{1+\psi}\right)
+  \label{eq:ut}
+\end{equation}
+\noindent where $0<\beta^\star<1$ is a constant discount factor, $c_t$ is consumption in period
+$t$, $h_t$ is the fraction of total available time devoted to productive activity in period $t$, $\theta>0$ and $\psi\geqslant 0$. We assume that there exists a central planner that determines hours, consumption and capital accumulation maximizing the household's utility function subject to the following budget constraint 
+\begin{equation}
+  c_t+i_t=y_t
+  \label{eq:bud}
+\end{equation}
+\noindent where $i_t$ is investment and $y_t$ is output. Investment is used to form physical capital, which accumulates in the standard form as:
+\begin{equation}
+k_{t+1}=\exp(b_t) i_t+(1-\delta)k_t \mbox{ with } 0<\delta<1
+\label{eq:acc}
+\end{equation}
+where $\delta$ is the constant physical depreciation rate. $b_t$ is a shock affecting incorporated technological progress, which properties will be defined later.
+
+Output is produced by means of capital and labor services, relying on a constant returns to scale technology represented by the following Cobb--Douglas production function:
+\begin{equation}
+ y_t=\exp(a_t) k_t^\alpha h_t^{1-\alpha} \mbox{ with }0<\alpha<1 \label{eq:prod}
+\end{equation}
+$a_t$ represents a stochastic shock to technology or Solow residual. We assume that the shocks to technology are distributed with zero mean, but display both persistence across time and correlation in the current period.
+Let us consider the joint process $(a_t,b_t)$ defined as
+\begin{equation}
+\left(
+\begin{array}{c}
+a_t\\b_t
+\end{array}
+\right)=
+\left(
+\begin{array}{cc}
+\rho&\tau\\
+\tau&\rho\\ 
+\end{array}
+\right)\left(
+\begin{array}{c}
+a_{t-1}\\b_{t-1}
+\end{array}
+\right)
++\left(
+\begin{array}{c}
+\varepsilon_t\\ \nu_t
+\end{array}
+\right)  \label{eq:process}
+\end{equation}
+where $|\rho+\tau|<1$ and $|\rho-\tau|<1 $ for sake of stationarity and 
+\begin{eqnarray*}
+E(\varepsilon_t)&=& 0,\\
+E(\nu_t)&=& 0,\\
+E(\varepsilon_t\varepsilon_s)&=&\left\{
+\begin{array}{lcl}
+\sigma^2_\varepsilon & \mbox{ if } & t=s \\
+0 & \mbox{ if } & t\neq s \\
+\end{array}\right. \mbox{, }\\ 
+E(\nu_t\nu_s)&=&\left\{
+\begin{array}{lcl}
+\sigma^2_\nu & \mbox{ if } & t=s \\
+0 & \mbox{ if } & t\neq s \\
+\end{array}\right. \mbox{, } \\
+E(\varepsilon_t\nu_s)&=&\left\{
+\begin{array}{lcl}
+\varphi\sigma_\varepsilon\sigma_\nu & \mbox{ if } & t=s \\
+0 & \mbox{ if } & t\neq s \\
+\end{array}\right. \mbox{. } 
+\end{eqnarray*}
+
+ 
+\section{Dynamic Equilibrium}
+The dynamic equilibrium of this economy follows from the first order conditions for optimality: 
+\begin{eqnarray*}
+&&c_t \theta h_t^{1+\psi}=(1-\alpha) y_t \\
+&&\beta E_t\left[\left(\frac{\exp(b_t) c_t}{\exp(b_{t+1})c_{t+1}}\right)\left(\exp(b_{t+1})\alpha \frac{y_{t+1}}{k_{t+1}}+1-\delta\right)\right]=1\\
+&&y_t=\exp(a_t) k_t^\alpha h_t^{1-\alpha} \\
+&&k_{t+1}=\exp(b_t)(y_t-c_t)+(1-\delta)k_t \\
+&&a_t=\rho a_{t-1}+\tau b_{t-1}+\varepsilon_t \\
+&&b_t=\tau a_{t-1}+\rho b_{t-1}+\nu_t 
+\end{eqnarray*}
+\section{The {\sc dynare} code}
+The dynare code is straightforward to write, as the equilibrium is written in the natural way. The whole code is reported at the end of the section. Before that we proceed step by step.
+\paragraph{Preamble}
+The preamble consists of the some declarations to setup the number of periods the model should be simulated, the endogenous and exogenous variables, the parameters and assign values to these parameters. 
+\begin{enumerate}
+\item {\tt periods 20100}; specifies that the model will be simulated over 20100 periods in order to compute the moments of the simulated variables.
+\item {\tt var y, c, k, h, a, b;} specifies the endogenous variables in the model since we have output ({\tt y}), consumption ({\tt c}), capital ({\tt k}), hours ({\tt h}) and the two shocks ({\tt a, b}).
+\item {\tt varexo e, u}; specifies the exogenous variables in the model --- namely the innovations of the shocks, since we have the innovation of the non--incorporated shock ({\tt e}), and the innovation of the incorporated shock ({\tt u}).
+\item {\tt parameters list;} specifies the list of parameters of the model. In the case we are studying:
+
+{\tt parameters beta, alpha, delta, theta, psi, rho, tau}
+
+\begin{tabular}{ll}
+\hline
+\hline
+{\tt beta}  & discount factor                               \\
+{\tt alpha} & capital elasticity in the production function \\
+{\tt delta} & depreciation rate                             \\
+{\tt theta} & disutility of labor parameter                 \\
+{\tt psi}   & labor supply elasticity                       \\
+{\tt rho}   & persistence                                   \\
+{\tt tau}   & cross--persistence                            \\
+\hline
+\hline
+\end{tabular}
+\item Assignment of parameter values. This is done the standard way in MATLAB. For example, we write
+
+\begin{verbatim}
+alpha = 0.36;
+rho   = 0.95;
+tau   = 0.025;
+beta  = 0.99;
+delta = 0.025;
+psi   = 0;
+theta = 2.95;
+\end{verbatim}
+
+
+\item Note that $\varphi$, the conditional correlation of the shocks, is not, strickly speaking, a parameter of the recursive equations and doesn't need to be listed in the {\tt parameters} instruction. It may however be convenient to express it as a parameter in the expression of the variance--covariance matrix of the shocks (see below) and one may simply write:
+
+{\tt phi = 0.1; }
+
+\end{enumerate}
+
+\paragraph{Declaration of the model:}
+This step is done in a straightforward way. It starts with the instruction {\tt model;} and ends with {\tt end;}, in between all equilibrium conditions are written exactly the way we write it ``by hand''. However, there is a simple rule that should be kept in mind when the model is written. Let us consider a variable $x$: 
+\begin{itemize}
+\item If $x$ is decided in period $t$ then we simply write ${\tt x}$. 
+\item When the variable is decided in $t-1$, such as the capital stock in our simple model, we write $x(-1)$. \item Finally, when a variable is decided in the next period, $t+1$, such as consumption in the Euler equation, we write $x(+1)$. 
+\end{itemize}
+Hence the required code to declare our model in {\sc Dynare} will be:
+\begin{verbatim}
+model;
+c*theta*h^(1+psi)=(1-alpha)*y;
+k = beta*(((exp(b)*c)/(exp(b(+1))*c(+1)))*
+    (exp(b(+1))*alpha*y(+1)+(1-delta)*k));
+y = exp(a)*(k(-1)^alpha)*(h^(1-alpha));
+k = exp(b)*(y-c)+(1-delta)*k(-1);
+a = rho*a(-1)+tau*b(-1) + e;
+b = tau*a(-1)+rho*b(-1) + u;
+end;
+\end{verbatim}
+Assume now that we want to take a Taylor series expansion in logs rather than in level, we just rewrite the model as
+\begin{verbatim}
+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;
+\end{verbatim}
+so that the level of consumption is actually given by ${\tt exp(c)}$.
+\paragraph{Solving the model}
+\begin{enumerate} 
+\item Now we need to provide numerical initial conditions for the computation of the deterministic steady state. This is done with the sequence between {\tt initval;} and {\tt end;}. Each variable, endogenous or exogenous, should be initialized. In our example, we give the exact values of the deterministic equilibrium in absence of shocks. This takes the form
+\begin{verbatim}
+initval;
+y = 1.08068253095672;
+c = 0.80359242014163;
+h = 0.29175631001732;
+k = 11.08360443260358;
+a = 0;
+b = 0;
+e = 0;
+u = 0;
+end;
+\end{verbatim}
+
+Alternatively, we could provide only approximated values. {\sc Dynare} would then automatically compute the exact values.
+
+\item We then specify the innovations and their matrix of variance--covariance. This is done using the {\tt Sigma\_e} command. As the matrix is symmetrical, one enters onlys the upper (or lower) triangular part:
+\begin{verbatim}
+Sigma_e = [ 0.000081, (phi*0.009*0.009); ...
+             0.000081];
+\end{verbatim}
+where the variance of both innovations is set to {\tt 0.000081} and the correlation between them is equal to $\varphi$. Note that if an element is computed as an expression, this expression must be put in parenthese. In the {\tt Sigma\_e} command, the shock variables are ordered as in the {\tt varexo} declaration.
+ 
+Alternatively, it is possible to use a {\tt shock;} and {\tt end;} block and declare only the nonzero elements of the covariance matrix:
+\begin{verbatim}
+shocks;
+var e = 0.009^2;
+var u = 0.009^2;
+var e,u =  phi*0.009*0.009;
+end; 
+\end{verbatim}
+Note that in the current version of {\sc Dynare}, it isn't possible to shut down of shock by assigning it a zero variance. To shut down a shock the variable must be removed from the {\tt varexo} and {\tt initval} list, added to the {\tt parameters} list and assigned a value of zero.
+
+\item The model is then solved and simulated using the {\tt stoch\_simul;} command. By default, the coefficients of the approximated decision rules are reported as well as the moments of the simulated variables and impulse response functions for each exogenous shocks are ploted. In addition, the following options are aavailable:
+\begin{itemize}
+\item {\tt DR\_ALG0 = [0,1]}: Specify the algorithm used to compute the quadratic approximation of the decision rules. [0] (default) uses a ``pure'' perturbation method as in \cite{SGU/02}; [1] moves the point around which the Taylor approximation is computed toward the mean of the distribution as in  \cite{COLL/JUIL/01a}.  
+\item AR = Integer
+Order of autocorrelation coefficients to compute and to print (default = 5)
+\item NOCORR
+Doesn't print the correlation matrix (default = PRINT)
+\item DROP = Integer
+Number of points dropped at the beginning of simulation before computing the summary statistics (default = 100)
+\item IRF = Integer
+Number of periods on which to compute the IRFs (default = 40)
+\item NOFUNCTIONS
+Doesn't print the coefficients of the approximated solution
+\item LINEAR
+Indicates that the original model is linear
+\item NOMOMENTS
+Doesn't print moments of the endogenous variables 
+\item ORDER = [1,2]
+Order of Taylor approximation (default = 2)
+\item REPLIC = Integer
+Number of simulated series used to compute the IRFs (default = 1, if order = 1, and 50 otherwise)
+\end{itemize} 
+The simulated trajectories are returned in MATLAB vectors named as the variables (be careful not to use MATLAB reserved names such as INV for your variables \ldots). Note that the specification of the variance--covariance matrix of the shocks is enough to compute a second order approximation of the policy function. In addition, for the simulation and the computation of moments, {\sc Dynare} assumes that the shocks follow a normal distribution.
+
+In our example, we use simply 
+\begin{verbatim}
+stoch_simul;
+\end{verbatim}
+
+If one wants to use the algorithm in \cite{COLL/JUIL/01a} and to drop 200 initial values instead of 100, one would write
+\begin{verbatim}
+simul_stoch(dr_algo=1,drop=200);
+\end{verbatim}
+\end{enumerate}
+
+\clearpage
+
+\begin{center}
+{\sc Dynare code for the model in level}
+\end{center}
+Here is the model file for the model in level. The last instructions are regular MATLAB commands for graphics. It can be found in file {\tt example1.mod}.
+
+\begin{verbatim}
+periods 20100;
+
+var y, c, k, a, h, b;
+varexo e,u;
+
+parameters beta, rho, beta, 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*(((exp(b)*c)/(exp(b(+1))*c(+1)))
+    *(exp(b(+1))*alpha*y(+1)+(1-delta)*k));
+y = exp(a)*(k(-1)^alpha)*(h^(1-alpha));
+k = exp(b)*(y-c)+(1-delta)*k(-1);
+a = rho*a(-1)+tau*b(-1) + e;
+b = tau*a(-1)+rho*b(-1) + u;
+end;
+
+initval;
+y = 1.08068253095672;
+c = 0.80359242014163;
+h = 0.29175631001732;
+k = 11.08360443260358;
+a = 0;
+b = 0;
+e = 0;
+u = 0;
+end;
+
+Sigma_e = [ 0.000081, phi*0.009*0.009; 0.000081 ];
+stoch_simul;
+\end{verbatim}
+\newpage
+
+\begin{center}
+{\sc Dynare code for the model in logs}
+\end{center}
+Here is the model file for the model in logs. In this case, {\tt initval} only contains guessed values and {\tt steady} is used to compute and display the exact value of the deterministic equilibrium. The shocks are supposed to be uncorrelated. Also, Collard \& Juillard (2001) algorithm is used. The model file can be found in {\tt example2.mod}.
+
+\begin{verbatim}
+periods 20100;
+
+var y, c, k, a, h, b;
+varexo e,u;
+
+parameters beta, rho, beta, 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;
+
+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 = 0.1;
+c = -0.2;
+h = -1.2;
+k =  2.4;
+a = 0;
+b = 0;
+e = 0;
+u = 0;
+end;
+
+steady;
+
+shocks;
+var e = 0.009^2;
+var u = 0.009^2;
+end;
+
+stoch_simul(dr_algo=1,drop=200);
+\end{verbatim}
+\bibliographystyle{Usmad}
+\bibliography{/papers/biblio/michel}
+
+\end{document}
+
+
+
+
+
diff --git a/tags/v_3.062/doc/makefile b/tags/v_3.062/doc/makefile
new file mode 100644
index 0000000000000000000000000000000000000000..c715ec6ef256c9dc45ae6c007e2bddf1fc3c6552
--- /dev/null
+++ b/tags/v_3.062/doc/makefile
@@ -0,0 +1,17 @@
+all: guide.pdf manual.pdf manual/index.html
+
+guide.pdf: guide.tex
+	pdflatex guide
+
+manual/index.html: manual.xml
+	xsltproc -stringparam base.dir ./manual/ dynare_html.xsl manual.xml 
+
+
+manual.pdf: manual.xml
+	xsltproc dynare_fo.xsl manual.xml >manual.fo
+	pdfxmltex manual.fo	
+	pdfxmltex manual.fo	
+
+install: manual.pdf manual/index.html
+	scp manual.pdf pythie.cepremap.cnrs.fr:public_html/mambo/download/manual/
+	scp manual/* pythie.cepremap.cnrs.fr:public_html/mambo/download/manual/
diff --git a/tags/v_3.062/doc/manual.xml b/tags/v_3.062/doc/manual.xml
new file mode 100644
index 0000000000000000000000000000000000000000..5074fe14d8d6996294c4e546772c45b19be90f6b
--- /dev/null
+++ b/tags/v_3.062/doc/manual.xml
@@ -0,0 +1,2919 @@
+<?xml version="1.0"?>
+<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">
+
+<book>
+  <bookinfo>
+    <title>DYNARE MANUAL</title>
+    <subtitle>Version 3.0</subtitle>
+    <titleabbrev>DYNARE</titleabbrev>
+    <author><firstname>Michel</firstname><surname>Juillard</surname>
+<affiliation><orgname>CEPREMAP and University Paris 8</orgname></affiliation>
+<email>michel.juillard@cepremap.cnrs.fr</email>
+<address>
+<street>142 rue du Chevaleret</street>
+<postcode>75013</postcode><city>Paris</city><country>France</country>
+</address>
+</author>
+
+<copyright><year>1996, 2005</year><holder> Michel Juillard</holder>
+
+</copyright>
+<legalnotice>
+<para>
+Permission is granted to make and distribute verbatim copies of
+this manual provided the copyright notice and this permission notice
+are preserved on all copies.
+</para>
+
+<para>
+Permission is granted to copy and distribute modified versions of
+this manual under the conditions for verbatim copying, provided that
+the entire resulting derived work is distributed under the terms of
+a permission notice identical to this one.
+</para>
+<para>
+Permission is granted to copy and distribute translations of this
+manual into another language, under the above conditions for
+modified versions.
+</para>
+</legalnotice>
+<indexterm zone="Dynare"><primary>Dynare</primary></indexterm>
+<indexterm zone="var"><primary>var</primary></indexterm>
+<indexterm zone="varexo"><primary>varexo</primary></indexterm>
+<indexterm zone="varexo_det"><primary>varexo_det</primary></indexterm>
+<indexterm zone="parameters"><primary>parameters</primary></indexterm>
+<indexterm zone="model"><primary>model</primary></indexterm>
+<indexterm zone="initval"><primary>initval</primary></indexterm>
+<indexterm zone="endval"><primary>endval</primary></indexterm>
+<indexterm zone="histval"><primary>histval</primary></indexterm>
+<indexterm zone="shocks"><primary>shocks</primary></indexterm>
+<indexterm zone="periods"><primary>periods</primary></indexterm>
+<indexterm zone="simul"><primary>simul</primary></indexterm>
+<indexterm zone="check"><primary>check</primary></indexterm>
+<indexterm zone="stoch_simul"><primary>stoch_simul</primary></indexterm>
+<indexterm zone="estimated_params"><primary>estimated_params</primary></indexterm>
+<indexterm zone="estimated_params_init"><primary>estimated_params_init</primary></indexterm>
+<indexterm zone="estimated_params_bounds"><primary>estimated_params_bounds</primary></indexterm>
+<indexterm zone="varobs"><primary>varobs</primary></indexterm>
+<indexterm zone="observation_trends"><primary>observation_trends</primary></indexterm>
+<indexterm zone="estimation"><primary>estimation</primary></indexterm>
+<indexterm zone="rplot"><primary>rplot</primary></indexterm>
+<indexterm zone="dynasave"><primary>dynasave</primary></indexterm>
+<indexterm zone="dynatype"><primary>dynatype</primary></indexterm>
+<indexterm zone="unit_root_vars"><primary>unit_root_vars</primary></indexterm>
+<indexterm zone="olr"><primary>olr</primary></indexterm>
+<indexterm zone="olr_inst"><primary>olr_inst</primary></indexterm>
+<indexterm zone="optim_weights"><primary>optim_weights</primary></indexterm>
+<indexterm zone="osr"><primary>osr</primary></indexterm>
+<indexterm zone="osr_params"><primary>osr_params</primary></indexterm>
+<indexterm zone="define"><primary>@define</primary></indexterm>
+<indexterm zone="forecast"><primary>forecast</primary></indexterm>
+<indexterm zone="if_elseif_else_end"><primary>@if...@elseif...@else...@end</primary></indexterm>
+  </bookinfo>
+
+<preface><title>Preface</title><para>
+Dynare is a pre-processor and a collection of Matlab, Scilab or Gauss routines which solve, simulate and estimate non-linear
+models with forward looking variables. It is the result of research carried at
+CEPREMAP by several people (see Laffargue, 1990, Boucekkine, 1995, and
+Juillard, 1996, Collard and Juillard 2001a and 2001b).
+</para>
+<para>
+When the framework is deterministic, Dynare can be used for models with the assumption of perfect
+foresight. Typically, the system is supposed to be in a state of
+equilibrium before a period ``1'' when the news of a contemporaneous
+or of a future shock is learned by the agents in the model. The
+purpose of the simulation is to describe the reaction in anticipation of,
+then in reaction to the shock, until the system returns to the old or
+to a new state of equilibrium. In most models, this return to
+equilibrium is only an asymptotic phenomenon, which one must
+approximate by an horizon of simulation far enough in the future.
+Another exercise for which Dynare is well suited is to study the
+transition path to a new equilibrium following a permanent shock.
+</para>
+<para>
+For deterministic simulations, Dynare uses a Newton-type algorithm, first
+proposed by Laffargue (1990), instead of a first order technique like
+the one proposed by Fair and Taylor (1983), and used in earlier generation simulation programs. We believe
+this approach to be in general both faster and more robust. The
+details of the algorithm used in Dynare can be found in Juillard (1996).
+</para>
+<para>
+In a stochastic context, Dynare computes one or several simulations corresponding to a random draw of the shocks. Starting with version 2.3 (not available for Gauss), Dynare uses a second order Taylor approximation of the expectation functions (see Judd, 1996, Collard and Juillard, 2001a, 2001b, and Schmitt-Grohe and Uribe, 2002).
+</para>
+<para>
+Starting with version 3.0, it is possible to use Dynare to estimate model parameters either by maximum likelihood as in Ireland (2004) or using a Bayesian approach as in Rabanal and Rubio-Ramirez (2002), Schorfheide (2000) or Smets and Wouters (2002).
+</para>
+
+<para>
+Currently the development team of Dynare is composed of S. Adjemian, M. Juillard and O. Kamenik. Several parts of Dynare use or have strongly benefited from publicly available programs by F. Collard, L. Ingber, P. Klein, S. Sakata, F. Schorfheide, C. Sims, P. Soederlind and R. Wouters.  
+</para>
+
+<section><title>Changes</title>
+<para>December 30, 2005</para>
+<itemizedlist>
+<listitem><para>added details about parameter transformation in <xref linkend="model"/> and in <xref linkend="estimated_params"/></para></listitem>
+<listitem><para>added conditional compilation commands <xref linkend="define"/> and <xref linkend="if_elseif_else_end"/></para></listitem>
+<listitem><para>enhanced output section of command <xref linkend="estimation"/></para></listitem>
+<listitem><para>added exogenous deterministic shocks in stochastic models. See <xref linkend="varexo_det"/>, <xref linkend="forecast"/>, <xref linkend="shocks"/>, <xref linkend="stoch_simul"/></para></listitem>
+<listitem><para>added a forecast command for calibrated models. See <xref linkend="forecast"/>.</para></listitem>
+</itemizedlist>
+<para>October 14, 2005</para>
+<itemizedlist>
+<listitem><para>added syntax for computing optimal policy. See <xref linkend='olr'/>, <xref linkend='olr_inst'/>, <xref linkend='optim_weights'/>, <xref linkend='osr'/>, <xref linkend='osr_params'/>.</para></listitem>
+<listitem><para>added syntax for estimating correlation between two shocks or two measurment errors in <xref linkend="estimated_params"/>, <xref linkend="estimated_params_bounds"/> and <xref linkend="estimated_params_init"/>
+</para></listitem>
+</itemizedlist>
+<para>July 20, 2005</para>
+<itemizedlist>
+<listitem><para>Expanded description of <xref linkend="unit_root_vars"/> statement</para></listitem>
+<listitem><para>changed the default for nonlinear solver in <xref linkend="steady"/></para></listitem>
+<listitem><para>added a mention of the possibility to write explicitly a steady state function in <xref linkend="steady"/>, <xref linkend="stoch_simul"/>, <xref linkend="estimation"/> and <xref linkend="unit_root_vars"/></para></listitem>
+<listitem><para>added a brief <emphasis>Ouput</emphasis> section in <xref linkend="estimation"/></para></listitem>
+<listitem><para>corrected misleading description of option <command>prefilter</command> in <xref linkend="estimation"/></para></listitem>
+<listitem><para>added variance decomposition among the statistics computed with option <command>moments_varendo</command> in <xref linkend="estimation"/></para></listitem>
+<listitem><para>tex option in <xref linkend="estimation"/> isn't yet implemented</para></listitem>
+</itemizedlist>
+<para>May 3, 2005</para>
+<itemizedlist>
+<listitem><para>added option <command>noprint</command> in <xref linkend="stoch_simul"/></para></listitem>
+<listitem><para>modified option <command>irf</command> in <xref linkend="stoch_simul"/></para></listitem>
+<listitem><para>modified option <command>simul_seed</command> in <xref linkend="stoch_simul"/></para></listitem>
+</itemizedlist>
+<para>March 6, 2005</para>
+<itemizedlist>
+<listitem><para>corrected typos in equations for 1st and 2nd order approximation formulas in <xref linkend="stoch_simul"/>.</para></listitem>
+<listitem><para>temporarily removed description of output variables in <xref linkend="estimation"/> as old content was outdated and the new one isn't ready yet.</para></listitem>
+<listitem><para>added cross-references</para></listitem>
+</itemizedlist>
+</section>
+</preface>
+
+<chapter><title>Introduction</title>
+
+<para>
+In order to give instructions to Dynare, the user has to write a <emphasis>model file</emphasis> whose file name must terminate by ".mod". This file contains the description of the model and the computing tasks required by the user.
+</para>
+<para>
+In practice, the handling of your model file is done in two
+steps: in the first one, the model and the processing instructions
+written by the user in a <emphasis>model file</emphasis> are
+interpreted and the proper Gauss, Matlab or Scilab instructions are generated; in the
+second step, the program actually runs the computations. Both steps
+are triggered by a single keyword: <command>Dynare</command>.
+</para>
+
+<sect1><title>Software requirements</title>
+<para>
+This version of Dynare works only under Windows 98/NT/2000/XP. For a Unix version, please, write me.
+</para>
+<para>
+The Matlab version has been written with Matlab 6.5.1.
+</para>
+<para>
+The Scilab version has been tested with Scilab 3.0.
+</para>
+<para>
+The Gauss version of Dynare has been written with Gauss version 3.2. It most likely doesn't work with previous versions.
+</para>
+</sect1>
+
+<sect1><title>Installation</title>
+<para>
+In case of update from a previous version, it is a good idea to copy
+the old version in a backup directory so as to be able to revert to it
+in case of problems. None of the previous files are usefull anymore, so you are strongly encouraged to remove them from directory <filename>c:\dynare</filename>. The Matlab version of Dynare lets you now easily have different versions of Dynare on your computer.
+</para>
+
+<para>
+After installation, Dynare can be used in any directory on your computer. It is best practive to keep your model files in directories different from the one containing the Dynare toolbox. That way you can upgrade Dynare and discard the previous version without having to worry about your own files.
+</para>
+ 
+<sect2><title>Installing the Matlab version</title>
+<para>
+Starting with version 3.0, by default, Dynare is installed in a directory whose name contains the version number. For example
+<informalexample><programlisting>
+Dynare_v3.0
+</programlisting>
+</informalexample>
+This directory contains several sub-directories, among which <filename>matlab</filename>, <filename>doc</filename> and <filename>examples</filename>.
+</para>
+<para>
+After unpacking the archive, start the Matlab program and use the menu <command>File/Set path</command> to add the path to Dynare <filename>matlab</filename> subdirectory. For example
+<informalexample>
+<programlisting>
+c:\dynare_v3.0\matlab
+</programlisting>
+</informalexample>
+</para>
+</sect2>
+
+
+<sect2><title>Installing the Scilab version</title>
+<para>
+Unpack the zip file in the directory <filename>c:\</filename> (If you want to use another
+directory, see below). The Scilab version in automatically installed in <filename>c:\dynare\scilab</filename>.
+</para>
+<para>
+Then, find the <filename>scilab.star</filename> file, in the top directory of your Scilab distribution. Edit this file and add the following line after similar statements:
+<informalexample>
+<programlisting>
+load('c:/dynare/scilab/lib');
+</programlisting>
+</informalexample>
+</para>
+<para>
+If you installed Dynare for Scilab in a directory different from <filename>c:\dynare\scilab</filename>, change the above instructions accordingly and edit the following line in <filename>Dynare.sci</filename>
+<informalexample>
+<programlisting>
+command = 'c:\dynare\scilab\dynare_s '+fname;
+</programlisting>
+</informalexample>
+Then, restart Scilab and run the command <command>uplib()</command>.
+</para>
+</sect2>
+
+<sect2><title>Installing the Gauss version</title>
+<para>
+Unpack the zip file in the directory <filename>c:\</filename> (If you want to use another
+directory, see below). The Gauss version in automatically installed in <filename>c:\dynare\gauss</filename>.
+</para>
+<para>
+If you had any previous version of Dynare, use the Gauss editor or any text editor to remove all references to it from the library file <filename>user.lcg</filename>.
+</para>
+<para>
+After unpacking the archive, start the Gauss program and type the following:
+<informalexample>
+<programlisting>
+   library pgraph
+   lib user c:\dynare\gauss\dynare.src
+   lib user c:\dynare\gauss\dynare1.src
+   lib user c:\dynare\gauss\dynare2.src
+   lib user c:\dynare\gauss\dynare3.src
+</programlisting>
+</informalexample>
+</para>
+<para>
+If you installed Dynare for Gauss in a directory different from <filename>c:\dynare\gauss</filename>, change the above instructions accordingly and edit the following line in <filename>Dynare.src</filename>
+<informalexample>
+  <programlisting>
+declare string PARSER = "c:\\dynare\\gauss\\dynare_g ";
+  </programlisting>
+</informalexample>
+</para>
+</sect2>
+
+</sect1>
+</chapter>
+
+<chapter><title>Commands</title>
+<para>
+Dynare commands are either single instructions or a block of instructions. Each single instructions or block elements are terminated by <command>;</command>. Block of instructions are terminated by <command>end;</command>.
+</para>
+
+<para>
+Most Dynare commands have arguments and several accept options, indicated in parentheses after the command keyword.
+</para>
+<para>
+In the description of Dynare commands, the following conventions are observed:
+<itemizedlist>
+<listitem><para>optional arguments or options are indicated between square brackets <command>[]</command></para></listitem>
+<listitem><para>repreated arguments are indicated by ellipses <command>...</command></para></listitem>
+<listitem><para><command><replaceable>INTEGER</replaceable></command> indicates an integer number</para></listitem>
+<listitem><para><command><replaceable>DOUBLE</replaceable></command> indicates a double precision number. The following syntaxes are valid: 1.1e3, 1.1E3, 1.1d3, 1.1D3.</para></listitem>
+<listitem><para><command><replaceable>EXPRESSION</replaceable></command> indicates a mathematical expression valid in the underlying language (Matlab, Scilab or Gauss)</para></listitem>
+<listitem><para><command><replaceable>VARIABLE_NAME</replaceable></command> indicates a variable name starting with an alphabetical character and can't contain ()+-*/^=!;:@#. or accentuated characters</para></listitem>
+<listitem><para><command><replaceable>PARAMETER_NAME</replaceable></command> indicates a parameter name starting with an alphabetical charcater and can't contain ()+-*/^=!;:@#. or accentuated characters</para></listitem>
+<listitem><para><command><replaceable>FILENAME</replaceable></command> indicates a file name valid under your operating system (Windows, Linux or Unix)</para></listitem>
+</itemizedlist>
+</para>
+
+<sect1><title>Executing Dynare</title>
+
+<refentry id="Dynare">
+  <refmeta>
+    <refentrytitle>dynare</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>dynare</refname>
+    <refpurpose>executes Dynare</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>dynare</command>
+      <arg choice="plain">
+      <replaceable>FILENAME</replaceable>[.mod]
+      </arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>Description</title>
+<para>
+<command>dynare</command> executes instruction included in <filename>filename.mod</filename>.
+<filename>filename.mod</filename> is the name of the model file containing the
+model and the processing instructions.
+</para>
+</refsect1>
+
+<refsect1><title>Details</title>
+<para>
+In Matlab, <command>dynare</command> creates three intermediary files:
+<itemizedlist spacing='compact'>
+<listitem><para> <filename>filename.m</filename> with the instructions for the simulations</para></listitem>
+<listitem><para> <filename>filename_ff.m</filename> with the dynamic model equations</para></listitem>
+<listitem><para> <filename>filename_fff.m</filename> with the long run static model equations</para></listitem>
+</itemizedlist>
+</para>
+<para>
+In Scilab, <command>dynare</command> creates three intermediary files:
+<itemizedlist spacing='compact'>
+<listitem><para> <filename>filename.sci</filename> with the instructions for the simulations</para></listitem>
+<listitem><para> <filename>filename_ff.sci</filename> with the dynamic model equations</para></listitem>
+<listitem><para> <filename>filename_fff.sci</filename> with the long run static model equations</para></listitem>
+</itemizedlist>
+</para>
+<para>
+In Gauss, <command>dynare</command> creates an intermediary file <filename>filename.gau</filename> with the instructions for the simulations. The Gauss version still accepts the former <filename>.mdl</filename> extension, but it is now deprecated.
+</para>
+<para>
+These files may be looked at to understand errors reported at the simulation stage.
+</para>
+</refsect1>
+
+<refsect1><title>Output</title>
+<para>
+Depending on the computing tasks requested in the *.mod file, executing command <command>dynare</command> will leave in the workspace variables containing results available for further processing. More details are given under the relevant computing tasks.
+</para>
+
+<para>
+Under Matlab, some results are also saved in a file called <replaceable>FILENAME</replaceable><filename>_results.mat</filename>. Currently, this file contains when available the structures <varname>dr_</varname> and <varname>oo_</varname>.
+</para>
+</refsect1>
+
+<refsect1><title>Examples</title>
+<programlisting>
+dynare ramst
+</programlisting>
+<para>or</para>
+<programlisting>
+dynare ramst.mod
+</programlisting>
+</refsect1>
+</refentry>
+</sect1>
+
+<sect1><title>General declarations</title>
+
+<para>General declarations of variables and parameters are made with the following commands:</para>
+<itemizedlist>
+<listitem><para><xref linkend='periods'/> (deprecated)</para></listitem>
+<listitem><para><xref linkend='var'/></para></listitem>
+<listitem><para><xref linkend='varexo'/></para></listitem>
+<listitem><para><xref linkend='varexo_det'/></para></listitem>
+<listitem><para><xref linkend='parameters'/></para></listitem>
+</itemizedlist>
+
+<refentry id="periods">
+  <refmeta>
+    <refentrytitle>periods</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>periods</refname>
+    <refpurpose>specifies the number of simulation periods</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>periods</command> <arg choice="plain">
+      <replaceable>INTEGER</replaceable>;
+      </arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>Description</title>
+<para>
+This command is now deprecated (but will still work for older model files). It is not necessary when no simulation is performed and is replaced by an option PERIODS in SIMUL and STOCH_SIMUL.
+</para>
+<para>
+Set the number of periods in the simulation. The periods are numbered from 1 to <replaceable>INTEGER</replaceable>. In perfect foresight simulations, it is assumed that all future events are perfectly known at the beginning of period 1.
+</para>
+</refsect1>
+
+<refsect1><title>Example</title>
+<programlisting>
+periods 100;
+</programlisting>
+</refsect1>
+</refentry>
+
+<refentry id="var">
+  <refmeta>
+    <refentrytitle>var</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>var</refname>
+    <refpurpose>declares endogenous variables</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>var</command>
+      <arg choice="plain">
+	<replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+      <arg>
+	,
+      </arg>
+      <arg rep="repeat">
+	<replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+    <arg choice="plain">;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>Description</title>
+<para>
+This required command declares the endogenous variables in the model. The variable names must start with a letter and can't contain the following characters : ()+-*/^=!;:@#. or accentuated characters.
+</para>
+<para>
+In Gauss, setting <varname>_longname = 1</varname> allows the use of more than 8 characters in the variable names and makes a distinction between lower and upper case letters.
+</para>
+</refsect1>
+
+<refsect1><title>Example</title>
+<programlisting>
+var c gnp q1 q2;
+</programlisting>
+</refsect1>
+</refentry>
+
+<refentry id="varexo">
+  <refmeta>
+    <refentrytitle>varexo</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>varexo</refname>
+    <refpurpose>declares exogenous variables</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>varexo</command>
+      <arg choice="plain">
+	<replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+      <arg>
+	,
+      </arg>
+      <arg rep="repeat">
+	<replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+    <arg choice="plain">;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>Description</title>
+<para>
+This optional command declares the exogenous variables in the model. See command <xref linkend="var"/> for the syntax of <replaceable>VARIABLE_NAME</replaceable>.
+</para>
+<para>
+Exogenous variables are required if the user wants to be able to apply shocks to her model. 
+</para>
+</refsect1>
+
+<refsect1><title>Example</title>
+<programlisting>
+varexo m gov;
+</programlisting>
+</refsect1>
+</refentry>
+
+<refentry id="varexo_det">
+  <refmeta>
+    <refentrytitle>varexo_det</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>varexo_det</refname>
+    <refpurpose>declares exogenous deterministic variables in a stochastic  model</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>varexo_det</command>
+      <arg choice="plain">
+	<replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+      <arg>
+	,
+      </arg>
+      <arg rep="repeat">
+	<replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+    <arg choice="plain">;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>Description</title>
+<para>
+This optional command declares exogenous deterministic variables in a stochastic model. See command <xref linkend="var"/> for the syntax of <replaceable>VARIABLE_NAME</replaceable>.
+</para>
+<para>It is possible to mix deterministic and stochastic shocks to build models where agents know from the start of the simulation about future exogenous changes. In that case <xref linkend="stoch_simul"/> will compute the rational expectation solution adding future information to the state space (nothing is shown in the output of <xref linkend="stoch_simul"/>) and <xref linkend="forecast"/> will compute a simulation conditional on initial  conditions and future information.
+</para>
+</refsect1>
+
+<refsect1><title>Example</title>
+<programlisting>
+varexo m gov;
+varexo_det tau;
+</programlisting>
+</refsect1>
+</refentry>
+
+<refentry id="parameters">
+  <refmeta>
+    <refentrytitle>parameters</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>parameters</refname>
+    <refpurpose>declares parameters</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>parameters</command>
+      <arg choice="plain">
+	<replaceable>PARAMETER_NAME</replaceable>
+      </arg>
+      <arg>
+	,
+      </arg>
+      <arg rep="repeat">
+	<replaceable>PARAMETER_NAME</replaceable>
+      </arg>
+    <arg choice="plain">;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>Description</title>
+<para>
+This optional command declares parameters used in the model, in variable initialization or in shock declarations. The parameters must then be assigned values using standard syntax of underlying matrix programming language. Be carefull not to use names reserved by Dynare or the underlying language (Matlab, Scilab or Gauss).
+</para>
+</refsect1>
+
+<refsect1><title>Example</title>
+<programlisting>
+parameters alpha, bet;
+
+alpha = 0.3;
+bet = sqrt(2);
+</programlisting>
+</refsect1>
+</refentry>
+</sect1>
+
+<sect1><title>Model declaration</title>
+
+<para>The model is declared inside a <xref linkend="model"/> block.</para>
+
+<refentry id="model">
+  <refmeta>
+    <refentrytitle>model</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>model</refname>
+    <refpurpose>declares the model equations</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>model</command>
+      <arg>
+	(linear)
+      </arg>
+      <arg choice="plain">
+      ;
+      </arg><sbr/>
+      <arg choice="plain">
+	<synopfragmentref linkend="pound_exp">MATLAB EXPRESSION</synopfragmentref>;
+      </arg><sbr/>
+      <arg rep="repeat">
+	<synopfragmentref linkend="pound_exp">MATLAB EXPRESSION</synopfragmentref>;
+      </arg><sbr/>
+      <arg choice="plain">
+	end;
+      </arg>
+
+      <arg choice="plain">
+	<synopfragmentref linkend="eq">EQUATION</synopfragmentref>;
+      </arg><sbr/>
+      <arg rep="repeat">
+	<synopfragmentref linkend="eq">EQUATION</synopfragmentref>;
+      </arg><sbr/>
+      <arg choice="plain">
+	end;
+      </arg>
+
+      <synopfragment id="pound_exp">
+	<arg choice="plain">#<replaceable>EXPRESSION</replaceable></arg>
+	<arg>= #<replaceable>EXPRESSION</replaceable></arg>
+	<arg choice="plain">;</arg>
+      </synopfragment>
+
+      <synopfragment id="eq">
+	<arg choice="plain"><replaceable>EXPRESSION</replaceable></arg>
+	<arg>= <replaceable>EXPRESSION</replaceable></arg>
+	<arg choice="plain">;</arg>
+      </synopfragment>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>Description</title>
+<para>
+The equations of the model are written in a block delimited by <command>model;</command> and <command>end;</command>.
+</para>
+<para>
+There must be as many equations as there are endogenous variables in the model, except when used to compute the unconstrained optimal policy with <command>olr</command>. The lead and lag of the variables are written in parenthesis immediately after the variable name. Leads or lags of more than one period are allowed. All the functions available in Matlab, Scilab or Gauss, respectively, are recognized. Each equation must be terminated by a semicolon (;).
+</para>
+<para>
+When the equations are written in homogenous form, it is possible to omit the "= 0" part and write only the left hand side of the equation.
+</para>
+<para>
+It is possible to include arbitrary Matlab expressions in a model. It must be preceeded by a pound sign (#) as the first character of the line. This is particularily usefull to declare tansformation of parameters for estimation purpose (see <xref linkend="estimated_params"/>).
+</para>
+
+<para>
+The option <command>linear</command> declares the model as being linear. It avoids to have to declare initial values for computing the steady state and it sets automatically <command>order=1</command> in <command>stoch_simul</command>.
+</para>
+</refsect1>
+
+<refsect1><title>Example 1</title>
+<programlisting>
+model;
+c =  - k + aa*x*k(-1)^alph + (1-delt)*k(-1);
+c^(-gam) = (aa*alph*x(+1)*k^(alph-1) + 1 - delt)*c(+1)^(-gam)/(1+bet);
+end;
+</programlisting>
+</refsect1>
+
+<refsect1><title>Example 2</title>
+<programlisting>
+model;
+c + k - aa*x*k(-1)^alph - (1-delt)*k(-1);
+c^(-gam) - (aa*alph*x(+1)*k^(alph-1) + 1 - delt)*c(+1)^(-gam)/(1+bet);
+end;
+</programlisting>
+</refsect1>
+
+<refsect1><title>Example 3</title>
+<programlisting>
+model(linear);
+# b = 1/c;
+x = a*x(-1)+b*y(+1)+e_x;
+y = d*y(-1)+e_y;
+end;
+</programlisting>
+</refsect1>
+</refentry>
+</sect1>
+
+<sect1><title>Initial and terminal conditions</title>
+<para>
+In many contexts, it is necessary to compute the steady state of a non-linear model <xref linkend='initval'/> specifies then numerical initial values for the non-linear solver.
+</para>
+<para>
+Used in perfect foresight mode, the types of forward-loking models for which Dynare was designed require both initial and terminal conditions. Most often these initial and terminal conditions are static equilibria, but not necessarily. 
+</para>
+<para>
+One typical application is to consider an economy at the equilibrium, trigger a shock in first period, and study the trajectory of return at the initial equilbrium. To do that, one needs <xref linkend='initval'/> and <xref linkend='shocks'/>(see next section). 
+</para>
+<para>
+Another one is to study, how an economy, starting from arbitrary initial conditions converges toward equilibrium. To do that, one needs <xref linkend='initval'/> and <xref linkend='endval'/>; 
+</para>
+<para>
+For models with lags on more than one period, the command <xref linkend='histval'/> permits to specify different historical initial values in different periods. 
+</para>
+<itemizedlist>
+<listitem><para><xref linkend='initval'/></para></listitem>
+<listitem><para><xref linkend='endval'/></para></listitem>
+<listitem><para><xref linkend='histval'/></para></listitem>
+</itemizedlist>
+
+<refentry id="initval">
+  <refmeta>
+    <refentrytitle>initval</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>initval</refname>
+    <refpurpose>specifies numerical starting values for finding the steady state and/or initial values for simulations</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>initval;</command><sbr/>
+      <arg choice="plain">
+	<replaceable>VARIABLE_NAME</replaceable> = <replaceable>EXPRESSION</replaceable>;
+	</arg><sbr/>
+	<arg rep="repeat">
+	<replaceable>VARIABLE_NAME</replaceable> = <replaceable>EXPRESSION</replaceable>;
+	  </arg><sbr/>
+	  <arg choice="plain">
+	    end;
+	  </arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>Description</title>
+<para>
+<replaceable>EXPRESSION</replaceable> is any valid expression returning a numerical value and can contain already initialized variable names.
+</para>
+<para>
+The <command>initval;</command> ... <command>end;</command> block serves two purposes. It set the initial and, possibly, terminal conditions for the simulation and provides numerical initialization for various computation tasks (<xref linkend='steady'/>, <xref linkend='simul'/>, <xref linkend='stoch_simul'/>).  
+</para>
+<para>
+Theoreticaly, initial conditions are only necessary for lagged variables. However, as <command>initval</command> provides also numerical initialization, it is necessary to provide values for all variables in the model, except if the model is declared as linear.
+</para>
+<para>
+For stochastic models, it isn't necessary to delcare 0 as initial values for exogneous stochastic variables as it is the only possible value.
+</para>
+<para>
+When the <command>initval</command> block is followed by the command <xref linkend='steady'/>, it is not necessary to provide exact initialization values for the endogenous variables. <xref linkend='steady'/> will use the values provided in the <command>initval</command> block as initial guess in the non-linear equation solver and computes exact values for the endogenous variables at the steady state. The steady state is defined by keeping constant the value of the exogenous variables.  
+</para>
+</refsect1>
+
+<refsect1><title>Example</title>
+<programlisting>
+initval;
+c = 1.2;
+k = 12;
+x = 1;
+end;
+
+steady;
+</programlisting>
+</refsect1>
+</refentry>
+
+<refentry id="endval">
+  <refmeta>
+    <refentrytitle>endval</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>endval</refname>
+    <refpurpose>specifies terminal values for deterministic simulations</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>endval;</command><sbr/>
+      <arg choice="plain">
+	<replaceable>VARIABLE_NAME</replaceable> = <replaceable>EXPRESSION</replaceable>;
+	</arg><sbr/>
+	<arg rep="repeat">
+	<replaceable>VARIABLE_NAME</replaceable> = <replaceable>EXPRESSION</replaceable>;
+	  </arg><sbr/>
+	  <arg choice="plain">
+	    end;
+	  </arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>Description</title>
+<para>
+<replaceable>EXPRESSION</replaceable> is any valid expression returning a numerical value and can contain already initialized variable names.
+</para>
+<para>
+The optional <command>endval;</command> ... <command>end;</command> block serves two purposes. It set the terminal conditions for the simulation with the LBJ alogrithm, when those differ from the initial conditions. When it is the case, the <command>endval</command> block also provides the numerical initialization for various computation tasks (<xref linkend='steady'/>, <xref linkend='simul'/>), starting in period 1.  
+</para>
+<para>
+Theoreticaly, terminal conditions are required in the LBJ algorithm only for forward variables. However, as <command>endval</command> provides also numerical initialization, it is necessary to provide values for all variables in the model.
+</para>
+<para>
+When the <command>endval</command> block is followed by the command <xref linkend='steady'/>, it is not necessary to provide exact values for the endogenous variables. <xref linkend='steady'/> will use the values provided in the <command>endval</command> block as initial guess in the non-linear equation solver and computes exact values for the endogenous variables at the steady state. The steady state is defined by keeping constant the value of the exogenous variables.  
+</para>
+</refsect1>
+
+<refsect1><title>Example</title>
+<programlisting>
+var c k;
+varexo x;
+...
+initval;
+c = 1.2;
+k = 12;
+x = 1;
+end;
+
+steady;
+
+endval;
+c = 2;
+k = 20;
+x = 2;
+end;
+
+steady;
+</programlisting>
+<para>
+The initial equilibrium is comptuted by <xref linkend='steady'/> for x=1, and the terminal one, for x=2.
+</para>
+</refsect1>
+</refentry>
+
+<refentry id="histval">
+  <refmeta>
+    <refentrytitle>histval</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>histval</refname>
+    <refpurpose>specifies historical values before the start of a simulation</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>histval;</command><sbr/>
+      <arg choice="plain">
+	<replaceable>VARIABLE_NAME</replaceable> (<replaceable>INTEGER</replaceable>) = <replaceable>EXPRESSION</replaceable>;
+	</arg><sbr/>
+	<arg rep="repeat">
+	<replaceable>VARIABLE_NAME</replaceable> (<replaceable>INTEGER</replaceable>) = <replaceable>EXPRESSION</replaceable>;
+	  </arg><sbr/>
+	  <arg choice="plain">
+	    end;
+	  </arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>Description</title>
+<para>
+<replaceable>EXPRESSION</replaceable> is any valid expression returning a numerical value and can contain already initialized variable names.
+</para>
+<para>
+In models with lags on more than one period, the optional <command>histval;</command> ... <command>end;</command> block permits to specify different historical initial values for different periods.
+</para>
+<para>
+By convention in Dynare, period 1 is the first period of the simulation. Going backward in time, the first period before the start of the simulation is period 0, then period -1, and so on.
+</para>
+<para>
+If your lagged variables are linked by identities, be careful to satisfy these identities when you set historical initial values.
+</para>
+</refsect1>
+
+<refsect1><title>Example</title>
+<programlisting>
+var x y;
+varexo e;
+
+model;
+x = y(-1)^alpha*y(-2)^(1-alpha)+e;
+...
+end;
+
+initval;
+x = 1;
+y = 1;
+e = 0.5;
+end;
+
+steady;
+
+histval;
+y(0) = 1.1;
+y(-1) = 0.9;
+end;
+</programlisting>
+</refsect1>
+
+</refentry>
+</sect1>
+
+<sect1><title>Shocks on exogenous variables</title>
+<para>
+In a deterministic context, when one wants to study the transition of one equilibrium position to another, it is equivalent to analyze the consequences of a permanent shock and this in done in Dynare through the proper use of <xref linkend='initval'/> and <xref linkend='endval'/>.
+</para>
+<para>
+Another typical experiment is to study the effects of a temporary shock after which the system goes back to the original equilibrium (if the model is stable ...). A temporary shock is a temporary change of value of one or several exogenous variables in the model. Temporary shocks are specified with the command <xref linkend='shocks'/>.
+</para>
+<para>
+In a stochastic framework, the exogenous variables take random values in each period. In Dynare, these random values follow a normal distribution with zero mean, but it belongs to the user to specify the variability of these shocks. The non-zero elements of the matrix of variance-covariance of the shocks can be entered with the <xref linkend='shocks'/> command. Or, the entire matrix can be direclty entered with <xref linkend='Sigma_e'/>. Note that, starting with version 2.5.2, the direct specification of the <emphasis>internal</emphasis> matrix <varname>Sigma_e_</varname>, prone to errors, is discouraged.
+</para>
+<para>
+If the variance of an exogenous variable is set to zero, this variable will appear in the report on policy and transition functions, but isn't used in the computation of moments and of Impulse Response Functions. Setting a variance to zero is an easy way of removing an exogenous shock.
+</para>
+<itemizedlist>
+<listitem><para><xref linkend='shocks'/></para></listitem>
+<listitem><para><xref linkend='Sigma_e'/></para></listitem>
+</itemizedlist>
+
+<refentry id="shocks">
+  <refmeta>
+    <refentrytitle>shocks</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>shocks</refname>
+    <refpurpose>specifies shocks on deterministic or stochastic exogenous variables</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>shocks</command>
+      <arg>(<arg rep="repeat" choice="plain"><replaceable>OPTION</replaceable>,</arg>);</arg><sbr/>
+      <group choice="plain">
+	<arg choice="plain">
+	  <synopfragmentref linkend="det_shock">DETERMINISTIC SHOCK STATEMENT</synopfragmentref>
+	</arg>
+	<arg choice="plain">
+	  <synopfragmentref linkend="st_shock">STOCHASTIC SHOCK STATEMENT</synopfragmentref>
+	</arg>
+      </group><sbr/>
+      <group rep="repeat">
+	<arg choice="plain">
+	  <synopfragmentref linkend="det_shock">DETERMINISTIC SHOCK STATEMENT</synopfragmentref>
+	</arg>
+	<arg choice="plain">
+	  <synopfragmentref linkend="st_shock">STOCHASTIC SHOCK STATEMENT</synopfragmentref>
+	</arg>
+      </group><sbr/>
+      <arg choice ="plain">end;</arg>
+      <synopfragment id="det_shock">
+	<arg choice="plain">var <replaceable>VARIABLE_NAME</replaceable>;</arg>
+	<arg choice="plain">periods <synopfragmentref linkend="period_st">PERIOD STATEMENT</synopfragmentref>;</arg>
+	<arg choice="plain">values EXPRESSION;</arg>
+      </synopfragment>
+      <synopfragment id="period_st">
+	    <arg choice="plain"><replaceable>INTEGER</replaceable></arg>
+	    <arg>: <replaceable>INTEGER</replaceable></arg>
+	    <arg rep="repeat"><replaceable>INTEGER</replaceable>
+	    <arg>: <replaceable>INTEGER</replaceable></arg>
+	    </arg><arg choice="plain">;</arg>
+      </synopfragment>
+      <synopfragment id="st_shock">
+	<group choice="plain">
+	  <arg choice="plain">
+	    <synopfragmentref linkend="var_st">VARIANCE STATEMENT</synopfragmentref>
+	  </arg>
+	  <arg choice="plain">
+	    <synopfragmentref linkend="covar_st">COVARIANCE STATEMENT</synopfragmentref>
+	  </arg>
+	  <arg choice="plain">
+	    <synopfragmentref linkend="stderr_st">STANDARD ERROR STATEMENT</synopfragmentref>
+	  </arg>
+	</group>
+      </synopfragment>
+      <synopfragment id="var_st">
+	<arg choice="plain">
+	  var <replaceable>VARIABLE_NAME</replaceable> = <replaceable>EXPRESSION</replaceable>;
+	</arg>
+      </synopfragment>
+      <synopfragment id="covar_st">
+	<arg choice="plain">
+	  var <replaceable>VARIABLE_NAME</replaceable> , <replaceable>VARIABLE_NAME</replaceable> = <replaceable>EXPRESSION</replaceable>;
+	</arg>
+      </synopfragment>
+      <synopfragment id="stderr_st">
+	<arg choice="plain">
+	  var <replaceable>VARIABLE_NAME</replaceable>; stderr <replaceable>EXPRESSION</replaceable>;
+	</arg>
+      </synopfragment>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+<refsect1><title>Options</title>
+<itemizedlist spacing='compact'>
+<listitem>
+  <para><command>shocks_file</command> = FILENAME: reads sequence of deterministic shocks from FILENAME. It can be either a *.m or a *.mat file. The file must create vectors with the same names as the deterministic exogenous variables.</para>
+</listitem>
+</itemizedlist>
+</refsect1>
+
+<refsect1><title>Description</title>
+<refsect2><title>In deterministic context</title>
+<para>
+For deterministic simulations, the <command>shocks</command> block specifies temporary changes in the value of an exogenous variables. For permanent shocks, use an <xref linkend='endval'/> block.
+</para>
+
+<para>
+  When specifying shocks on several periods, the <command>values</command> <replaceable>EXPRESSION</replaceable> must return either a scalar value common to all periods with a shock or a column vector with as many elements as there are periods in the <command>periods</command> statement just before it.
+</para>
+
+<refsect3><title>Example</title> 
+<programlisting>
+shocks;
+var e;
+periods 1;
+values 0.5;
+var u;
+periods 4:5;
+values 0;
+var v;
+periods 4 5 6;
+values 0;
+var u;
+periods 4  5   6;
+values  1 1.1 0.9;
+end;
+</programlisting>
+</refsect3>
+</refsect2>
+
+<refsect2><title>In stochastic context</title>
+<para>
+For stochastic simulations (available only in the Matlab or Scilab versions), the <command>shocks</command> block specifies the non zero elements of the covariance matrix of the shocks.
+</para>
+
+<refsect3><title>Example</title> 
+<programlisting>
+shocks;
+var e = 0.000081;
+var e,u = phi*0.009*0.009;
+var u = 0.000081;
+var v; stderr 0.009;
+end;
+</programlisting>
+</refsect3>
+<refsect3><title>See also</title>
+<para>
+<command>Sigma_e</command>
+</para>
+</refsect3>
+</refsect2>
+
+<refsect2><title>Mixing determininistic and stochastic shocks</title>
+<para>It is possible to mix deterministic and stochastic shocks to build models where agents know from the start of the simulation about future exogenous changes. In that case <xref linkend="stoch_simul"/> will compute the rational expectation solution adding future information to the state space (nothing is shown in the output of <xref linkend="stoch_simul"/>) and <xref linkend="forecast"/> will compute a simulation conditional on initial  conditions and future information.
+</para>
+
+<refsect3><title>Example</title>
+<informalexample>
+  <programlisting>
+varexo_det tau;
+varexo e;
+
+...
+
+shocks;
+var e; stderr 0.01;
+var tau;
+periods 1:9;
+values -0.15;
+end;
+
+stoch_simul(irf=0);
+
+forecast;
+  </programlisting>
+</informalexample>
+</refsect3>
+</refsect2>
+
+</refsect1>
+</refentry>
+
+<refentry id="Sigma_e">
+  <refmeta>
+    <refentrytitle>Sigma_e</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>Sigma_e</refname>
+    <refpurpose>specifies directly the covariance matrix of the stochastic shocks</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>Sigma_e</command>
+      <arg choice="plain">
+	= [<synopfragmentref linkend="matrix_el">MATRIX ELEMENT</synopfragmentref>
+	<arg rep="repeat"><arg>,</arg><synopfragmentref linkend="matrix_el">MATRIX ELEMENT</synopfragmentref></arg>
+	<arg rep="repeat"><arg choice="plain">;</arg><synopfragmentref linkend="matrix_el">MATRIX ELEMENT</synopfragmentref></arg>];
+      </arg>
+
+      <synopfragment id="matrix_el">
+	<group choice="plain">
+	  <arg choice="plain">
+	    <replaceable>INTEGER</replaceable>
+	  </arg>
+	  <arg choice="plain">
+	    <replaceable>DOUBLE</replaceable>
+	  </arg>
+	  <arg choice="plain">
+	    (<replaceable>EXPRESSION</replaceable>)
+	  </arg>
+	</group>
+      </synopfragment>
+    </cmdsynopsis>
+    <para>
+      WARNING: the matrix elements are actually written beween square brackets ([]). Here, the initial [ and final ] don't have the meaning of "optional element" as elsewhere.
+    </para>
+  </refsynopsisdiv>
+
+
+<refsect1><title>Description</title>
+
+<para>
+The matrix of variance-covariance of the shocks can be directly specified as a upper (or lower) triangular matrix. Dynare builds the corresponding symmetrix matrix. Each row of the triangular matrix, except the last one, must be terminated by a semi-colon ';'. For a given element, an <replaceable>EXPRESSION</replaceable> using predefined parameters is allowed but must be placed between parentheses. THE ORDER OF THE COVARIANCES IN THE MATRIX IS THE SAME AS THE ONE USED IN THE VAREXO DECLARATION.
+</para>
+<note>
+<para>In previous versions, it was possible to directly set Dynare's internal covariance matrix <varname>Sigma_e_</varname>. This is still possible for compatibility with older .mod files, but STRONGLY DISCOURAGED as too prone to error. When setting <varname>Sigma_e_</varname> directly, the order of the exogenous shocks is the ALPHABETICAL order of their names.
+</para>
+</note>
+</refsect1>
+
+<refsect1><title>Example</title>
+<programlisting>
+varexo u, e;
+...
+Sigma_e = [ 0.81 (phi*0.9*0.009); 0.000081];
+</programlisting>
+<para>
+where the variance of <varname>u</varname> is 0.81, the variance of <varname>e</varname>, 0.000081, and the correlation between <varname>e</varname> and <varname>u</varname> is <varname>phi</varname>.
+</para>
+</refsect1>
+</refentry>
+</sect1>
+
+<sect1><title>Solving and simulating</title>
+<para>
+Dynare has special commands for the computation of the static equilibrium of the model (<xref linkend='steady'/>, of the eigenvalues of the linearized model (<xref linkend='check'/>) for dynamics local analysis, of a deterministic simulation (<xref linkend='simul'/>) and for solving and/or simulating a stochastic model (<xref linkend='stoch_simul'/>).
+</para>
+<itemizedlist>
+<listitem><para><xref linkend='steady'/></para></listitem>
+<listitem><para><xref linkend='check'/></para></listitem>
+<listitem><para><xref linkend='forecast'/></para></listitem>
+<listitem><para><xref linkend='simul'/></para></listitem>
+<listitem><para><xref linkend='stoch_simul'/></para></listitem>
+</itemizedlist>
+
+<refentry id="steady">
+  <refmeta>
+    <refentrytitle>steady</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>steady</refname>
+    <refpurpose>copmutes the steady state of a model</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>steady</command>
+      <arg>
+      (solve_algo = 
+      <group choice="plain">
+	<arg choice="plain">0</arg>
+	<arg choice="plain">1</arg>
+	<arg choice="plain">2</arg>
+      </group>)
+      </arg>
+      <arg choice='plain'>;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>Options</title>
+<itemizedlist spacing='compact'>
+<listitem><para><command>solve_algo = 0</command>: uses Matlab Optimization Toolbox FSOLVE</para></listitem>
+<listitem><para><command>solve_algo = 1</command>: uses Dynare's own nonlinear equation solver</para></listitem>
+<listitem><para><command>solve_algo = 2</command>: splits the model into recursive blocks and solves each block in turn. (Thanks to Manfred Gilli for showing me Matlab's function DMPERM) (this is the default since Dynare version 3.046).</para>
+</listitem>
+</itemizedlist>
+</refsect1>
+
+<refsect1><title>Description</title>
+
+<para>
+Computes the equilibrium value of the endogenous variables for the value of the exogenous variables specified in the previous <xref linkend='initval'/> or <xref linkend='endval'/> block.
+</para>
+<para>
+<command>steady</command> uses an iterative procedure and takes as initial guess the value of the endogenous variables set in the previous <xref linkend='initval'/> or <xref linkend='endval'/> block.
+</para>
+<para>
+For complicated models, finding good numerical initial values for the endogenous variables is the trickiest part of finding the equilibrium of that model. Often, it is better to start with a smaller model and add new variables one by one.
+</para>
+
+<para>If you know how to compute the steady state for your model, you can provide a Matlab function doing the computation instead of using <command>steady</command>. The function should be called with the name of the <filename>.mod</filename> file followed by <filename>_steadystate</filename>. See <filename>fs2000a_steadystate.m</filename> in <filename>examples/fs2000</filename> directory.
+</para>
+
+</refsect1>
+
+<refsect1><title>Output variables</title>
+<para>
+  The steeady state is available in <varname>ys_</varname>. Endogenous variables are ordered alphabeticaly as in <varname>lgy_</varname>.  
+</para>
+</refsect1>
+
+<refsect1><title>Examples</title>
+<para>
+See <xref linkend='initval'/> and <xref linkend='endval'/>.
+</para>
+</refsect1>
+</refentry>     
+
+<refentry id="check">
+  <refmeta>
+    <refentrytitle>check</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>check</refname>
+    <refpurpose>computes the eigenvalues of the (linearized) model</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>check</command>
+      <arg choice='plain'>;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>Description</title>
+<para>
+Computes the eigenvalues of the model linearized around the values specified by the last <xref linkend='initval'/>, <xref linkend='endval'/> or <xref linkend='steady'/> statement. Generally, the eigenvalues are only meaningfull if the linearization is done around a steady state of the model. It is a device for local analysis in the neighborhood of this steady state.
+</para>
+<para>
+A necessary condition for the uniqueness of a stable equilibrium in the neighborhood of the steady state is that there are as many eigenvalues larger than one in modulus as there are forward looking variables in the system. An additional rank condition requires that the square submatrix of the right Schur vectors corresponding to the forward looking variables (jumpers) and to the explosive eigenvalues must have full rank.
+</para>
+</refsect1>
+
+<refsect1><title>Output variables</title>
+<para>
+<command>check</command> returns the eigenvalues in the global variable <varname>eigenvalues_</varname>.
+</para>
+</refsect1>
+</refentry>
+
+<refentry id="forecast">
+  <refmeta>
+    <refentrytitle>forecast</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>forecast</refname>
+    <refpurpose>computes a simulation of a stochastic model from a given state</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>forecast</command>
+      <arg>(<arg rep="repeat" choice="plain"><replaceable>OPTION</replaceable>,</arg>)</arg>
+      <arg choice="plain"><replaceable>VARIABLE_NAME</replaceable></arg>
+      <arg rep="repeat"><replaceable>VARIABLE_NAME</replaceable></arg>
+      <arg choice='plain'>;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>Options</title>
+<itemizedlist spacing='compact'>
+<listitem><para><command>periods</command> = INTEGER: number of periods of the forecast (default = 40)</para></listitem>
+<listitem><para><command>conf_sig</command> = DOUBLE: level of significance for confidence interval (default = 0.90)</para></listitem>
+</itemizedlist>
+</refsect1>
+
+<refsect1><title>Description</title>
+<para><command>forecast</command> computes a simulation of a stochastic model from an arbitrary initial point.</para>
+<para>When the model also contains deterministic exogenous shocks, the simulation is computed conditionaly to the agents knowing the future values of the deterministic exogenous variables.</para>
+
+<para><command>forecast</command> must be called after <xref linkend="stoch_simul"/>.</para>
+
+<para> <command>forecast</command> plots the trajectory of endogenous variables. When a list of variable names follows the command, only those variables are ploted. A 90% confidence interval is ploted around the mean trajectory. Use option <command>conf_sig</command> to change the level of the confidence interval.</para>
+</refsect1>
+
+<refsect1><title>Output variables</title>
+<para>The following variables are set in structure <varname>oo_</varname>:
+<itemizedlist spacing="compact">
+<listitem><para><varname>oo_.forecast.Mean.</varname><replaceable>VARIABLE NAME</replaceable>: mean forecast of endogenous variables</para></listitem>
+<listitem><para><varname>oo_.forecast.HPDinf.</varname><replaceable>VARIABLE NAME</replaceable>: lower bound of a confidence interval around the forecast</para></listitem>
+<listitem><para><varname>oo_.forecast.HPDsup.</varname><replaceable>VARIABLE NAME</replaceable>: upper bound of a confidence interval around the forecast</para></listitem>
+<listitem><para><varname>oo_.forecast.Exogenous.</varname><replaceable>VARIABLE NAME</replaceable>: trajectory of the deterministic exogenous variables</para></listitem>
+</itemizedlist>
+</para>
+</refsect1>
+
+
+<refsect1><title>Example</title>
+<informalexample>
+  <programlisting>
+varexo_det tau;
+varexo e;
+
+...
+
+shocks;
+var e; stderr 0.01;
+var tau;
+periods 1:9;
+values -0.15;
+end;
+
+stoch_simul(irf=0);
+
+forecast;
+  </programlisting>
+</informalexample>
+</refsect1>
+</refentry>
+
+<refentry id="simul">
+  <refmeta>
+    <refentrytitle>simul</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>simul</refname>
+    <refpurpose>simulates a deterministic model</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>simul</command>
+      <arg>
+	(periods=<replaceable>INTEGER</replaceable>)
+      </arg>
+      <arg choice='plain'>;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+  <refsect1><title>Description</title>
+  <para>
+    Triggers the computation of a deterministic simulation of the model for the number of periods set in the option <command>periods=</command>. <command>simul</command> uses a Newton method to solve simultaneously all the equations for every period (see Juillard, 1996).
+  </para>
+  </refsect1>
+<refsect1><title>Output variables</title>
+<para>
+the simulated variables are available in global matrix <varname>y_</varname>. The variables are arranged row by row, in alphabetical order.
+</para>
+</refsect1>
+</refentry>
+
+
+<refentry id="stoch_simul">
+  <refmeta>
+    <refentrytitle>stoch_simul</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>stoch_simul</refname>
+    <refpurpose>computes the solution and simulates the model</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>stoch_simul</command>
+      <arg>(<arg rep="repeat" choice="plain"><replaceable>OPTION</replaceable>,</arg>)</arg>
+      <arg choice="plain"><replaceable>VARIABLE_NAME</replaceable></arg>
+      <arg rep="repeat"><replaceable>VARIABLE_NAME</replaceable></arg>
+      <arg choice='plain'>;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>Options</title>
+<itemizedlist spacing='compact'>
+<listitem><para><anchor id="ar" xreflabel="ar"/> <command>ar</command> = <replaceable>INTEGER</replaceable>:
+Order of autocorrelation coefficients to compute and to print (default = 5)
+n</para></listitem>
+<listitem><para> <command>dr_algo = 0 | 1</command>: 
+specifies the algorithm used for computing the quadratic approximation of the decision rules:
+<itemizedlist spacing='compact'>
+<listitem><para> 0: uses a <emphasis>pure</emphasis> perturbation approach as in Schmitt-Grohe and Uribe (2002) (default)
+</para></listitem>
+<listitem><para> 1: moves the point around which the Taylor expansion is computed toward the means of the distribution as in Collard and Juillard (2001)
+</para></listitem>
+</itemizedlist>
+</para></listitem>
+<listitem><para> <command>drop</command> = <replaceable>INTEGER</replaceable>:
+number of points dropped at the beginning of simulation before computing the summary statistics (default = 100)
+</para></listitem>
+<listitem><para> <command>hp_filter</command> = <replaceable>INTEGER</replaceable>:
+ uses HP filter with lambda = <replaceable>INTEGER</replaceable> before computing moments (default: no filter)
+</para></listitem>
+<listitem><para> <command>hp_ngrid</command> = <replaceable>INTEGER</replaceable>:
+number of points in the grid for the discreet Inverse Fast Fourier Transform used in the HP filter computation. It may be necessary to increase it for highly autocorrelated processes (default = 512) 
+</para></listitem>
+<listitem><para> <command>irf</command> = <replaceable>INTEGER</replaceable>:
+ number of periods on which to compute the IRFs (default = 40). Setting IRF=0, suppresses the plotting of IRF's. 
+</para></listitem>
+<listitem><para><command>relative_irf</command> requests the computation of normalized IRFs in percentage of the standard error of each shock</para></listitem>
+<listitem><para> <command>linear</command>:
+ indicates that the original model is linear (put it rather in the MODEL command).
+</para></listitem>
+<listitem><para> <command>nocorr</command>: 
+doesn't print the correlation matrix (printing them is the default)
+</para></listitem>
+<listitem><para> <command>nofunctions</command>:
+ doesn't print the coefficients of the approximated solution (printing them is the default)
+</para></listitem>
+<listitem><para> <command>nomoments</command>: 
+doesn't print moments of the endogenous variables (printing them is the default)</para></listitem>
+<listitem><para> <command>noprint</command>: cancel any printing. Usefull for loops.</para></listitem>
+<listitem><para> <command>order</command> = 1 | 2 :
+order of Taylor approximation (default = 2)
+</para></listitem>
+<listitem><para> <command>periods</command> = <replaceable>INTEGER</replaceable>: specifies the number of periods to use in simulations. At order=1, no simulation is necessary to compute theoretical moments and IRFs. A number of periods larger than one triggers automatically option <command>simul</command> (default = 0).
+</para></listitem>
+<listitem><para> <command>qz_criterium</command> = <replaceable>INTEGER</replaceable> | <replaceable>DOUBLE</replaceable>:
+value used to split stable from unstable eigenvalues in reordering the Generalized Schur decomposition used for solving 1st order problems (default 1.000001)
+</para></listitem>
+<listitem><para> <command>replic</command> = <replaceable>INTEGER</replaceable>: number of simulated series used to compute the IRFs (default = 1, if order = 1, and 50 otherwise)
+</para></listitem>
+<listitem><para> <command>simul</command>: 
+computes a stochastic simulation of the model for the number of periods specified in the <command>periods</command> statement. Uses <xref linkend='initval'/> values, possibly recomputed by <xref linkend='steady'/>, as initial values for the simulation. The simulated endogenous variables are made available to the user in a vector for each variable and in the global matrix <varname>y_</varname>. The variables are ordered alphabeticaly in the <varname>y_</varname> matrix (default: no simulation)
+</para></listitem>
+<listitem><para> <command>simul_seed</command> = <replaceable>INTEGER</replaceable>|<replaceable>DOUBLE</replaceable>|<replaceable>(EXPRESSION)</replaceable>:
+ specifies a seed for the random generator so as to obtain the same random sample at each run of the program. Otherwise a different sample is used for each run (default: seed not specified). Note that if you use an EXPRESSION rather than an INTEGER or a DOUBLE, the EXPRESSION must be in parenthesis.
+</para></listitem>
+<listitem><para> all <command>steady</command> options (see <xref linkend='steady'/>)</para></listitem>
+</itemizedlist>
+<para>
+When a list of VARIABLE_NAMEs is specified, results are displayed only for these variables.
+</para>
+</refsect1>
+<refsect1><title>Description</title>
+<para>
+<command>stoch_simul</command> computes a Taylor approximation of the decision and transition functions for the model, impulse response functions and various descriptive statistics (moments, variance decomposition, correlation and autocorrelation coefficients). For correlated shocks, the variance decomposition is computed as in the VAR literature through a Cholesky decomposition of the covariance matrix of the exogenous variables. When the shocks are correlated, the variance decomposition depends upon the order of the variables in the <xref linkend='varexo'/> command.
+</para>
+
+<para>The Taylor approximation is computed around the steady state (except whith option <command>dr_algo=1</command>). If you know how to compute the steady state for your model, you can provide a Matlab function doing the computation instead of using the nonlinear solver. The function should be called with the name of the <filename>.mod</filename> file followed by <filename>_steadystate</filename>. See <filename>fs2000a_steadystate.m</filename> in <filename>examples/fs2000</filename> directory.
+</para>
+
+<para>
+Variance decomposition, correlation, autocorrelation are only displayed for variables with positive variance. Impulse response functions are only ploted for variables with response larger than 1e-10.
+</para>
+<para>
+Currently, the IRF's are only ploted for 12 variables. Select the ones you want to see, if your model contains more than 12 endogenous variables.
+</para>
+<para>Currently, the HP filter is only available when computing theoretical moments, not for for moments of simulated variables.
+</para>
+<para>
+The covariance matrix of the shocks is specified either with the <xref linkend='shocks'/> command or with the <xref linkend='Sigma_e'/> command.
+</para>
+</refsect1>
+
+<refsect1><title>Decision rules</title>
+<para>
+The approximated solution of a model takes the form of a set of decision rules or transition equations expressing the current value of the endogenous variables of the model as function of the previous state of the model and shocks oberved at the beginning of the period.
+</para>
+<refsect2><title>First order approximation</title>
+<blockquote><para>
+y<subscript>t</subscript> = ys + A yh<subscript>t-1</subscript> + B u<subscript>t</subscript>
+</para>
+<para>
+where ys is the steady state value of y and yh<subscript>t</subscript>=y<subscript>t</subscript>-ys.
+</para>
+</blockquote>
+</refsect2>
+<refsect2><title>Second order approximation</title>
+<blockquote><para>
+y<subscript>t</subscript> = ys + 0.5&Delta;<superscript>2</superscript> + A yh<subscript>t-1</subscript> + B u<subscript>t</subscript> + 0.5C(yh<subscript>t-1</subscript>&otimes;yh<subscript>t-1</subscript>) + 0.5D(u<subscript>t</subscript>&otimes;u<subscript>t</subscript>) + E(yh<subscript>t-1</subscript>&otimes;u<subscript>t</subscript>)
+</para>
+<para>
+where ys is the steady state value of y, yh<subscript>t</subscript>=y<subscript>t</subscript>-ys, and &Delta;<superscript>2</superscript> is the shift effect of the variance of future shocks.
+</para>
+</blockquote>
+</refsect2>
+</refsect1>
+
+<refsect1><title>Output variables</title>
+<para>
+<command>stoch_simul</command> sets several fields in global variable <varname>oo_</varname>. The descriptive statistics are theoretical moments when no simulation is requested and otherwise represent the moments of the simulated variables. 
+<itemizedlist>
+<listitem><para>the coefficients of the decision rules are stored in global structure<varname>dr_</varname>. Here is the correspondance with the symbols used in the above description of the decision rules:
+<itemizedlist><title>Decision rule coefficients</title>
+
+<listitem><para><varname>ys</varname>: <varname>dr_.ys</varname>. The vector rows correspond to variables in alphabetical order of the variable names.</para></listitem>
+<listitem><para>&Delta;<superscript>2</superscript>: <varname>dr_.ghs2</varname>. The vector rows correspond to re-ordered variables (see below).</para></listitem>
+<listitem><para><varname>A</varname>: <varname>dr_.ghx</varname>. The matrix rows correspond to re-ordered variables. The matrix columns correspond to state variables (see below).</para></listitem>
+<listitem><para><varname>B</varname>: <varname>dr_.ghu</varname>. The matrix rows correspond to re-ordered variables (see below). The matrix columns correspond to exogenous variables in alphabetical order.</para></listitem>
+<listitem><para><varname>C</varname>: <varname>dr_.ghxx</varname>. The matrix rows correspond to re-ordered variables. The matrix columns correspond to the Kronecker product of the vector of state variables (see below).</para></listitem>
+<listitem><para><varname>D</varname>: <varname>dr_.ghuu</varname>. The matrix rows correspond to re-ordered variables (see below). The matrix columns correspond to the Kronecker product of exogenous variables in alphabetical order.</para></listitem>
+<listitem><para><varname>E</varname>: <varname>dr_.ghxu</varname>. The matrix rows correspond to re-ordered variables. The matrix columns correspond to the Kronecker product of the vector of state variables (see below) by the vector of exogenous variables in alphabetical order.</para></listitem>
+</itemizedlist>
+When reordered, the variables are stored in the following order: static variables, purely predetermined variables (variables that appear only at the current and lagged periods in the model), variables that are both predetermined and forward-looking (variables that appear at the current, future and lagged periods in the model), purely forward-looking variables (variables that appear only at the current and future periods in the model). In each category, the variables are arranged alphabetically.</para>
+<para>
+The state variables of the model are purely predetermined variables and variables that are both predetermined and forward-looking. They are ordered in that order. When there are lags on more than one period, the state variables are ordered first according to their lag: first variables from the previous period, then variables from two periods before and so on. Note also that when a variable appears in the model at a lag larger than one period, it is automatically included at all inferior lags.
+</para>
+</listitem>
+<listitem><para>The mean of the endogenous variables is available in the vector <varname>oo_.mean</varname>. The variables are arranged in alphabetical order.
+</para></listitem>
+<listitem><para>The matrix of variance-covariance of the endogenous variables in the matrix <varname>oo_.var</varname>. The variables are arranged in alphabetical order.</para></listitem>
+<listitem><para>The matrix of autocorrelation of the endogenous variables are made available in cell array <varname>oo_.autocorr</varname>. The element number of the matrix in the cell array corresponds to the order of autocorrelation. The option <varname>AR</varname> (default ar=5) specifies the number of autocorrelation matrices available.
+</para></listitem>
+<listitem>
+<para>
+  Simulated variables, when they have been computed, are available in Matlab
+vectors with the same name as the endogenous variables.</para>
+</listitem>
+<listitem>
+<para>
+  Impulse responses, when they have been computed, are available in Matlab vectors witht the following naming convention <replaceable>VARIABLE_NAME</replaceable>_<replaceable>shock name</replaceable>.
+</para>
+<informalexample><para>
+  <varname>gnp_ea</varname> contains the effect on <varname>gnp</varname> of a one standard deviation shock on <varname>ea</varname>.
+</para>
+</informalexample>
+</listitem>
+</itemizedlist>
+</para>
+</refsect1>
+
+<refsect1><title>Example 1</title>
+<programlisting>
+shocks;
+var e;
+stderr 0.0348;
+end;
+
+stoch_simul;
+</programlisting>
+<para>
+performs the simulation of the 2nd order approximation of a model with a single stochastic shock, e, with a standard error of 0.0348.
+</para>
+</refsect1>
+
+<refsect1><title>Example 2</title>
+<programlisting>
+stoch_simul(linear,irf=60) y k;
+</programlisting>
+<para>
+performs the simulation of a linear model and displays impulse response functions on 60 periods for variables <varname>y</varname> and <varname>k</varname>.
+</para>
+</refsect1>
+</refentry>
+</sect1>
+
+<sect1><title>Estimation</title>
+<para>
+Provided that you have observations on some endogenous variables, it is possible to use Dynare to estimate some or all parameters. Both maximum likelihood and Bayesian techniques are available.
+</para>
+
+<para>
+Note that in order to avoid stochastic singularity, you must have at least as many shocks or measurement errors in your model as you have observed variables. 
+</para>
+<itemizedlist>
+<listitem><para><xref linkend='varobs'/></para></listitem>
+<listitem><para><xref linkend='observation_trends'/></para></listitem>
+<listitem><para><xref linkend='estimated_params'/></para></listitem>
+<listitem><para><xref linkend='estimated_params_init'/></para></listitem>
+<listitem><para><xref linkend='estimated_params_bounds'/></para></listitem>
+<listitem><para><xref linkend='estimated_params_init'/></para></listitem>
+<listitem><para><xref linkend='estimation'/></para></listitem>
+<listitem><para><xref linkend='unit_root_vars'/></para></listitem>
+</itemizedlist>
+
+<refentry id="varobs">
+  <refmeta>
+    <refentrytitle>varobs</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>varobs</refname>
+    <refpurpose>lists the observed variables</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>varobs</command>
+      <arg choice="plain" rep="repeat">
+	<replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+      <arg rep="repeat">
+	<replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+      <arg choice="plain">;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>Description</title>
+<para>
+<command>varobs</command> lists the name of observed endogenous variables for the estimation procedure. These variables must be available in the data file (see <xref linkend='estimation'/>).
+</para>
+</refsect1>
+
+<refsect1><title>Example</title>
+<para>
+  <informalexample>
+    <programlisting>
+      varobs C y rr;
+    </programlisting>
+  </informalexample>
+</para>
+</refsect1>
+
+</refentry>
+
+<refentry id="observation_trends">
+  <refmeta>
+    <refentrytitle>observation_trends</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>observation_trends</refname>
+    <refpurpose>specifies linear trends for observed variables</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>observation_trends;</command><sbr/>
+      <arg choice="plain">
+	<replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+      <arg choice="plain">
+	(<replaceable>EXPRESSION</replaceable>);
+      </arg><sbr/>
+      <arg choice="plain">
+	end;
+      </arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>Description</title>
+<para>
+<command>observation_trends</command> specifies trends for observed variables as functions of model parameters. In most cases, variables shouldn't be centered when <command>observation_trends</command> is used. 
+</para>
+</refsect1>
+
+<refsect1><title>Example</title>
+<para>
+  <informalexample>
+    <programlisting>
+      observation_trends;
+      Y (eta);
+      P (mu/eta);
+      end;
+    </programlisting>
+  </informalexample>
+</para>
+</refsect1>
+
+</refentry>
+
+<refentry id="estimated_params">
+  <refmeta>
+    <refentrytitle>estimated_params</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>estimated_params</refname>
+    <refpurpose>specifies the estimated parameters and their prior</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <para>Syntax I (maximum likelihood estimation)</para>
+    <cmdsynopsis>
+      <command>estimated_params;</command><sbr/>
+      <group choice="req">
+      <arg choice="plain">
+	stderr <replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+      <arg choice="plain">
+	corr <replaceable>VARIABLE_NAME_1, VARIABLE_NAME_2</replaceable>
+      </arg>
+      <arg choice="plain">
+	<replaceable>PARAMETER_NAME</replaceable>
+	</arg>
+      </group>
+	<arg choice="plain">
+	  <replaceable>, INITIAL_VALUE</replaceable>
+	</arg>
+	<arg choice="opt">
+	  <replaceable>, LOWER_BOUND</replaceable>
+	</arg>
+	<arg choice="opt">
+	  <replaceable>, UPPER_BOUND</replaceable>
+	</arg>
+	<arg choice="plain">;</arg><sbr/>
+	<arg choice='plain'>...</arg><sbr/>
+	  <arg choice="plain">end;</arg>
+    </cmdsynopsis>
+    <para>Syntax II (Bayesian estimation)</para>
+    <cmdsynopsis>
+      <command>estimated_params;</command><sbr/>
+      <group choice="req">
+      <arg choice="plain">
+	stderr <replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+      <arg choice="plain">
+	corr <replaceable>VARIABLE_NAME_1, VARIABLE_NAME_2</replaceable>
+      </arg>
+      <arg choice="plain">
+	<replaceable>PARAMETER_NAME</replaceable>
+	</arg>
+      </group>
+      <arg choice="plain">
+	<replaceable>, PRIOR_SHAPE</replaceable>
+      </arg>
+      <arg choice="plain">
+	<replaceable>, PRIOR_MEAN</replaceable>
+      </arg>
+      <arg choice="plain">
+	<replaceable>, PRIOR_STANDARD_ERROR</replaceable>
+      </arg>
+      <arg choice="opt">
+	  <replaceable>, PRIOR_3RD_PARAMETER</replaceable>
+      </arg>
+      <arg choice="opt">
+	<replaceable>, PRIOR_4TH_PARAMETER</replaceable>
+      </arg>
+      <arg choice="opt">
+	<replaceable>, SCALE_PARAMETER</replaceable>
+      </arg>
+	<arg choice="plain">;</arg>
+	<sbr/>
+	<arg choice="plain">...</arg><sbr/>
+	<arg choice="plain">end;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>Description</title>
+<para>
+  The <command>estimated_params;....end;</command> block lists all parameters to be estimated and specifies bounds and priors as necessary.
+</para>
+</refsect1>
+
+<refsect1><title>Estimated parameter specification</title>
+<para>
+Each line corresponds to an estimated parameter and follows this syntax:
+<itemizedlist spacing='compact'> 
+  <listitem><para><command>stderr</command> is a keyword indicating that the standard error of the exogenous variable, <replaceable>VARIABLE_NAME</replaceable>, or of the observation error associated with endogenous observed variable, <replaceable>VARIABLE_NAME</replaceable>, is to be estimated</para></listitem>
+  <listitem><para><command>corr</command> is a keyword indicating that the correlation between the exogenous variables, <replaceable>VARIABLE_NAME_1</replaceable> and <replaceable>VARIABLE_NAME_2</replaceable>, or the correlation of the observation errors associated with endogenous observed variables, <replaceable>VARIABLE_NAME_1</replaceable> and <replaceable>VARIABLE_NAME_2</replaceable>, is to be estimated</para></listitem>
+  <listitem><para> <replaceable>PARAMETER_NAME</replaceable> is the name of a model parameter to be estimated</para></listitem>
+<listitem><para> <replaceable>INITIAL_VALUE</replaceable> specifies a starting value for maximum likelihood estimation</para></listitem>
+<listitem><para> <replaceable>LOWER_BOUND</replaceable> specifies a lower bound for the parameter value in maximum likelihood estimation</para></listitem>
+<listitem><para> <replaceable>UPPER_BOUND</replaceable> specifies an upper bound for the parameter value in maximum likelihood estimation</para></listitem>
+  <listitem><para> <replaceable>PRIOR_SHAPE</replaceable> is prior density among <command>beta_pdf</command>, <command>gamma_pdf</command>, <command>normal_pdf</command>, <command>inv_gamma_pdf</command>, <command>inv_gamma1_pdf</command>, <command>inv_gamma2_pdf</command>, <command>uniform_pdf</command></para></listitem>
+  <listitem><para> <replaceable>PRIOR_MEAN</replaceable> is the mean of the prior distribution</para></listitem>
+  <listitem><para> <replaceable>PRIOR_STANDARD_ERROR</replaceable> is the standard error of the prior distribution</para></listitem>
+  <listitem><para> <replaceable>PRIOR_3RD_PARAMETER</replaceable> is a third parameter of the prior used for generalized beta distribution, generalized gamma and for the uniform distribution (default 0)</para></listitem>
+  <listitem><para> <replaceable>PRIOR_4TH_PARAMETER</replaceable> is a fourth parameter of the prior used for generalized beta distribution, generalized gamma and for the uniform distribution (default 1)</para></listitem>
+  <listitem><para> <replaceable>SCALE_PARAMETER</replaceable> is the scale parameter to be used for the jump distribution of the Metropolis-Hasting algorithm</para></listitem>
+</itemizedlist>
+
+<note><para> At minimum, one must specify the name of the parameter and an initial guess. That will trigger unconstrained maximum likelihood estimation.
+</para></note>
+
+<note><para> As one uses options more towards the end of the list, all previous options must be filled: if you want to specify <replaceable>jscale</replaceable>, you must specify <replaceable>prior_p3</replaceable> and <replaceable>prior_p4</replaceable>. Use default values, if these parameters don't apply. 
+</para></note>
+</para>
+</refsect1>
+
+<refsect1><title>Parameter transformation</title>
+<para>
+Sometimes, it is desirable to estimate a transformation of a parameter appearing in the model, rather than the parameter itself. It is of course possible to replace the original parameter by a function of the estimated parameter everywhere is the model, but it is often unpractical.
+</para>
+
+<para>
+In such a case, it is possible to declare the parameter to be estimated in the <xref linkend="parameters"/> statement and to define the transformation at the top of the <xref linkend="model"/> section, as a Matlab expression. The first character of the line must be a pound  sign (#).
+</para>
+</refsect1>
+
+<refsect1><title>Example</title>
+<informalexample>
+    <programlisting>
+      parameters bet;
+
+      model;
+      # sig = 1/bet;
+      c = sig*c(+1)*mpk;
+      end;
+
+      estimated_params;
+      bet,normal_pdf,1,0.05;
+      end;
+    </programlisting>
+  </informalexample>
+</refsect1>
+
+
+
+</refentry>
+
+<refentry id="estimated_params_init">
+  <refmeta>
+    <refentrytitle>estimated_params_init</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>estimated_params_init</refname>
+    <refpurpose>specifies initial values for optimization</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>estimated_params_init;</command><sbr/>
+      <group choice="req">
+      <arg choice="plain">
+	stderr <replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+      <arg choice="plain">
+	corr <replaceable>VARIABLE_NAME_1, VARIABLE_NAME_2</replaceable>
+      </arg>
+      <arg choice="plain">
+	<replaceable>PARAMETER_NAME</replaceable>
+	</arg>
+      </group>
+	<arg choice="plain">
+	  <replaceable>, INITIAL_VALUE</replaceable>
+	</arg> 
+	<arg choice="plain">;</arg><sbr/>
+	<arg choice='plain'>...</arg><sbr/>
+	  <arg choice="plain">end;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>Description</title>
+<para>
+  The <command>estimated_params_init;....end;</command> block declares numerical initial values for the optimizer when these ones are different from the prior mean
+</para>
+</refsect1>
+
+<refsect1><title>Estimated parameter initial value specification</title>
+<para>
+Each line corresponds to an estimated parameter and follows this syntax:
+<itemizedlist spacing='compact'> 
+  <listitem><para><command>stderr</command> is a keyword indicating that the standard error of the exogenous variable, <replaceable>VARIABLE_NAME</replaceable>, or of the observation error associated with endogenous observed variable, <replaceable>VARIABLE_NAME</replaceable>, is to be estimated</para></listitem>
+  <listitem><para><command>corr</command> is a keyword indicating that the correlation between the exogenous variables, <replaceable>VARIABLE_NAME_1</replaceable> and <replaceable>VARIABLE_NAME_2</replaceable>, or the correlation of the observation errors associated with endogenous observed variables, <replaceable>VARIABLE_NAME_1</replaceable> and <replaceable>VARIABLE_NAME_2</replaceable>, is to be estimated</para></listitem>
+  <listitem><para> <replaceable>PARAMETER_NAME</replaceable> is the name of a model parameter to be estimated</para></listitem>
+<listitem><para> <replaceable>INITIAL_VALUE</replaceable> specifies a starting value for maximum likelihood estimation</para></listitem>
+</itemizedlist>
+</para>
+</refsect1>
+
+</refentry>
+
+<refentry id="estimated_params_bounds">
+  <refmeta>
+    <refentrytitle>estimated_params_bounds</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>estimated_params_bounds</refname>
+    <refpurpose>specifies lower and upper bounds for the estimated parameters</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>estimated_params_bounds;</command><sbr/>
+      <group choice="req">
+      <arg choice="plain">
+	stderr <replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+      <arg choice="plain">
+	corr <replaceable>VARIABLE_NAME_1, VARIABLE_NAME_2</replaceable>
+      </arg>
+      <arg choice="plain">
+	<replaceable>PARAMETER_NAME</replaceable>
+	</arg>
+      </group>
+	<arg choice="plain">
+	  <replaceable>, LOWER_BOUND</replaceable>
+	</arg>
+	<arg choice="plain">
+	  <replaceable>, UPPER_BOUND</replaceable>
+	</arg>
+	<arg choice="plain">;</arg><sbr/>
+	<arg choice='plain'>...</arg><sbr/>
+	  <arg choice="plain">end;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>Description</title>
+<para>
+  The <command>estimated_params;....end;</command> block lists all parameter to be estimated and specifies bounds and priors when required.
+</para>
+</refsect1>
+
+<refsect1><title>Estimated parameter specification</title>
+<para>
+Each line corresponds to an estimated parameter and follows this syntax:
+<itemizedlist spacing='compact'> 
+  <listitem><para><command>stderr</command> is a keyword indicating that the standard error of the exogenous variable, <replaceable>VARIABLE_NAME</replaceable>, or of the observation error associated with endogenous observed variable, <replaceable>VARIABLE_NAME</replaceable>, is to be estimated</para></listitem>
+  <listitem><para><command>corr</command> is a keyword indicating that the correlation between the exogenous variables, <replaceable>VARIABLE_NAME_1</replaceable> and <replaceable>VARIABLE_NAME_2</replaceable>, or the correlation of the observation errors associated with endogenous observed variables, <replaceable>VARIABLE_NAME_1</replaceable> and <replaceable>VARIABLE_NAME_2</replaceable>, is to be estimated</para></listitem>
+  <listitem><para> <replaceable>PARAMETER_NAME</replaceable> is the name of a model parameter to be estimated</para></listitem>
+<listitem><para> <replaceable>LOWER_BOUND</replaceable> specifies a lower bound for the parameter value in maximum likelihood estimation</para></listitem>
+<listitem><para> <replaceable>UPPER_BOUND</replaceable> specifies an upper bound for the parameter value in maximum likelihood estimation</para></listitem>
+</itemizedlist>
+</para>
+</refsect1>
+</refentry>
+
+<refentry id="estimation">
+ <refmeta>
+    <refentrytitle>estimation</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>estimation</refname>
+    <refpurpose>computes estimation.</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>estimation</command>
+      <arg>(OPTIONS)</arg>
+      <arg choice='plain'>;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>OPTIONS</title>
+<itemizedlist spacing='compact'>
+<listitem><para> <command>datafile</command> =
+	  <replaceable>FILENAME</replaceable>: the datafile (a .m file or a .mat file)</para></listitem>
+<listitem><para><command>nobs</command> = <replaceable>INTEGER</replaceable>: the number of observations to be used (default: all observations in the file)</para>
+<para><command>nobs</command> = ([<replaceable>INTEGER_1</replaceable>:<replaceable>INTEGER_2</replaceable>]): runs a recursive estimation and forecast for samples of size ranging of <varname>INTEGER_1</varname> to <varname>INTEGER_2</varname>. Option <varname>FORECAST</varname> must also be specified.</para> 
+</listitem>
+<listitem><para> <command>first_obs</command> = <replaceable>INTEGER</replaceable>: the number of the first observation to be used (default = 1)</para></listitem>
+<listitem><para> <command>prefilter</command> = 1: the estimation procedure demeans the data (default=0, no prefiltering)</para></listitem>
+<listitem><para> <command>presample</command> = <replaceable>INTEGER</replaceable>: the number of observations to be skipped before evaluating the likelihood (default = 1)</para></listitem>
+<listitem><para> <command>loglinear</command>: computes a log--linear approximation of the model instead of a linear (default) approximation. The data must correspond to the definition of the variables used in the modelx.</para></listitem>
+<listitem><para> <command>nograph</command>: no graphs should be plotted</para></listitem>
+<listitem><para> <command>lik_init</command>: <replaceable>INTEGER</replaceable>: type of initialization of Kalman filter.
+<itemizedlist spacing='compact'>
+  <listitem><para>1 (default): for stationary models, the initial matrix of variance of the error of forecast is set equal to the unconditional variance of the state variables.</para></listitem>
+  <listitem><para>2: for nonstationary models: a wide prior is used with an initial matrix of variance of the error of forecast diagonal with 10 on the diagonal.</para></listitem>
+</itemizedlist>
+</para></listitem>
+<listitem><anchor id="conf_sig" xreflabel="conf_sig"/><para><command>conf_sig</command> = <replaceable>{INTEGER | DOUBLE}</replaceable>: the level for the confidence intervals reported in the results (default = 0.90)</para></listitem>
+<listitem><anchor id="mh_replic" xreflabel="mh_replic"/><para> <command>mh_replic</command> = <replaceable>INTEGER</replaceable>: number of replication for Metropolis Hasting algorithm. For the time being, mh_replic should be larger than 1200 (default = 20000.)</para></listitem>
+<listitem><para> <command>mh_nblocks</command> = <replaceable>INTEGER</replaceable>: number of paralletl chains for Metropolis Hasting algorithm (default = 2).</para></listitem>
+<listitem><para> <command>mh_drop</command> = <replaceable>DOUBLE</replaceable>: the fraction of initially generated parameter vectors to be dropped before using posterior simulations (default = 0.5)</para></listitem>
+<listitem><para> <command>mh_jscale</command> = <replaceable>DOUBLE</replaceable>: the scale to be used for the jumping distribution in MH algorithm. The default value is rarely satisfactory. This option must be tune to obtain, ideally, an accpetation rate of 25% in the Metropolis-Hastings algorithm (default = 0.2).</para></listitem>
+<listitem><para><command>mh_init_scale</command>=<replaceable>DOUBLE</replaceable>: the scale to be used for drawing the initial value of the Metropolis-Hastings chain (default=2*mh_scale).</para>
+</listitem>
+<listitem><para><command>mode_file</command>=<replaceable>FILENAME</replaceable>: name of the file containing previous value for the mode. When computing the mode, Dynare stores the mode (<varname>xparam1</varname>) and the hessian (<varname>hh</varname>) in a file called <filename><replaceable>MODEL NAME</replaceable>_mode</filename>.</para></listitem>
+<listitem><para><command>mode_compute</command>=<replaceable>INTEGER</replaceable>: specifies the optimizer for the mode computation.
+<itemizedlist spacing='compact'>
+  <listitem><para>0: the mode isn't computed. mode_file must be specified</para></listitem>
+  <listitem><para>1: uses Matlab <command>fmincon</command>.</para></listitem>
+  <listitem><para>2: uses Lester Ingber's Adaptive Simulated Annealing.</para></listitem>
+  <listitem><para>3: uses Matlab <command>fminunc</command>.</para></listitem>
+  <listitem><para>4 (default): uses Chris Sim's <command>csminwel</command>.</para></listitem>
+</itemizedlist></para></listitem>
+<listitem><para><command>mode_check</command>: when <command>mode_check</command> is set, Dynare plots the posterior density for values around the computed mode for each estimated parameter in turn. This is helpful to diagnose problems with the optimizer.</para></listitem>
+<listitem><para><command>prior_trunc</command>=<replaceable>DOUBLE</replaceable>: probability of extreme values of the prior density that is ignored when computing bounds for the parameters (default=1e-32).</para></listitem>
+<listitem><anchor id="load_mh_file" xreflabel="load_mh_file"/><para><command>load_mh_file</command>: when <command>load_mh_file</command> is declared, Dynare adds to previous Metropolis-Hastings simulations instead of starting from scratch.</para></listitem>
+<listitem><para><command>optim</command>=(<replaceable>fmincon options</replaceable>): can be used to set options for fmincon, the optimizing function of Matlab Optimizaiton toolbox. Use Matlab syntax for these options</para>
+<para> (default: ('display','iter','LargeScale','off','MaxFunEvals',100000,'TolFun',1e-8,'TolX',1e-6))</para></listitem>
+<listitem>
+  <para>
+    <command>nodiagnostic</command>: doesn't compute the convergence diagnostics for Metropolis (default: diagnostics are computed and displayed).
+  </para>
+</listitem>
+<listitem><para><anchor id="bayesian_irf" xreflabel="bayesian_irf"/><command>bayesian_irf</command> triggers the computation of the posterior distribution of IRFs. The length of the IRFs are controlled by the <command>irf</command> option</para></listitem>
+<listitem><para><anchor id="moments_varendo" xreflabel="moments_varendo"/><command>moments_varendo</command> triggers the computation of the posterior distribution of the theoretical moments of the endogenous variables</para></listitem>
+<listitem><para><anchor id="filtered_vars" xreflabel="filtered_vars"/><command>filtered_vars</command> triggers the computation of the posterior distribution of filtered endogenous variables and shocks</para></listitem>
+<listitem><anchor id="smoother" xreflabel="smoother"/><para><command>smoother</command> triggers the computation of the posterior distribution of smoothered endogenous variables and shocks</para></listitem>
+<listitem><para><anchor id="forecast_opt" xreflabel="forecast"/><command>forecast = </command><replaceable>INTEGER</replaceable> computes the posterior distribution of a forecast on <replaceable>INTEGER</replaceable> periods after the end of the sample used in estimation</para></listitem>
+<listitem><para><command>tex</command> requests the printing of results and graphs in TeX tables and graphics that can be later directly included in Latex files (not yet implemented)</para></listitem>
+<listitem><para>All options for <xref linkend="stoch_simul"/></para></listitem>
+</itemizedlist>
+
+<note><para> If no <command>mh_jscale</command> parameter is used in estimated_params, the procedure uses <command>mh_jscale</command> for all parameters. If <command>mh_jscale</command> option isn't set, the procedure uses 0.2 for all parameters.
+</para></note>
+</refsect1>
+
+<refsect1><title>Results</title>
+<itemizedlist spacing='compact'>
+<listitem><para> results from posterior optimization (also for maximum likelihood)</para></listitem>
+<listitem><para> marginal log density</para></listitem>
+<listitem><para> mean and shortest confidence interval from posterior simulation</para></listitem>
+<listitem><para>Metropolis-Hastings convergence graphs that still need to be documented</para></listitem>
+<listitem><para> graphs with prior, posterior and mode</para></listitem>
+<listitem><para> graphs of smoothed shocks, smoothed observation errors, smoothed and historical variables</para></listitem>
+</itemizedlist>
+</refsect1>
+
+<refsect1><title>Output</title>
+<para>After running <command>estimation</command>, the parameters and the variance matrix of the shocks are set to the mode for maximum likelihood estimation or posterior mode computation without Metropolis iterations.
+</para>
+<para>After <command>estimation</command> with Metropolis iterations (option <command>mh_replic</command> > 0 or option <command>load_mh_file</command> set) the parameters and the variance matrix of the shocks are set to the posterior mean.</para>
+
+<para>Depending on the options, <command>estimation</command> stores results in the following fields of structure <varname>oo_</varname>:
+<table orient="land"><title>Content of <varname>oo_</varname></title><tgroup cols='2'>
+<thead>
+<row><entry>Field 1</entry><entry>Field 2</entry><entry>Field 3</entry><entry>Field 4</entry><entry>Field 5</entry><entry>Required options</entry></row>
+</thead>
+<tbody>
+<row><entry><varname>Forecast</varname></entry><entry>See <xref linkend="ForecastsMoments"/></entry><entry><replaceable>Variable name</replaceable></entry><entry></entry><entry></entry><entry><xref linkend="forecast_opt"/></entry></row>
+<row><entry morerows='1'><varname>MarginalDensity</varname></entry><entry><varname>LaplaceApproximation</varname></entry><entry/><entry></entry><entry></entry><entry>Always provided</entry></row>
+<row><entry><varname>ModifiedHarmonicMean</varname></entry><entry></entry><entry></entry><entry></entry><entry><para><xref linkend="mh_replic"/>&gt; 0 or <xref linkend="load_mh_file"/></para></entry></row>
+<row><entry><varname>PosteriorFilteredVariables</varname></entry><entry>See <xref linkend="MomentsNames"/></entry><entry><replaceable>Variable name</replaceable></entry><entry></entry><entry></entry><entry><para><xref linkend="filtered_vars"/></para></entry></row>
+<row><entry><varname>PosteriorIRF</varname></entry><entry><varname>Dsge</varname></entry><entry>See <xref linkend="MomentsNames"/></entry><entry><para>IRF name: name of endogenous variable '_' name of shock</para></entry><entry></entry><entry><xref linkend="bayesian_irf"/></entry></row>
+<row><entry><varname>PosteriorSmoothedObservationErrors</varname></entry><entry>See <xref linkend="MomentsNames"/></entry><entry><replaceable>Variable name</replaceable></entry><entry></entry><entry></entry><entry><para><xref linkend="smoother"/></para></entry></row>
+<row><entry><varname>PosteriorSmoothedShocks</varname></entry><entry>See <xref linkend="MomentsNames"/></entry><entry><replaceable>Variable name</replaceable></entry><entry></entry><entry></entry><entry><para><xref linkend="smoother"/></para></entry></row>
+<row><entry><varname>PosteriorSmoothedVariables</varname></entry><entry>See <xref linkend="MomentsNames"/></entry><entry><replaceable>Variable name</replaceable></entry><entry></entry><entry></entry><entry><para><xref linkend="smoother"/></para></entry></row>
+<row><entry><varname>PosteriorTheoreticalMoments</varname></entry><entry>See <xref linkend="TheoreticalMoments"/></entry><entry>See <xref linkend="EstimatedObjects"/></entry><entry>See <xref linkend="MomentsNames"/></entry><entry><replaceable>Variable name</replaceable></entry><entry><xref linkend="moments_varendo"/></entry></row>
+<row><entry><varname>posterior_density</varname></entry><entry><replaceable>Parameter name</replaceable></entry><entry></entry><entry></entry><entry></entry><entry><para><xref linkend="mh_replic"/>&gt; 0 or <xref linkend="load_mh_file"/></para></entry></row>
+<row><entry><varname>posterior_hpdinf</varname></entry><entry>See <xref linkend="EstimatedObjects"/></entry><entry><replaceable>Variable name</replaceable></entry><entry></entry><entry></entry><entry><para><xref linkend="mh_replic"/>&gt; 0 or <xref linkend="load_mh_file"/></para></entry></row>
+<row><entry><varname>posterior_hpdsup</varname></entry><entry>See <xref linkend="EstimatedObjects"/></entry><entry><replaceable>Variable name</replaceable></entry><entry></entry><entry></entry><entry><para><xref linkend="mh_replic"/>&gt; 0 or <xref linkend="load_mh_file"/></para></entry></row>
+<row><entry><varname>posterior_mean</varname></entry><entry>See <xref linkend="EstimatedObjects"/></entry><entry><replaceable>Variable name</replaceable></entry><entry></entry><entry></entry><entry><para><xref linkend="mh_replic"/>&gt; 0 or <xref linkend="load_mh_file"/></para></entry></row>
+<row><entry><varname>posterior_mode</varname></entry><entry>See <xref linkend="EstimatedObjects"/></entry><entry><replaceable>Variable name</replaceable></entry><entry></entry><entry></entry><entry><para><xref linkend="mh_replic"/>&gt; 0 or <xref linkend="load_mh_file"/></para></entry></row>
+<row><entry><varname>posterior_std</varname></entry><entry>See <xref linkend="EstimatedObjects"/></entry><entry><replaceable>Variable name</replaceable></entry><entry></entry><entry></entry><entry><para><xref linkend="mh_replic"/>&gt; 0 or <xref linkend="load_mh_file"/></para></entry></row>
+</tbody>
+</tgroup>
+</table>
+</para>
+
+<para><anchor id="ForecastsMoments" xreflabel="Moments of forecasts"/>
+<table><title>Moments of forecasts</title>
+<tgroup cols='2'>
+<thead>
+<row><entry>Field name</entry><entry>Description</entry></row>
+</thead>
+<tbody>
+<row><entry><varname>HPDinf</varname></entry><entry>Lower bound of a 90% HPD interval<footnote id="see_conf_sig"><para>See option <xref linkend="conf_sig"/> to change the size of the HPD interval</para></footnote> of forecast  due to parameter uncertainty</entry></row> 
+<row><entry><varname>HPDsup</varname></entry><entry>Lower bound of a 90% HPD interval <footnoteref linkend="see_conf_sig"/> due to parameter uncertainty</entry></row> 
+<row><entry><varname>HPDTotalinf</varname></entry><entry>Lower bound of a 90% HPD interval of forecast <footnoteref linkend="see_conf_sig"/> due to parameter uncertainty and future shocks</entry></row> 
+<row><entry><varname>HPDTotalsup</varname></entry><entry>Lower bound of a 90% HPD interval <footnoteref linkend="see_conf_sig"/> due to parameter uncertainty and future shocks</entry></row>
+<row><entry><varname>Mean</varname></entry><entry>Mean of the posterior distribution of forecasts</entry></row> 
+<row><entry><varname>Median</varname></entry><entry>Median of the posterior distribution of forecasts</entry></row>  
+<row><entry><varname>Std</varname></entry> <entry>Standard deviation of the posterior distribution of forecasts</entry></row> 
+</tbody>
+</tgroup>
+</table>
+</para>
+<para><anchor id="MomentsNames" xreflabel="Moments Names"/>
+<table><title>Moments Names</title>
+<tgroup cols='2'>
+<thead>
+<row><entry>Field name</entry><entry>Description</entry></row>
+</thead>
+<tbody>
+<row><entry><varname>HPDinf</varname></entry><entry>Lower bound of a 90% HPD interval<footnote id="see_conf_sig1"><para>See option <xref linkend="conf_sig"/> to change the size of the HPD interval</para></footnote></entry></row> 
+<row><entry><varname>HPDsup</varname></entry><entry>Upper bound of a 90% HPD interval <footnoteref linkend="see_conf_sig1"/> </entry></row> 
+<row><entry><varname>Mean</varname></entry><entry>Mean of the posterior distribution</entry></row> 
+<row><entry><varname>Median</varname></entry><entry>Median of the posterior distribution</entry></row>  
+<row><entry><varname>Std</varname></entry> <entry>Standard deviation of the posterior distribution</entry></row> 
+</tbody>
+</tgroup>
+</table>
+</para>
+<para><anchor id="TheoreticalMoments" xreflabel="Theoretical Moments"/>
+<table><title>Theoretical Moments</title>
+<tgroup cols='2'>
+<thead>
+<row><entry>Field name</entry><entry>Description</entry></row>
+</thead>
+<tbody>
+<row><entry><varname>Autocorrelation</varname></entry><entry>Autocorrelation of endogenous variables<footnote><para>The autocorrlation coefficients are computed for the number of periods specified in option <xref linkend="ar"/>.</para></footnote></entry></row>
+<row><entry><varname>Correlation</varname></entry><entry>Correlation between two endogenous variables</entry></row>
+<row><entry><varname>Decomp</varname></entry><entry>Decomposition of variance<footnote><para>When the shocks are correlated, it is the decomposition of orthogonalized shocks via Cholesky decompostion according to the order of declaration of shocks (see <xref linkend="varexo"/>).</para></footnote> </entry></row>
+<row><entry><varname>Expectation</varname></entry><entry>Expectation of endogenous variables</entry></row>
+<row><entry><varname>Variance</varname></entry><entry>(co-)variance of endogenous variables</entry></row>
+</tbody>
+</tgroup>
+</table>
+</para>
+
+<para><anchor id="EstimatedObjects" xreflabel="Estimated Objects"/>
+<table><title>Estimated objects</title>
+<tgroup cols='2'>
+<thead>
+<row><entry>Field name</entry><entry>Description</entry></row>
+</thead>
+<tbody>
+<row><entry><varname>measurement_errors_corr</varname></entry><entry>Correlation between two measurement errors</entry></row>
+<row><entry><varname>measurement_errors_std</varname></entry><entry>Standard deviation of measurement errors</entry></row>
+<row><entry><varname>parameters</varname></entry><entry>Parameters</entry></row>
+<row><entry><varname>shocks_corr</varname></entry><entry>Correlation between two structural shocks</entry></row>
+<row><entry><varname>shocks_std</varname></entry><entry>Standard deviation of structural shocks</entry></row>
+</tbody>
+</tgroup>
+</table>
+</para>
+
+<refsect2><title>Examples</title>
+<para>
+<informalexample>
+<programlisting>
+oo_.posterior_mode.parameters.alp
+oo_.posterior_mean.shocks_std.ex
+oo_.posterior_hpdsup.measurement_errors_corr.gdp_conso
+</programlisting>
+</informalexample>
+</para>
+</refsect2>
+
+</refsect1>
+
+<refsect1><title>Note on steady state computation</title>
+<para>If you know how to compute the steady state for your model, you can provide a Matlab function doing the computation instead of using <command>steady</command>. The function should be called with the name of the <filename>.mod</filename> file followed by <filename>_steadystate</filename>. See <filename>fs2000a_steadystate.m</filename> in <filename>examples/fs2000</filename> directory.
+</para>
+</refsect1>
+</refentry>
+
+<refentry id="unit_root_vars">
+  <refmeta>
+    <refentrytitle>unit_root_vars</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>unit_root_vars</refname>
+    <refpurpose>declares unit-root variables for estimation</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>unit_root_vars</command>
+      <arg choice="plain">
+      <replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+      <arg rep="repeat">
+      <replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+      <arg choice="plain">;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>Description</title>
+<para>
+<command>unit_root_vars</command> is used to declare unit-root variables of a model so that a diffuse prior can be used in the initialization of the Kalman filter for these variables only. For stationary variables, the unconditional covariance matrix of these variables is used for initialization. The algorithm to compute a true diffuse prior is taken from Durbin and Koopman (2001, 2003).
+</para>
+
+<para>When <command>unit_root_vars</command> is used the <command>lik_init</command> option of <xref linkend="estimation"/> has no effect.
+</para>
+
+<para>When there are nonstationary variables in a model, there is no unique deterministic steady state. The user must supply a Matlab function that computes the steady state values of the stationary variables in the model and returns dummy values for the nonstationary ones. The function should be called with the name of the <filename>.mod</filename> file followed by <filename>_steadystate</filename>. See <filename>fs2000a_steadystate.m</filename> in <filename>examples/fs2000</filename> directory.
+</para>
+
+<para>Note that the nonstationary variables in the model must be integrated processes(their first difference or k-difference must be stationary).</para>
+</refsect1>
+</refentry>
+</sect1>
+
+<sect1><title>Optimal policy</title>
+<para>Dynare has tools to compute optimal policies for quadratic objectives. You can either solve for optimal policy under commitment with <xref linkend='olr'/> or for optimal simple rule with <xref linkend='osr'/>.
+</para>
+
+<itemizedlist>
+<listitem><para><xref linkend='olr'/></para></listitem>
+<listitem><para><xref linkend='olr_inst'/></para></listitem>
+<listitem><para><xref linkend='optim_weights'/></para></listitem>
+<listitem><para><xref linkend='osr'/></para></listitem>
+<listitem><para><xref linkend='osr_params'/></para></listitem>
+</itemizedlist>
+
+<refentry id="olr">
+  <refmeta>
+    <refentrytitle>olr</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>olr</refname>
+    <refpurpose>computes optimal policy under commitment</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>olr</command>
+      <arg>(<arg rep="repeat" choice="plain"><replaceable>OPTION</replaceable>,</arg>)</arg>
+      <arg choice="plain"><replaceable>VARIABLE_NAME</replaceable></arg>
+      <arg rep="repeat"><replaceable>VARIABLE_NAME</replaceable></arg>
+      <arg choice='plain'>;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>OPTIONS</title>
+<itemizedlist spacing='compact'>
+<listitem><para><command>olr_beta=VALUE</command> sets the value of the discount factor for the intertemporal optimization problem</para></listitem>
+<listitem><para>All options for <xref linkend="stoch_simul"/></para></listitem>
+</itemizedlist>
+</refsect1>
+
+<refsect1><title>Description</title>
+<para>
+<command>olr</command> computes optimal policies under commitment (Ramsey plans) for linear--quadratic problems of the form
+</para>
+<blockquote><para>
+max<subscript>u</subscript> E<subscript>0</subscript>&Sigma;<subscript>t=0</subscript><superscript>&infin;</superscript>&beta;<superscript>t</superscript>(y<subscript>t</subscript>&prime;W<subscript>11</subscript>y<subscript>t</subscript>+2y<subscript>t</subscript>&prime;W<subscript>12</subscript>u<subscript>t</subscript>+u<subscript>t</subscript>&prime;W<subscript>22</subscript>u<subscript>t</subscript>)
+</para>
+<para>s.t.</para>
+<para>
+  A<subscript>1</subscript>E<subscript>t</subscript>(y<subscript>t+1</subscript>)+A<subscript>2</subscript>y<subscript>t</subscript>+A<subscript>3</subscript>y<subscript>t-1</subscript>+Bu<subscript>t</subscript>+Ce<subscript>t</subscript>=0
+</para>
+</blockquote>
+<para>with</para>
+<itemizedlist>
+<listitem><para>y: endogenous variables</para></listitem>
+<listitem><para>u: policiy instrument</para></listitem>
+<listitem><para>e: exogenous stochastic shocks</para></listitem>
+<listitem><para>&beta;: discount factor</para></listitem>
+</itemizedlist>
+<para>The policy instruments must be listed with <xref linkend='olr_inst'/>.
+</para>
+<para>The quadratic objectives must be listed with <xref linkend='optim_weights'/>.
+</para>
+<para>Multipliers are automatically added to the model. Note, however, that the representation isn't minimal and that, in the solution, some multipliers could be sustituted off.
+</para>
+<para>
+Forward-looking endogenous variables don't need to be present in the dynamics of the economy.
+</para>
+<para>
+Dynare automatically builds the corresponding linear rational expectation model and solves it as with <xref linkend='stoch_simul'/>.
+</para>
+</refsect1>
+</refentry>
+
+<refentry id="olr_inst">
+  <refmeta>
+    <refentrytitle>olr_inst</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>olr_inst</refname>
+    <refpurpose>declares instruments for optimal policy under commitment</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>olr_inst</command>
+      <arg choice="plain"><replaceable>VARIABLE_NAME</replaceable></arg>
+      <arg rep="repeat"><replaceable>VARIABLE_NAME</replaceable></arg>
+      <arg choice='plain'>;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+
+<refsect1><title>Description</title>
+<para>
+<command>olr_inst</command> declares instruments for optimal policy computed by <xref linkend='olr'/>.
+</para>
+</refsect1>
+</refentry>
+
+<refentry id="optim_weights">
+  <refmeta>
+    <refentrytitle>optim_weights</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>optim_weights</refname>
+    <refpurpose>specifies quadratic objectives for optimal policy problems</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>optim_weights;</command><sbr/>
+	<group choice="plain">
+	  <arg choice="plain">
+	    <synopfragmentref linkend="var_st1">VARIANCE STATEMENT</synopfragmentref>
+	  </arg>
+	  <arg choice="plain">
+	    <synopfragmentref linkend="covar_st1">COVARIANCE STATEMENT</synopfragmentref>
+	  </arg>
+	  <arg choice="plain">
+	    <synopfragmentref linkend="stderr_st1">STANDARD ERROR STATEMENT</synopfragmentref>
+	  </arg>
+	</group>
+      <arg choice ="plain">end;</arg>
+      <synopfragment id="var_st1">
+	<arg choice="plain">
+	  var <replaceable>VARIABLE_NAME</replaceable> = <replaceable>EXPRESSION</replaceable>;
+	</arg>
+      </synopfragment>
+      <synopfragment id="covar_st1">
+	<arg choice="plain">
+	  var <replaceable>VARIABLE_NAME</replaceable> , <replaceable>VARIABLE_NAME</replaceable> = <replaceable>EXPRESSION</replaceable>;
+	</arg>
+      </synopfragment>
+      <synopfragment id="stderr_st1">
+	<arg choice="plain">
+	  var <replaceable>VARIABLE_NAME</replaceable>; stderr <replaceable>EXPRESSION</replaceable>;
+	</arg>
+      </synopfragment>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+<refsect1><title>Description</title>
+<para>
+<command>optim_weights</command> secifies the nonzero elements of the quadratic weight matrices for the objectives in <xref linkend='olr'/> and <xref linkend='osr'/>
+</para>
+</refsect1>
+</refentry>
+
+<refentry id="osr">
+  <refmeta>
+    <refentrytitle>osr</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>osr</refname>
+    <refpurpose>computes optimal simple policy rules</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>osr</command>
+      <arg>(<arg rep="repeat" choice="plain"><replaceable>OPTION</replaceable>,</arg>)</arg>
+      <arg choice="plain"><replaceable>VARIABLE_NAME</replaceable></arg>
+      <arg rep="repeat"><replaceable>VARIABLE_NAME</replaceable></arg>
+      <arg choice='plain'>;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>OPTIONS</title>
+<itemizedlist spacing='compact'>
+<listitem><para>All options for <xref linkend="stoch_simul"/></para></listitem>
+</itemizedlist>
+</refsect1>
+
+<refsect1><title>Description</title>
+<para>
+<command>osr</command> computes optimal simple policy rules for linear--quadratic problems of the form
+</para>
+<blockquote><para>
+max<subscript>&gamma;</subscript> E(y<subscript>t</subscript>&prime;Wy<subscript>t</subscript>)
+</para>
+<para>s.t.</para>
+<para>
+  A<subscript>1</subscript>E<subscript>t</subscript>(y<subscript>t+1</subscript>)+A<subscript>2</subscript>y<subscript>t</subscript>+A<subscript>3</subscript>y<subscript>t-1</subscript>+Ce<subscript>t</subscript>=0
+</para>
+</blockquote>
+<para>with</para>
+<itemizedlist>
+<listitem><para>&gamma;: parameters to be optimized. They must be elements of matrices A<subscript>1</subscript>, A<subscript>2</subscript>, A<subscript>3</subscript>.</para></listitem>
+<listitem><para>y: endogenous variables</para></listitem>
+<listitem><para>e: exogenous stochastic shocks</para></listitem>
+</itemizedlist>
+<para>The parameters to be optimized must be listed with <xref linkend='osr_params'/>.
+</para>
+<para>The quadratic objectives must be listed with <xref linkend='optim_weights'/>.
+</para>
+<para>
+This problem is solved using a numerical optimizer.
+</para>
+</refsect1>
+</refentry>
+
+<refentry id="osr_params">
+  <refmeta>
+    <refentrytitle>osr_params</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>osr_params</refname>
+    <refpurpose>declares the parameters to be optimized for optimal simple rules</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>osr_params</command>
+      <arg choice="plain"><replaceable>PARAMETER_NAME</replaceable></arg>
+      <arg rep="repeat"><replaceable>PARAMETER_NAME</replaceable></arg>
+      <arg choice='plain'>;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+
+<refsect1><title>Description</title>
+<para>
+<command>osr_params</command> declares parameters to be optimized  by <xref linkend='osr'/>.
+</para>
+</refsect1>
+</refentry>
+
+
+</sect1>
+<sect1><title>Displaying and saving results</title>
+<para>
+Dynare has comments to plot the results of a simulation and to save the results.
+</para>
+<itemizedlist>
+<listitem><para><xref linkend='rplot'/></para></listitem>
+<listitem><para><xref linkend='dynatype'/></para></listitem>
+<listitem><para><xref linkend='dynasave'/></para></listitem>
+</itemizedlist>
+
+<refentry id="rplot">
+  <refmeta>
+    <refentrytitle>rplot</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>rplot</refname>
+    <refpurpose>plot variables</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>rplot</command>
+      <arg choice="plain">
+      <replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+      <arg rep="repeat">
+      <replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+      <arg choice="plain">;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+<refsect1><title>Description</title>
+<para>
+Plots one or several variables
+</para>
+</refsect1>
+</refentry>
+
+<refentry id="dynatype">
+  <refmeta>
+    <refentrytitle>dynatype</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>dynatype</refname>
+    <refpurpose>print simulated variables</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>dynatype</command>
+      <arg>
+      (<replaceable>FILENAME</replaceable>)
+      </arg>
+      <arg choice="plain">
+      <replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+      <arg rep="repeat">
+      <replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+      <arg choice="plain">;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>Description</title>
+<para>
+<command>dynatype</command> prints the listed variables in a text file named <replaceable>FILENAME</replaceable>. If no <replaceable>VARIABLE_NAME</replaceable> are listed, all endogenous variables are printed.
+</para>
+</refsect1>
+
+</refentry>
+
+<refentry id="dynasave">
+  <refmeta>
+    <refentrytitle>dynasave</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>dynasave</refname>
+    <refpurpose>save simulated variables in a binary file</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>dynasave</command>
+      <arg>
+      (<replaceable>FILENAME</replaceable>)
+      </arg>
+      <arg choice="plain">
+      <replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+      <arg rep="repeat">
+      <replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+      <arg choice="plain">;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+<refsect1><title>Description</title>
+<para>
+<command>dynasave</command> saves the listed variables in a binary file named <replaceable>FILENAME</replaceable>. If no <replaceable>VARIABLE_NAME</replaceable> are listed, all endogenous variables are saved.
+</para>
+<para>
+In Matlab, variables saved with the <command>dynasave</command> command can be retrieved by the Matlab command <command>load -mat <replaceable>FILENAME</replaceable></command>.
+</para>
+</refsect1>
+</refentry>
+</sect1>
+
+<sect1><title>Conditional compilation</title>
+<para>
+Dynare has the following commands to choose which part of the *.mod file is executed. This is useful to maintain several versions of a model in the same *.mod file.
+</para>
+<itemizedlist>
+<listitem><para><xref linkend='define'/></para></listitem>
+<listitem><para><xref linkend='if_elseif_else_end'/></para></listitem>
+</itemizedlist>
+
+<refentry id="define">
+  <refmeta>
+    <refentrytitle>@define</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>@define</refname>
+    <refpurpose>defines a macro</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>@define</command>
+      <arg choice="plain">
+      <replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+      <arg choice="plain">
+      <replaceable>INTEGER</replaceable>
+      </arg>
+      <arg choice="plain">;</arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+<refsect1><title>Description</title>
+<para>
+<command>@define</command> defines a macro with name <replaceable>VARIABLE_NAME</replaceable> and value <replaceable>INTEGER</replaceable>. This macro can be used later in the *.mod file only in <command>@if</command> or <command>@elseif</command> statements. The macros can't be used to replace arbitrary part of codes like in C, for example.
+</para>
+</refsect1>
+
+<refsect1><title>Example</title>
+<para>
+<informalexample>
+<programlisting>
+  @define version 1;
+</programlisting>
+</informalexample>
+</para>
+</refsect1>
+
+</refentry>
+
+<refentry id="if_elseif_else_end">
+  <refmeta>
+    <refentrytitle>@if ... @elseif ... @else ... @end</refentrytitle>
+  </refmeta>
+
+  <refnamediv>
+    <refname>@if ... @elseif ... @else ... @end</refname>
+    <refpurpose>defines conditional compilation of the *.mod file</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>@if</command>
+      <arg choice="plain">
+      <replaceable>VARIABLE_NAME</replaceable>
+      </arg>
+      <arg choice="plain">
+      <replaceable>LOGICAL_OPERATOR</replaceable>
+      </arg>
+      <arg choice="plain">
+      <replaceable>INTEGER</replaceable>
+      </arg>
+      <arg choice="plain">;</arg><sbr/>
+      <arg choice="plain">...</arg><sbr/>
+        
+    </cmdsynopsis>
+  </refsynopsisdiv>
+<refsect1><title>Description</title>
+<para><replaceable>LOGICAL_OPERATOR</replaceable> are
+<itemizedlist>
+<listitem><para>== equal</para></listitem>
+<listitem><para>!= not equal</para></listitem>
+<listitem><para>&lt; lesser than</para></listitem>
+<listitem><para>&gt; greater than</para></listitem>
+<listitem><para>&lt;= lesser or equal than</para></listitem>
+<listitem><para>&gt;= greater or equal than</para></listitem>
+</itemizedlist>
+</para>
+
+<para>
+These commands let the user define which part of the *.mod file should be handled by Dynare
+</para>
+</refsect1>
+
+<refsect1><title>Example</title>
+<para>
+<informalexample>
+<programlisting>
+  @define version 1;
+  parameters alph bet;
+  alph = 0.3;
+  @if version == 1;
+    bet = 0.9;
+  @elseif version == 2;
+    bet = 0.95;
+  @else;
+    bet = 0.98;
+  @end;
+</programlisting>
+</informalexample>
+</para>
+</refsect1>
+
+</refentry>
+
+</sect1>
+</chapter>
+
+<chapter><title>Examples</title>
+<para>
+Fabrice Collard (GREMAQ, University of Toulouse) has written a guide to stochastic simulations with Dynare entitled "Dynare in Practice" which is in <filename>guide.pdf</filename>.
+</para>
+</chapter>
+
+<bibliography>
+<biblioentry>
+  <biblioset relation="article">
+    <author>
+      <surname> Boucekkine</surname>
+      <firstname> Raouf</firstname>
+    </author>
+    <pubdate>1995</pubdate>
+    <title>An alternative methodology for solving nonlinear forward-looking models</title>
+  </biblioset>
+  <biblioset relation="journal">
+    <title>Journal of Economic Dynamics and Control</title>
+    <volumenum>19</volumenum>
+    <pagenums>711-734</pagenums>
+  </biblioset>
+</biblioentry>
+<biblioentry>
+  <biblioset relation="article">
+    <authorgroup>
+      <author>
+	<surname>Collard</surname>
+	<firstname>Fabrice</firstname>
+      </author>
+      <author>
+	<surname>Juillard</surname>
+	<firstname>Michel</firstname>
+      </author>
+    </authorgroup>
+    <pubdate>2001</pubdate>
+    <title>Accuracy of stochastic perturbation methods: The case of asset pricing models</title>
+  </biblioset>
+  <biblioset relation="journal">
+    <title>Journal of Economic Dynamics and Control</title>
+    <volumenum>25</volumenum>
+    <pagenums>979-999</pagenums>
+  </biblioset>
+</biblioentry>
+
+<biblioentry> 
+  <biblioset relation="article">
+    <authorgroup>
+      <author>
+	<surname>Collard</surname>
+	<firstname>Fabrice</firstname>
+      </author>
+      <author>
+	<surname>Juillard</surname>
+	<firstname>Michel</firstname>
+      </author>
+    </authorgroup>
+    <pubdate>2001</pubdate>
+    <title>A Higher-Order Taylor Expansion Approach to Simulation of Stochastic Forward-Looking Models with an Application to a Non-Linear Phillips Curve</title>
+  </biblioset>
+  <biblioset relation="journal">
+    <title>Computational Economics</title>
+    <volumenum>17</volumenum>
+    <pagenums>125-139</pagenums>
+  </biblioset>
+</biblioentry>
+
+<biblioentry>
+  <biblioset relation="book">
+    <authorgroup>
+      <author>
+	<surname>Durbin</surname>
+	<firstname>J.</firstname>
+      </author>
+      <author>
+	<surname>Koopman</surname>
+	<firstname>S.J.</firstname>
+      </author>
+    </authorgroup>
+    <pubdate>2001</pubdate>
+    <title>Time Series Analysis by State Space Methods</title>
+    <publishername>Oxford University Press</publishername>
+  </biblioset>
+</biblioentry>
+
+<biblioentry>
+  <biblioset relation="article">
+    <authorgroup>
+      <author>
+	<surname>Fair</surname>
+	<firstname>Ray</firstname>
+      </author>
+      <author>
+	<surname>Taylor</surname>
+	<firstname>John</firstname>
+      </author>
+    </authorgroup>
+    <pubdate>1983</pubdate>
+    <title>Solution and Maximum Likelihood Estimation of Dynamic Nonlinear Rational Expectation Models</title>
+  </biblioset>
+  <biblioset relation="journal">
+    <title>Econometrica</title>
+    <volumenum>51</volumenum>
+    <pagenums>1169-1185</pagenums>
+  </biblioset>
+</biblioentry>
+
+<biblioentry>
+  <biblioset relation="article">
+    <authorgroup>
+      <author>
+	<surname>Fernandez-Villaverde</surname>
+	<firstname>Jesus</firstname>
+      </author>
+      <author>
+	<surname>Rubio-Ramirez</surname>
+	<firstname>Juan</firstname>
+      </author>
+    </authorgroup>
+    <pubdate>2004</pubdate>
+    <title>Comparing Dynamic Equilibrium Economies to Data: A Bayesian Approach</title>
+  </biblioset>
+  <biblioset relation="journal">
+  <title>Journal of Econometrics</title>
+  <volumenum>123</volumenum>
+    <pagenums>153-187</pagenums>
+  </biblioset>
+</biblioentry>
+
+<biblioentry>   
+  <biblioset relation="article">
+    <author>
+      <surname>Ireland</surname>
+      <firstname>Peter</firstname>
+    </author>
+    <pubdate>2004</pubdate>
+    <title>A Method for Taking Models to the Data</title>
+  </biblioset>
+  <biblioset relation="journal">
+    <title>Journal of Economic Dynamics and Control</title>
+    <volumenum>28</volumenum>
+    <pagenums>1205-26</pagenums>
+  </biblioset>
+</biblioentry>
+
+<biblioentry>  
+  <biblioset relation="article">
+    <author>
+      <surname>Judd</surname>
+      <firstname>Kenneth</firstname>
+    </author>
+    <pubdate>1996</pubdate>    
+    <title>Approximation, Perturbation, and Projection Methods in Economic Analysis</title>
+  </biblioset>
+  <biblioset relation="book">
+    <authorgroup>
+      <author>
+	<surname>Amman</surname>
+	<firstname>Hans</firstname>
+      </author>
+      <author>
+	<surname>Kendrick</surname>
+	<firstname>David</firstname>
+      </author>
+      <author>
+	<surname>Rust</surname>
+	<firstname>John</firstname>
+      </author>
+    </authorgroup>
+    <title>Handbook of Computational Economics</title>
+    <pubdate>1996</pubdate>
+    <publishername>North Holland Press</publishername>
+    <pagenums>511-585</pagenums>
+  </biblioset>
+</biblioentry>
+
+<biblioentry> 
+      <author>
+	<surname>Juillard</surname>
+	<firstname>Michel</firstname>
+      </author>
+      <pubdate>1996</pubdate>
+      <title>Dynare: A program for the resolution and simulation of dynamic models with forward variables through the use of a relaxation algorithm</title>
+      <orgname>CEPREMAP</orgname>
+      <citetitle>Couverture Orange</citetitle>
+      <volumenum>9602</volumenum>
+</biblioentry>
+
+<biblioentry>
+  <biblioset relation="article">
+    <authorgroup>
+      <author>
+	<surname>Koopman</surname>
+	<firstname>S.J.</firstname>
+      </author>
+      <author>
+	<surname>Durbin</surname>
+	<firstname>J.</firstname>
+      </author>
+    </authorgroup>
+    <pubdate>2003</pubdate>
+    <title>Filtering and Smoothing of State Vector for Diffuse State Space Models</title>
+  </biblioset>
+  <biblioset relation="journal">
+    <title>Journal of Time Series Analysis</title>
+    <volumenum>24</volumenum>
+    <pagenums>85-98</pagenums>
+  </biblioset>
+</biblioentry>
+
+<biblioentry>   
+  <biblioset relation="article">
+    <author>
+      <surname>Laffargue</surname>
+      <firstname>Jean-Pierre</firstname>
+    </author>
+    <title>Résolution d'un modèle macroéconomique avec anticipations rationnelles</title>
+    <pubdate>1990</pubdate>
+  </biblioset>
+  <biblioset relation="journal">
+    <title>Annales d'Economie et Statistique</title>
+    <volumenum>17</volumenum>
+    <pagenums>97-119</pagenums>
+  </biblioset>
+</biblioentry>
+<biblioentry> 
+  <authorgroup>
+  <author>
+    <surname>Lubik</surname>
+    <firstname>Thomas</firstname>
+  </author>
+  <author>
+    <surname>Schorfheide</surname>
+    <firstname>Frank</firstname>
+  </author>
+  </authorgroup>
+  <pubdate>2003</pubdate>
+  <title>Do Central Banks Target Exchange Rates? A Structural Investigation</title>
+  <orgname>University of Pennsylvania</orgname>
+</biblioentry>
+<biblioentry> 
+  <authorgroup>
+    <author>
+      <surname>Rabanal</surname>
+      <firstname>Pau</firstname>
+    </author>
+    <author>
+      <surname>Rubio-Ramirez</surname>
+      <firstname>Juan</firstname>
+    </author>
+  </authorgroup>
+  <pubdate>2003</pubdate>
+  <title>Comparing New Keynesian Models of the Business Cycle: A Bayesian Approach</title>
+  <orgname>Atlanta Fed</orgname>
+<citetitle>Working Paper</citetitle>
+<volumenum>2001-22a, rev 2003</volumenum>
+</biblioentry>
+
+<biblioentry> 
+  <biblioset relation="article">
+    <author>
+      <surname>Schorfheide</surname>
+      <firstname>Frank</firstname>
+    </author>
+  <pubdate>2000</pubdate>
+  <title>Loss Function-based evaluation of DSGE models</title>
+  </biblioset>
+  <biblioset relation="journal">
+    <title>Journal of Applied Econometrics</title>
+    <volumenum>15</volumenum>
+    <pagenums>645-70</pagenums>
+  </biblioset>
+</biblioentry>
+
+<biblioentry> 
+  <authorgroup>
+    <author>
+      <surname>Schmitt-Grohe</surname>
+      <firstname>Stephanie</firstname>
+    </author>
+    <author>
+      <surname>Uribe</surname>
+      <firstname>Martin</firstname>
+    </author>
+  </authorgroup>
+  <pubdate>2002</pubdate>
+  <title>Solving Dynamic General Equilibrium Models Using a Second-Order Approximation to the Policy Function</title>
+  <orgname>Rutgers University</orgname>
+</biblioentry>
+
+<biblioentry> 
+  <authorgroup>
+    <author>
+      <surname>Smets</surname>
+      <firstname>Frank</firstname>
+    </author>
+    <author>
+      <surname>Wouters</surname>
+      <firstname>Rafael</firstname>
+    </author>
+  </authorgroup>
+  <pubdate>2002</pubdate>
+  <title>An Estimated Stochastic Dynamic General
+Equilibrium Model of the Euro Area</title>
+  <orgname>European Central Bank</orgname>
+      <citetitle>ECB Working Paper</citetitle>
+      <volumenum>171</volumenum>
+</biblioentry>
+</bibliography>
+<index>
+</index>
+</book>
+
diff --git a/tags/v_3.062/doc/unit_roots.tex b/tags/v_3.062/doc/unit_roots.tex
new file mode 100644
index 0000000000000000000000000000000000000000..b6f42ac6859f307eceb6711e12a405e4d821ae2d
--- /dev/null
+++ b/tags/v_3.062/doc/unit_roots.tex
@@ -0,0 +1,89 @@
+\documentclass{article}
+\usepackage{times}
+\begin{document}
+\title{Notes on estimating models with unit-roots}
+\author{Michel Juillard}
+\maketitle
+
+It is now possible to estimate with DYNARE models with unit-roots. These models must satisfy the following restriction: the dynamics of stochastic trends must be (log)--linear and the dynamics of the stationary part around the stochastic trends may be non-linear. 
+
+\section{Steady state}
+
+For stationay models, DYNARE linearizes around the steady state, using the internal function dynare\_solve.m. When the dynamics of the stochastic trends doesn't contain a deterministic trend (when it is a pure random walk without displacement), there is an infinity of value of $\bar y$ satisfying $f(\bar y)=0$ and it is possible to specify one of them in INITVAL.
+
+When the stochastic trends contain a deterministic trend, there is no solution to the equation $f(\bar y)=0$. It is then necessary to provide DYNARE with a hand written function called \emph{fname\_steadystate.m} that returns the steady state values of the stationary variables and 0 for nonstationary variables when the model is linearized or 1 for nonstationary variables when the model is log--linearized. The variables must be ordered in alphabetical order. See /examples/fs2000a\_steadystate.m for an example. This procedure is cumbersome and we will be trying to automatize it in the future.
+
+\section{Estimation}
+
+For initializing the Kalman filter and for computing the smoother, DYNARE uses now the algorithm described in chapter 5 of J. Durbin and S.J. Koopman (2001) and in S.J. Koopman and J. Durbin (2003). Following the advice of these authors, we prefer it to the augmented filter advocated by De Jong. Note that the results are identical.
+
+In DYNARE, it is necessary to declare the stochastic trends thru the following statement:
+\begin{quote}
+  options\_.unit\_root\_vars = {'P\_obs'; 'Y\_obs'};
+\end{quote}
+This syntax is temporary and will be made more DYNARE-like.
+
+It is also necessary to set the option lik\_init=2 in the estimation statement.
+In the future, this should be triggered automatically from the declaration of a stochastic trend.
+
+It is also necessary to declare the deterministic components of the stochastic trends with the OBSERVATION\_TREND instruction (see /examples/fs2000/fs2000a.mod)
+
+The new functions are
+\begin{itemize}
+\item DgesLikelihood.m: replaces mj\_optmumlik for filtering
+\item DiffuseLikelihood1.m
+\item DiffuseLikelihood2.m
+\item DiffuseLikelihoodH1.m
+\item DiffuseLikelihoodH2.m
+\item DiffuseLikelihoodH3.m
+\item DgseSmoother.m: replaces mj\_optmumlik for smoothing
+\item DiffuseKalmanSmoother.m
+\item DiffuseKalmanSmootherH.m
+\end{itemize}
+They still need thorough testing.
+
+\section{Examples}
+
+DYNARE is now able to estimate purely backward models, in addition to forward--looking models. The first two examples are such to isolate the problematic of estimating nonstationary models from the difficulties of estimating forward--looking rational expectation models.
+
+\subsection{Two unrelated random walks}
+Artificial data (10000 observations) are generated by /examples/arima/mod1.mod for
+\begin{eqnarray*}
+  dx_t = 0.5dx_{t-1}+{e_x}_t\\
+  dy_t = -0.3dy_{t-1}+{e_y}_t\\
+  x_t = x_{t-1}+dx_t\\
+  y_t = y_{t-1}+dy_t
+\end{eqnarray*}
+
+mod1a.mod estimates this model when $dx_t$ and $dy_t$ are observed, and
+mod1b.mod when the level of the data, $x_t$ and $y_t$, are observed. As expected, the results are the same.
+
+\subsection{A cointegrated system} 
+
+Artificial data (10000 observations) are generated by /examples/arima/mod2.mod for
+\begin{eqnarray*}
+  dx_t = 0.5dx_{t-1}-0.1(x_{t-1}-y_{t-1})+{e_x}_t\\
+  dy_t = -0.3dy_{t-1}+0.2(x_{t-1}-y_{t-1})+{e_y}_t\\
+  x_t = x_{t-1}+dx_t\\
+  y_t = y_{t-1}+dy_t
+\end{eqnarray*}
+
+mod2a.mod estimates this model when $dx_t$ and $dy_t$ are observed, and $x$ and $y$ are treated as unobservable variables. The estimation procedure fails as the data is first difference don't contain any information about the initial level of $x$ and $y$.
+
+mod2c.mod again estimates this model when $dx_t$ and $dy_t$ are observed, but the model is reparametrized so as to have the cointegration error as stationary unobservable variable.
+
+mod2b.mod estimates the model with data in level: $x_t$ and $y_t$, are observed.In this case, and on moderate samples (100 observations), data in level provide additional information on the cointegrating relationship. 
+
+\subsection{Schorfheide, 2000}
+
+fs2000.mod estimates the CIA model of Schorfheide (2000) with observation of the rate of growth of prices and output. fs2000a.mod estimates with data in level. The posterior mode of parameters is somewhat different.
+
+
+\section*{References}
+\begin{description}
+\item J. Durbin and S.J. Koopman (2001) \emph{Time Series Analysis by State Space Methods}. Oxford: Oxford University Press.
+\item S.J. Koopman and J. Durbin (2003) ``Filtering and Smoothing of State Vector for Diffuse State Space Models'' in \emph{Journal of Time Series Analysis}, \emph{24}, pp. 85-98.  
+\end{description}
+
+ 
+\end{document}
diff --git a/tags/v_3.062/examples/arima/mod1.mod b/tags/v_3.062/examples/arima/mod1.mod
new file mode 100644
index 0000000000000000000000000000000000000000..7a8dabf2b5cc6cb72a2d3839e0658df66f8f9a80
--- /dev/null
+++ b/tags/v_3.062/examples/arima/mod1.mod
@@ -0,0 +1,23 @@
+var dx dy x y;
+varexo e_x e_y;
+
+parameters rho_x rho_y;
+
+rho_x = 0.5;
+rho_y = -0.3;
+
+model;
+dx = rho_x*dx(-1)+e_x;
+dy = rho_y*dy(-1)+e_y;
+x = x(-1)+dx;
+y = y(-1)+dy;
+end;
+
+shocks;
+var e_x; stderr 0.01;
+var e_y; stderr 0.01;
+end;
+
+stoch_simul(order=1,periods=1000,irf=0,nomoments);
+
+save data1 dx dy x y;
\ No newline at end of file
diff --git a/tags/v_3.062/examples/arima/mod1a.mod b/tags/v_3.062/examples/arima/mod1a.mod
new file mode 100644
index 0000000000000000000000000000000000000000..0d01eac00217c9cc95e89bc83ac9363cd8a2f887
--- /dev/null
+++ b/tags/v_3.062/examples/arima/mod1a.mod
@@ -0,0 +1,23 @@
+var dx dy;
+varexo e_x e_y;
+
+parameters rho_x rho_y;
+
+rho_x = 0.5;
+rho_y = -0.3;
+
+model;
+dx = rho_x*dx(-1)+e_x;
+dy = rho_y*dy(-1)+e_y;
+end;
+
+estimated_params;
+rho_x,NORMAL_PDF,0.5,0.1;
+rho_y,NORMAL_PDF,-0.3,0.1;
+stderr e_x,INV_GAMMA_PDF,0.01,inf;
+stderr e_y,INV_GAMMA_PDF,0.01,inf;
+end;
+
+varobs dx dy;
+
+estimation(datafile=data1,nobs=1000,mh_replic=2000);
\ No newline at end of file
diff --git a/tags/v_3.062/examples/arima/mod1b.mod b/tags/v_3.062/examples/arima/mod1b.mod
new file mode 100644
index 0000000000000000000000000000000000000000..39ed9d638af41d7cc6cc34851c9205f5f792d4f0
--- /dev/null
+++ b/tags/v_3.062/examples/arima/mod1b.mod
@@ -0,0 +1,25 @@
+var dx dy x y;
+varexo e_x e_y;
+
+parameters rho_x rho_y;
+
+rho_x = 0.5;
+rho_y = -0.3;
+
+model;
+dx = rho_x*dx(-1)+e_x;
+dy = rho_y*dy(-1)+e_y;
+x = x(-1)+dx;
+y = y(-1)+dy;
+end;
+
+estimated_params;
+rho_x,NORMAL_PDF,0.5,0.1;
+rho_y,NORMAL_PDF,-0.3,0.1;
+stderr e_x,INV_GAMMA_PDF,0.01,inf;
+stderr e_y,INV_GAMMA_PDF,0.01,inf;
+end;
+
+varobs x y;
+options_.unit_root_vars = {'x'; 'y'};
+estimation(datafile=data1,nobs=1000,mh_replic=0,load_mh_file,mode_compute=0,mode_file=mod1b_mode,kalman_algo=3,smoother,forecast=4,bayesian_irf,irf=10,filtered_vars,moments_varendo);
\ No newline at end of file
diff --git a/tags/v_3.062/examples/arima/mod1c.mod b/tags/v_3.062/examples/arima/mod1c.mod
new file mode 100644
index 0000000000000000000000000000000000000000..a77478a856f9ecbf719817cfba29e6e5a212f52f
--- /dev/null
+++ b/tags/v_3.062/examples/arima/mod1c.mod
@@ -0,0 +1,27 @@
+var dx dy x y;
+varexo e_x e_y;
+
+parameters rho_x rho_y;
+
+rho_x = 0.5;
+rho_y = -0.3;
+
+model;
+dx = rho_x*dx(-1)+e_x;
+dy = rho_y*dy(-1)+e_y;
+x = x(-1)+dx;
+y = y(-1)+dy;
+end;
+
+estimated_params;
+rho_x,NORMAL_PDF,0.5,0.1;
+rho_y,NORMAL_PDF,-0.3,0.1;
+stderr e_x,INV_GAMMA_PDF,0.01,inf;
+stderr e_y,INV_GAMMA_PDF,0.01,inf;
+stderr x,INV_GAMMA_PDF,0.01,inf;
+stderr y,INV_GAMMA_PDF,0.01,inf;
+end;
+
+varobs x y;
+options_.unit_root_vars = {'x'; 'y'};
+estimation(datafile=data1,nobs=1000,mh_replic=2000,lik_init=2);
\ No newline at end of file
diff --git a/tags/v_3.062/examples/arima/mod1d.mod b/tags/v_3.062/examples/arima/mod1d.mod
new file mode 100644
index 0000000000000000000000000000000000000000..f19e9888c6fba2c3a5290e945afc3bae1ca070ae
--- /dev/null
+++ b/tags/v_3.062/examples/arima/mod1d.mod
@@ -0,0 +1,26 @@
+var dx dy x y;
+varexo e_x e_y;
+
+parameters rho_x rho_y;
+
+rho_x = 0.5;
+rho_y = -0.3;
+
+model;
+dx = rho_x*dx(-1)+e_x;
+dy = rho_y*dy(-1)+e_y;
+x = x(-1)+dx;
+y = y(-1)+dy;
+end;
+
+estimated_params;
+rho_x,NORMAL_PDF,0.5,0.1;
+rho_y,NORMAL_PDF,-0.3,0.1;
+stderr e_x,INV_GAMMA_PDF,0.01,inf;
+stderr e_y,INV_GAMMA_PDF,0.01,inf;
+corr e_x, e_y, BETA_PDF,0.0,0.3,-1,1;
+end;
+
+varobs x y;
+options_.unit_root_vars = {'x'; 'y'};
+estimation(datafile=data1,nobs=1000,mh_replic=2000,mh_jscale=1.2,kalman_algo=3,smoother,forecast=4,bayesian_irf,irf=10,filtered_vars);
\ No newline at end of file
diff --git a/tags/v_3.062/examples/arima/mod2.mod b/tags/v_3.062/examples/arima/mod2.mod
new file mode 100644
index 0000000000000000000000000000000000000000..c84df189282c1422a5fbdcd2a2d4e0f545eaa70a
--- /dev/null
+++ b/tags/v_3.062/examples/arima/mod2.mod
@@ -0,0 +1,26 @@
+var dx dy x y;
+varexo e_x e_y;
+
+parameters rho_x rho_y b a1 a2;
+
+rho_x = 0.5;
+rho_y = -0.3;
+b = 1;
+a1 = -0.1;
+a2 = 0.2;
+
+model;
+dx = rho_x*dx(-1)+a1*(x(-1)-b*y(-1))+e_x;
+dy = rho_y*dy(-1)+a2*(x(-1)-b*y(-1))+e_y;
+x = x(-1)+dx;
+y = y(-1)+dy;
+end;
+
+shocks;
+var e_x; stderr 0.01;
+var e_y; stderr 0.01;
+end;
+
+stoch_simul(order=1,periods=1000,irf=0,nomoments);
+
+save data2 dx dy x y;
\ No newline at end of file
diff --git a/tags/v_3.062/examples/arima/mod2a.mod b/tags/v_3.062/examples/arima/mod2a.mod
new file mode 100644
index 0000000000000000000000000000000000000000..9414afa902c6cc374bb157d969cad8927db5120c
--- /dev/null
+++ b/tags/v_3.062/examples/arima/mod2a.mod
@@ -0,0 +1,33 @@
+var dx dy x y;
+varexo e_x e_y;
+
+parameters rho_x rho_y b a1 a2;
+
+rho_x = 0.5;
+rho_y = -0.3;
+b = 1;
+a1 = -0.1;
+a2 = 0.2;
+
+model;
+dx = rho_x*dx(-1)+a1*(x(-1)-b*y(-1))+e_x;
+dy = rho_y*dy(-1)+a2*(x(-1)-b*y(-1))+e_y;
+x = x(-1)+dx;
+y = y(-1)+dy;
+end;
+
+estimated_params;
+rho_x,NORMAL_PDF,0.5,0.1;
+rho_y,NORMAL_PDF,-0.3,0.1;
+b,NORMAL_PDF,1,0.1;
+a1,NORMAL_PDF,-0.1,0.1;
+a2,NORMAL_PDF,0.2,0.1;
+
+stderr e_x,INV_GAMMA_PDF,0.01,inf;
+stderr e_y,INV_GAMMA_PDF,0.01,inf;
+end;
+
+varobs dx dy;
+
+options_.unit_root_vars = {'x'; 'y'};
+estimation(datafile=data2,nobs=100,mh_replic=0,lik_init=2);
diff --git a/tags/v_3.062/examples/arima/mod2b.mod b/tags/v_3.062/examples/arima/mod2b.mod
new file mode 100644
index 0000000000000000000000000000000000000000..d2465a22c31088d51f0fb62a78470df1399e7a66
--- /dev/null
+++ b/tags/v_3.062/examples/arima/mod2b.mod
@@ -0,0 +1,33 @@
+var dx dy x y;
+varexo e_x e_y;
+
+parameters rho_x rho_y b a1 a2;
+
+rho_x = 0.5;
+rho_y = -0.3;
+b = 1;
+a1 = -0.1;
+a2 = 0.2;
+
+model;
+dx = rho_x*dx(-1)+a1*(x(-1)-b*y(-1))+e_x;
+dy = rho_y*dy(-1)+a2*(x(-1)-b*y(-1))+e_y;
+x = x(-1)+dx;
+y = y(-1)+dy;
+end;
+
+estimated_params;
+rho_x,NORMAL_PDF,0.5,0.1;
+rho_y,NORMAL_PDF,-0.3,0.1;
+b,NORMAL_PDF,1,0.1;
+a1,NORMAL_PDF,-0.1,0.1;
+a2,NORMAL_PDF,0.2,0.1;
+
+stderr e_x,INV_GAMMA_PDF,0.01,inf;
+stderr e_y,INV_GAMMA_PDF,0.01,inf;
+end;
+
+varobs x y;
+
+options_.unit_root_vars = {'x'; 'y'};
+estimation(datafile=data2,nobs=100,mh_replic=0,lik_init=2);
diff --git a/tags/v_3.062/examples/arima/mod2c.mod b/tags/v_3.062/examples/arima/mod2c.mod
new file mode 100644
index 0000000000000000000000000000000000000000..8ce2cae8ef608b6cdd6c1772929306410dd83ad0
--- /dev/null
+++ b/tags/v_3.062/examples/arima/mod2c.mod
@@ -0,0 +1,31 @@
+var dx dy coint_err;
+varexo e_x e_y;
+
+parameters rho_x rho_y b a1 a2;
+
+rho_x = 0.5;
+rho_y = -0.3;
+b = 1;
+a1 = -0.1;
+a2 = 0.2;
+
+model;
+dx = rho_x*dx(-1)+a1*coint_err(-1)+e_x;
+dy = rho_y*dy(-1)+a2*coint_err(-1)+e_y;
+coint_err = dx-b*dy+coint_err(-1);
+end;
+
+estimated_params;
+rho_x,NORMAL_PDF,0.5,0.1;
+rho_y,NORMAL_PDF,-0.3,0.1;
+b,NORMAL_PDF,1,0.1;
+a1,NORMAL_PDF,-0.1,0.1;
+a2,NORMAL_PDF,0.2,0.1;
+
+stderr e_x,INV_GAMMA_PDF,0.01,inf;
+stderr e_y,INV_GAMMA_PDF,0.01,inf;
+end;
+
+varobs dx dy;
+
+estimation(datafile=data2,nobs=100,mh_replic=0);
diff --git a/tags/v_3.062/examples/example1.mod b/tags/v_3.062/examples/example1.mod
new file mode 100644
index 0000000000000000000000000000000000000000..334ef7906a06896d36370214e328291cf94bfd00
--- /dev/null
+++ b/tags/v_3.062/examples/example1.mod
@@ -0,0 +1,44 @@
+// example 1 from Collard's guide to Dynare
+var y, c, k, a, h, b;
+varexo e,u;
+
+parameters beta, rho, beta, 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*(((exp(b)*c)/(exp(b(+1))*c(+1)))
+    *(exp(b(+1))*alpha*y(+1)+(1-delta)*k));
+y = exp(a)*(k(-1)^alpha)*(h^(1-alpha));
+k = exp(b)*(y-c)+(1-delta)*k(-1);
+a = rho*a(-1)+tau*b(-1) + e;
+b = tau*a(-1)+rho*b(-1) + u;
+end;
+
+initval;
+y = 1.08068253095672;
+c = 0.80359242014163;
+h = 0.29175631001732;
+k = 5;
+a = 0;
+b = 0;
+e = 0;
+u = 0;
+end;
+
+shocks;
+var e; stderr 0.009;
+var u; stderr 0.009;
+var e, u = phi*0.009*0.009;
+end;
+
+stoch_simul(periods=2100);
diff --git a/tags/v_3.062/examples/example2.mod b/tags/v_3.062/examples/example2.mod
new file mode 100644
index 0000000000000000000000000000000000000000..e2c4eeb1b6b52e50bfbbd794e3a51db26221ed8a
--- /dev/null
+++ b/tags/v_3.062/examples/example2.mod
@@ -0,0 +1,44 @@
+// example 2 from Collard's guide to Dynare
+var y, c, k, a, h, b;
+varexo e,u;
+
+parameters beta, rho, beta, 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;
+
+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 = 0.1;
+c = -0.2;
+h = -1.2;
+k =  2.4;
+a = 0;
+b = 0;
+e = 0;
+u = 0;
+end;
+
+steady;
+
+shocks;
+var e = 0.009^2;
+var u = 0.009^2;
+end;
+
+stoch_simul(dr_algo=1,drop=200);
+
diff --git a/tags/v_3.062/examples/fs2000/fs2000.mod b/tags/v_3.062/examples/fs2000/fs2000.mod
new file mode 100644
index 0000000000000000000000000000000000000000..90c2853b7506b24a8bfc1faa1cd1509587a6d4fa
--- /dev/null
+++ b/tags/v_3.062/examples/fs2000/fs2000.mod
@@ -0,0 +1,91 @@
+// This file replicates the estimation of the CIA model from 
+// Frank Schorfheide (2000) "Loss function-based evaluation of DSGE models" 
+// Journal of  Applied Econometrics, 15, 645-670.
+// the data are the ones provided on Schorfheide's web site with the programs.
+// http://www.econ.upenn.edu/~schorf/programs/dsgesel.ZIP
+// You need to have fsdat.m in the same directory as this file.
+// This file replicates: 
+// -the posterior mode as computed by Frank's Gauss programs
+// -the parameter mean posterior estimates reported in the paper
+// -the model probability (harmonic mean) reported in the paper
+// This file was tested with dyn_mat_test_0218.zip
+// the smooth shocks are probably stil buggy
+//
+// The equations are taken from J. Nason and T. Cogley (1994) 
+// "Testing the implications of long-run neutrality for monetary business
+// cycle models" Journal of Applied Econometrics, 9, S37-S70.
+// Note that there is an initial minus sign missing in equation (A1), p. S63.
+//
+// Michel Juillard, February 2004
+
+var m P c e W R k d n l gy_obs gp_obs y dA;
+varexo e_a e_m;
+
+parameters alp bet gam mst rho psi del;
+
+alp = 0.33;
+bet = 0.99;
+gam = 0.003;
+mst = 1.011;
+rho = 0.7;
+psi = 0.787;
+del = 0.02;
+
+model;
+dA = exp(gam+e_a);
+log(m) = (1-rho)*log(mst) + rho*log(m(-1))+e_m;
+-P/(c(+1)*P(+1)*m)+bet*P(+1)*(alp*exp(-alp*(gam+log(e(+1))))*k^(alp-1)*n(+1)^(1-alp)+(1-del)*exp(-(gam+log(e(+1)))))/(c(+2)*P(+2)*m(+1))=0;
+W = l/n;
+-(psi/(1-psi))*(c*P/(1-n))+l/n = 0;
+R = P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(-alp)/W;
+1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)/(m*l*c(+1)*P(+1)) = 0;
+c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1);
+P*c = m;
+m-1+d = l;
+e = exp(e_a);
+y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a));
+gy_obs = dA*y/y(-1);
+gp_obs = (p/p(-1))*m(-1)/dA;
+end;
+
+initval;
+k = 6;
+m = mst;
+P = 2.25;
+c = 0.45;
+e = 1;
+W = 4;
+R = 1.02;
+d = 0.85;
+n = 0.19;
+l = 0.86;
+y = 0.6;
+gy_obs = exp(gam);
+gp_obs = exp(-gam); 
+dA = exp(gam);
+end;
+
+shocks;
+var e_a; stderr 0.014;
+var e_m; stderr 0.005;
+end;
+
+steady;
+
+estimated_params;
+alp, beta_pdf, 0.356, 0.02; 
+bet, beta_pdf, 0.993, 0.002;
+gam, normal_pdf, 0.0085, 0.003;
+mst, normal_pdf, 1.0002, 0.007;
+rho, beta_pdf, 0.129, 0.223;
+psi, beta_pdf, 0.65, 0.05;
+del, beta_pdf, 0.01, 0.005;
+stderr e_a, inv_gamma_pdf, 0.035449, inf;
+stderr e_m, inv_gamma_pdf, 0.008862, inf;
+end;
+
+varobs gp_obs gy_obs;
+
+// computes only the posterior mode for demonstration. 
+//For full Metropolis simulation set mh_replic=20000. It will take several hours
+estimation(datafile=fsdat,nobs=192,loglinear,mh_replic=0,mh_nblocks=5,mh_jscale=0.8);
\ No newline at end of file
diff --git a/tags/v_3.062/examples/fs2000/fs2000a.mod b/tags/v_3.062/examples/fs2000/fs2000a.mod
new file mode 100644
index 0000000000000000000000000000000000000000..b481d54e2d794408e42f78a6a17f1c43936193d2
--- /dev/null
+++ b/tags/v_3.062/examples/fs2000/fs2000a.mod
@@ -0,0 +1,112 @@
+// This file replicates the estimation of the CIA model from 
+// Frank Schorfheide (2000) "Loss function-based evaluation of DSGE models" 
+// Journal of  Applied Econometrics, 15, 645-670.
+// the data are the ones provided on Schorfheide's web site with the programs.
+// http://www.econ.upenn.edu/~schorf/programs/dsgesel.ZIP
+// You need to have fsdat.m in the same directory as this file.
+// This file replicates: 
+// -the posterior mode as computed by Frank's Gauss programs
+// -the parameter mean posterior estimates reported in the paper
+// -the model probability (harmonic mean) reported in the paper
+// This file was tested with dyn_mat_test_0218.zip
+// the smooth shocks are probably stil buggy
+//
+// The equations are taken from J. Nason and T. Cogley (1994) 
+// "Testing the implications of long-run neutrality for monetary business
+// cycle models" Journal of Applied Econometrics, 9, S37-S70.
+// Note that there is an initial minus sign missing in equation (A1), p. S63.
+//
+// Michel Juillard, February 2004
+
+// This version estimates the model in level.
+// Because the model in level contains unit roots, the problem for computing
+// the steady state is cirumvent by using fs2000a_steadystate.m that computes
+// the analytical steady state for the stationary part of the model and
+// set values of Y_obs and P_obs, the two stochastic trends in the model,
+// to the arbitrary value of 1. As the unit root dynamic is loglinear, 
+// it doesn't matter around which value the loglinearization is computed.
+// This handling of stochastic trends will be made simpler in a future version
+// of Dynare
+
+var m P c e W R k d n l gy_obs gp_obs Y_obs P_obs y dA;
+varexo e_a e_m;
+
+parameters alp bet gam mst rho psi del;
+
+alp = 0.33;
+bet = 0.99;
+gam = 0.003;
+mst = 1.011;
+rho = 0.7;
+psi = 0.787;
+del = 0.02;
+
+model;
+dA = exp(gam+e_a);
+log(m) = (1-rho)*log(mst) + rho*log(m(-1))+e_m;
+-P/(c(+1)*P(+1)*m)+bet*P(+1)*(alp*exp(-alp*(gam+log(e(+1))))*k^(alp-1)*n(+1)^(1-alp)+(1-del)*exp(-(gam+log(e(+1)))))/(c(+2)*P(+2)*m(+1))=0;
+W = l/n;
+-(psi/(1-psi))*(c*P/(1-n))+l/n = 0;
+R = P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(-alp)/W;
+1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)/(m*l*c(+1)*P(+1)) = 0;
+c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1);
+P*c = m;
+m-1+d = l;
+e = exp(e_a);
+y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a));
+gy_obs = dA*y/y(-1);
+gp_obs = (p/p(-1))*m(-1)/dA;
+Y_obs/Y_obs(-1) = gy_obs;
+P_obs/P_obs(-1) = gp_obs;
+end;
+
+initval;
+k = 6;
+m = mst;
+P = 2.25;
+c = 0.45;
+e = 1;
+W = 4;
+R = 1.02;
+d = 0.85;
+n = 0.19;
+l = 0.86;
+y = 0.6;
+gy_obs = exp(gam);
+gp_obs = exp(-gam); 
+dA = exp(gam);
+end;
+
+shocks;
+var e_a; stderr 0.014;
+var e_m; stderr 0.005;
+end;
+
+steady;
+
+check;
+
+estimated_params;
+alp, beta_pdf, 0.356, 0.02; 
+bet, beta_pdf, 0.993, 0.002;
+gam, normal_pdf, 0.0085, 0.003;
+mst, normal_pdf, 1.0002, 0.007;
+rho, beta_pdf, 0.129, 0.223;
+psi, beta_pdf, 0.65, 0.05;
+del, beta_pdf, 0.01, 0.005;
+stderr e_a, inv_gamma_pdf, 0.035449, inf;
+stderr e_m, inv_gamma_pdf, 0.008862, inf;
+end;
+
+varobs P_obs Y_obs;
+
+observation_trends;
+P_obs (log(exp(gam)/mst));
+Y_obs (gam);
+end;
+
+options_.unit_root_vars = {'P_obs'; 'Y_obs'};
+
+//stoch_simul(order=1,nomoments,irf=0);
+// 
+estimation(datafile=fsdat,nobs=192,loglinear,mh_replic=5000,mh_nblocks=5,mh_drop=0.45,mh_jscale=0.8);
\ No newline at end of file
diff --git a/tags/v_3.062/examples/fs2000/fs2000a_steadystate.m b/tags/v_3.062/examples/fs2000/fs2000a_steadystate.m
new file mode 100644
index 0000000000000000000000000000000000000000..849c04b26d38bd4417ce8b022d92920b1b814617
--- /dev/null
+++ b/tags/v_3.062/examples/fs2000/fs2000a_steadystate.m
@@ -0,0 +1,53 @@
+% computes the steady state of fs2000 analyticaly
+% largely inspired by the program of F. Schorfheide
+function [ys,check] = fs2000a_steadystate(junk,ys)
+  global alp bet gam mst rho psi del;
+
+  check = 0;
+  
+  dA = exp(gam);
+  gst = 1/dA;
+  m = mst;
+  
+  khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1));
+  xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1);
+  nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp );
+  n  = xist/(nust+xist);
+  p  = xist + nust;
+  k  = khst*n;
+
+  l  = psi*mst*n/( (1-psi)*(1-n) );
+  c  = mst/p;
+  d  = l - mst + 1;
+  y  = k^alp*n^(1-alp)*gst^alp;
+  r  = mst/bet;
+  w  = l/n;
+  ist  = y-c;
+  q  = 1 - d;
+
+  e = 1;
+  
+  gp_obs = m/dA;
+  gy_obs = dA;
+  
+  P_obs = 1;
+  Y_obs = 1;
+  
+  ys =[
+      c
+      d
+      dA
+      e
+      gp_obs
+      gy_obs
+      k
+      l
+      m
+      n
+      p
+      P_obs
+      r
+      w
+      y
+      Y_obs
+      ];
\ No newline at end of file
diff --git a/tags/v_3.062/examples/fs2000/fsdat.m b/tags/v_3.062/examples/fs2000/fsdat.m
new file mode 100644
index 0000000000000000000000000000000000000000..5a0e3658d4031fe8f32bee59f33c515549b8ee23
--- /dev/null
+++ b/tags/v_3.062/examples/fs2000/fsdat.m
@@ -0,0 +1,210 @@
+data_q = [
+18.02 1474.5 150.2
+17.94 1538.2 150.9
+18.01 1584.5 151.4
+18.42 1644.1 152
+18.73 1678.6 152.7
+19.46 1693.1 153.3
+19.55 1724   153.9
+19.56 1758.2 154.7
+19.79 1760.6 155.4
+19.77 1779.2 156
+19.82 1778.8 156.6
+20.03 1790.9 157.3
+20.12 1846   158
+20.1  1882.6 158.6
+20.14 1897.3 159.2
+20.22 1887.4 160
+20.27 1858.2 160.7
+20.34 1849.9 161.4
+20.39 1848.5 162
+20.42 1868.9 162.8
+20.47 1905.6 163.6
+20.56 1959.6 164.3
+20.62 1994.4 164.9
+20.78 2020.1 165.7
+21    2030.5 166.5
+21.2  2023.6 167.2
+21.33 2037.7 167.9
+21.62 2033.4 168.7
+21.71 2066.2 169.5
+22.01 2077.5 170.2
+22.15 2071.9 170.9
+22.27 2094   171.7
+22.29 2070.8 172.5
+22.56 2012.6 173.1
+22.64 2024.7 173.8
+22.77 2072.3 174.5
+22.88 2120.6 175.3
+22.92 2165   176.045
+22.91 2223.3  176.727
+22.94 2221.4  177.481
+23.03 2230.95 178.268
+23.13 2279.22 179.694
+23.22 2265.48 180.335
+23.32 2268.29 181.094
+23.4  2238.57 181.915
+23.45 2251.68 182.634
+23.51 2292.02 183.337
+23.56 2332.61 184.103
+23.63 2381.01 184.894
+23.75 2422.59 185.553
+23.81 2448.01 186.203
+23.87 2471.86 186.926
+23.94 2476.67 187.68
+24    2508.7  188.299
+24.07 2538.05 188.906
+24.12 2586.26 189.631
+24.29 2604.62 190.362
+24.35 2666.69 190.954
+24.41 2697.54 191.56
+24.52 2729.63 192.256
+24.64 2739.75 192.938
+24.77 2808.88 193.467
+24.88 2846.34 193.994
+25.01 2898.79 194.647
+25.17 2970.48 195.279
+25.32 3042.35 195.763
+25.53 3055.53 196.277
+25.79 3076.51 196.877
+26.02 3102.36 197.481
+26.14 3127.15 197.967
+26.31 3129.53 198.455
+26.6  3154.19 199.012
+26.9  3177.98 199.572
+27.21 3236.18 199.995
+27.49 3292.07 200.452
+27.75 3316.11 200.997
+28.12 3331.22 201.538
+28.39 3381.86 201.955
+28.73 3390.23 202.419
+29.14 3409.65 202.986
+29.51 3392.6  203.584
+29.94 3386.49 204.086
+30.36 3391.61 204.721
+30.61 3422.95 205.419
+31.02 3389.36 206.13
+31.5  3481.4  206.763
+31.93 3500.95 207.362
+32.27 3523.8  208
+32.54 3533.79 208.642
+33.02 3604.73 209.142
+33.2  3687.9  209.637
+33.49 3726.18 210.181
+33.95 3790.44 210.737
+34.36 3892.22 211.192
+34.94 3919.01 211.663
+35.61 3907.08 212.191
+36.29 3947.11 212.708
+37.01 3908.15 213.144
+37.79 3922.57 213.602
+38.96 3879.98 214.147
+40.13 3854.13 214.7
+41.05 3800.93 215.135
+41.66 3835.21 215.652
+42.41 3907.02 216.289
+43.19 3952.48 216.848
+43.69 4044.59 217.314
+44.15 4072.19 217.776
+44.77 4088.49 218.338
+45.57 4126.39 218.917
+46.32 4176.28 219.427
+47.07 4260.08 219.956
+47.66 4329.46 220.573
+48.63 4328.33 221.201
+49.42 4345.51 221.719
+50.41 4510.73 222.281
+51.27 4552.14 222.933
+52.35 4603.65 223.583
+53.51 4605.65 224.152
+54.65 4615.64 224.737
+55.82 4644.93 225.418
+56.92 4656.23 226.117
+58.18 4678.96 226.754
+59.55 4566.62 227.389
+61.01 4562.25 228.07
+62.59 4651.86 228.689
+64.15 4739.16 229.155
+65.37 4696.82 229.674
+66.65 4753.02 230.301
+67.87 4693.76 230.903
+68.86 4615.89 231.395
+69.72 4634.88 231.906
+70.66 4612.08 232.498
+71.44 4618.26 233.074
+72.08 4662.97 233.546
+72.83 4763.57 234.028
+73.48 4849    234.603
+74.19 4939.23 235.153
+75.02 5053.56 235.605
+75.58 5132.87 236.082
+76.25 5170.34 236.657
+76.81 5203.68 237.232
+77.63 5257.26 237.673
+78.25 5283.73 238.176
+78.76 5359.6  238.789
+79.45 5393.57 239.387
+79.81 5460.83 239.861
+80.22 5466.95 240.368
+80.84 5496.29 240.962
+81.45 5526.77 241.539
+82.09 5561.8  242.009
+82.68 5618    242.52
+83.33 5667.39 243.12
+84.09 5750.57 243.721
+84.67 5785.29 244.208
+85.56 5844.05 244.716
+86.66 5878.7  245.354
+87.44 5952.83 245.966
+88.45 6010.96 246.46
+89.39 6055.61 247.017
+90.13 6087.96 247.698
+90.88 6093.51 248.374
+92    6152.59 248.928
+93.18 6171.57 249.564
+94.14 6142.1  250.299
+95.11 6078.96 251.031
+96.27 6047.49 251.65
+97    6074.66 252.295
+97.7  6090.14 253.033
+98.31 6105.25 253.743
+99.13 6175.69 254.338
+99.79 6214.22 255.032
+100.17 6260.74 255.815
+100.88 6327.12 256.543
+101.84 6327.93 257.151
+102.35 6359.9  257.785
+102.83 6393.5  258.516
+103.51 6476.86 259.191
+104.13 6524.5  259.738
+104.71 6600.31 260.351
+105.39 6629.47 261.04
+106.09 6688.61 261.692
+106.75 6717.46 262.236
+107.24 6724.2  262.847
+107.75 6779.53 263.527
+108.29 6825.8  264.169
+108.91 6882    264.681
+109.24 6983.91 265.258
+109.74 7020    265.887
+110.23 7093.12 266.491
+111    7166.68 266.987
+111.43 7236.5  267.545
+111.76 7311.24 268.171
+112.08 7364.63 268.815
+];
+%GDPD  GDPQ   GPOP
+
+series = zeros(193,2);
+series(:,2) = data_q(:,1);
+series(:,1) = 1000*data_q(:,2)./data_q(:,3);
+
+Y_obs = series(:,1);
+P_obs = series(:,2);
+
+series = series(2:193,:)./series(1:192,:);
+
+gy_obs = series(:,1);
+gp_obs = series(:,2);
+
+ti = [1950:0.25:1997.75];
\ No newline at end of file
diff --git a/tags/v_3.062/examples/ls2003/data_ca1.m b/tags/v_3.062/examples/ls2003/data_ca1.m
new file mode 100644
index 0000000000000000000000000000000000000000..b0b4f054613b41ebd91b9492f4edca5d38f6cb26
--- /dev/null
+++ b/tags/v_3.062/examples/ls2003/data_ca1.m
@@ -0,0 +1,100 @@
+data = [0.928467646476  11.8716889412   20  0.418037507392  0.227382377518 ...
+-0.705994063083 11.7522582094   21.25   1.09254424511   -1.29488274994 ...
+-0.511895351926 9.68144025625   17.25   -1.66150408407  0.331508393098 ...
+-0.990955971267 10.0890781236   17  1.43016275252   -2.43589670141 ...
+-0.981233061806 12.1094840679   18.25   2.91293288733   -0.790246576864 ...
+-0.882182844512 8.54559460406   15  0.419579139481  0.358729719566 ...
+-0.930893002836 6.19238374422   12.5    -1.48847457959  0.739779938797 ...
+1.53158206947   2.76544271886   11.5    -0.336216769682 0.455559918769 ...
+2.2659052834    5.47418162513   11  0.306436789767  -0.0707985731221 ...
+1.05419803797   6.35698426189   11  0.140700250477  0.620401487202 ...
+1.20161076793   3.4253301593    11  0.461296492351  0.14354323987 ...
+1.73934077971   4.70926070322   11.5    1.35798282982   0.38564694435 ...
+1.71735262584   3.54232079749   12.5    2.9097529155    -0.804308583301 ...
+0.426343657844  3.32719108897   13  1.64214862652   -1.18214664701 ...
+1.67751812324   2.93444727338   11.25   0.344434910651  -1.6529373719 ...
+1.37013301099   4.72303361923   11.75   2.61511526582   0.327684243041 ...
+0.281231073781  4.4893853071    10.5    1.17043449257   1.12855106649 ...
+1.53638992834   3.7325309699    10.25   -0.683947046728 0.11943538737 ...
+1.68081431462   3.34729969129   10  1.41159342106   -1.59065680853 ...
+-0.343321601133 5.05563513564   12  1.75117366498   -2.40127764642 ...
+0.873415608666  3.2779996255    10.25   -1.39895866711  0.0971444398216 ...
+0.26399696544   4.78229419828   9.75    0.0914692438124 0.299310457612 ...
+-0.562233624818 3.88598638237   9.75    -0.0505384765105    0.332826708151 ...
+2.15161914936   3.84859710132   8.75    -3.44811080489  0.789138678784 ...
+1.2345093726    5.62225030942   9.5 -0.366945407434 2.32974981198 ...
+1.62554967459   4.24667132831   10  -0.800958371402 0.0293183770935 ...
+1.33035402527   2.75248979249   9.75    -0.855723113225 0.852493939813 ...
+1.52078814077   3.53415985826   9.75    -3.37963469203  -1.05133958119 ...
+1.16704983697   4.92754079464   10.75   -3.0142303324   0.459907431978 ...
+0.277213572101  4.55532133037   11.75   -0.851995599415 2.03242034852 ...
+0.842215068977  3.11164509647   12.25   -1.08290421696  0.014323281961 ...
+1.05325028606   4.92882647578   13.5    -1.1953883867   0.706764750654 ...
+0.453051253568  6.82998950103   13.5    0.111803656462  0.088462593153 ...
+0.199885995525  5.82643354662   13.5    -0.920501518421 -0.26504958666 ...
+0.137907999624  2.66076369132   13.5    -1.17122929812  -0.995642430514 ...
+0.721949686709  5.70497876823   14.25   1.19378169018   -1.10644839651 ...
+-0.418465249225 3.75861110232   14.75   -1.03131674824  0.188507675831 ...
+-0.644028342116 4.15104788154   13.75   -1.48911756546  0.204560913792 ...
+-0.848213852668 5.65580324027   12.75   0.677011703877  -0.849628054542 ...
+-1.51954076928  11.4866911266   11.25   -0.446024680774 -0.456342350765 ...
+0.265275055215  2.85472749592   9.75    -0.598778202436 -0.907311640831 ...
+0.356162529063  2.29614015658   9.5 -0.46820788432  -1.22130883441 ...
+0.368308864363  -0.539083504685 8   -0.781333991956 0.374007246518 ...
+-0.145751412732 1.61507621789   8.25    3.68291932628   1.32438399845 ...
+0.285457283664  2.14334055993   7   1.42819405379   -0.00818660844123 ...
+0.372390129412  1.60000213334   6.25    0.626106424052  -0.10136772765 ...
+0.382720203063  1.72614243263   7.25    4.89631941021   -1.10060711916 ...
+0.737957515573  2.90430582851   6   -0.0422721010314    0.4178952497 ...
+0.649532581668  0.657135682543  6   0.692066153971  0.422299120276 ...
+0.627159201987  1.70352689913   5.75    2.62066711305   -1.29237304034 ...
+0.905441299817  1.95663197267   5.5 1.5949697565    -0.27115830703 ...
+1.49322577898   -2.08741765309  6.25    1.23027694802   0.418336889527 ...
+1.48750731567   -1.57274121871  8   3.01660550994   -0.893958254365 ...
+1.39783858087   2.22623066426   7   -0.80842319214  1.47625453886 ...
+0.89274836317   1.30378081742   8   -0.249485058661 0.159871204185 ...
+0.920652246088  4.1437741965    9.75    2.8204453623    0.178149239655 ...
+-0.00264276644799   3.07989972052   8.75    -2.56342461535  2.105998353 ...
+0.0198190461681 0.766283759256  8   -1.15838865989  1.56888883418 ...
+0.440050515311  0.127570085801  7.5 0.0400753569995 0.028914333532 ...
+0.129536637901  1.78174141526   6.75    0.959943962785  0.307781224401 ...
+0.398549827172  3.03606770667   6.5 -0.340209794742 0.100979469478 ...
+1.17174775425   0.629625188037  5.75    0.403003686814  0.902394579377 ...
+0.991163981251  2.50862910684   4.75    -1.44963996982  1.16150986945 ...
+0.967603566096  2.12003739013   4.75    0.610846030775  -0.889994896068 ...
+1.14689383604   1.24185011459   4.75    2.01098091308   -1.73846431001 ...
+1.32593824054   0.990713820685  4.75    -0.0955142989332    -0.0369257308362 ...
+0.861135002644  -0.24744943605  6   1.72793107135   -0.691506789639 ...
+1.26870850151   2.09844764887   6.5 1.50720217572   -1.31399187077 ...
+0.260364987715  1.10650139716   6.5 1.13659047496   0.0720441664643 ...
+1.09731242214   0.490796381346  7.25    4.59123894147   -2.14073070763 ...
+1.63792841781   0.612652594286  6.75    1.79604605035   -0.644363995357 ...
+1.48465576034   0.978295808687  6.75    -2.00753620902  1.39437534964 ...
+1.0987608663    4.25212569087   6.25    -2.58901196498  2.56054320803 ...
+1.42592178132   2.76984518311   6.25    0.888195752358  1.03114549274 ...
+1.52958239462   1.31795955491   6.5 -0.902907564082 -0.0952198893776 ...
+1.0170168994    2.14733589918   7   -1.3054866978   2.68803738466 ...
+0.723253652257  3.43552889347   7.5 1.8213700853    0.592593586195 ...
+1.24720806008   3.87383806577   7.5 0.0522300654168 0.988871238698 ...
+0.482531471239  2.67793287032   7.5 2.9693944293    -0.108591166081 ...
+0.154056100439  0.927269031704  6.75    0.119222057561  3.30489209451 ...
+0.0694865769274 6.65916526788   6.25    0.889014476084  -2.83976849035 ...
+-0.121267434867 0.341442615696  5.25    0.323053239216  -3.49289229012 ...
+0.726473690375  -3.5423730964   4   2.19149290449   -3.20855054004 ...
+1.39271709108   2.63121085718   3.75    0.88406577736   0.75622580197 ...
+1.07502077727   5.88578836799   4.25    -2.55088273352  2.89018116374 ...
+0.759049251607  4.24703604223   4.5 0.575687665685  -0.388292506167 ...
+]; 
+ 
+data = reshape(data,5,86)'; 
+y_obs = data(:,1); 
+pie_obs = data(:,2); 
+R_obs = data(:,3); 
+de = data(:,4); 
+dq = data(:,5); 
+ 
+%Country: Canada 
+%Sample Range: 1981:2 to 2002:3 
+%Observations: 86 
+%Variables: Real GDP Growth [%], Inflation [annualized %], Nom Rate [%], 
+%           Exchange Rate Change [%], Terms of Trade Change [%] 
diff --git a/tags/v_3.062/examples/ls2003/ls2003.mod b/tags/v_3.062/examples/ls2003/ls2003.mod
new file mode 100644
index 0000000000000000000000000000000000000000..1d2ec9de496e1e9010bdfeaef796b258735eaccc
--- /dev/null
+++ b/tags/v_3.062/examples/ls2003/ls2003.mod
@@ -0,0 +1,65 @@
+var y y_s R pie dq pie_s de A y_obs pie_obs R_obs;
+varexo e_R e_q e_ys e_pies e_A;
+
+parameters psi1 psi2 psi3 rho_R tau alpha rr k rho_q rho_A rho_ys rho_pies;
+
+psi1 = 1.54;
+psi2 = 0.25;
+psi3 = 0.25;
+rho_R = 0.5;
+alpha = 0.3;
+rr = 2.51;
+k = 0.5;
+tau = 0.5;
+rho_q = 0.4;
+rho_A = 0.2;
+rho_ys = 0.9;
+rho_pies = 0.7;
+
+
+model(linear);
+y = y(+1) - (tau +alpha*(2-alpha)*(1-tau))*(R-pie(+1))-alpha*(tau +alpha*(2-alpha)*(1-tau))*dq(+1) + alpha*(2-alpha)*((1-tau)/tau)*(y_s-y_s(+1))-A(+1);
+pie = exp(-rr/400)*pie(+1)+alpha*exp(-rr/400)*dq(+1)-alpha*dq+(k/(tau+alpha*(2-alpha)*(1-tau)))*y+alpha*(2-alpha)*(1-tau)/(tau*(tau+alpha*(2-alpha)*(1-tau)))*y_s;
+pie = de+(1-alpha)*dq+pie_s;
+R = rho_R*R(-1)+(1-rho_R)*(psi1*pie+psi2*(y+alpha*(2-alpha)*((1-tau)/tau)*y_s)+psi3*de)+e_R;
+dq = rho_q*dq(-1)+e_q;
+y_s = rho_ys*y_s(-1)+e_ys;
+pie_s = rho_pies*pie_s(-1)+e_pies;
+A = rho_A*A(-1)+e_A;
+y_obs = y-y(-1)+A;
+pie_obs = 4*pie;
+R_obs = 4*R;
+end;
+
+shocks;
+var e_R = 1.25^2;
+var e_q = 2.5^2;
+var e_A = 1.89;
+var e_ys = 1.89;
+var e_pies = 1.89;
+end;
+
+varobs y_obs R_obs pie_obs dq de;
+
+estimated_params;
+psi1 , gamma_pdf,1.5,0.5;
+psi2 , gamma_pdf,0.25,0.125;
+psi3 , gamma_pdf,0.25,0.125;
+rho_R ,beta_pdf,0.5,0.2;
+alpha ,beta_pdf,0.3,0.1;
+rr ,gamma_pdf,2.5,1;
+k , gamma_pdf,0.5,0.25;
+tau ,gamma_pdf,0.5,0.2;
+rho_q ,beta_pdf,0.4,0.2;
+rho_A ,beta_pdf,0.5,0.2;
+rho_ys ,beta_pdf,0.8,0.1;
+rho_pies,beta_pdf,0.7,0.15;
+stderr e_R,inv_gamma_pdf,1.2533,0.6551;
+stderr e_q,inv_gamma_pdf,2.5066,1.3103;
+stderr e_A,inv_gamma_pdf,1.2533,0.6551;
+stderr e_ys,inv_gamma_pdf,1.2533,0.6551;
+stderr e_pies,inv_gamma_pdf,1.88,0.9827;
+end;
+
+estimation(datafile=data_ca1,first_obs=8,nobs=79,mh_nblocks=10,prefilter=1,mh_jscale=0.5,mh_replic=0);
+
diff --git a/tags/v_3.062/examples/pi2004/idata.m b/tags/v_3.062/examples/pi2004/idata.m
new file mode 100644
index 0000000000000000000000000000000000000000..9ce34b9eb76be9241efcb6ad422f93be370f4fec
--- /dev/null
+++ b/tags/v_3.062/examples/pi2004/idata.m
@@ -0,0 +1,5 @@
+load ych.dat;
+data = log(ych);
+oy = data(:,1);
+oc = data(:,2);
+oh = data(:,3);
\ No newline at end of file
diff --git a/tags/v_3.062/examples/pi2004/ireland.mod b/tags/v_3.062/examples/pi2004/ireland.mod
new file mode 100644
index 0000000000000000000000000000000000000000..51ef3508ffa68fe754bdc337bc4e690aa7c55ad3
--- /dev/null
+++ b/tags/v_3.062/examples/pi2004/ireland.mod
@@ -0,0 +1,90 @@
+var y a k c i h eoy eoc eoh oy oc oh;
+varexo e eeoy eeoc eeoh;
+
+parameters theta rho eta gam bet delta aa r11 r12 r13 r21 r22 r23 r31 r32 r33 scy shc shy;
+
+bet = 0.99;
+delta = 0.025;
+theta = 0.2;
+rho = 0.9959; 
+eta = 1.0051;  
+gam = 0.0045;
+aa = 1.8;
+r11 = 0.99;
+r12 = 0;
+r13 = 0;
+r21 = 0;
+r22 = 0.99;
+r23 = 0;
+r31 = 0;
+r32 = 0;
+r33 = 0.99;
+scy = 0.0040;
+shy = 0.0015;
+shc = 0.0010;
+
+model;
+exp(y) = exp(a)*exp(k(-1))^theta*exp(h)^(1-theta);
+a = (1-rho)*aa+rho*a(-1)+e;
+exp(y) = exp(c) + exp(i);
+eta*exp(k) = (1-delta)*exp(k(-1))+exp(i);
+gam*exp(c)*exp(h) = (1-theta)*exp(y);
+eta/exp(c) = bet*(1/exp(c(+1)))*(theta*(exp(y(+1))/exp(k))+1-delta);
+eoy = r11*eoy(-1) + r12*eoc(-1) + r13*eoh(-1) + eeoy; 
+eoc = r21*eoy(-1) + r22*eoc(-1) + r23*eoh(-1) + scy*eeoy+eeoc; 
+eoh = r31*eoy(-1) + r32*eoc(-1) + r33*eoh(-1) + shy*eeoy+shc*eeoc+eeoh; 
+oy = y + eoy;
+oc = c + eoc;
+oh = h + eoh;
+end;
+
+initval;
+a = 1.7;
+y = 8;
+c = 8;
+k = 10;
+i = 5;
+h = 4;
+eoy = 0;
+eoc = 0;
+eoh = 0;
+oy = y;
+oc = c;
+oh = h;
+end;
+
+steady;
+check;
+
+estimated_params;
+theta , 0.22, 0.1, 0.5;
+rho , 0.99, 0.7, 0.9999; 
+eta , 1.0051, 1, 1.03;  
+gam , 0.0045, 0.001, 0.01;
+aa , 1.8, 0.1, 4;
+r11 , 1.4187, -2, 2;
+r12 , 0.2251, -2, 2;
+r13 , -0.4441, -2, 2;
+r21 , 0.0935, -2, 2;
+r22 , 1.0236, -2, 2;
+r23 , -0.0908, -2, 2;
+r31 , 0.7775, -2, 2;
+r32 , 0.3706, -2, 2;
+r33 , 0.2398, -2, 2;
+scy , 0.0040, -2, 2;
+shy , 0.0015, -2, 2;
+shc , 0.0010, -2, 2;
+stderr e , 0.0056, 0, 0.2;
+stderr eeoy , 0.0070, 0, 0.1;
+stderr eeoc , 0.0069, 0, 0.1;
+stderr eeoh , 0.0018, 0, 0.1;
+end;
+
+varobs oy oc oh;
+
+observation_trends;
+oy (log(eta));
+oc (log(eta));
+end;
+
+estimation(datafile=idata,mode_compute=1,nograph);
\ No newline at end of file
diff --git a/tags/v_3.062/examples/pi2004/ych.dat b/tags/v_3.062/examples/pi2004/ych.dat
new file mode 100644
index 0000000000000000000000000000000000000000..cda9d789d893506bdf43c4bcbef9c402fb20767d
--- /dev/null
+++ b/tags/v_3.062/examples/pi2004/ych.dat
@@ -0,0 +1,218 @@
+    2912.874 2402.117 198.8318
+    2959.229 2423.837 197.3532
+    2955.961 2420.605    198.6
+    2944.613 2436.721 196.7741
+     2865.54 2435.214 192.1405
+    2837.352 2466.823 187.9169
+    2866.923 2465.011 185.2876
+     2869.69 2492.395 182.3583
+    3000.477  2527.61 183.9728
+    3085.831 2561.171 189.8728
+    3255.871 2686.503 196.8083
+    3261.025 2613.773 200.6933
+    3261.223  2681.19 204.7635
+    3206.972 2610.838 206.4334
+    3190.085 2639.831 205.2288
+    3153.084 2650.442 204.8585
+    3168.886 2654.884 207.0878
+    3173.132 2702.447 205.2592
+    3199.558 2706.406 206.3172
+    3320.152 2792.021 211.0694
+    3333.583 2800.407 211.3402
+     3346.44 2812.085 211.4742
+    3319.499 2799.617 209.1935
+    3248.271 2771.542 205.3107
+    3243.519 2772.147 200.5438
+    3268.486 2799.347 198.4387
+    3321.089 2829.358 196.7325
+    3391.751 2878.587 198.3282
+    3498.798 2932.503 201.0089
+    3576.754 2976.939 204.5467
+    3609.954 3003.859 206.0148
+    3649.965 3032.826 207.8803
+    3625.207 3030.321 208.5925
+     3618.86 3032.152  207.818
+    3608.703 3030.239 205.7291
+    3633.863 3063.106 207.7698
+    3634.522 3075.089 207.3511
+    3628.888 3071.301 205.2741
+     3654.03 3085.679 203.4572
+     3594.76 3076.223 198.9135
+    3503.293 3024.868 193.4752
+     3506.06 3040.773 189.2161
+    3580.923  3079.37 190.8325
+    3649.701  3103.69 193.5263
+    3722.726 3149.563 197.1324
+    3809.309 3187.886 200.4534
+    3787.083  3210.28 198.4483
+    3798.375 3203.989 198.1458
+    3865.427 3211.443 199.3042
+    3828.074 3242.787 198.7233
+    3799.687 3219.673 196.7171
+     3719.52 3211.349  193.664
+    3716.143 3198.191 190.8133
+    3789.954 3235.106 190.6975
+    3841.155 3241.368 192.1397
+    3910.574  3301.88 194.0709
+    3974.538 3330.997 194.6404
+    3994.347 3359.016 196.8206
+    4014.564 3370.705 196.2717
+    4017.905 3399.337  194.901
+    4053.971 3405.746 194.5344
+    4080.082 3423.602 195.9045
+    4131.421 3455.826 195.9157
+    4150.544 3470.287  195.917
+    4229.112 3524.024 195.5849
+     4272.24  3572.78 197.0242
+    4336.042 3623.155 197.4885
+    4332.184 3617.237  198.811
+    4465.719 3681.029 200.7368
+    4488.039 3707.114 201.7553
+    4563.691 3758.136 202.7332
+    4657.963 3851.754 205.0265
+    4769.576 3898.869 207.5881
+    4751.946 3898.531 208.8921
+    4775.072 3931.495 209.8688
+    4783.388 3936.299 210.2431
+    4770.091  3946.92 209.1094
+    4766.574 3984.883 207.6639
+    4783.135  3985.69 208.0611
+    4801.834 3991.937 208.7085
+    4894.604 4068.425 208.3597
+    4975.616 4118.065 209.5735
+    5005.671 4179.017 210.9004
+    5009.407 4177.453 211.3179
+    5086.308 4204.501 212.5445
+    5084.863  4213.54 213.6703
+    5100.858 4214.495 214.3839
+    5063.156 4226.537 213.5259
+    5036.423 4230.978 211.4778
+    5032.681 4228.959 208.3091
+    5053.799 4241.721 205.5294
+     4965.09 4203.845 202.0428
+    5116.926 4261.198 201.5087
+    5152.069  4275.63 201.2279
+    5167.576 4284.769 200.0614
+    5180.986 4331.279 201.1027
+    5237.217 4339.349 201.0968
+    5342.982 4395.387 202.4846
+    5397.077 4438.577 202.6435
+    5484.454 4521.399 204.6093
+    5599.656 4580.229 206.5316
+    5605.247 4551.878  207.638
+    5560.139 4547.278  207.561
+    5550.477 4512.704 208.2113
+    5422.633 4450.734 207.0236
+    5407.967 4444.172 205.7419
+    5341.599 4438.929 204.6589
+    5248.491 4344.377  200.536
+    5098.451 4356.942 193.2349
+    5127.117  4412.68    190.6
+    5224.673 4451.618 191.7895
+    5266.744 4478.207 193.5049
+    5416.411 4553.764 195.7526
+    5473.807 4575.388 195.9103
+    5496.508 4600.334 195.6317
+    5542.322  4642.48 195.9109
+    5620.583 4677.803 197.1447
+    5681.448 4680.833 199.7234
+    5754.575 4702.857 200.9543
+    5776.808 4752.082  202.373
+    5794.987 4757.858 202.3499
+    5938.233 4839.798 206.8288
+    5965.396 4842.542 207.8288
+    6002.337 4857.874 209.0832
+    6006.791 4867.903 210.1847
+    5974.557 4840.912 209.8585
+    5971.562  4863.66 210.2244
+    5937.051 4856.383 209.8079
+    5897.765 4830.827 208.8941
+    5669.422 4702.666 204.6229
+    5622.784 4730.812 202.7781
+    5752.439 4771.074 204.9687
+    5847.447  4774.81 206.1936
+    5783.328 4762.645 205.2802
+    5845.223 4768.572 204.8371
+    5751.495 4715.179 203.0329
+    5654.764 4729.383 200.2751
+    5646.146 4728.229 197.5565
+    5648.711 4745.201 195.2339
+    5635.351 4810.282 192.9487
+    5692.631 4841.503  192.931
+    5864.656 4929.513 194.9285
+    5984.689 4993.857 197.5937
+    6150.889 5061.722 201.0485
+    6296.581 5094.102 203.5924
+    6389.626 5150.168 205.4862
+    6433.069 5172.136  206.615
+    6460.989 5223.355 207.6607
+    6486.085 5290.602 208.5043
+     6538.91 5326.746 209.0396
+    6606.849  5410.05 209.3752
+    6653.043 5412.688  210.214
+     6664.94 5432.911 210.1493
+    6680.737  5476.91 209.3983
+    6715.628 5557.117 209.6171
+    6733.646 5578.244 210.0342
+    6748.714 5562.734 211.4856
+    6800.924 5617.672 212.5146
+    6840.249 5664.805 214.0241
+    6928.494  5662.19 214.9892
+    6947.701 5745.585 215.7109
+    6995.117 5771.484 216.8663
+     7031.88 5804.469 217.7172
+    7095.824 5858.734 219.2336
+    7145.561 5863.484 220.1136
+    7138.196 5874.486  220.269
+    7157.869 5912.841 220.1049
+    7154.805 5921.098  220.317
+    7161.057 5922.459  220.214
+    7161.636 5926.962 219.8513
+     7140.38 5935.485 218.7281
+    6988.206 5869.524 216.6599
+    6901.448 5830.479 214.2069
+    6921.772 5861.221 212.7658
+    6951.212 5865.776 212.5561
+    6964.494 5837.183 211.8733
+    7013.679 5915.408 210.9388
+    7101.702 5930.574 211.8948
+    7139.773 5958.446 211.5333
+    7240.504 6024.693 212.2314
+    7263.686 6021.066 213.0739
+    7309.617  6067.04 214.1464
+    7357.691 6122.096 215.3232
+    7460.728  6162.81 216.6132
+    7552.707 6204.697 217.5596
+    7666.317 6243.449 220.1539
+    7671.023 6273.154 221.4916
+     7773.38 6317.792 222.8923
+    7800.103 6331.551 223.6901
+    7801.608 6378.859  223.503
+    7819.518 6412.249 224.1399
+    7881.173 6435.988 224.4756
+    7942.145 6475.127 224.7463
+    8067.358 6527.758 226.5057
+    8135.065 6540.091 227.7462
+    8160.041 6567.023 228.9124
+    8246.348 6609.208 229.6994
+    8351.972 6625.695 231.2019
+    8446.197 6714.596 232.3205
+    8514.464 6751.037 233.8458
+    8708.139 6820.495 235.1582
+    8756.497 6905.883 235.4095
+    8849.165  6951.56 236.1083
+    8972.445  7016.94 236.9981
+     9053.37 7071.144 236.9439
+    9103.359 7150.307 237.5947
+    9209.004 7210.145 238.3943
+    9335.028 7276.898 239.4022
+    9429.358 7361.761 240.6652
+    9547.745 7400.777 240.4972
+    9558.757 7450.665 240.0893
+     9550.45 7466.543 239.5769
+    9462.932 7494.242 239.0031
+    9373.848 7502.387 237.5366
+    9349.589 7507.978 235.3389
+    9346.637 7595.472 232.4265
+    9459.937 7637.787 231.5627
+    9511.663 7656.648 231.0083
\ No newline at end of file
diff --git a/tags/v_3.062/examples/ramst.mod b/tags/v_3.062/examples/ramst.mod
new file mode 100644
index 0000000000000000000000000000000000000000..9fa14019dec64864710ad3b4a1338291f49fc8f0
--- /dev/null
+++ b/tags/v_3.062/examples/ramst.mod
@@ -0,0 +1,36 @@
+var c k;
+varexo x;
+
+parameters alph gam delt bet aa;
+alph=0.5;
+gam=0.5;
+delt=0.02;
+bet=0.05;
+aa=0.5;
+
+
+model;
+c + k - aa*x*k(-1)^alph - (1-delt)*k(-1);
+c^(-gam) - (1+bet)^(-1)*(aa*alph*x(+1)*k^(alph-1) + 1 - delt)*c(+1)^(-gam);
+end;
+
+initval;
+x = 1;
+k = ((delt+bet)/(1.0*aa*alph))^(1/(alph-1));
+c = aa*k^alph-delt*k;
+end;
+
+steady;
+
+check;
+
+shocks;
+var x;
+periods 1;
+values 1.2;
+end;
+
+simul(periods=200);
+
+rplot c;
+rplot k;
diff --git a/tags/v_3.062/makefile b/tags/v_3.062/makefile
new file mode 100644
index 0000000000000000000000000000000000000000..be2b805309a0d4d7f4b7e9dd559f6655dc868e1e
--- /dev/null
+++ b/tags/v_3.062/makefile
@@ -0,0 +1,23 @@
+DATE = $(shell date +%m%d)
+VERSION = v3_062
+DYNARE_ROOT = dynare_v3
+FNAME_MAT = $(DYNARE_ROOT)/zips/dyn_mat_$(VERSION)
+FNAME_PAR = $(DYNARE_ROOT)/zips/dyn_parser_$(VERSION)
+MZIP_FILE = dyn_mat_$(VERSION).zip 
+PZIP_FILE = dyn_parser_$(VERSION).zip 
+
+all: install
+
+parser.src/dynare_m.exe: parser.src/dynare.c parser.src/d.y parser.src/dyn.l doc/guide.tex doc/manual.xml
+	cd parser.src;make dynare_m.exe
+	cd doc;make
+
+$(MZIP_FILE):
+	cd ..;zip $(FNAME_MAT) $(DYNARE_ROOT)/matlab/*.m $(DYNARE_ROOT)/matlab/*.exe $(DYNARE_ROOT)/matlab/*.dll $(DYNARE_ROOT)/examples/*.mod $(DYNARE_ROOT)/examples/fs2000/* $(DYNARE_ROOT)/doc/*.pdf $(DYNARE_ROOT)/doc/manual/*
+
+$(PZIP_FILE): parser.src/dynare_m.exe
+	cd ..;zip $(FNAME_PAR) $(DYNARE_ROOT)/parser.src/*.h $(DYNARE_ROOT)/parser.src/*.l $(DYNARE_ROOT)/parser.src/*.y $(DYNARE_ROOT)/parser.src/*.c $(DYNARE_ROOT)/parser.src/makefile $(DYNARE_ROOT)/parser.src/d.output
+
+install: $(MZIP_FILE) $(PZIP_FILE) 
+	cd zips; chmod a+rx $(MZIP_FILE); scp $(MZIP_FILE) pythie.cepremap.cnrs.fr:public_html/mambo/download;chmod a+rx $(PZIP_FILE); scp $(PZIP_FILE) pythie.cepremap.cnrs.fr:public_html/mambo/download
+
diff --git a/tags/v_3.062/matlab/ChangeLog b/tags/v_3.062/matlab/ChangeLog
new file mode 100644
index 0000000000000000000000000000000000000000..4be887c9ac46888d68721e30bce3d92754bf1360
--- /dev/null
+++ b/tags/v_3.062/matlab/ChangeLog
@@ -0,0 +1,690 @@
+:ext:pythie.cepremap.cnrs.fr/var/lib/cvs
+2004-08-02  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* dr1.m:
+	corrected test for presence of all variables at the current period
+
+2004-07-29  benzougar  <benzougar@michel-lat>
+
+	* sec2hms.m:
+	New file :just converts a number (in seconds) into a string in format
+	 hour:minute:second.
+	A call to this file is in mymodel.m
+
+	* sec2hms.m: New file.
+
+	* make_ex_.m, steady.m, kalman_transition_matrix.m, dr11.m, dynare_resolve.m, dynare_solve.m, ff1_.m, irf.m, metropolis.m, mj_optmumlik.m, resol1.m, sim1.m, simult_.m, th_autocovariances.m, dr1.m:
+	Using jacobian provided by mymodel_static.m and mymodel_dynamic.m
+
+2004-07-20  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* resol.m: added oo_.exo_simul to <model>_static call
+
+2004-07-19  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* steady_.m, check.m:
+	added oo_.exo_simul to calls to <model>_static funtion
+
+2004-07-14  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* ChangeLog: version 3.0
+
+	* uniform_specification.m: new function
+
+	* set_prior.m: added UNIFORM
+	modified loaction parameters for BETA and GAMMA
+
+	* priordens.m, prior_bounds.m: UNIFORM use p1 and p2
+
+	* dynare_estimation.m: added UNIFORM
+	added test for complex variables
+	added Laplace approximation after mode computation
+	modified report
+
+	* dynare.m: added automatic path finder
+	removed "Press a key"
+
+:ext:pythie.cepremap.cnrs.fr/var/lib/cvs
+2004-07-14  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* uniform_specification.m: new function
+
+	* set_prior.m: added UNIFORM
+	modified loaction parameters for BETA and GAMMA
+
+	* priordens.m, prior_bounds.m: UNIFORM use p1 and p2
+
+	* dynare_estimation.m: added UNIFORM
+	added test for complex variables
+	added Laplace approximation after mode computation
+	modified report
+
+	* dynare.m: added automatic path finder
+	removed "Press a key"
+
+2004-07-06  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* dr1.m, dynare.m, resol.m, sim1.m, steady_.m, stoch_simul.m:
+	modified for version 4
+
+2004-06-21  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* disp_moments.m, disp_th_moments.m: corrected test for hp_filter > 1
+
+2004-06-08  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* ChangeLog: update
+
+	* gensylv.m, aa_gensylv.dll, dummy.h: *** empty log message ***
+
+2004-06-07  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* ChangeLog: update
+
+	* resid.m: declares ys0_ as global
+
+	* set_shocks.m: added exogenous deterministic variables
+
+	* simultxdet_.m: New file.
+
+	* make_ex_.m, resol.m, simultxdet_.m, steady_.m, ff1_.m:
+	added exogenous deterministic variables
+
+	* dynare_m.exe: updated
+
+	* dynare.m: find dynare_m.exe automatically
+
+	* dr1.m:
+	added leads on several periods, exogenous deterministic variables, Kamenik's algorithm
+
+	* aa_gensylv.dll, dummy.h, gensylv.m: Adding Kamenik's algorithm
+
+	* aa_gensylv.dll, dummy.h, gensylv.m: New file.
+
+2004-05-28  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* sim1.m: it_ must be declared global instead of it
+
+	* sim1.m: calls to _dynamic
+
+	* simul.m: set more missing options_ defaults
+
+	* check.m: suppressed oo_.eigenvalues = oo_.eigenvalues
+
+	* check.m:
+	suppressed oo_.eigenvalues = dr.eigenvalues. This is done in dr1()
+
+	* simul.m: set defautl options_.scalv = 1
+
+	* check.m: corrected dr.oo_.eigenvalues
+
+	* dr1.m:
+	doesn't compute Jacobian with respect to exogenous variables when used for computing only eigenvalues (check == 1)
+
+	* ff1_.m: cal to _static
+
+	* resol1.m: call to _static
+
+	* osr1.m, olr1.m: call _static
+
+	* dr2.m: call to _static
+
+2004-05-26  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* ff1_.m: ff1_ calls ..._dynamic
+
+	* jacob_a.m: forgot some changes...
+
+	* jacob_a.m: a function can't return a structure element
+
+	* resol.m: dr.fbias is computed with ..._static function
+
+	* resol.m: steady state computation uses ..._static function
+
+2004-05-12  kamenik  <kamenik@michel-lat>
+
+	* CVSROOT/modules: Added a nickname dync for dynare_cpp.
+
+2004-04-30  benzougar  <benzougar@michel-lat>
+
+	* dynare_m.exe: Remove because added by error
+
+	* check.m, dr2.m, dynare.m, dynare_m.exe, ff1_.m, linear.m, olr1.m, osr1.m, resid.m, resol.m, resol1.m, sim1.m, simk.m:
+	Outputs Model Files : Replacing "_ff" with "_static" and "_fff" with "_dynamic"
+
+	* dynare.m:
+	1. Changing matlab global variables (outputs) into strctured global varaiables
+	2. Dyanre can now be installed any where, no need to change change this file if installation folder differe from c:\dyanre
+
+	* bksup.m, bksup1.m, bksupk.m, calib.m, calib_obj.m, calib_obj2.m, check.m, compDist.m, dcompare.m, disp_dr.m, disp_moments.m, disp_th_moments.m, dr1.m, dr11.m, dr2.m, dsample.m, dy_date.m, dyn2vec.m, dynare_estimation.m, dynare_resolve.m, dynare_solve.m, dynasave.m, dynatype.m, ff1_.m, forcst.m, gcompare.m, hessian.m, hessian_sparse.m, initvalf_.m, irf.m, jacob.m, jacob_a.m, kalman_transition_matrix.m, linear.m, make_ex_.m, make_y_.m, marginal_density.m, mcmc_diagnostic.m, mcmcdiags.m, mcompare.m, metropolis.m, mj_optmumlik.m, olr.m, olr1.m, olr2.m, osr.m, osr1.m, osr_obj.m, resid.m, resol.m, resol1.m, rplot.m, set_prior.m, set_shocks.m, set_state_space.m, sim1.m, simk.m, simul.m, simult.m, simult_.m, solve1.m, steady.m, steady_.m, stoch_simul.m, th_autocovariances.m:
+	Changing matlab global variables (outputs) into strctured global varaiables
+
+2004-04-21  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* ChangeLog: *** empty log message ***
+
+	* sylvester3a.m: added limit to number of iterations and warning
+
+	* stoch_simul.m: corrected bug in saved irf variables name
+
+:ext:pythie.cepremap.cnrs.fr/var/lib/cvs
+2004-04-21  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* sylvester3a.m: added limit to number of iterations and warning
+
+	* stoch_simul.m: corrected bug in saved irf variables name
+
+2004-04-19  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* lpdfgbeta.m, compDist.m, priordens.m: *** empty log message ***
+
+:ext:pythie.cepremap.cnrs.fr/var/lib/cvs
+2004-04-19  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* compDist.m, lpdfgbeta.m, priordens.m: *** empty log message ***
+
+2004-03-31  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* ChangeLog, dynare_m.exe, dynare.m: *** empty log message ***
+
+2004-03-30  benzougar  <benzougar@michel-lat>
+
+	* sim1.m: global variable start_simul removed : defined only here
+
+	* ff1_.m:
+	Moving this file from not_used  : ff1_.m is used by dr1.m, m2html fails
+	declaring this file unused.
+
+2004-03-29  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* ChangeLog: *** empty log message ***
+
+2004-03-27  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* ChangeLog, dr1.m, sylvester3a.m, th_autocovariances.m:
+	merged changes in r0327
+
+	* ChangeLog, brm.m, cols.m, datatomfile.m, diffext.m, equiv.m, ff1_.m, ff2_.m, ff2a_.m, ff_simul.m, ff_simul1.m, ff_simul2.m, fff.m, fs_dyn.m, fx_.m, hessext.m, hpfast.m, jacob2.m, lpdfig.m, pdfig.m, reshapel.m, resid0.m, rfrot.m, set_start_date.m, testifft.m, transition_matrix.m, var_index.m, var_state_index.m:
+	*** empty log message ***
+
+	* brm.m, cols.m, datatomfile.m, diffext.m, equiv.m, ff1_.m, ff2_.m, ff2a_.m, ff_simul.m, ff_simul1.m, ff_simul2.m, fff.m, fs_dyn.m, fx_.m, hessext.m, hpfast.m, jacob2.m, lpdfig.m, pdfig.m, reshapel.m, resid0.m, rfrot.m, set_start_date.m, testifft.m, transition_matrix.m, var_index.m, var_state_index.m:
+	adding abdel change
+
+	* brm.m, cols.m, datatomfile.m, diffext.m, equiv.m, ff1_.m, ff2_.m, ff2a_.m, ff_simul.m, ff_simul1.m, ff_simul2.m, fff.m, fs_dyn.m, fx_.m, hessext.m, hpfast.m, jacob2.m, lpdfig.m, pdfig.m, reshapel.m, resid0.m, rfrot.m, set_start_date.m, testifft.m, transition_matrix.m, var_index.m, var_state_index.m:
+	adding Abdel change
+
+	* ChangeLog, asamin.dll, asamin.m: abdels sorting unused functions
+
+	* th_autocovariances.m:
+	corrected bug in computation of theoretical mean of 2nd order approximation of models with lags on more than 1 period
+
+	* sylvester3a.m:
+	new function: increases accuracy of sylvester solution by running iterations
+
+	* dr1.m: call sylvester3a after sylvester3 to increase accuracy
+
+:ext:pythie.cepremap.cnrs.fr/var/lib/cvs
+2004-03-27  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* th_autocovariances.m:
+	corrected bug in computation of theoretical mean of 2nd order approximation of models with lags on more than 1 period
+
+	* sylvester3a.m:
+	new function: increases accuracy of sylvester solution by running iterations
+
+	* dr1.m: call sylvester3a after sylvester3 to increase accuracy
+
+2004-02-28  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* dynare_m.exe: *** empty log message ***
+
+	* initial_estimation_checks.m: new function
+
+	* mj_optmumlik.m:
+	set dr1_test_(1)=4 when f matrix is singular in Kalman filter
+
+	* dynare_estimation.m: added call to init_estimation_check()
+
+:ext:pythie.cepremap.cnrs.fr/var/lib/cvs
+2004-02-28  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* dynare_m.exe: *** empty log message ***
+
+	* initial_estimation_checks.m: new function
+
+	* mj_optmumlik.m:
+	set dr1_test_(1)=4 when f matrix is singular in Kalman filter
+
+	* dynare_estimation.m: added call to init_estimation_check()
+
+2004-02-24  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* dynare_estimation.m: - set default for option loglinear
+
+2004-02-20  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* rplot.m: added legend when several curves
+
+	* rplot.m: corrected bug for several variables
+
+	* varprior.m, rfvar3.m: new file
+
+	* prior_bounds.m: replaced qgamma by mj_qgamma to avoid overflow
+
+	* numgrad.m, mj_qgamma.m, mgnldnsty.m, matrictint.m: new file
+
+	* marginal_density.m: use maxpost as standardization factor
+
+	* fs_dyn.m: new file
+
+	* dynare_m.exe, asamin.dll: *** empty log message ***
+
+	* dynare_estimation.m: added option nodiagnostic
+
+	* csminwel.m, csminit.m: new file
+
+	* compDist.m: -replaced qgamma by mj_qgamma to avoid overflow problems
+	-added 'Interpreter' 'none' to title()
+
+	* bfgsi.m: new file
+
+	* ChangeLog: *** empty log message ***
+
+:ext:pythie.cepremap.cnrs.fr/var/lib/cvs
+2004-02-20  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* rplot.m: added legend when several curves
+
+	* rplot.m: corrected bug for several variables
+
+	* varprior.m, rfvar3.m: new file
+
+	* prior_bounds.m: replaced qgamma by mj_qgamma to avoid overflow
+
+	* numgrad.m, mj_qgamma.m, mgnldnsty.m, matrictint.m: new file
+
+	* marginal_density.m: use maxpost as standardization factor
+
+	* fs_dyn.m: new file
+
+	* dynare_m.exe, asamin.dll: *** empty log message ***
+
+	* dynare_estimation.m: added option nodiagnostic
+
+	* csminwel.m, csminit.m: new file
+
+	* compDist.m: -replaced qgamma by mj_qgamma to avoid overflow problems
+	-added 'Interpreter' 'none' to title()
+
+	* bfgsi.m: new file
+
+	* ChangeLog: *** empty log message ***
+
+2004-02-17  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* set_prior.m: -bug correction (options_ must be global)
+
+	* posterior_density_estimate.m: -bug removal
+
+	* mj_optmumlik.m: -adapted for non zero means and linear trend
+	-modified for use with different optimizers
+
+	* dynare_resolve.m:
+	-now returns also steady state for current parameter values
+
+	* dynare_m.exe: -added new options
+
+	* dynare_estimation.m: -added trend_coeff
+	-prefilter default is now zero
+	-default optimizer is Sims' csminwel
+	-prints priors first
+	-added non zero means
+	-different report for ML and Bayesian estimation
+	-corrected bug in sscanf syntax
+	-added automatic loglinear approximation
+
+	* dr11.m: added option loglinear
+	non-unique steady state triggers dir_test(1) = 5
+
+	* dr1.m: added option loglinear
+
+	* compDist.m:
+	-Changed to display first priors, then priors and posterior
+	-various bugs corrected
+
+:ext:pythie.cepremap.cnrs.fr/var/lib/cvs
+2004-02-17  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* set_prior.m: -bug correction (options_ must be global)
+
+	* posterior_density_estimate.m: -bug removal
+
+	* mj_optmumlik.m: -adapted for non zero means and linear trend
+	-modified for use with different optimizers
+
+	* dynare_resolve.m:
+	-now returns also steady state for current parameter values
+
+	* dynare_m.exe: -added new options
+
+	* dynare_estimation.m: -added trend_coeff
+	-prefilter default is now zero
+	-default optimizer is Sims' csminwel
+	-prints priors first
+	-added non zero means
+	-different report for ML and Bayesian estimation
+	-corrected bug in sscanf syntax
+	-added automatic loglinear approximation
+
+	* dr11.m: added option loglinear
+	non-unique steady state triggers dir_test(1) = 5
+
+	* dr1.m: added option loglinear
+
+	* compDist.m:
+	-Changed to display first priors, then priors and posterior
+	-various bugs corrected
+
+2004-02-13  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* prior_bounds.m: added offset for gamma distribution (p3)
+
+2004-02-11  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* priordens.m: added shift parameter p3(i) to gamma density
+
+2004-02-09  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* posterior_moments.m: post_mean is now a column instead of a row
+
+2004-02-03  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* mcmc_diagnostic.m:
+	corrected bug (missing parentheses) in parameter offsets
+
+2004-01-27  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* metropolis.m:
+	corrected computation of logpo2 for initial value of MH chain
+
+	* dynare_estimation.m:
+	added initialization of logpo2 when mh_load_file == 0 and included it in argument of metropolis()
+
+:ext:pythie.cepremap.cnrs.fr/var/lib/cvs
+2004-01-27  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* metropolis.m:
+	corrected computation of logpo2 for initial value of MH chain
+
+	* dynare_estimation.m:
+	added initialization of logpo2 when mh_load_file == 0 and included it in argument of metropolis()
+
+2004-01-26  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* dynare_m.exe: corrected option bugs
+
+	* dynare_estimation.m: changed options defaults to match manual
+
+	* disp_th_moments.m: removed bugs in writing moments to oo_
+
+	* disp_moments.m: write moments in global variable oo_
+
+:ext:pythie.cepremap.cnrs.fr/var/lib/cvs
+2004-01-26  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* dynare_m.exe: corrected option bugs
+
+	* dynare_estimation.m: changed options defaults to match manual
+
+	* disp_th_moments.m: removed bugs in writing moments to oo_
+
+	* disp_moments.m: write moments in global variable oo_
+
+2004-01-24  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* simult_.m: corrected 02 instead of o2 for simul_algo == 1
+
+	* disp_th_moments.m: put mean, var and autocorr in global variable oo_
+
+2004-01-23  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* priordens.m: changed pmean into p1
+
+	* marginal_density.m: suppressed debug printings
+
+	* mj_optmumlik.m: suppressed message when singularity in Kalman filter
+
+	* set_prior.m: suppressed debug printing
+
+	* set_prior.m: new function
+
+	* qchisq.m: new function from stixbox
+
+	* priordens.m:
+	changed calling sequence of inverse gamma 1 and added inverse gamma 2
+
+	* mj_optmumlik.m:
+	-added early return if singularity inside Kalman filter
+	-now passes p1 and not pmean to priordens
+
+	* metropolis.m:
+	add logpo2 (log of posterior density) to function output
+
+	* mcmc_diagnostic.m: added 'Interpreter','none' to graph titles
+
+	* marginal_density.m, lpdfig2.m, lpdfig1.m, inverse_gamma_specification.m:
+	new function
+
+	* dynare_m.exe: added new estimation options
+
+	* dynare_estimation.m: -mh_init_scale set to 2*mh_jscale
+	-priors are now set in set_prior()
+	-p2 is now pstdev (as specified by the user)
+	-modified code for load_mh_file option when mh_replic = 0
+	-metropolis now returns x2 and logpo2
+	-added call to marginal density and report
+	-smoothed observation error graph only if observation errors
+
+	* dr11.m: removed warnings for singularity and other conditions
+
+	* ChangeLog: *** empty log message ***
+
+:ext:pythie.cepremap.cnrs.fr/var/lib/cvs
+2004-01-23  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* set_prior.m: new function
+
+	* qchisq.m: new function from stixbox
+
+	* priordens.m:
+	changed calling sequence of inverse gamma 1 and added inverse gamma 2
+
+	* mj_optmumlik.m:
+	-added early return if singularity inside Kalman filter
+	-now passes p1 and not pmean to priordens
+
+	* metropolis.m:
+	add logpo2 (log of posterior density) to function output
+
+	* mcmc_diagnostic.m: added 'Interpreter','none' to graph titles
+
+	* marginal_density.m, lpdfig2.m, lpdfig1.m, inverse_gamma_specification.m:
+	new function
+
+	* dynare_m.exe: added new estimation options
+
+	* dynare_estimation.m: -mh_init_scale set to 2*mh_jscale
+	-priors are now set in set_prior()
+	-p2 is now pstdev (as specified by the user)
+	-modified code for load_mh_file option when mh_replic = 0
+	-metropolis now returns x2 and logpo2
+	-added call to marginal density and report
+	-smoothed observation error graph only if observation errors
+
+	* dr11.m: removed warnings for singularity and other conditions
+
+	* ChangeLog: *** empty log message ***
+
+2004-01-20  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* mcmcdiags.m: added deletion of temporary files
+
+2004-01-17  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* mj_optmumlik.m:
+	changed filter so that first observation is used. State variables go now from period 0 to T
+
+	* dynare_estimation.m:
+	change code at the end of the function to match the fact that aTt starts now in period 0 instead of 1.
+
+:ext:pythie.cepremap.cnrs.fr/var/lib/cvs
+2004-01-17  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* mj_optmumlik.m:
+	changed filter so that first observation is used. State variables go now from period 0 to T
+
+	* dynare_estimation.m:
+	change code at the end of the function to match the fact that aTt starts now in period 0 instead of 1.
+
+:ext:pythie.cepremap.cnrs.fr/var/lib/cvs
+2004-01-17  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* dynare_estimation.m:
+	change code at the end of the function to match the fact that aTt starts now in period 0 instead of 1.
+
+2004-01-16  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* asamin.dll, asamin.m, check_mh.m, generalized_cholesky.m, generalized_cholesky2.m, hessian2.m, lpdfnorm.m, mcmc_diagnostic.m, mcmcdiags.m, mode_check.m, my_subplot.m, pdfig.m, pgamma.m, pnorm.m, posterior_density_estimate.m, prior_bounds.m, qbeta.m, qgamma.m, qnorm.m:
+	*** empty log message ***
+
+	* resol1.m: changed specification of invalid conditions
+
+	* posterior_moments.m: adapted for several chains
+
+	* metropolis.m: added random initial point and several chains
+
+	* dynare_resolve.m: changed specification of invalid conditions
+
+	* dynare_m.exe: new version of parser
+
+	* dynare_estimation.m:
+	added options for partial processing and MCMC convergence diagnostics
+
+	* dr11.m: changed specification of invalid conditions
+
+	* dr1.m: *** empty log message ***
+
+	* compDist.m:
+	corrected bug on density of lognormal instead of log of normal density
+
+	* mj_optmumlik.m:
+	corrected bug that included presample observations in computing log likelihood constant
+
+2004-01-01  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* stoch_simul.m: corrects bug in orthogonalized shocks
+
+	* th_autocovariances.m:
+	corrects bug in computing second order theorectical mean
+
+	* priordens.m:
+	corrected bug in priordens: log of normal density was in fact density of lognormal...
+
+	* metropolis.m: now keeps track of rejected draws in x3
+
+	* make_ex_.m:
+	corrected bug in initialization of exe_ in absecnce of initval data
+
+	* dynare_m.exe: *** empty log message ***
+
+2003-12-31  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* priordens.m:
+	corrected bug for uniform distribution (ln instead of log)
+
+2003-12-04  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* dynare_estimation.m, dynare_m.exe:
+	corrected bug in setting estimated parameter value with ML estimation
+
+2003-12-03  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* dynare_estimation.m: corrected typo
+
+2003-12-02  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* dynare_estimation.m: firt release of dynare_test to testers
+
+2003-12-01  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* compDist.m, dynare_estimation.m, dynare_m.exe, metropolis.m:
+	added jscale option and minor changes
+
+	* compDist.m, dynare_estimation.m, dynare_m.exe, lpdfig.m, metropolis.m, mj_optmumlik.m, posterior_moments.m, priordens.m:
+	integrates metropolis hasting
+
+2003-11-26  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* hessian_sparse.m, hessian.m:
+	resolved name conflict between hessian matrix and hessian function
+
+2003-11-25  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* dgamma.m, dbeta.m, dynare_estimation.m, metropolis.m:
+	recompute hessian after optimization in dynare_estimation
+
+	* dynare_m.exe, hessian.m, hessian_sparse.m: *** empty log message ***
+
+	* dr11.m, dr1.m: replaced jacob2 by hessian_sparse
+
+	* mjdgges.dll, compDist.m, metropolis.m, rndprior.m:
+	*** empty log message ***
+
+	* compDist.m:
+	debugging metropolis, corrected call for gamma_rnd in rndprior
+
+2003-11-24  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* dynare_estimation.m: removed comments that inhibited graphs
+
+	* resol1.m: put back in computation of steady state if necessary. 
+	It should matter for models where estimated parameters don't change 
+	the steady state
+
+2003-11-23  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* stoch_simul.m: changed to orthogonalized IRFs
+
+	* rndprior.m, priordens.m: need to check parameters
+
+	* metropolis.m: adapted for Dynare
+
+	* lpdfig.m: need to check arguments
+
+	* irf.m: changed input for orthogonalized IRF
+
+	* dynare_estimation.m: added metropolis
+
+	* compDist.m: need to check distribution arguments
+
+	* dynare.m: changed directory name
+
+2003-11-18  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* mj_optmumlik.m: changed input parameters for priordens()
+
+2003-11-17  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* beta_rnd.m, gamm_rnd.m, rand_beta.m: *** empty log message ***
+
+2003-11-16  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* rand_beta.m: *** empty log message ***
+
+2003-11-14  michel@MICHEL-LAT  <michel@michel-lat>
+
+	* bicgstab.m, bksup.m, bksup1.m, bksupk.m, brm.m, bseastr.m, calib.m, calib_obj.m, calib_obj2.m, check.m, cols.m, compDist.m, datatomfile.m, dcompare.m, diffext.m, disp_dr.m, disp_moments.m, disp_th_moments.m, dlognorm.m, dnorm.m, dr1.m, dr11.m, dr2.m, dsample.m, dy_date.m, dyn2vec.m, dynare.m, dynare_estimation.m, dynare_resolve.m, dynare_solve.m, dynasave.m, dynatype.m, equiv.m, f_var.m, fbeta.m, ff1_.m, ff2_.m, ff2a_.m, ff_simul.m, ff_simul1.m, ff_simul2.m, fff.m, ffill.m, fgamma.m, figamm.m, fnorm.m, forcst.m, ftest.m, fx_.m, gcompare.m, hessext.m, hpfast.m, indnv.m, initvalf_.m, irf.m, jacob.m, jacob2.m, jacob_a.m, kalman_transition_matrix.m, linear.m, lnsrch.m, lnsrch1.m, lpdfbeta.m, lpdfgam.m, lpdfig.m, lyapunov_symm.m, make_ex_.m, make_y_.m, mcompare.m, metropolis.m, mj_optmumlik.m, olr.m, olr1.m, olr2.m, osr.m, osr1.m, osr_obj.m, p2toperc.m, priordens.m, qzdiv.m, qzswitch.m, reshapel.m, resid.m, resid0.m, resol.m, resol1.m, rfrot.m, rndprior.m, rows.m, rplot.m, selif.m, set_default_option.m, set_shocks.m, set_start_date.m, set_state_space.m, sim1.m, simk.m, simul.m, simult.m, simult_.m, solve1.m, steady.m, steady_.m, sylvester3.m, table.m, testifft.m, th_autocovariances.m, transition_matrix.m, union.m, var_index.m, var_state_index.m:
+	start
+
+	* stoch_simul.m: New file.
+
diff --git a/tags/v_3.062/matlab/CompareModels.m b/tags/v_3.062/matlab/CompareModels.m
new file mode 100644
index 0000000000000000000000000000000000000000..824385d3ce5eb08f1f6167941d885b85703b2be0
--- /dev/null
+++ b/tags/v_3.062/matlab/CompareModels.m
@@ -0,0 +1,69 @@
+function PosteriorOddsTable = model_comparison(ModelNames,ModelPriors)
+% 05-30-2005
+%
+% type is a string  = Laplace
+%                   = ModifiedHarmonicMean
+% ModelPriors is a m*1 column vector
+% ModelNames is m*1 cell array
+
+global oo_ options_
+
+type = options_.model_comparison_approximation;
+if strcmp(type,'Laplace')
+  type = 'LaplaceApproximation';
+end
+
+NumberOfModels = size(ModelNames,1);
+MarginalLogDensity = zeros(NumberOfModels,1);
+
+% Get the estimates of the (logged) marginal densities
+
+init_loop = 1;
+if isempty(type)
+    oo_ = load(['ModelNames{1} '_results.mat' ],'oo_');
+    try
+        eval(['MarginalLogDensity(1) = oo_.MarginalDensity.ModifiedHarmonicMean']); 
+    catch
+      try
+        eval(['MarginalLogDensity(1) =' ...
+	      ' oo_.MarginalDensity.LaplaceApproximation']);
+      catch
+	disp(['CompareModels :: I cant''t find any marginal density approximation associated to model ' ModelNames{1}])
+	return
+      end
+    end
+
+end
+for i = init_loop:NumberOfModels
+    oo_ = load(['ModelNames(i) '_results.mat' ],'oo_');
+    try
+        eval(['MarginalLogDensity(i) = oo_.MarginalDensity.' type ';']) 
+    catch
+        if strcmpi(type,'LaplaceApproximation')
+            disp(['CompareModels :: I cant''t find the Laplace approximation associated to model ' ModelNames(i,:)])
+            return
+        elseif strcmpi(type,'ModifiedHarmonicMean')
+            disp(['CompareModels :: I cant''t find the modified harmonic mean estimate associated to model ' ModelNames(i,:)])
+            return
+        end
+    end
+end
+
+MarginalDensity = exp(MarginalLogDensity);
+ConstantOfIntegration  = ModelPriors'*MarginalDensity;
+PosteriorProbabilities = ModelPriors.*MarginalDensity / ConstantOfIntegration;
+PosteriorOddsTable = PosteriorProbabilities.*PosteriorProbabilities.^(-1);
+
+% Now I display the posterior probabilities:
+if NumberOfModels == 2
+    disp(' ')
+    disp(['Posterior odd ('ModelNames(1) '/' ModelNames(2) ') =  ' num2str(PosteriorOddsTable(1,2))])
+    disp(' ')
+else
+    disp(' ')
+    disp(' Posterior probabilities:')
+    for i=1:NumberOfModels
+            disp([ 'Model ' int2str(i) ' (' ModelNames(i) ') = ' num2str(PosteriorProbabilities(i))])
+    end
+    disp(' ')
+end
diff --git a/tags/v_3.062/matlab/DiffuseKalmanSmoother.m b/tags/v_3.062/matlab/DiffuseKalmanSmoother.m
new file mode 100644
index 0000000000000000000000000000000000000000..e2a0224a3a596c438412d90147c8152ae28194c4
--- /dev/null
+++ b/tags/v_3.062/matlab/DiffuseKalmanSmoother.m
@@ -0,0 +1,107 @@
+function [alphahat,etahat,a] = DiffuseKalmanSmoother(T,R,Q,Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf)
+% stephane.adjemian@cepremap.cnrs.fr [09-16-2004]
+% 
+%   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).  
+spinf   = size(Pinf1);
+spstar  = size(Pstar1);
+v       = zeros(pp,smpl);
+a       = zeros(mm,smpl+1);
+iF      = zeros(pp,pp,smpl);
+Fstar   = zeros(pp,pp,smpl);
+iFinf   = zeros(pp,pp,smpl);
+K       = zeros(mm,pp,smpl);
+L       = zeros(mm,mm,smpl);
+Linf    = zeros(mm,mm,smpl);
+Kstar   = zeros(mm,pp,smpl);
+P       = zeros(mm,mm,smpl+1);
+Pstar   = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1;
+Pinf    = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1;
+crit    = 10^(-12);
+steady  = smpl;
+rr      = size(Q,1);
+QQ      = R*Q*transpose(R);
+QRt		= Q*transpose(R);
+
+Z = zeros(pp,mm);
+for i=1:pp;
+	Z(i,mf(i)) = 1;
+end
+
+t = 0;
+while rank(Pinf(:,:,t+1),crit) & t<smpl
+    t = t+1;
+    v(:,t) 		 	= Y(:,t) - a(mf,t) - trend(:,t);
+    iFinf(:,:,t) 	= inv(Pinf(mf,mf,t));
+    Kinf(:,:,t)	 	= T*Pinf(:,mf,t)*iFinf(:,:,t);
+    a(:,t+1) 	 	= T*a(:,t) + Kinf(:,:,t)*v(:,t);
+    Linf(:,:,t)  	= T - Kinf(:,:,t)*Z;
+    Fstar(:,:,t) 	= Pstar(mf,mf,t);
+    Kstar(:,:,t) 	= (T*Pstar(:,mf,t)-Kinf(:,:,t)*Fstar(:,:,t))*iFinf(:,:,t);
+    Pstar(:,:,t+1)	= T*Pstar(:,:,t)*transpose(T)-T*Pstar(:,mf,t)*transpose(Kinf(:,:,t))-Kinf(:,:,t)*Pinf(mf,mf,t)*transpose(Kstar(:,:,t)) + QQ;
+    Pinf(:,:,t+1)	= T*Pinf(:,:,t)*transpose(T)-T*Pinf(:,mf,t)*transpose(Kinf(:,:,t));
+end
+d = t;
+P(:,:,d+1) = Pstar(:,:,d+1);
+iFinf = iFinf(:,:,1:d);
+Linf  = Linf(:,:,1:d);
+Fstar = Fstar(:,:,1:d);
+Kstar = Kstar(:,:,1:d);
+%Kstar = Kinf(:,:,1:d); ??? MJ
+Pstar = Pstar(:,:,1:d);
+Pinf  = Pinf(:,:,1:d);
+notsteady = 1;
+while notsteady & t<smpl
+    t = t+1;
+    v(:,t)      = Y(:,t) - a(mf,t) - trend(:,t);
+    iF(:,:,t)   = inv(P(mf,mf,t));
+    K(:,:,t)    = T*P(:,mf,t)*iF(:,:,t);
+    L(:,:,t)    = T-K(:,:,t)*Z;
+    a(:,t+1)    = T*a(:,t) + K(:,:,t)*v(:,t);    
+    P(:,:,t+1)  = T*P(:,:,t)*transpose(T)-T*P(:,mf,t)*transpose(K(:,:,t)) + QQ;
+    notsteady   = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
+end
+K_s = K(:,:,t); % ?? MJ
+iF_s = iF(:,:,t); % ?? MJ
+P_s = P(:,:,t+1); % ?? MJ
+if t<smpl
+	t_steady = t+1;
+	P  = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1]));
+	iF = cat(3,iF(:,:,1:t),repmat(inv(P_s(mf,mf)),[1 1 smpl-t_steady+1]));
+	L  = cat(3,L(:,:,1:t),repmat(T-K_s*Z,[1 1 smpl-t_steady+1]));
+	K  = cat(3,K(:,:,1:t),repmat(T*P_s(:,mf)*iF_s,[1 1 smpl-t_steady+1]));
+end
+while t<smpl
+    t=t+1;
+    v(:,t) = Y(:,t) - a(mf,t) - trend(:,t);
+    a(:,t+1) = T*a(:,t) + K_s*v(:,t);
+end
+alphahat   = zeros(mm,smpl);
+etahat	   = zeros(rr,smpl);
+r 		   = zeros(mm,smpl);
+t = smpl+1;
+while t>d+2
+	t = t-1;
+    r(:,t-1) = transpose(Z)*iF(:,:,t)*v(:,t) + transpose(L(:,:,t))*r(:,t);
+    alphahat(:,t)	= a(:,t) + P(:,:,t)*r(:,t-1);
+	etahat(:,t)		= QRt*r(:,t);
+end
+if d
+	r0 = zeros(mm,d); r0(:,d) = r(:,d);
+	r1 = zeros(mm,d);
+	for t = d:-1:2
+    	r0(:,t-1) = transpose(Linf(:,:,t))*r0(:,t);
+		r1(:,t-1) = transpose(Z)*(iFinf(:,:,t)*v(:,t)-transpose(Kstar(:,:,t))*r0(:,t)) + transpose(Linf(:,:,t))*r1(:,t);
+		alphahat(:,t)	= a(:,t) + Pstar(:,:,t)*r0(:,t-1) + Pinf(:,:,t)*r1(:,t-1);
+		etahat(:,t)		= QRt*r0(:,t);
+	end
+	r0_0 = transpose(Linf(:,:,1))*r0(:,1);
+	r1_0 = transpose(Z)*(iFinf(:,:,1)*v(:,1)-transpose(Kstar(:,:,1))*r0(:,1)) + transpose(Linf(:,:,1))*r1(:,1);
+	alphahat(:,1)  	= a(:,1) + Pstar(:,:,1)*r0_0 + Pinf(:,:,1)*r1_0;
+	etahat(:,1)		= QRt*r0_0(:,1);
+else
+      r0 = transpose(Z)*iF(:,:,1)*v(:,1) + transpose(L(:,:,1))*r(:,1);
+      alphahat(:,1)	= a(:,1) + P(:,:,1)*r0;
+      etahat(:,1)	= QRt*r(:,1);
+end
diff --git a/tags/v_3.062/matlab/DiffuseKalmanSmoother1.m b/tags/v_3.062/matlab/DiffuseKalmanSmoother1.m
new file mode 100644
index 0000000000000000000000000000000000000000..e634603a8b2c2157aa3ea8510b6999d1cff54f3d
--- /dev/null
+++ b/tags/v_3.062/matlab/DiffuseKalmanSmoother1.m
@@ -0,0 +1,137 @@
+function [alphahat,etahat,a, aK] = DiffuseKalmanSmoother1(T,R,Q,Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf)
+% modified by M. Ratto:
+% 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 
+%
+% stephane.adjemian@cepremap.cnrs.fr [09-16-2004]
+% 
+%   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).  
+
+global options_
+
+nk = options_.nk;
+spinf   	= size(Pinf1);
+spstar  	= size(Pstar1);
+v       	= zeros(pp,smpl);
+a       	= zeros(mm,smpl+1);
+aK              = zeros(nk,mm,smpl+1);
+iF      	= zeros(pp,pp,smpl);
+Fstar   	= zeros(pp,pp,smpl);
+iFinf   	= zeros(pp,pp,smpl);
+K       	= zeros(mm,pp,smpl);
+L       	= zeros(mm,mm,smpl);
+Linf    	= zeros(mm,mm,smpl);
+Kstar   	= zeros(mm,pp,smpl);
+P       	= zeros(mm,mm,smpl+1);
+Pstar   	= zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1;
+Pinf    	= zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1;
+crit    	= options_.kalman_tol;
+crit1       = 1.e-8;
+steady  	= smpl;
+rr      	= size(Q,1);
+QQ      	= R*Q*transpose(R);
+QRt			= Q*transpose(R);
+alphahat   	= zeros(mm,smpl);
+etahat	   	= zeros(rr,smpl);
+r 		   	= zeros(mm,smpl);
+
+Z = zeros(pp,mm);
+for i=1:pp;
+	Z(i,mf(i)) = 1;
+end
+
+t = 0;
+while rank(Pinf(:,:,t+1),crit1) & t<smpl
+    t = t+1;
+    v(:,t) 		 	= Y(:,t) - a(mf,t) - trend(:,t);
+    if rcond(Pinf(mf,mf,t)) < crit
+    	return		
+    end
+    iFinf(:,:,t) 	= inv(Pinf(mf,mf,t));
+    Kinf(:,:,t)	 	= T*Pinf(:,mf,t)*iFinf(:,:,t);
+    a(:,t+1) 	 	= T*a(:,t) + Kinf(:,:,t)*v(:,t);
+    aK(1,:,t+1) 	 	= a(:,t+1);
+    for jnk=2:nk,
+        aK(jnk,:,t+jnk) 	 	= T^(jnk-1)*a(:,t+1);
+    end
+    Linf(:,:,t)  	= T - Kinf(:,:,t)*Z;
+    Fstar(:,:,t) 	= Pstar(mf,mf,t);
+    Kstar(:,:,t) 	= (T*Pstar(:,mf,t)-Kinf(:,:,t)*Fstar(:,:,t))*iFinf(:,:,t);
+    Pstar(:,:,t+1)	= T*Pstar(:,:,t)*transpose(T)-T*Pstar(:,mf,t)*transpose(Kinf(:,:,t))-Kinf(:,:,t)*Pinf(mf,mf,t)*transpose(Kstar(:,:,t)) + QQ;
+    Pinf(:,:,t+1)	= T*Pinf(:,:,t)*transpose(T)-T*Pinf(:,mf,t)*transpose(Kinf(:,:,t));
+end
+d = t;
+P(:,:,d+1) = Pstar(:,:,d+1);
+iFinf = iFinf(:,:,1:d);
+Linf  = Linf(:,:,1:d);
+Fstar = Fstar(:,:,1:d);
+Kstar = Kstar(:,:,1:d);
+Pstar = Pstar(:,:,1:d);
+Pinf  = Pinf(:,:,1:d);
+notsteady = 1;
+while notsteady & t<smpl
+    t = t+1;
+    v(:,t)      = Y(:,t) - a(mf,t) - trend(:,t);
+    P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
+    if rcond(P(mf,mf,t)) < crit
+    	return		
+    end    
+    iF(:,:,t)   = inv(P(mf,mf,t));
+    K(:,:,t)    = T*P(:,mf,t)*iF(:,:,t);
+    L(:,:,t)    = T-K(:,:,t)*Z;
+    a(:,t+1)    = T*a(:,t) + K(:,:,t)*v(:,t);    
+    aK(1,:,t+1) 	 	= a(:,t+1);
+    for jnk=2:nk,
+        aK(jnk,:,t+jnk) 	 	= T^(jnk-1)*a(:,t+1);
+    end
+    P(:,:,t+1)  = T*P(:,:,t)*transpose(T)-T*P(:,mf,t)*transpose(K(:,:,t)) + QQ;
+    notsteady   = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
+end
+K_s = K(:,:,t);
+iF_s = iF(:,:,t);
+P_s = P(:,:,t+1);
+if t<smpl
+	t_steady = t+1;
+	P  = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1]));
+	iF = cat(3,iF(:,:,1:t),repmat(inv(P_s(mf,mf)),[1 1 smpl-t_steady+1]));
+	L  = cat(3,L(:,:,1:t),repmat(T-K_s*Z,[1 1 smpl-t_steady+1]));
+	K  = cat(3,K(:,:,1:t),repmat(T*P_s(:,mf)*iF_s,[1 1 smpl-t_steady+1]));
+end
+while t<smpl
+    t=t+1;
+    v(:,t) = Y(:,t) - a(mf,t) - trend(:,t);
+    a(:,t+1) = T*a(:,t) + K_s*v(:,t);
+    aK(1,:,t+1) 	 	= a(:,t+1);
+    for jnk=2:nk,
+        aK(jnk,:,t+jnk) 	 	= T^(jnk-1)*a(:,t+1);
+    end
+end
+t = smpl+1;
+while t>d+1 & t>2
+	t = t-1;
+    r(:,t-1) = transpose(Z)*iF(:,:,t)*v(:,t) + transpose(L(:,:,t))*r(:,t);
+    alphahat(:,t)	= a(:,t) + P(:,:,t)*r(:,t-1);
+	etahat(:,t)		= QRt*r(:,t);
+end
+if d
+	r0 = zeros(mm,d); r0(:,d) = r(:,d);
+	r1 = zeros(mm,d);
+	for t = d:-1:2
+    	r0(:,t-1) = transpose(Linf(:,:,t))*r0(:,t);
+		r1(:,t-1) = transpose(Z)*(iFinf(:,:,t)*v(:,t)-transpose(Kstar(:,:,t))*r0(:,t)) + transpose(Linf(:,:,t))*r1(:,t);
+		alphahat(:,t)	= a(:,t) + Pstar(:,:,t)*r0(:,t-1) + Pinf(:,:,t)*r1(:,t-1);
+		etahat(:,t)		= QRt*r0(:,t);
+	end
+	r0_0 = transpose(Linf(:,:,1))*r0(:,1);
+	r1_0 = transpose(Z)*(iFinf(:,:,1)*v(:,1)-transpose(Kstar(:,:,1))*r0(:,1)) + transpose(Linf(:,:,1))*r1(:,1);
+	alphahat(:,1)  	= a(:,1) + Pstar(:,:,1)*r0_0 + Pinf(:,:,1)*r1_0;
+	etahat(:,1)		= QRt*r0(:,1);
+else
+    r0 = transpose(Z)*iF(:,:,1)*v(:,1) + transpose(L(:,:,1))*r(:,1);
+    alphahat(:,1)	= a(:,1) + P(:,:,1)*r0;
+    etahat(:,1)	= QRt*r(:,1);
+end
diff --git a/tags/v_3.062/matlab/DiffuseKalmanSmoother3.m b/tags/v_3.062/matlab/DiffuseKalmanSmoother3.m
new file mode 100644
index 0000000000000000000000000000000000000000..e00e78954eb53c4a07abe1febf4b3e98dff0f1a4
--- /dev/null
+++ b/tags/v_3.062/matlab/DiffuseKalmanSmoother3.m
@@ -0,0 +1,253 @@
+function [alphahat,etahat,a1, aK] = DiffuseKalmanSmoother3(T,R,Q,Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf)
+% Modified by M. Ratto
+% New output argument aK: 1-step to nk-stpe ahed predictions)
+% New input argument nk: max order of predictions in aK
+% New global variable id_ where the DKF stops (common with
+% diffuselikelihood3)
+% New icc variable to count number of iterations for Finf steps
+% Pstar % Pinf simmetric
+% New termination of DKF iterations based on id_
+% Li also stored during DKF iterations !!
+% some bugs corrected in the DKF part of the smoother (Z matrix and
+% alphahat)
+%
+% stephane.adjemian@cepremap.cnrs.fr [09-16-2004]
+% 
+%   See "Fast Filtering and Smoothing for Multivariate State Space
+%   Models", S.J. Koopman and J. Durbin (2000, in Journal of Time Series 
+%   Analysis, vol. 21(3), pp. 281-296).  
+
+global options_
+
+nk = options_.nk;
+spinf   	= size(Pinf1);
+spstar  	= size(Pstar1);
+v       	= zeros(pp,smpl);
+a       	= zeros(mm,smpl+1);
+a1			= a;
+aK          = zeros(nk,mm,smpl+nk);
+Fstar   	= zeros(pp,smpl);
+Finf		= zeros(pp,smpl);
+Ki       	= zeros(mm,pp,smpl);
+Li      	= zeros(mm,mm,pp,smpl);
+Linf    	= zeros(mm,mm,pp,smpl);
+L0      	= zeros(mm,mm,pp,smpl);
+Kstar   	= zeros(mm,pp,smpl);
+P       	= zeros(mm,mm,smpl+1);
+P1			= P;
+Pstar   	= zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1;
+Pinf    	= zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1;
+Pstar1 		= Pstar;
+Pinf1  		= Pinf;
+crit   	 	= options_.kalman_tol;
+crit1       = 1.e-6;
+steady  	= smpl;
+rr      	= size(Q,1);
+QQ      	= R*Q*transpose(R);
+QRt			= Q*transpose(R);
+alphahat   	= zeros(mm,smpl);
+etahat	   	= zeros(rr,smpl);
+r 		   	= zeros(mm,smpl);
+
+Z = zeros(pp,mm);
+for i=1:pp;
+	Z(i,mf(i)) = 1;
+end
+
+t = 0;
+icc=0;
+newRank	  = rank(Pinf(:,:,1),crit1);
+while newRank & t < smpl
+  t = t+1;
+  a1(:,t) = a(:,t);
+  Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1));
+  Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1));
+  Pstar1(:,:,t) = Pstar(:,:,t);
+  Pinf1(:,:,t) = Pinf(:,:,t);
+  for i=1:pp
+    v(i,t) 	= Y(i,t)-a(mf(i),t)-trend(i,t);
+    Fstar(i,t) 	= Pstar(mf(i),mf(i),t);
+    Finf(i,t)	= Pinf(mf(i),mf(i),t);
+    Kstar(:,i,t) 	= Pstar(:,mf(i),t);
+    if Finf(i,t) > crit & newRank,  % original MJ: if Finf(i,t) > crit
+      icc=icc+1;
+      Kinf(:,i,t)	= Pinf(:,mf(i),t);
+      Linf(:,:,i,t)  	= eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t);
+      L0(:,:,i,t)  	= (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Z(i,:)/Finf(i,t);
+      a(:,t)		= a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t);
+      Pstar(:,:,t)	= Pstar(:,:,t) + ...
+	  Kinf(:,i,t)*transpose(Kinf(:,i,t))*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ...
+	  (Kstar(:,i,t)*transpose(Kinf(:,i,t)) +...
+	   Kinf(:,i,t)*transpose(Kstar(:,i,t)))/Finf(i,t);
+      Pinf(:,:,t)	= Pinf(:,:,t) - Kinf(:,i,t)*transpose(Kinf(:,i,t))/Finf(i,t);
+      Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1));
+      Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1));
+      % new terminiation criteria by M. Ratto
+      P0=Pinf(:,:,t);
+      %             newRank = any(diag(P0(mf,mf))>crit);
+      %             if newRank==0, id = i; end,
+      if ~isempty(options_.diffuse_d),  
+	newRank = (icc<options_.diffuse_d);  
+	%if newRank & any(diag(P0(mf,mf))>crit)==0; 
+	if newRank & (any(diag(P0(mf,mf))>crit)==0 & rank(P0,crit1)==0); 
+	  disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF')
+	  options_.diffuse_d = icc;
+	  newRank=0;
+	end
+      else
+	%newRank = any(diag(P0(mf,mf))>crit);                 
+	newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1));                 
+	if newRank==0, 
+	  options_.diffuse_d = icc;
+	end                    
+      end,
+      if newRank==0, 
+	options_.diffuse_d=i;
+      end                    
+      % end new terminiation criteria by M. Ratto
+    else 
+      %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
+      %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
+      %% rank(Pinf)=0. [st�phane,11-03-2004].	  
+      Li(:,:,i,t)    = eye(mm)-Kstar(:,i,t)*Z(i,:)/Fstar(i,t);  % we need to store Li for DKF smoother
+      a(:,t) 		= a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t);
+      Pstar(:,:,t)	= Pstar(:,:,t) - Kstar(:,i,t)*transpose(Kstar(:,i,t))/Fstar(i,t);
+      Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1));
+    end
+  end
+  a(:,t+1) 	 	= T*a(:,t);
+  for jnk=1:nk,
+    aK(jnk,:,t+jnk) 	 	= T^jnk*a(:,t);
+  end
+  Pstar(:,:,t+1)	= T*Pstar(:,:,t)*transpose(T)+ QQ;
+  Pinf(:,:,t+1)	= T*Pinf(:,:,t)*transpose(T);
+  P0=Pinf(:,:,t+1);
+  if newRank,
+    %newRank = any(diag(P0(mf,mf))>crit);
+    newRank	  = rank(P0,crit1);
+  end
+end
+
+
+d = t;
+P(:,:,d+1) = Pstar(:,:,d+1);
+Linf  = Linf(:,:,:,1:d);
+L0  = L0(:,:,:,1:d);
+Fstar = Fstar(:,1:d);
+Finf = Finf(:,1:d);
+Kstar = Kstar(:,:,1:d);
+Pstar = Pstar(:,:,1:d);
+Pinf  = Pinf(:,:,1:d);
+Pstar1 = Pstar1(:,:,1:d);
+Pinf1  = Pinf1(:,:,1:d);
+notsteady = 1;
+while notsteady & t<smpl
+  t = t+1;
+  a1(:,t) = a(:,t);
+  P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
+  P1(:,:,t) = P(:,:,t);
+  for i=1:pp
+    v(i,t)  = Y(i,t) - a(mf(i),t) - trend(i,t);
+    Fi(i,t) = P(mf(i),mf(i),t);
+    Ki(:,i,t) = P(:,mf(i),t);
+    if Fi(i,t) > crit
+      Li(:,:,i,t)    = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t);
+      a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t);
+      P(:,:,t) = P(:,:,t) - Ki(:,i,t)*transpose(Ki(:,i,t))/Fi(i,t);
+      P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
+    end
+  end
+  a(:,t+1) = T*a(:,t);
+  for jnk=1:nk,
+    aK(jnk,:,t+jnk) 	 	= T^jnk*a(:,t);
+  end
+  P(:,:,t+1) = T*P(:,:,t)*transpose(T) + QQ;
+  notsteady   = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
+end
+P_s=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
+Fi_s = Fi(:,t);
+Ki_s = Ki(:,:,t);
+L_s  =Li(:,:,:,t);
+if t<smpl
+  t_steady = t+1;
+  P  = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1]));
+  Fi = cat(2,Fi(:,1:t),repmat(Fi_s,[1 1 smpl-t_steady+1]));
+  Li  = cat(4,Li(:,:,:,1:t),repmat(L_s,[1 1 smpl-t_steady+1]));
+  Ki  = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t_steady+1]));
+end
+while t<smpl
+  t=t+1;
+  a1(:,t) = a(:,t);
+  for i=1:pp
+    v(i,t)      = Y(i,t) - a(mf(i),t) - trend(i,t);
+    if Fi_s(i) > crit
+      a(:,t) = a(:,t) + Ki_s(:,i)*v(i,t)/Fi_s(i);
+    end
+  end
+  a(:,t+1) = T*a(:,t);
+  for jnk=1:nk,
+    aK(jnk,:,t+jnk)	= T^jnk*a(:,t);
+  end
+end
+a1(:,t+1) = a(:,t+1);
+ri=r;
+t = smpl+1;
+while t>d+1 & t>2,
+  t = t-1;
+  for i=pp:-1:1
+    if Fi(i,t) > crit
+      ri(:,t)=transpose(Z(i,:))/Fi(i,t)*v(i,t)+transpose(Li(:,:,i,t))*ri(:,t);
+    end
+  end
+  r(:,t-1) = ri(:,t);
+  alphahat(:,t)	= a1(:,t) + P1(:,:,t)*r(:,t-1);
+  etahat(:,t)		= QRt*r(:,t);
+  ri(:,t-1) = transpose(T)*ri(:,t);
+end
+if d
+  r0 = zeros(mm,d); r0(:,d) = ri(:,d);
+  r1 = zeros(mm,d);
+  for t = d:-1:2
+    for i=pp:-1:1
+      if Finf(i,t) > crit & ~(t==d & i>options_.diffuse_d),  % use of options_.diffuse_d to be sure of DKF termination
+					     %r1(:,t) = transpose(Z)*v(:,t)/Finf(i,t) + ... BUG HERE in transpose(Z)
+					     r1(:,t) = transpose(Z(i,:))*v(i,t)/Finf(i,t) + ...
+						       transpose(L0(:,:,i,t))*r0(:,t) + transpose(Linf(:,:,i,t))*r1(:,t);
+					     r0(:,t) = transpose(Linf(:,:,i,t))*r0(:,t);
+      elseif Fstar(i,t) > crit % step needed whe Finf == 0
+	r0(:,t)=transpose(Z(i,:))/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t);
+      end
+    end
+    alphahat(:,t)	= a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t);
+    r(:,t-1)		= r0(:,t);
+    etahat(:,t)		= QRt*r(:,t);
+    r0(:,t-1) = transpose(T)*r0(:,t);
+    r1(:,t-1) = transpose(T)*r1(:,t);
+  end
+  r0_0 = r0(:,1);
+  r1_0 = r1(:,1);
+  for i=pp:-1:1
+    if Finf(i,1) > crit,
+      %r1_0 = transpose(Z)*v(:,1)/Finf(i,1) + ... %bug with Z here
+      r1_0 = transpose(Z(i,:))*v(i,1)/Finf(i,1) + ...
+	     transpose(L0(:,:,i,1))*r0_0 + transpose(Linf(:,:,i,1))*r1_0;
+      r0_0 = transpose(Linf(:,:,i,1))*r0_0;
+    elseif Fstar(i,1) > crit, % step needed when Finf=0
+      r0_0=transpose(Z(i,:))/Fstar(i,1)*v(i,1)+Li(:,:,i,1)'*r0_0;
+    end
+  end
+  %alphahat(:,1)  	= a(:,1) + Pstar(:,:,1)*r0_0 + Pinf(:,:,1)*r1_0; %this line is buggy
+  alphahat(:,1)  	= a1(:,1) + Pstar1(:,:,1)*r0_0 + Pinf1(:,:,1)*r1_0;
+  etahat(:,1)		= QRt*r(:,1);
+else
+  r0 = ri(:,1);
+  for i=pp:-1:1
+    if Fi(i,1) > crit
+      r0=transpose(Z(i,:))/Fi(i,1)*v(i,1)+transpose(Li(:,:,i,1))*r0;
+    end
+  end 
+  %alphahat(:,1)	= a(:,1) + P(:,:,1)*r0;  % this line is buggy
+  alphahat(:,1)	= a1(:,1) + P1(:,:,1)*r0;
+  etahat(:,1)	= QRt*r(:,1);
+end
+
diff --git a/tags/v_3.062/matlab/DiffuseKalmanSmootherH.m b/tags/v_3.062/matlab/DiffuseKalmanSmootherH.m
new file mode 100644
index 0000000000000000000000000000000000000000..6aed813cbe5b2e5a21f52515f8f2f837a7fde361
--- /dev/null
+++ b/tags/v_3.062/matlab/DiffuseKalmanSmootherH.m
@@ -0,0 +1,112 @@
+function [alphahat,epsilonhat,etahat,a] = DiffuseKalmanSmootherH(T,R,Q,H,Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf)
+% stephane.adjemian@cepremap.cnrs.fr [09-16-2004]
+% 
+%   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).  
+spinf   = size(Pinf1);
+spstar  = size(Pstar1);
+v       = zeros(pp,smpl);
+a       = zeros(mm,smpl+1);
+iF      = zeros(pp,pp,smpl);
+Fstar   = zeros(pp,pp,smpl);
+iFinf   = zeros(pp,pp,smpl);
+K       = zeros(mm,pp,smpl);
+L       = zeros(mm,mm,smpl);
+Linf    = zeros(mm,mm,smpl);
+Kstar   = zeros(mm,pp,smpl);
+P       = zeros(mm,mm,smpl+1);
+Pstar   = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1;
+Pinf    = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1;
+crit    = 10^(-12);
+steady  = smpl;
+rr      = size(Q,1);
+QQ      = R*Q*transpose(R);
+QRt		= Q*transpose(R);
+
+Z = zeros(pp,mm);
+for i=1:pp;
+	Z(i,mf(i)) = 1;
+end
+
+t = 0;
+while rank(Pinf(:,:,t+1),crit) & t<smpl
+    t = t+1;
+    v(:,t) 		 	= Y(:,t) - a(mf,t) - trend(:,t);
+    iFinf(:,:,t) 	= inv(Pinf(mf,mf,t));
+    Kinf(:,:,t)	 	= T*Pinf(:,mf,t)*iFinf(:,:,t);
+    a(:,t+1) 	 	= T*a(:,t) + Kinf(:,:,t)*v(:,t);
+    Linf(:,:,t)  	= T - Kinf(:,:,t)*Z;
+    Fstar(:,:,t) 	= Pstar(mf,mf,t) + H;
+    Kstar(:,:,t) 	= (T*Pstar(:,mf,t)-Kinf(:,:,t)*Fstar(:,:,t))*iFinf(:,:,t);
+    Pstar(:,:,t+1)	= T*Pstar(:,:,t)*transpose(T)-T*Pstar(:,mf,t)*transpose(Kinf(:,:,t))-Kinf(:,:,t)*Pinf(mf,mf,t)*transpose(Kstar(:,:,t)) + QQ;
+    Pinf(:,:,t+1)	= T*Pinf(:,:,t)*transpose(T)-T*Pinf(:,mf,t)*transpose(Kinf(:,:,t));
+end
+d = t;
+P(:,:,d+1) = Pstar(:,:,d+1);
+iFinf = iFinf(:,:,1:d);
+Linf  = Linf(:,:,1:d);
+Fstar = Fstar(:,:,1:d);
+Kstar = Kstar(:,:,1:d);
+%Kstar = Kinf(:,:,1:d);
+Pstar = Pstar(:,:,1:d);
+Pinf  = Pinf(:,:,1:d);
+notsteady = 1;
+while notsteady & t<smpl
+    t = t+1;
+    v(:,t)      = Y(:,t) - a(mf,t) - trend(:,t);
+    iF(:,:,t)   = inv(P(mf,mf,t)+H);
+    K(:,:,t)    = T*P(:,mf,t)*iF(:,:,t);
+    L(:,:,t)    = T-K(:,:,t)*Z;
+    a(:,t+1)    = T*a(:,t) + K(:,:,t)*v(:,t);    
+    P(:,:,t+1)  = T*P(:,:,t)*transpose(T)-T*P(:,mf,t)*transpose(K(:,:,t)) + QQ;
+    notsteady   = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
+end
+K_s = K(:,:,t); % ?? MJ
+iF_s = iF(:,:,t); % ?? MJ
+P_s = P(:,:,t+1); % ?? MJ
+if t<smpl
+	t_steady = t+1;
+	P  = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1]));
+	iF = cat(3,iF(:,:,1:t),repmat(inv(P_s(mf,mf) + H),[1 1 smpl-t_steady+1]));
+	L  = cat(3,L(:,:,1:t),repmat(T-K_s*Z,[1 1 smpl-t_steady+1]));
+	K  = cat(3,K(:,:,1:t),repmat(T*P_s(:,mf)*iF_s,[1 1 smpl-t_steady+1]));
+end
+while t<smpl
+    t=t+1;
+    v(:,t) = Y(:,t) - a(mf,t) - trend(:,t);
+    a(:,t+1) = T*a(:,t) + K_s*v(:,t);
+end
+alphahat   = zeros(mm,smpl);
+epsilonhat = zeros(pp,smpl);
+etahat	   = zeros(rr,smpl);
+r 		   = zeros(mm,smpl);
+t = smpl+1;
+while t>d+2
+	t = t-1;
+    r(:,t-1) = transpose(Z)*iF(:,:,t)*v(:,t) + transpose(L(:,:,t))*r(:,t);
+    alphahat(:,t)	= a(:,t) + P(:,:,t)*r(:,t-1);
+	etahat(:,t)		= QRt*r(:,t);
+	epsilonhat(:,t)	= H*(iF(:,:,t)*v(:,t)-transpose(K(:,:,t))*r(:,t));
+end
+if d
+	r0 = zeros(mm,d); r0(:,d) = r(:,d);
+	r1 = zeros(mm,d);
+	for t = d:-1:2
+    	r0(:,t-1) = transpose(Linf(:,:,t))*r0(:,t);
+		r1(:,t-1) = transpose(Z)*(iFinf(:,:,t)*v(:,t)-transpose(Kstar(:,:,t))*r0(:,t)) + transpose(Linf(:,:,t))*r1(:,t);
+		alphahat(:,t)	= a(:,t) + Pstar(:,:,t)*r0(:,t-1) + Pinf(:,:,t)*r1(:,t-1);
+		etahat(:,t)		= QRt*r0(:,t);
+		epsilonhat(:,t)	= -H*transpose(Kinf(:,:,t))*r0(:,t);
+	end
+	r0_0 = transpose(Linf(:,:,1))*r0(:,1);
+	r1_0 = transpose(Z)*(iFinf(:,:,1)*v(:,1)-transpose(Kstar(:,:,1))*r0(:,1)) + transpose(Linf(:,:,1))*r1(:,1);
+	alphahat(:,1)  	= a(:,1) + Pstar(:,:,1)*r0_0 + Pinf(:,:,1)*r1_0;
+	etahat(:,1)		= QRt*r0_0(:,1);
+	epsilonhat(:,1)	= -H*transpose(Kinf(:,:,1))*r0_0(:,1);
+else
+      r0 = transpose(Z)*iF(:,:,1)*v(:,1) + transpose(L(:,:,1))*r(:,1);
+      alphahat(:,1)	= a(:,1) + P(:,:,1)*r0;
+      etahat(:,1)	= QRt*r(:,1);
+      epsilonhat(:,1)	= H*(iF(:,:,1)*v(:,1)-transpose(K(:,:,1))*r(:,1));
+end
diff --git a/tags/v_3.062/matlab/DiffuseKalmanSmootherH1.m b/tags/v_3.062/matlab/DiffuseKalmanSmootherH1.m
new file mode 100644
index 0000000000000000000000000000000000000000..d6c038e6e4eef1024382e96fd9342f68bb7f255b
--- /dev/null
+++ b/tags/v_3.062/matlab/DiffuseKalmanSmootherH1.m
@@ -0,0 +1,138 @@
+function [alphahat,epsilonhat,etahat,a, aK] = DiffuseKalmanSmootherH1(T,R,Q,H,Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf)
+% modified by M. Ratto:
+% 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 
+%
+% stephane.adjemian@cepremap.cnrs.fr [09-16-2004]
+% 
+%   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).  
+
+global options_
+
+nk = options_.nk;
+spinf   	= size(Pinf1);
+spstar  	= size(Pstar1);
+v       	= zeros(pp,smpl);
+a       	= zeros(mm,smpl+1);
+iF      	= zeros(pp,pp,smpl);
+Fstar   	= zeros(pp,pp,smpl);
+iFinf   	= zeros(pp,pp,smpl);
+K       	= zeros(mm,pp,smpl);
+L       	= zeros(mm,mm,smpl);
+Linf    	= zeros(mm,mm,smpl);
+Kstar   	= zeros(mm,pp,smpl);
+P       	= zeros(mm,mm,smpl+1);
+Pstar   	= zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1;
+Pinf    	= zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1;
+crit    	= options_.kalman_tol;
+crit1       = 1.e-8;
+steady  	= smpl;
+rr      	= size(Q,1);
+QQ      	= R*Q*transpose(R);
+QRt			= Q*transpose(R);
+alphahat   	= zeros(mm,smpl);
+etahat	   	= zeros(rr,smpl);
+epsilonhat      = zeros(size(Y));
+r 		   	= zeros(mm,smpl);
+
+Z = zeros(pp,mm);
+for i=1:pp;
+	Z(i,mf(i)) = 1;
+end
+
+t = 0;
+while rank(Pinf(:,:,t+1),crit1) & t<smpl
+    t = t+1;
+    v(:,t) 		 	= Y(:,t) - a(mf,t) - trend(:,t);
+    if rcond(Pinf(mf,mf,t)) < crit
+    	return		
+    end
+    iFinf(:,:,t) 	= inv(Pinf(mf,mf,t));
+    Kinf(:,:,t)	 	= T*Pinf(:,mf,t)*iFinf(:,:,t);
+    a(:,t+1) 	 	= T*a(:,t) + Kinf(:,:,t)*v(:,t);
+    aK(1,:,t+1) 	 	= a(:,t+1);
+    for jnk=2:nk,
+        aK(jnk,:,t+jnk) 	 	= T^(jnk-1)*a(:,t+1);
+    end
+    Linf(:,:,t)  	= T - Kinf(:,:,t)*Z;
+    Fstar(:,:,t) 	= Pstar(mf,mf,t) + H;
+    Kstar(:,:,t) 	= (T*Pstar(:,mf,t)-Kinf(:,:,t)*Fstar(:,:,t))*iFinf(:,:,t);
+    Pstar(:,:,t+1)	= T*Pstar(:,:,t)*transpose(T)-T*Pstar(:,mf,t)*transpose(Kinf(:,:,t))-Kinf(:,:,t)*Pinf(mf,mf,t)*transpose(Kstar(:,:,t)) + QQ;
+    Pinf(:,:,t+1)	= T*Pinf(:,:,t)*transpose(T)-T*Pinf(:,mf,t)*transpose(Kinf(:,:,t));
+end
+d = t;
+P(:,:,d+1) = Pstar(:,:,d+1);
+iFinf = iFinf(:,:,1:d);
+Linf  = Linf(:,:,1:d);
+Fstar = Fstar(:,:,1:d);
+Kstar = Kstar(:,:,1:d);
+Pstar = Pstar(:,:,1:d);
+Pinf  = Pinf(:,:,1:d);
+notsteady = 1;
+while notsteady & t<smpl
+    t = t+1;
+    v(:,t)      = Y(:,t) - a(mf,t) - trend(:,t);
+    P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
+    if rcond(P(mf,mf,t) + H) < crit
+    	return		
+    end    
+    iF(:,:,t)   = inv(P(mf,mf,t) + H);
+    K(:,:,t)    = T*P(:,mf,t)*iF(:,:,t);
+    L(:,:,t)    = T-K(:,:,t)*Z;
+    a(:,t+1)    = T*a(:,t) + K(:,:,t)*v(:,t);    
+    aK(1,:,t+1) 	 	= a(:,t+1);
+    for jnk=2:nk,
+        aK(jnk,:,t+jnk) 	 	= T^(jnk-1)*a(:,t+1);
+    end
+    P(:,:,t+1)  = T*P(:,:,t)*transpose(T)-T*P(:,mf,t)*transpose(K(:,:,t)) + QQ;
+    notsteady   = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
+end
+K_s = K(:,:,t);
+iF_s = iF(:,:,t);
+P_s = P(:,:,t+1);
+if t<smpl
+	t_steady = t+1;
+	P  = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1]));
+	iF = cat(3,iF(:,:,1:t),repmat(inv(P_s(mf,mf)+H),[1 1 smpl-t_steady+1]));
+	L  = cat(3,L(:,:,1:t),repmat(T-K_s*Z,[1 1 smpl-t_steady+1]));
+	K  = cat(3,K(:,:,1:t),repmat(T*P_s(:,mf)*iF_s,[1 1 smpl-t_steady+1]));
+end
+while t<smpl
+    t=t+1;
+    v(:,t) = Y(:,t) - a(mf,t) - trend(:,t);
+    a(:,t+1) = T*a(:,t) + K_s*v(:,t);
+    aK(1,:,t+1) 	 	= a(:,t+1);
+    for jnk=2:nk,
+        aK(jnk,:,t+jnk) 	 	= T^(jnk-1)*a(:,t+1);
+    end
+end
+t = smpl+1;
+while t>d+1 & t>2
+	t = t-1;
+    r(:,t-1) = transpose(Z)*iF(:,:,t)*v(:,t) + transpose(L(:,:,t))*r(:,t);
+    alphahat(:,t)	= a(:,t) + P(:,:,t)*r(:,t-1);
+	etahat(:,t)		= QRt*r(:,t);
+end
+if d
+	r0 = zeros(mm,d); r0(:,d) = r(:,d);
+	r1 = zeros(mm,d);
+	for t = d:-1:2
+    	r0(:,t-1) = transpose(Linf(:,:,t))*r0(:,t);
+		r1(:,t-1) = transpose(Z)*(iFinf(:,:,t)*v(:,t)-transpose(Kstar(:,:,t))*r0(:,t)) + transpose(Linf(:,:,t))*r1(:,t);
+		alphahat(:,t)	= a(:,t) + Pstar(:,:,t)*r0(:,t-1) + Pinf(:,:,t)*r1(:,t-1);
+		etahat(:,t)		= QRt*r0(:,t);
+	end
+	r0_0 = transpose(Linf(:,:,1))*r0(:,1);
+	r1_0 = transpose(Z)*(iFinf(:,:,1)*v(:,1)-transpose(Kstar(:,:,1))*r0(:,1)) + transpose(Linf(:,:,1))*r1(:,1);
+	alphahat(:,1)  	= a(:,1) + Pstar(:,:,1)*r0_0 + Pinf(:,:,1)*r1_0;
+	etahat(:,1)		= QRt*r0(:,1);
+else
+    r0 = transpose(Z)*iF(:,:,1)*v(:,1) + transpose(L(:,:,1))*r(:,1);
+    alphahat(:,1)	= a(:,1) + P(:,:,1)*r0;
+    etahat(:,1)	= QRt*r(:,1);
+end
+epsilonhat = Y-alphahat(mf,:)-trend;
diff --git a/tags/v_3.062/matlab/DiffuseKalmanSmootherH3.m b/tags/v_3.062/matlab/DiffuseKalmanSmootherH3.m
new file mode 100644
index 0000000000000000000000000000000000000000..09bfa89246b124b5446232f88b88feabacd3281d
--- /dev/null
+++ b/tags/v_3.062/matlab/DiffuseKalmanSmootherH3.m
@@ -0,0 +1,255 @@
+function [alphahat,epsilonhat,etahat,a1, aK] = DiffuseKalmanSmootherH3(T,R,Q,H,Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf)
+% Modified by M. Ratto
+% New output argument aK: 1-step to nk-stpe ahed predictions)
+% New input argument nk: max order of predictions in aK
+% New global variable id_ where the DKF stops (common with
+% diffuselikelihood3)
+% New icc variable to count number of iterations for Finf steps
+% Pstar % Pinf simmetric
+% New termination of DKF iterations based on id_
+% Li also stored during DKF iterations !!
+% some bugs corrected in the DKF part of the smoother (Z matrix and
+% alphahat)
+%
+% stephane.adjemian@cepremap.cnrs.fr [09-16-2004]
+% 
+%   See "Fast Filtering and Smoothing for Multivariate State Space
+%   Models", S.J. Koopman and J. Durbin (2000, in Journal of Time Series 
+%   Analysis, vol. 21(3), pp. 281-296).  
+
+global options_
+
+nk = options_.nk;
+spinf   	= size(Pinf1);
+spstar  	= size(Pstar1);
+v       	= zeros(pp,smpl);
+a       	= zeros(mm,smpl+1);
+a1			= a;
+aK          = zeros(nk,mm,smpl+nk);
+Fstar   	= zeros(pp,smpl);
+Finf		= zeros(pp,smpl);
+Ki       	= zeros(mm,pp,smpl);
+Li      	= zeros(mm,mm,pp,smpl);
+Linf    	= zeros(mm,mm,pp,smpl);
+L0      	= zeros(mm,mm,pp,smpl);
+Kstar   	= zeros(mm,pp,smpl);
+P       	= zeros(mm,mm,smpl+1);
+P1			= P;
+Pstar   	= zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1;
+Pinf    	= zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1;
+Pstar1 		= Pstar;
+Pinf1  		= Pinf;
+crit   	 	= options_.kalman_tol;
+crit1       = 1.e-6;
+steady  	= smpl;
+rr      	= size(Q,1);
+QQ      	= R*Q*transpose(R);
+QRt			= Q*transpose(R);
+alphahat   	= zeros(mm,smpl);
+etahat	   	= zeros(rr,smpl);
+epsilonhat      = zeros(size(Y));
+r 		   	= zeros(mm,smpl);
+
+Z = zeros(pp,mm);
+for i=1:pp;
+	Z(i,mf(i)) = 1;
+end
+
+t = 0;
+icc=0;
+newRank	  = rank(Pinf(:,:,1),crit1);
+while newRank & t < smpl
+  t = t+1;
+  a1(:,t) = a(:,t);
+  Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1));
+  Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1));
+  Pstar1(:,:,t) = Pstar(:,:,t);
+  Pinf1(:,:,t) = Pinf(:,:,t);
+  for i=1:pp
+    v(i,t) 	= Y(i,t)-a(mf(i),t)-trend(i,t);
+    Fstar(i,t) 	= Pstar(mf(i),mf(i),t) + H(i,i);
+    Finf(i,t)	= Pinf(mf(i),mf(i),t);
+    Kstar(:,i,t) 	= Pstar(:,mf(i),t);
+    if Finf(i,t) > crit & newRank,  % original MJ: if Finf(i,t) > crit
+      icc=icc+1;
+      Kinf(:,i,t)	= Pinf(:,mf(i),t);
+      Linf(:,:,i,t)  	= eye(mm) - Kinf(:,i,t)*Z(i,:)/Finf(i,t);
+      L0(:,:,i,t)  	= (Kinf(:,i,t)*Fstar(i,t)/Finf(i,t) - Kstar(:,i,t))*Z(i,:)/Finf(i,t);
+      a(:,t)		= a(:,t) + Kinf(:,i,t)*v(i,t)/Finf(i,t);
+      Pstar(:,:,t)	= Pstar(:,:,t) + ...
+	  Kinf(:,i,t)*transpose(Kinf(:,i,t))*Fstar(i,t)/(Finf(i,t)*Finf(i,t)) - ...
+	  (Kstar(:,i,t)*transpose(Kinf(:,i,t)) +...
+	   Kinf(:,i,t)*transpose(Kstar(:,i,t)))/Finf(i,t);
+      Pinf(:,:,t)	= Pinf(:,:,t) - Kinf(:,i,t)*transpose(Kinf(:,i,t))/Finf(i,t);
+      Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1));
+      Pinf(:,:,t)=tril(Pinf(:,:,t))+transpose(tril(Pinf(:,:,t),-1));
+      % new terminiation criteria by M. Ratto
+      P0=Pinf(:,:,t);
+      %             newRank = any(diag(P0(mf,mf))>crit);
+      %             if newRank==0, options_.diffuse_d = i; end,
+      if ~isempty(options_.diffuse_d),  
+	newRank = (icc<options_.diffuse_d);  
+	%if newRank & any(diag(P0(mf,mf))>crit)==0; 
+	if newRank & (any(diag(P0(mf,mf))>crit)==0 & rank(P0,crit1)==0); 
+	  disp('WARNING!! Change in OPTIONS_.DIFFUSE_D in univariate DKF')
+	  options_.diffuse_d = icc;
+	  newRank=0;
+	end
+      else
+	%newRank = any(diag(P0(mf,mf))>crit);                 
+	newRank = (any(diag(P0(mf,mf))>crit) | rank(P0,crit1));                 
+	if newRank==0, 
+	  options_.diffuse_d = icc;
+	end                    
+      end,
+      if newRank==0, 
+	options_.diffuse_d=i;
+      end                    
+      % end new terminiation criteria by M. Ratto
+    else 
+      %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
+      %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
+      %% rank(Pinf)=0. [st�phane,11-03-2004].	  
+      Li(:,:,i,t)    = eye(mm)-Kstar(:,i,t)*Z(i,:)/Fstar(i,t);  % we need to store Li for DKF smoother
+      a(:,t) 		= a(:,t) + Kstar(:,i,t)*v(i,t)/Fstar(i,t);
+      Pstar(:,:,t)	= Pstar(:,:,t) - Kstar(:,i,t)*transpose(Kstar(:,i,t))/Fstar(i,t);
+      Pstar(:,:,t)=tril(Pstar(:,:,t))+transpose(tril(Pstar(:,:,t),-1));
+    end
+  end
+  a(:,t+1) 	 	= T*a(:,t);
+  for jnk=1:nk,
+    aK(jnk,:,t+jnk) 	 	= T^jnk*a(:,t);
+  end
+  Pstar(:,:,t+1)	= T*Pstar(:,:,t)*transpose(T)+ QQ;
+  Pinf(:,:,t+1)	= T*Pinf(:,:,t)*transpose(T);
+  P0=Pinf(:,:,t+1);
+  if newRank,
+    %newRank = any(diag(P0(mf,mf))>crit);
+    newRank	  = rank(P0,crit1);
+  end
+end
+
+
+d = t;
+P(:,:,d+1) = Pstar(:,:,d+1);
+Linf  = Linf(:,:,:,1:d);
+L0  = L0(:,:,:,1:d);
+Fstar = Fstar(:,1:d);
+Finf = Finf(:,1:d);
+Kstar = Kstar(:,:,1:d);
+Pstar = Pstar(:,:,1:d);
+Pinf  = Pinf(:,:,1:d);
+Pstar1 = Pstar1(:,:,1:d);
+Pinf1  = Pinf1(:,:,1:d);
+notsteady = 1;
+while notsteady & t<smpl
+  t = t+1;
+  a1(:,t) = a(:,t);
+  P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
+  P1(:,:,t) = P(:,:,t);
+  for i=1:pp
+    v(i,t)  = Y(i,t) - a(mf(i),t) - trend(i,t);
+    Fi(i,t) = P(mf(i),mf(i),t);
+    Ki(:,i,t) = P(:,mf(i),t) + H(i,i);
+    if Fi(i,t) > crit
+      Li(:,:,i,t)    = eye(mm)-Ki(:,i,t)*Z(i,:)/Fi(i,t);
+      a(:,t) = a(:,t) + Ki(:,i,t)*v(i,t)/Fi(i,t);
+      P(:,:,t) = P(:,:,t) - Ki(:,i,t)*transpose(Ki(:,i,t))/Fi(i,t);
+      P(:,:,t)=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
+    end
+  end
+  a(:,t+1) = T*a(:,t);
+  for jnk=1:nk,
+    aK(jnk,:,t+jnk) 	 	= T^jnk*a(:,t);
+  end
+  P(:,:,t+1) = T*P(:,:,t)*transpose(T) + QQ;
+  notsteady   = ~(max(max(abs(P(:,:,t+1)-P(:,:,t))))<crit);
+end
+P_s=tril(P(:,:,t))+transpose(tril(P(:,:,t),-1));
+Fi_s = Fi(:,t);
+Ki_s = Ki(:,:,t);
+L_s  =Li(:,:,:,t);
+if t<smpl
+  t_steady = t+1;
+  P  = cat(3,P(:,:,1:t),repmat(P(:,:,t),[1 1 smpl-t_steady+1]));
+  Fi = cat(2,Fi(:,1:t),repmat(Fi_s,[1 1 smpl-t_steady+1]));
+  Li  = cat(4,Li(:,:,:,1:t),repmat(L_s,[1 1 smpl-t_steady+1]));
+  Ki  = cat(3,Ki(:,:,1:t),repmat(Ki_s,[1 1 smpl-t_steady+1]));
+end
+while t<smpl
+  t=t+1;
+  a1(:,t) = a(:,t);
+  for i=1:pp
+    v(i,t)      = Y(i,t) - a(mf(i),t) - trend(i,t);
+    if Fi_s(i) > crit
+      a(:,t) = a(:,t) + Ki_s(:,i)*v(i,t)/Fi_s(i);
+    end
+  end
+  a(:,t+1) = T*a(:,t);
+  for jnk=1:nk,
+    aK(jnk,:,t+jnk)	= T^jnk*a(:,t);
+  end
+end
+a1(:,t+1) = a(:,t+1);
+ri=r;
+t = smpl+1;
+while t>d+1 & t>2,
+  t = t-1;
+  for i=pp:-1:1
+    if Fi(i,t) > crit
+      ri(:,t)=transpose(Z(i,:))/Fi(i,t)*v(i,t)+transpose(Li(:,:,i,t))*ri(:,t);
+    end
+  end
+  r(:,t-1) = ri(:,t);
+  alphahat(:,t)	= a1(:,t) + P1(:,:,t)*r(:,t-1);
+  etahat(:,t)		= QRt*r(:,t);
+  ri(:,t-1) = transpose(T)*ri(:,t);
+end
+if d
+  r0 = zeros(mm,d); r0(:,d) = ri(:,d);
+  r1 = zeros(mm,d);
+  for t = d:-1:2
+    for i=pp:-1:1
+      if Finf(i,t) > crit & ~(t==d & i>options_.diffuse_d),  % use of options_.diffuse_d to be sure of DKF termination
+					     %r1(:,t) = transpose(Z)*v(:,t)/Finf(i,t) + ... BUG HERE in transpose(Z)
+					     r1(:,t) = transpose(Z(i,:))*v(i,t)/Finf(i,t) + ...
+						       transpose(L0(:,:,i,t))*r0(:,t) + transpose(Linf(:,:,i,t))*r1(:,t);
+					     r0(:,t) = transpose(Linf(:,:,i,t))*r0(:,t);
+      elseif Fstar(i,t) > crit % step needed whe Finf == 0
+	r0(:,t)=transpose(Z(i,:))/Fstar(i,t)*v(i,t)+Li(:,:,i,t)'*r0(:,t);
+      end
+    end
+    alphahat(:,t)	= a1(:,t) + Pstar1(:,:,t)*r0(:,t) + Pinf1(:,:,t)*r1(:,t);
+    r(:,t-1)		= r0(:,t);
+    etahat(:,t)		= QRt*r(:,t);
+    r0(:,t-1) = transpose(T)*r0(:,t);
+    r1(:,t-1) = transpose(T)*r1(:,t);
+  end
+  r0_0 = r0(:,1);
+  r1_0 = r1(:,1);
+  for i=pp:-1:1
+    if Finf(i,1) > crit,
+      %r1_0 = transpose(Z)*v(:,1)/Finf(i,1) + ... %bug with Z here
+      r1_0 = transpose(Z(i,:))*v(i,1)/Finf(i,1) + ...
+	     transpose(L0(:,:,i,1))*r0_0 + transpose(Linf(:,:,i,1))*r1_0;
+      r0_0 = transpose(Linf(:,:,i,1))*r0_0;
+    elseif Fstar(i,1) > crit, % step needed when Finf=0
+      r0_0=transpose(Z(i,:))/Fstar(i,1)*v(i,1)+Li(:,:,i,1)'*r0_0;
+    end
+  end
+  %alphahat(:,1)  	= a(:,1) + Pstar(:,:,1)*r0_0 + Pinf(:,:,1)*r1_0; %this line is buggy
+  alphahat(:,1)  	= a1(:,1) + Pstar1(:,:,1)*r0_0 + Pinf1(:,:,1)*r1_0;
+  etahat(:,1)		= QRt*r(:,1);
+else
+  r0 = ri(:,1);
+  for i=pp:-1:1
+    if Fi(i,1) > crit
+      r0=transpose(Z(i,:))/Fi(i,1)*v(i,1)+transpose(Li(:,:,i,1))*r0;
+    end
+  end 
+  %alphahat(:,1)	= a(:,1) + P(:,:,1)*r0;  % this line is buggy
+  alphahat(:,1)	= a1(:,1) + P1(:,:,1)*r0;
+  etahat(:,1)	= QRt*r(:,1);
+end
+epsilonhat = Y-alphahat(mf,:)-trend;
+
diff --git a/tags/v_3.062/matlab/DiffuseLikelihood1.m b/tags/v_3.062/matlab/DiffuseLikelihood1.m
new file mode 100644
index 0000000000000000000000000000000000000000..1beb7beacda388d864e5f73e9fa21d4eb28632ea
--- /dev/null
+++ b/tags/v_3.062/matlab/DiffuseLikelihood1.m
@@ -0,0 +1,90 @@
+function LIK = DiffuseLikelihood1(T,R,Q,Pinf,Pstar,Y,trend,start)
+% stephane.adjemian@cepremap.cnrs.fr [07-19-2004]
+%
+% Same as DiffuseLikelihoodH1 without measurement error.
+  global bayestopt_ options_
+  
+  mf = bayestopt_.mf;
+  smpl = size(Y,2);
+  mm   = size(T,2);
+  pp   = size(Y,1);
+  a    = zeros(mm,1);
+  dF = 1;
+  QQ   = R*Q*transpose(R);
+  t    = 0;
+  lik  = zeros(smpl+1,1);
+  LIK  = Inf;
+  lik(smpl+1) = smpl*pp*log(2*pi);
+  notsteady   = 1;
+  crit        = options_.kalman_tol;
+  reste       = 0;
+  while rank(Pinf,crit) & t < smpl
+    t     = t+1;
+    v  	  = Y(:,t)-a(mf)-trend(:,t);
+    Finf  = Pinf(mf,mf);
+    if rcond(Finf) < crit 
+      if ~all(abs(Finf(:)) < crit)
+	return
+      else
+	iFstar	= inv(Pstar(mf,mf));
+	dFstar	= det(Pstar(mf,mf));
+	Kstar	= Pstar(:,mf)*iFstar;
+	lik(t)	= log(dFstar) + transpose(v)*iFstar*v;
+	Pinf	= T*Pinf*transpose(T);
+	Pstar	= T*(Pstar-Pstar(:,mf)*transpose(Kstar))*transpose(T)+QQ;
+	a		= T*(a+Kstar*v);
+      end
+    else
+      lik(t)	= log(det(Finf));
+      iFinf	= inv(Finf);
+      Kinf	= Pinf(:,mf)*iFinf;					%%	premultiplication by the transition matrix T is removed (stephane) 
+      Fstar	= Pstar(mf,mf);
+      Kstar	= (Pstar(:,mf)-Kinf*Fstar)*iFinf; 	%%	premultiplication by the transition matrix T is removed (stephane)
+      Pstar	= T*(Pstar-Pstar(:,mf)*transpose(Kinf)-Pinf(:,mf)*transpose(Kstar))*transpose(T)+QQ;
+      Pinf	= T*(Pinf-Pinf(:,mf)*transpose(Kinf))*transpose(T);
+      a		= T*(a+Kinf*v);					
+    end  
+  end
+  if t == smpl                                                           
+    error(['There isn''t enough information to estimate the initial' ... 
+	   ' conditions of the nonstationary variables']);                   
+  end                                                                    
+  F_singular = 1;
+  while notsteady & t < smpl
+    t  = t+1;
+    v  	  = Y(:,t)-a(mf)-trend(:,t);
+    F  = Pstar(mf,mf);
+    oldPstar  = Pstar;
+    dF = det(F);
+    if rcond(F) < crit 
+      if ~all(abs(F(:))<crit)
+	return
+      else
+	a         = T*a;
+	Pstar     = T*Pstar*transpose(T)+QQ;
+      end
+    else
+      F_singular = 0;
+      iF        = inv(F);
+      lik(t)    = log(dF)+transpose(v)*iF*v;
+      K         = Pstar(:,mf)*iF; %% premultiplication by the transition matrix T is removed (stephane)
+      a         = T*(a+K*v);		%% --> factorization of the transition matrix...
+      Pstar     = T*(Pstar-Pstar(:,mf)*iF*Pstar(mf,:))*transpose(T)+QQ;	%% ... idem (stephane)
+    end
+    notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit);
+  end
+  if F_singular == 1
+    error(['The variance of the forecast error remains singular until the' ...
+	  'end of the sample'])
+  end
+  reste = smpl-t;
+  while t < smpl
+    t = t+1;
+    v = Y(:,t)-a(mf)-trend(:,t);
+    a = T*(a+K*v);
+    lik(t) = transpose(v)*iF*v;
+  end
+  lik(t) = lik(t) + reste*log(dF);
+
+
+  LIK    = .5*(sum(lik(start:end))-(start-1)*lik(smpl+1)/smpl);% Minus the log-likelihood.
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/DiffuseLikelihood3.m b/tags/v_3.062/matlab/DiffuseLikelihood3.m
new file mode 100644
index 0000000000000000000000000000000000000000..9c274c835ae3706769d997e6862e24268e4d7037
--- /dev/null
+++ b/tags/v_3.062/matlab/DiffuseLikelihood3.m
@@ -0,0 +1,222 @@
+function LIK = DiffuseLikelihood3(T,R,Q,Pinf,Pstar,Y,trend,start)%//Z,T,R,Q,Pinf,Pstar,Y)
+% changes by M. Ratto [April 2005]
+% introduced new global variable id_ for termination of DKF
+% introduced a persistent fmax, in order to keep track the max order of
+% magnitude of the 'zero' values in Pinf at DKF termination
+% new icc counter for Finf steps in DKF
+% new termination for DKF
+% likelihood terms for Fstar must be cumulated in DKF also when Pinf is non
+% zero. this bug is fixed.
+%
+% [4/5/2005] correctyed bug in the modified verson of Ratto for rank of Pinf 
+% introduced a specific crit1 for the DKF termination
+%
+% stepane.adjemian@cepremap.cnrs.fr [07-19-2004]
+% 
+%   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).  
+%
+%	Case where F_{\infty,t} is singular ==> Univariate treatment of multivariate
+%	time series.
+%
+%   THE PROBLEM:
+% 
+%   y_t =   Z_t * \alpha_t + \varepsilon_t
+%   \alpha_{t+1} = T_t  * \alpha_t + R_t * \eta_t
+% 
+%   with:
+% 
+%   \alpha_1 = a + A*\delta + R_0*\eta_0
+%
+%   m*q matrix A and m*(m-q) matrix R_0 are selection matrices (their
+%   columns constitue all the columns of the m*m identity matrix) so that 
+%
+%       A'*R_0 = 0 and A'*\alpha_1 = \delta
+%
+%   We assume that the vector \delta is distributed as a N(0,\kappa*I_q)
+%   for a given  \kappa > 0. So that the expectation of \alpha_1 is a and
+%   its variance is P, with
+%
+%       P = \kappa*P_{\infty} + P_{\star}
+%
+%           P_{\infty} = A*A'
+%           P_{\star}  = R_0*Q_0*R_0'
+%
+%   P_{\infty} is a m*m diagonal matrix with q ones and m-q zeros. 
+%
+% 
+%   and where:
+% 
+%   y_t             is a pp*1 vector
+%   \alpha_t        is a mm*1 vector
+%   \varepsilon_t   is a pp*1 multivariate random variable (iid N(0,H_t))
+%   \eta_t          is a rr*1 multivariate random variable (iid N(0,Q_t))
+%   a_1             is a mm*1 vector
+% 
+%   Z_t     is a pp*mm matrix
+%   T_t     is a mm*mm matrix
+%   H_t     is a pp*pp matrix
+%   R_t     is a mm*rr matrix
+%   Q_t     is a rr*rr matrix
+%   P_1     is a mm*mm matrix
+% 
+% 
+%   FILTERING EQUATIONS:
+% 
+%   v_t = y_t - Z_t* a_t
+%   F_t = Z_t * P_t * Z_t' + H_t
+%   K_t = T_t * P_t * Z_t' * F_t^{-1}
+%   L_t = T_t - K_t * Z_t
+%   a_{t+1} = T_t * a_t + K_t * v_t
+%   P_{t+1} = T_t * P_t * L_t' + R_t*Q_t*R_t'
+% 
+%
+%   DIFFUSE FILTERING EQUATIONS:
+%
+%   a_{t+1} = T_t*a_t + K_{\ast,t}v_t
+%   P_{\infty,t+1} = T_t*P_{\infty,t}*T_t'
+%   P_{\ast,t+1}  = T_t*P_{\ast,t}*L_{\ast,t}' + R_t*Q_t*R_t'
+%   K_{\ast,t}   = T_t*P_{\ast,t}*Z_t'*F_{\ast,t}^{-1}
+%   v_t = y_t - Z_t*a_t
+%   L_{\ast,t} = T_t - K_{\ast,t}*Z_t
+%   F_{\ast,t}  = Z_t*P_{\ast,t}*Z_t' + H_t
+global bayestopt_ options_
+
+mf = bayestopt_.mf;
+pp     = size(Y,1);
+mm     = size(T,1);
+smpl   = size(Y,2);
+a      = zeros(mm,1);
+QQ     = R*Q*transpose(R);
+t      = 0;
+lik	   = zeros(smpl+1,1);	
+lik(smpl+1) = smpl*pp*log(2*pi);		%% the constant of minus two times the log-likelihood
+notsteady 	= 1;
+crit      	= options_.kalman_tol;
+crit1      	= 1.e-6;
+newRank	 	= rank(Pinf,crit1);
+icc=0;
+while newRank & t < smpl
+  t = t+1;
+  for i=1:pp
+    v(i) 	= Y(i,t)-a(mf(i))-trend(i,t);
+    Fstar 	= Pstar(mf(i),mf(i));
+    Finf	= Pinf(mf(i),mf(i));
+    Kstar 	= Pstar(:,mf(i));
+    if Finf > crit & newRank,  %added newRank criterion 
+      icc=icc+1;
+      Kinf	= Pinf(:,mf(i));
+      a		= a + Kinf*v(i)/Finf;
+      Pstar	= Pstar + Kinf*transpose(Kinf)*Fstar/(Finf*Finf) - ...
+	  (Kstar*transpose(Kinf)+Kinf*transpose(Kstar))/Finf;
+      Pinf	= Pinf - Kinf*transpose(Kinf)/Finf;
+      lik(t) 	= lik(t) + log(Finf);
+      % start new termination criterion for DKF
+      if ~isempty(options_.diffuse_d),  
+	newRank = (icc<options_.diffuse_d);  
+	%if newRank & any(diag(Pinf(mf,mf))>crit)==0; %  M. Ratto this line is BUGGY
+	if newRank & (any(diag(Pinf(mf,mf))>crit)==0 & rank(Pinf,crit1)==0); 
+	  options_.diffuse_d = icc;
+	  newRank=0;
+	  disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF')
+	  disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)])
+	  disp('You may have to reset the optimisation')
+	end
+      else
+	%newRank = any(diag(Pinf(mf,mf))>crit);     % M. Ratto this line is BUGGY 
+	newRank = (any(diag(Pinf(mf,mf))>crit) | rank(Pinf,crit1));                 
+	if newRank==0, 
+	  P0=	T*Pinf*transpose(T);
+	  %newRank = any(diag(P0(mf,mf))>crit);   % M. Ratto this line is BUGGY
+	  newRank = (any(diag(Pinf(mf,mf))>crit) | rank(P0,crit1));   
+	  if newRank==0, 
+	    options_.diffuse_d = icc;
+	  end
+	end                    
+      end,
+      % end new termination and checks for DKF and fmax
+    elseif Fstar > crit 
+      %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
+      %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
+      %% rank(Pinf)=0. [st�phane,11-03-2004].	  
+      %if rank(Pinf,crit) == 0
+      % the likelihood terms should alwasy be cumulated, not only
+      % when Pinf=0, otherwise the lik would depend on the ordering
+      % of observed variables
+      lik(t) = lik(t) + log(Fstar) + v(i)*v(i)/Fstar;
+      %end
+      a	= a + Kstar*v(i)/Fstar;
+      Pstar = Pstar - Kstar*transpose(Kstar)/Fstar;
+    else
+      % disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fi)])
+    end
+  end 
+%     if all(abs(Pinf(:))<crit),
+%         oldRank = 0;
+%     else
+%         oldRank = rank(Pinf,crit);
+%     end
+    if newRank,
+        oldRank = rank(Pinf,crit1);
+    else
+        oldRank = 0;
+    end
+	a 		= T*a;
+	Pstar 	= T*Pstar*transpose(T)+QQ;
+	Pinf	= T*Pinf*transpose(T);
+%     if all(abs(Pinf(:))<crit),
+%         newRank = 0;
+%     else
+%     	newRank = rank(Pinf,crit);
+%     end
+    if newRank,
+        newRank = rank(Pinf,crit1);  % new crit1 is used 
+    end
+	if oldRank ~= newRank
+		disp('DiffuseLiklihood3 :: T does influence the rank of Pinf!')	
+	end  
+end
+if t == smpl                                                           
+  error(['There isn''t enough information to estimate the initial' ... 
+	 ' conditions of the nonstationary variables']);                   
+end   
+while notsteady & t < smpl
+  t = t+1;
+  oldP = Pstar;
+  for i=1:pp
+    v(i) = Y(i,t) - a(mf(i)) - trend(i,t);
+    Fi   = Pstar(mf(i),mf(i));
+    if Fi > crit
+      Ki		= Pstar(:,mf(i));
+      a		= a + Ki*v(i)/Fi;
+      Pstar 	= Pstar - Ki*transpose(Ki)/Fi;
+      lik(t) 	= lik(t) + log(Fi) + v(i)*v(i)/Fi;
+    else
+      %disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)])
+    end
+  end	
+  a 			= T*a;
+  Pstar 		= T*Pstar*transpose(T) + QQ;
+  notsteady 	= ~(max(max(abs(Pstar-oldP)))<crit);
+end
+while t < smpl
+  t = t+1;
+  Pstar = oldP;
+  for i=1:pp
+    v(i) = Y(i,t) - a(mf(i)) - trend(i,t);
+    Fi   = Pstar(mf(i),mf(i));
+    if Fi > crit
+      Ki 		= Pstar(:,mf(i));
+      a 		= a + Ki*v(i)/Fi;
+      Pstar 	= Pstar - Ki*transpose(Ki)/Fi;
+      lik(t)    	= lik(t) + log(Fi) + v(i)*v(i)/Fi;
+    else
+      %disp(['zero F term for observed ',int2str(i),' ',num2str(Fi)])
+    end
+  end	
+  a = T*a;
+end
+
+LIK = .5*(sum(lik(start:end))-(start-1)*lik(smpl+1)/smpl);
+
diff --git a/tags/v_3.062/matlab/DiffuseLikelihoodH1.m b/tags/v_3.062/matlab/DiffuseLikelihoodH1.m
new file mode 100644
index 0000000000000000000000000000000000000000..51fe5ec6e2a0bef699e4220d1209225ce6d60d95
--- /dev/null
+++ b/tags/v_3.062/matlab/DiffuseLikelihoodH1.m
@@ -0,0 +1,161 @@
+function LIK = DiffuseLikelihoodH1(T,R,Q,H,Pinf,Pstar,Y,trend,start)
+% stephane.adjemian@cepremap.cnrs.fr [07-19-2004]
+%
+%   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).  
+%
+%   THE PROBLEM:
+%
+%   y_t =   Z_t * \alpha_t + \varepsilon_t
+%   \alpha_{t+1} = T_t  * \alpha_t + R_t * \eta_t
+%
+%   with:
+%
+%   \alpha_1 = a + A*\delta + R_0*\eta_0
+%
+%   m*q matrix A and m*(m-q) matrix R_0 are selection matrices (their
+%   columns constitue all the columns of the m*m identity matrix) so that 
+%
+%       A'*R_0 = 0 and A'*\alpha_1 = \delta
+%
+%   We assume that the vector \delta is distributed as a N(0,\kappa*I_q)
+%   for a given  \kappa > 0. So that the expectation of \alpha_1 is a and
+%   its variance is P, with
+%
+%       P = \kappa*P_{\infty} + P_{\star}
+%
+%           P_{\infty} = A*A'
+%           P_{\star}  = R_0*Q_0*R_0'
+%
+%   P_{\infty} is a m*m diagonal matrix with q ones and m-q zeros. 
+%
+%
+%   and where:
+%
+%   y_t             is a pp*1 vector
+%   \alpha_t        is a mm*1 vector
+%   \varepsilon_t   is a pp*1 multivariate random variable (iid N(0,H_t))
+%   \eta_t          is a rr*1 multivariate random variable (iid N(0,Q_t))
+%   a_1             is a mm*1 vector
+%
+%   Z_t     is a pp*mm matrix
+%   T_t     is a mm*mm matrix
+%   H_t     is a pp*pp matrix
+%   R_t     is a mm*rr matrix
+%   Q_t     is a rr*rr matrix
+%   P_1     is a mm*mm matrix
+%
+%
+%   FILTERING EQUATIONS:
+%
+%   v_t = y_t - Z_t* a_t
+%   F_t = Z_t * P_t * Z_t' + H_t
+%   K_t = T_t * P_t * Z_t' * F_t^{-1}
+%   L_t = T_t - K_t * Z_t
+%   a_{t+1} = T_t * a_t + K_t * v_t
+%   P_{t+1} = T_t * P_t * L_t' + R_t*Q_t*R_t'
+%
+%
+%   DIFFUSE FILTERING EQUATIONS:
+%
+%   a_{t+1} = T_t*a_t + K_{\infty,t}v_t
+%   P_{\infty,t+1} = T_t*P_{\infty,t}*L_{\infty,t}'
+%   P_{\ast,t+1}  = T_t*P_{\ast,t}*L_{\infty,t}' - K_{\infty,t}*F_{\infty,t}*K_{\ast,t}' + R_t*Q_t*R_t'
+%   K_{\infty,t}   = T_t*P_{\infty,t}*Z_t'*F_{\infty,t}^{-1}
+%   v_t = y_t - Z_t*a_t
+%   L_{\infty,t} = T_t - K_{\infty,t}*Z_t
+%   F_{\infty,t} = Z_t*P_{\infty,t}*Z_t'
+%   K_{\ast,t}  = (T_t*P_{\ast,t}*Z_t' + K_{\infty,t}*F_{\ast,t})*F_{\infty,t}^{-1}
+%   F_{\ast,t}  = Z_t*P_{\ast,t}*Z_t' + H_t
+%
+%	Matrix Finf is assumed to be non singular. If this is not the case we have
+%   to switch to another algorithm (NewAlg=3).
+%
+%	start = options_.presample
+  global bayestopt_ options_
+  
+  mf = bayestopt_.mf;
+  smpl = size(Y,2);
+  mm   = size(T,2);
+  pp   = size(Y,1);
+  a    = zeros(mm,1);
+  dF = 1;
+  QQ   = R*Q*transpose(R);
+  t    = 0;
+  lik  = zeros(smpl+1,1);
+  LIK  = Inf;
+  lik(smpl+1) = smpl*pp*log(2*pi);
+  notsteady   = 1;
+  crit        = options_.kalman_tol;
+  reste       = 0;
+  while rank(Pinf,crit) & t < smpl
+    t     = t+1;
+    v  	  = Y(:,t)-a(mf)-trend(:,t);
+    Finf  = Pinf(mf,mf);
+    if rcond(Finf) < crit 
+      if ~all(abs(Finf(:))<crit)
+	return
+      else
+	iFstar	= inv(Pstar(mf,mf)+H);
+	dFstar	= det(Pstar(mf,mf)+H);
+	Kstar	= Pstar(:,mf)*iFstar;
+	lik(t)	= log(dFstar) + transpose(v)*iFstar*v;
+	Pinf	= T*Pinf*transpose(T);
+	Pstar	= T*(Pstar-Pstar(:,mf)*transpose(Kstar))*transpose(T)+QQ;
+	a		= T*(a+Kstar*v);
+      end
+    else
+      lik(t)	= log(det(Finf));
+      iFinf	= inv(Finf);
+      Kinf	= Pinf(:,mf)*iFinf;					%%	premultiplication by the transition matrix T is removed (stephane) 
+      Fstar	= Pstar(mf,mf)+H;
+      Kstar	= (Pstar(:,mf)-Kinf*Fstar)*iFinf; 	%%	premultiplication by the transition matrix T is removed (stephane)
+      Pstar	= T*(Pstar-Pstar(:,mf)*transpose(Kinf)-Pinf(:,mf)*transpose(Kstar))*transpose(T)+QQ;
+      Pinf	= T*(Pinf-Pinf(:,mf)*transpose(Kinf))*transpose(T);
+      a		= T*(a+Kinf*v);					
+    end  
+  end
+  if t == smpl                                                           
+    error(['There isn''t enough information to estimate the initial' ... 
+	   ' conditions of the nonstationary variables']);                   
+  end                                                                    
+  F_singular = 1;
+  while notsteady & t < smpl
+    t  = t+1;
+    v  = Y(:,t)-a(mf)-trend(:,t);
+    F  = Pstar(mf,mf)+H;
+    oldPstar  = Pstar;
+    dF = det(F);
+    if rcond(F) < crit 
+      if ~all(abs(F(:))<crit)
+	return
+      else
+	a         = T*a;
+	Pstar     = T*Pstar*transpose(T)+QQ;
+      end
+    else  
+      F_singular = 0;
+      iF		  = inv(F);
+      lik(t)    = log(dF)+transpose(v)*iF*v;
+      K         = Pstar(:,mf)*iF; %% premultiplication by the transition matrix T is removed (stephane)
+      a         = T*(a+K*v);		%% --> factorization of the transition matrix...
+      Pstar     = T*(Pstar-Pstar(:,mf)*iF*Pstar(mf,:))*transpose(T)+QQ;	%% ... idem (stephane)
+    end
+    notsteady = ~(max(max(abs(Pstar-oldPstar)))<crit);
+  end
+  if F_singular == 1
+    error(['The variance of the forecast error remains singular until the' ...
+	   'end of the sample'])
+  end
+  reste = smpl-t;
+  while t < smpl
+    t = t+1;
+    v = Y(:,t)-a(mf)-trend(:,t);
+    a = T*(a+K*v);
+    lik(t) = transpose(v)*iF*v;
+  end
+  lik(t) = lik(t) + reste*log(dF);
+  LIK    = .5*(sum(lik(start:end))-(start-1)*lik(smpl+1)/smpl);% Minus the
+							       % log-likelihood.
+							       
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/DiffuseLikelihoodH3.m b/tags/v_3.062/matlab/DiffuseLikelihoodH3.m
new file mode 100644
index 0000000000000000000000000000000000000000..83e05557024f90ea6fbc829a667284aef638f2ef
--- /dev/null
+++ b/tags/v_3.062/matlab/DiffuseLikelihoodH3.m
@@ -0,0 +1,203 @@
+function LIK = DiffuseLikelihoodH3(T,R,Q,H,Pinf,Pstar,Y,trend,start)
+% changes by M. Ratto
+% introduced new global variable id_ for termination of DKF
+% introduced a persistent fmax, in order to keep track the max order of
+% magnitude of the 'zero' values in Pinf at DKF termination
+% new icc counter for Finf steps in DKF
+% new termination for DKF
+% likelihood terms for Fstar must be cumulated in DKF also when Pinf is non
+% zero. this bug is fixed.
+%
+% stephane.adjemian@cepremap.cnrs.fr [07-19-2004]
+% 
+%   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).  
+%
+%	Case where F_{\infty,t} is singular ==> Univariate treatment of multivariate
+%	time series.
+%
+%   THE PROBLEM:
+% 
+%   y_t =   Z_t * \alpha_t + \varepsilon_t
+%   \alpha_{t+1} = T_t  * \alpha_t + R_t * \eta_t
+% 
+%   with:
+% 
+%   \alpha_1 = a + A*\delta + R_0*\eta_0
+%
+%   m*q matrix A and m*(m-q) matrix R_0 are selection matrices (their
+%   columns constitue all the columns of the m*m identity matrix) so that 
+%
+%       A'*R_0 = 0 and A'*\alpha_1 = \delta
+%
+%   We assume that the vector \delta is distributed as a N(0,\kappa*I_q)
+%   for a given  \kappa > 0. So that the expectation of \alpha_1 is a and
+%   its variance is P, with
+%
+%       P = \kappa*P_{\infty} + P_{\star}
+%
+%           P_{\infty} = A*A'
+%           P_{\star}  = R_0*Q_0*R_0'
+%
+%   P_{\infty} is a m*m diagonal matrix with q ones and m-q zeros. 
+%
+% 
+%   and where:
+% 
+%   y_t             is a pp*1 vector
+%   \alpha_t        is a mm*1 vector
+%   \varepsilon_t   is a pp*1 multivariate random variable (iid N(0,H_t))
+%   \eta_t          is a rr*1 multivariate random variable (iid N(0,Q_t))
+%   a_1             is a mm*1 vector
+% 
+%   Z_t     is a pp*mm matrix
+%   T_t     is a mm*mm matrix
+%   H_t     is a pp*pp matrix
+%   R_t     is a mm*rr matrix
+%   Q_t     is a rr*rr matrix
+%   P_1     is a mm*mm matrix
+% 
+% 
+%   FILTERING EQUATIONS:
+% 
+%   v_t = y_t - Z_t* a_t
+%   F_t = Z_t * P_t * Z_t' + H_t
+%   K_t = T_t * P_t * Z_t' * F_t^{-1}
+%   L_t = T_t - K_t * Z_t
+%   a_{t+1} = T_t * a_t + K_t * v_t
+%   P_{t+1} = T_t * P_t * L_t' + R_t*Q_t*R_t'
+% 
+%
+%   DIFFUSE FILTERING EQUATIONS:
+%
+%   a_{t+1} = T_t*a_t + K_{\ast,t}v_t
+%   P_{\infty,t+1} = T_t*P_{\infty,t}*T_t'
+%   P_{\ast,t+1}  = T_t*P_{\ast,t}*L_{\ast,t}' + R_t*Q_t*R_t'
+%   K_{\ast,t}   = T_t*P_{\ast,t}*Z_t'*F_{\ast,t}^{-1}
+%   v_t = y_t - Z_t*a_t
+%   L_{\ast,t} = T_t - K_{\ast,t}*Z_t
+%   F_{\ast,t}  = Z_t*P_{\ast,t}*Z_t' + H_t
+global bayestopt_ options_
+  
+mf = bayestopt_.mf;
+pp     = size(Y,1);
+mm     = size(T,1);
+smpl   = size(Y,2);
+a      = zeros(mm,1);
+QQ     = R*Q*transpose(R);
+t      = 0;
+lik    = zeros(smpl+1,1);
+lik(smpl+1) = smpl*pp*log(2*pi); %% the constant of minus two times the log-likelihood 
+notsteady 	= 1;
+crit      	= options_.kalman_tol;
+crit1      	= 1.e-6;
+newRank	  	= rank(Pinf,crit1);
+icc = 0;
+while newRank & t < smpl %% Matrix Finf is assumed to be zero
+  t = t+1;
+  for i=1:pp
+    v(i) 	= Y(i,t)-a(mf(i))-trend(i,t);
+    Fstar 	= Pstar(mf(i),mf(i))+H(i,i);
+    Finf	= Pinf(mf(i),mf(i));
+    Kstar 	= Pstar(:,mf(i));
+    if Finf > crit & newRank
+      icc = icc + 1;
+      Kinf	= Pinf(:,mf(i));
+      a		= a + Kinf*v(i)/Finf;
+      Pstar	= Pstar + Kinf*transpose(Kinf)*Fstar/(Finf*Finf) - ...
+	  (Kstar*transpose(Kinf)+Kinf*transpose(Kstar))/Finf;
+      Pinf	= Pinf - Kinf*transpose(Kinf)/Finf;
+      lik(t) 	= lik(t) + log(Finf);
+      % start new termination criterion for DKF
+      if ~isempty(options_.diffuse_d),  
+	newRank = (icc<options_.diffuse_d);  
+	%if newRank & any(diag(Pinf(mf,mf))>crit)==0; %  M. Ratto this line is BUGGY
+	if newRank & (any(diag(Pinf(mf,mf))>crit)==0 & rank(Pinf,crit1)==0); 
+	  options_.diffuse_d = icc;
+	  newRank=0;
+	  disp('WARNING: Change in OPTIONS_.DIFFUSE_D in univariate DKF')
+	  disp(['new OPTIONS_.DIFFUSE_D = ',int2str(icc)])
+	  disp('You may have to reset the optimisation')
+	end
+      else
+	%newRank = any(diag(Pinf(mf,mf))>crit);     % M. Ratto this line is BUGGY 
+	newRank = (any(diag(Pinf(mf,mf))>crit) | rank(Pinf,crit1));                 
+	if newRank==0, 
+	  P0=	T*Pinf*transpose(T);
+	  %newRank = any(diag(P0(mf,mf))>crit);   % M. Ratto this line is BUGGY
+	  newRank = (any(diag(Pinf(mf,mf))>crit) | rank(P0,crit1));   
+	  if newRank==0, 
+	    options_.diffuse_d = icc;
+	  end
+	end                    
+      end,
+      % end new termination and checks for DKF and fmax
+    elseif Finf > crit 
+      %% Note that : (1) rank(Pinf)=0 implies that Finf = 0, (2) outside this loop (when for some i and t the condition
+      %% rank(Pinf)=0 is satisfied we have P = Pstar and F = Fstar and (3) Finf = 0 does not imply that
+      %% rank(Pinf)=0. [st�phane,11-03-2004].	  
+      %if rank(Pinf) == 0
+      % the likelihood terms should alwasy be cumulated, not only
+      % when Pinf=0, otherwise the lik would depend on the ordering
+      % of observed variables
+      lik(t)	= lik(t) + log(Fstar) + v(i)*v(i)/Fstar;
+      %end
+      a 	= a + Kstar*v(i)/Fstar;
+      Pstar	= Pstar - Kstar*transpose(Kstar)/Fstar;					
+    else
+      % disp(['zero F term in DKF for observed ',int2str(i),' ',num2str(Fi)])
+    end
+  end
+  if newRank
+    oldRank = rank(Pinf,crit1);
+  else
+    oldRank = 0;
+  end
+  a 		= T*a;
+  Pstar 	= T*Pstar*transpose(T)+QQ;
+  Pinf	= T*Pinf*transpose(T);
+  if newRank
+    newRank = rank(Pinf,crit1);
+  end
+  if oldRank ~= newRank
+    disp('DiffuseLiklihoodH3 :: T does influence the rank of Pinf!')	
+  end		 		
+end
+if t == smpl                                                           
+  error(['There isn''t enough information to estimate the initial' ... 
+	 ' conditions of the nonstationary variables']);                   
+end                                                                    
+while notsteady & t < smpl
+  t = t+1;
+  for i=1:pp
+    v(i) = Y(i,t) - a(mf(i)) - trend(i,t);
+    Fi   = Pstar(mf(i),mf(i))+H(i,i);
+    if Fi > crit
+      Ki	= Pstar(:,mf(i));
+      a		= a + Ki*v(i)/Fi;
+      Pstar 	= Pstar - Ki*transpose(Ki)/Fi;
+      lik(t) 	= lik(t) + log(Fi) + v(i)*v(i)/Fi;
+    end
+  end	
+  oldP 		= Pstar;
+  a 		= T*a;
+  Pstar 	= T*Pstar*transpose(T) + QQ;
+  notsteady 	= ~(max(max(abs(Pstar-oldP)))<crit);
+end
+while t < smpl
+  t = t+1;
+  for i=1:pp
+    v(i) = Y(i,t) - a(mf(i)) - trend(i,t);
+    Fi   = Pstar(mf(i),mf(i))+H(i,i);
+    if Fi > crit
+      Ki 		= Pstar(:,mf(i));
+      a 		= a + Ki*v(i)/Fi;
+      Pstar 	= Pstar - Ki*transpose(Ki)/Fi;
+      lik(t) 	= lik(t) + log(Fi) + v(i)*v(i)/Fi;
+    end
+  end	
+  a = T*a;
+end
+LIK = .5*(sum(lik(start:end))-(start-1)*lik(smpl+1)/smpl);
+
diff --git a/tags/v_3.062/matlab/DsgeLikelihood.m b/tags/v_3.062/matlab/DsgeLikelihood.m
new file mode 100644
index 0000000000000000000000000000000000000000..888f6124bb5a974a2559eb1464699666323c301f
--- /dev/null
+++ b/tags/v_3.062/matlab/DsgeLikelihood.m
@@ -0,0 +1,173 @@
+function [fval,cost_flag,ys,trend_coeff,info] = DsgeLikelihood(xparam1,gend,data)
+% stephane.adjemian@cepremap.cnrs.fr [09-07-2004]
+%
+% Adapted from mj_optmumlik.m
+global bayestopt_ exo_nbr dr_ estim_params_ Sigma_e_ options_ xparam1_test
+  global trend_coeff_
+
+  fval = [];
+  cost_flag = [];
+  ys = [];
+  trend_coeff = [];
+
+  xparam1_test = xparam1;
+  cost_flag   = 1;
+  nobs 	= size(options_.varobs,1);
+
+  if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb)
+    k = find(xparam1 < bayestopt_.lb);
+    fval = bayestopt_.penalty+sum((bayestopt_.lb(k)-xparam1(k)).^2);
+    cost_flag = 0;
+    return;
+  end
+  if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub)
+    k = find(xparam1 > bayestopt_.ub);
+    fval = bayestopt_.penalty+sum((xparam1(k)-bayestopt_.ub(k)).^2);
+    cost_flag = 0;
+    return;
+  end
+  Q = Sigma_e_;
+  for i=1:estim_params_.nvx
+    k =estim_params_.var_exo(i,1);
+    Q(k,k) = xparam1(i)*xparam1(i);
+  end
+  offset = estim_params_.nvx;
+  if estim_params_.nvn
+    H = zeros(nobs,nobs);
+    for i=1:estim_params_.nvn
+      k = estim_params_.var_endo(i,1);
+      H(k,k) = xparam1(i+offset)*xparam1(i+offset);
+    end
+    offset = offset+estim_params_.nvn;
+  end	
+  if estim_params_.ncx
+    for i=1:estim_params_.ncx
+      k1 =estim_params_.corrx(i,1);
+      k2 =estim_params_.corrx(i,2);
+      Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2));
+      Q(k2,k1) = Q(k1,k2);
+    end
+    [CholQ,testQ] = chol(Q);
+    if testQ 	%% The variance-covariance matrix of the structural innovations is not definite positive.
+		%% We have to compute the eigenvalues of this matrix in order to build the penalty.
+		a = eig(Q);
+		k = a<0;
+		if k > 0
+		  fval = bayestopt_.penalty+sum(-a(k));
+		  cost_flag = 0;
+		  return
+		end
+    end
+    offset = offset+estim_params_.ncx;
+  end
+  if estim_params_.nvn & estim_params_.ncn 
+    for i=1:estim_params_.ncn
+      k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1));
+      k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2));
+      H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2));
+      H(k2,k1) = H(k1,k2);
+    end
+    [CholH,testH] = chol(H);
+    if testH
+      a = eig(H);
+      k = a<0;
+      if k > 0
+	fval = bayestopt_.penalty+sum(-a(k));
+	cost_flag = 0;
+	return
+      end
+    end
+    offset = offset+estim_params_.ncn;
+  end
+  for i=1:estim_params_.np
+    assignin('base',deblank(estim_params_.param_names(i,:)),xparam1(i+offset));
+  end
+  Sigma_e_ = Q;
+  %------------------------------------------------------------------------------
+  % 2. call model setup & reduction program
+  %------------------------------------------------------------------------------
+  [T,R,SteadyState,info] = dynare_resolve;
+  if info(1) == 1 | info(1) == 2 | info(1) == 5
+    fval = bayestopt_.penalty+1;
+    cost_flag = 0;
+    return
+  elseif info(1) == 3 | info(1) == 4 | info(1) == 20
+    fval = bayestopt_.penalty+info(2)^2;
+    cost_flag = 0;
+    return
+  end
+  if options_.loglinear == 1
+    constant = log(SteadyState(bayestopt_.mfys));
+  else
+    constant = SteadyState(bayestopt_.mfys);
+  end
+  if bayestopt_.with_trend == 1
+    trend_coeff = zeros(nobs,1);
+    for i=1:nobs
+      trend_coeff(i) = evalin('base',bayestopt_.trend_coeff{i});
+    end
+    trend = constant*ones(1,gend)+trend_coeff*(1:gend);
+  else
+    trend = constant*ones(1,gend);
+  end
+  start = options_.presample+1;
+  np    = size(T,1);
+  mf    = bayestopt_.mf;
+  %------------------------------------------------------------------------------
+  % 3. Initial condition of the Kalman filter
+  %------------------------------------------------------------------------------
+  if options_.lik_init == 1		% Kalman filter
+    Pstar = lyapunov_symm(T,R*Q*transpose(R));
+    Pinf	= [];
+  elseif options_.lik_init == 2	% Old Diffuse Kalman filter
+    Pstar = 10*eye(np);
+    Pinf	= [];
+  elseif options_.lik_init == 3	% Diffuse Kalman filter
+    Pstar = zeros(np,np);
+    ivs = bayestopt_.i_T_var_stable;
+    Pstar(ivs,ivs) = lyapunov_symm(T(ivs,ivs),R(ivs,:)*Q* ...
+				   transpose(R(ivs,:)));
+    Pinf  = bayestopt_.Pinf;
+  end
+  %------------------------------------------------------------------------------
+  % 4. Likelihood evaluation
+  %------------------------------------------------------------------------------
+  if estim_params_.nvn
+    if options_.kalman_algo == 1
+      LIK = DiffuseLikelihoodH1(T,R,Q,H,Pinf,Pstar,data,trend,start);
+      if isinf(LIK) & ~estim_params_.ncn %% The univariate approach considered here doesn't 
+					 %%	apply when H has some off-diagonal elements.
+					 LIK = DiffuseLikelihoodH3(T,R,Q,H,Pinf,Pstar,data,trend,start);
+      elseif isinf(LIK) & estim_params_.ncn
+	LIK = DiffuseLikelihoodH3corr(T,R,Q,H,Pinf,Pstar,data,trend,start);
+      end
+    elseif options_.kalman_algo == 3
+      if ~estim_params_.ncn %% The univariate approach considered here doesn't 
+			    %%	apply when H has some off-diagonal elements.
+			    LIK = DiffuseLikelihoodH3(T,R,Q,H,Pinf,Pstar,data,trend,start);
+      else
+	LIK = DiffuseLikelihoodH3corr(T,R,Q,H,Pinf,Pstar,data,trend,start);
+      end	
+    end	  
+  else
+    if options_.kalman_algo == 1
+      LIK = DiffuseLikelihood1(T,R,Q,Pinf,Pstar,data,trend,start);
+      if isinf(LIK)
+	LIK = DiffuseLikelihood3(T,R,Q,Pinf,Pstar,data,trend,start);
+      end
+    elseif options_.kalman_algo == 3
+      LIK = DiffuseLikelihood3(T,R,Q,Pinf,Pstar,data,trend,start);
+    end 	
+  end
+  if imag(LIK) ~= 0
+    likelihood = bayestopt_.penalty;
+  else
+    likelihood = LIK;
+  end
+  % ------------------------------------------------------------------------------
+  % Adds prior if necessary
+  % ------------------------------------------------------------------------------
+  lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p1,bayestopt_.p2,bayestopt_.p3,bayestopt_.p4);
+  fval    = (likelihood-lnprior);
+  
+  
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/DsgeSmoother.m b/tags/v_3.062/matlab/DsgeSmoother.m
new file mode 100644
index 0000000000000000000000000000000000000000..9ff87486268cfb29d96a4216422d1abcc4fa8f36
--- /dev/null
+++ b/tags/v_3.062/matlab/DsgeSmoother.m
@@ -0,0 +1,114 @@
+function [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff] = DsgeSmoother(xparam1,gend,Y)
+% stephane.adjemian@cepremap.cnrs.fr [09-07-2004]
+%
+% Adapted from mj_optmumlik.m
+global bayestopt_ exo_nbr dr_ estim_params_ Sigma_e_ options_ xparam1_test
+global trend_coeff_
+
+alphahat 	= [];
+epsilonhat	= [];
+etahat		= [];
+nobs 		= size(options_.varobs,1);
+smpl        = size(Y,2);
+
+Q = Sigma_e_;
+for i=1:estim_params_.nvx
+	k =estim_params_.var_exo(i,1);
+	Q(k,k) = xparam1(i)*xparam1(i);
+end
+offset = estim_params_.nvx;
+if estim_params_.nvn
+	H = zeros(nobs,nobs);
+	for i=1:estim_params_.nvn
+		k = estim_params_.var_endo(i,1);
+		H(k,k) = xparam1(i+offset)*xparam1(i+offset);
+	end
+end	
+offset = offset+estim_params_.nvn;
+for i=1:estim_params_.ncx
+	k1 =estim_params_.corrx(i,1);
+	k2 =estim_params_.corrx(i,2);
+	Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2));
+	Q(k2,k1) = Q(k1,k2);
+end
+offset = offset+estim_params_.ncx;
+
+if estim_params_.nvn & estim_params_.ncn 
+	for i=1:estim_params_.ncn
+		k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1));
+		k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2));
+		H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2));
+		H(k2,k1) = H(k1,k2);
+	end
+	offset = offset+estim_params_.ncn;
+end	
+for i=1:estim_params_.np
+	assignin('base',deblank(estim_params_.param_names(i,:)),xparam1(i+offset));
+end
+Sigma_e_ = Q;
+%------------------------------------------------------------------------------
+% 2. call model setup & reduction program
+%------------------------------------------------------------------------------
+[T,R,SteadyState] = dynare_resolve;
+if options_.loglinear == 1
+	constant = log(SteadyState(bayestopt_.mfys));
+else
+	constant = SteadyState(bayestopt_.mfys);
+end
+trend_coeff = zeros(nobs,1);
+if bayestopt_.with_trend == 1
+	trend_coeff = zeros(nobs,1);
+	nx1 = estim_params_.nvx+estim_params_.nvn+estim_params_.ncx+estim_params_.ncn;
+	for i=1:nobs
+    	trend_coeff(i) = evalin('base',bayestopt_.trend_coeff{i});
+	end
+	trend = constant*ones(1,gend)+trend_coeff*(1:gend);
+else
+	trend = constant*ones(1,gend);
+end
+start = options_.presample+1;
+np    = size(T,1);
+mf    = bayestopt_.mf;
+% ------------------------------------------------------------------------------
+%  3. Initial condition of the Kalman filter
+% ------------------------------------------------------------------------------
+% 
+%  C'est ici qu'il faut d�terminer Pinf et Pstar. Si le mod�le est stationnaire,
+%  alors il suffit de poser Pstar comme la solution de l'�uation de Lyapounov et
+%  Pinf=[].
+% 
+if options_.lik_init == 1		% Kalman filter
+  Pstar = lyapunov_symm(T,R*Q*transpose(R));
+  Pinf	= [];
+elseif options_.lik_init == 2 % Old Diffuse Kalman filter
+  Pstar = 10*eye(np);
+  Pinf	= [];
+elseif options_.lik_init == 3 % Diffuse Kalman filter
+  Pstar = zeros(np,np);
+  ivs = bayestopt_.i_T_var_stable;
+  Pstar(ivs,ivs) = lyapunov_symm(T(ivs,ivs),R(ivs,:)*Q* ...
+			transpose(R(ivs,:)));
+  Pinf  = bayestopt_.Pinf;
+end
+% -----------------------------------------------------------------------------
+%  4. Kalman smoother
+% -----------------------------------------------------------------------------
+if estim_params_.nvn
+	if options_.kalman_algo == 1
+		[alphahat,epsilonhat,etahat,ahat] = DiffuseKalmanSmootherH1(T,R,Q,H,Pinf,Pstar,Y,trend,nobs,np,smpl,mf);
+		if all(alphahat(:)==0)
+			[alphahat,epsilonhat,etahat,ahat] = DiffuseKalmanSmootherH3(T,R,Q,H,Pinf,Pstar,Y,trend,nobs,np,smpl,mf);
+		end
+	elseif options_.kalman_algo == 3
+		[alphahat,epsilonhat,etahat,ahat] = DiffuseKalmanSmootherH3(T,R,Q,H,Pinf,Pstar,Y,trend,nobs,np,smpl,mf);
+	end	
+else
+	if options_.kalman_algo == 1
+		[alphahat,etahat,ahat] = DiffuseKalmanSmoother1(T,R,Q,Pinf,Pstar,Y,trend,nobs,np,smpl,mf);
+		if all(alphahat(:)==0)
+			[alphahat,etahat,ahat] = DiffuseKalmanSmoother3(T,R,Q,Pinf,Pstar,Y,trend,nobs,np,smpl,mf);
+		end
+	elseif options_.kalman_algo == 3
+		[alphahat,etahat,ahat] = DiffuseKalmanSmoother3(T,R,Q,Pinf,Pstar,Y,trend,nobs,np,smpl,mf);
+	end		
+end
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/DsgeVarLikelihood.m b/tags/v_3.062/matlab/DsgeVarLikelihood.m
new file mode 100644
index 0000000000000000000000000000000000000000..8c34d5741e6ccb900bbb8ec185b3395add8b8a91
--- /dev/null
+++ b/tags/v_3.062/matlab/DsgeVarLikelihood.m
@@ -0,0 +1,234 @@
+function [fval,cost_flag,ys,trend_coeff,info,PHI,SIGMAu,tmp2] = DsgeVarLikelihood(xparam1,gend)
+% stephane.adjemian@ens.fr [06-17-2005]
+
+global bayestopt_ exo_nbr dr_ estim_params_ Sigma_e_ options_ xparam1_test trend_coeff_ 
+global dsge_prior_weight targ_ xparam_ dr_
+
+nvx = estim_params_.nvx;
+nvn = estim_params_.nvn;
+ncx = estim_params_.ncx;
+ncn = estim_params_.ncn;
+np  = estim_params_.np;
+nx = nvx+nvn+ncx+ncn+np;
+ns = nvx+nvn+ncx+ncn;
+
+info = [ ];
+
+mYY = evalin('base', 'mYY');
+mYX = evalin('base', 'mYX');
+mXY = evalin('base', 'mXY');
+mXX = evalin('base', 'mXX');
+
+fval = [];
+cost_flag = [];
+ys = [];
+trend_coeff = [];
+
+xparam_tmp = xparam1;
+
+if strcmpi(targ_,'deep')
+  indx = strmatch('dsge_prior_weight',estim_params_.param_names,'exact');
+  if ~isempty(indx)
+    if indx == 1
+      xparam1 = [xparam_tmp(1:ns);xparam_(ns+1);xparam_tmp(ns+1:end)];
+    elseif indx == np
+      xparam1 = [xparam_tmp(1:end);xparam_(end)];
+    else
+      xparam1 = [xparam_tmp(1:ns+indx-1);xparam_(ns+indx);xparam_tmp(ns+indx:end)];
+    end
+  end
+elseif strcmpi(targ_,'lambda')
+    indx = strmatch('dsge_prior_weight',estim_params_.param_names,'exact');
+    if ~isempty(indx)
+      xparam1 = xparam_;
+      xparam1(indx) = xparam_tmp;
+    end 
+else
+  xparam1 = xparam_tmp;
+end  
+
+xparam1_test = xparam1;
+cost_flag  = 1;
+nobs = size(options_.varobs,1);
+
+if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb)
+  k = find(xparam1 < bayestopt_.lb);
+  fval = bayestopt_.penalty*min(1e3,exp(sum(bayestopt_.lb(k)-xparam1(k))));
+  cost_flag = 0;
+  return;
+end
+
+if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub)
+  k = find(xparam1 > bayestopt_.ub);
+  fval = bayestopt_.penalty*min(1e3,exp(sum(xparam1(k)-bayestopt_.ub(k))));
+  cost_flag = 0;
+  return;
+end
+
+Q = Sigma_e_;
+for i=1:estim_params_.nvx
+  k = estim_params_.var_exo(i,1);
+  Q(k,k) = xparam1(i)*xparam1(i);
+end
+offset = estim_params_.nvx;
+if estim_params_.nvn
+  H = zeros(nobs,nobs);
+  for i=1:estim_params_.nvn
+    k = estim_params_.var_endo(i,1);
+    H(k,k) = xparam1(i+offset)*xparam1(i+offset);
+  end
+  offset = offset+estim_params_.nvn;
+end 
+if estim_params_.ncx
+  for i=1:estim_params_.ncx
+    k1 =estim_params_.corrx(i,1);
+    k2 =estim_params_.corrx(i,2);
+    Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2));
+    Q(k2,k1) = Q(k1,k2);
+  end
+  [CholQ,testQ] = chol(Q);
+  if testQ%% The variance-covariance matrix of the structural innovations is not definite positive.
+	  %% We have to compute the eigenvalues of this matrix in order to build the penalty.
+    a = eig(Q);
+    k = a<0;
+    if k > 0
+      fval = bayestopt_.penalty*min(1e3,exp(sum(-a(k))));
+      cost_flag = 0;
+      return
+    end
+  end
+  offset = offset+estim_params_.ncx;
+end
+if estim_params_.nvn & estim_params_.ncn 
+  for i=1:estim_params_.ncn
+    k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1));
+    k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2));
+    H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2));
+    H(k2,k1) = H(k1,k2);
+  end
+  [CholH,testH] = chol(H);
+  if testH
+    a = eig(H);
+    k = a<0;
+    if k > 0
+      fval = bayestopt_.penalty*min(1e3,exp(sum(-a(k))));
+      cost_flag = 0;
+      return
+    end
+  end
+  offset = offset+estim_params_.ncn;
+end
+for i=1:estim_params_.np
+  assignin('base',deblank(estim_params_.param_names(i,:)),xparam1(i+offset));
+end
+%%% Le probl�me est ici quand on n'optimise pas sur dsge prior weight
+indx = strmatch('dsge_prior_weight',estim_params_.param_names,'exact');
+if ~isempty(indx)
+  dsge_prior_weight = xparam1(ns+indx);
+end
+Sigma_e_ = Q;
+
+%------------------------------------------------------------------------------
+% 2. call model setup & reduction program
+%------------------------------------------------------------------------------
+[T,R,SteadyState,info] = dynare_resolve;
+if info(1) == 1 | info(1) == 2 | info(1) == 5
+  fval = bayestopt_.penalty;
+  cost_flag = 0;
+  return
+elseif info(1) == 3 | info(1) == 4 | info(1) == 20
+  fval = bayestopt_.penalty*min(1e3,exp(info(2)));
+  cost_flag = 0;
+  return
+end
+if options_.loglinear == 1
+  constant = log(SteadyState(bayestopt_.mfys));
+else
+  constant = SteadyState(bayestopt_.mfys);
+end
+if bayestopt_.with_trend == 1
+  trend_coeff = zeros(nobs,1);
+  for i=1:nobs
+    trend_coeff(i) = evalin('base',bayestopt_.trend_coeff{i});
+  end
+  trend = constant*ones(1,gend)+trend_coeff*(1:gend);
+else
+  trend = constant*ones(1,gend);
+end
+
+%------------------------------------------------------------------------------
+% 3. theorretical moments (second order)
+%------------------------------------------------------------------------------
+tmp = lyapunov_symm(T,R*Q*R');
+
+tmpbis = R*Q*R';
+tmpbis = tmpbis(bayestopt_.mf,bayestopt_.mf);
+
+NumberOfObservedVariables = size(options_.varobs,1);
+NumberOfLags = options_.varlag;
+k = NumberOfObservedVariables*NumberOfLags ;
+TheoreticalAutoCovarianceOfTheObservedVariables = zeros(NumberOfObservedVariables,NumberOfObservedVariables,NumberOfLags+1);
+if estim_params_.nvn
+  TheoreticalAutoCovarianceOfTheObservedVariables(:,:,1) = tmp(bayestopt_.mf,bayestopt_.mf)+H;
+else
+  TheoreticalAutoCovarianceOfTheObservedVariables(:,:,1) = tmp(bayestopt_.mf,bayestopt_.mf);
+end    
+for lag = 1:NumberOfLags
+  tmp = T*tmp;
+  if estim_params_.nvn
+    TheoreticalAutoCovarianceOfTheObservedVariables(:,:,lag+1) = tmp(bayestopt_.mf,bayestopt_.mf) + H;
+  else
+    TheoreticalAutoCovarianceOfTheObservedVariables(:,:,lag+1) = tmp(bayestopt_.mf,bayestopt_.mf);
+  end
+end
+GYX = zeros(NumberOfObservedVariables,k);
+for i=1:NumberOfLags
+  GYX(:,(i-1)*NumberOfObservedVariables+1:i*NumberOfObservedVariables) = ...
+      TheoreticalAutoCovarianceOfTheObservedVariables(:,:,i+1);
+end
+GXX = kron(eye(NumberOfLags),TheoreticalAutoCovarianceOfTheObservedVariables(:,:,1));
+for i = 1:NumberOfLags-1
+  tmp1 = diag(ones(NumberOfLags-i,1),i); 
+  tmp2 = diag(ones(NumberOfLags-i,1),-i);
+  GXX = GXX + kron(tmp1,TheoreticalAutoCovarianceOfTheObservedVariables(:,:,i+1));
+  GXX = GXX + kron(tmp2,TheoreticalAutoCovarianceOfTheObservedVariables(:,:,i+1)');
+end
+GYY = TheoreticalAutoCovarianceOfTheObservedVariables(:,:,1);
+
+assignin('base','GYY',GYY);
+assignin('base','GXX',GXX);
+assignin('base','GYX',GYX);
+
+if ~isinf(dsge_prior_weight) 
+  SIGMAu = dsge_prior_weight*gend*TheoreticalAutoCovarianceOfTheObservedVariables(:,:,1) + mYY ;
+  tmp1 = dsge_prior_weight*gend*GYX + mYX;
+  tmp2 = inv(dsge_prior_weight*gend*GXX+mXX);
+  SIGMAu = SIGMAu - tmp1*tmp2*tmp1';
+  SIGMAu = SIGMAu / (gend*(dsge_prior_weight+1));
+  PHI = tmp2*tmp1';
+  prodlng1 = sum(gammaln(.5*((1+dsge_prior_weight)*gend- ...
+			     NumberOfObservedVariables*NumberOfLags ...
+			     +1-(1:NumberOfObservedVariables)')));
+  prodlng2 = sum(gammaln(.5*(dsge_prior_weight*gend- ...
+			     NumberOfObservedVariables*NumberOfLags ...
+			     +1-(1:NumberOfObservedVariables)')));  
+  lik = .5*NumberOfObservedVariables*log(det(dsge_prior_weight*gend*GXX+mXX)) ...
+	+ .5*((dsge_prior_weight+1)*gend-k)*log(det((dsge_prior_weight+1)*gend*SIGMAu)) ...
+	- .5*NumberOfObservedVariables*log(det(dsge_prior_weight*gend*GXX)) ...
+	- .5*(dsge_prior_weight*gend-k)*log(det(dsge_prior_weight*gend*(GYY-GYX*inv(GXX)*GYX'))) ...
+	+ .5*NumberOfObservedVariables*gend*log(2*pi)  ...
+	- .5*log(2)*NumberOfObservedVariables*((dsge_prior_weight+1)*gend-k) ...
+	+ .5*log(2)*NumberOfObservedVariables*(dsge_prior_weight*gend-k) ...
+	- prodlng1 + prodlng2;
+else % cod� par SM (s�rement pas exact... Que font ici les moments empiriques ?).    
+  tmp1 = GYX;
+  tmp2 = inv(GXX);
+  PHI  = tmp2*tmp1';
+  SIGMAu = GYY - tmp1*tmp2*tmp1;
+  % � finir de corriger...
+  lik  = -.5*sum(diag(inv(tmp2)*(mYY-2*tmp1'*mYX'+tmp1'*mXX*tmp1))) ...
+	-(gend/2)*log(det(tmp2));
+end      
+
+lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p1,bayestopt_.p2,bayestopt_.p3,bayestopt_.p4);
+fval = (lik-lnprior);
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/EvalWelfare.m b/tags/v_3.062/matlab/EvalWelfare.m
new file mode 100644
index 0000000000000000000000000000000000000000..d0a4e72f26e8a689b449ff5ec909d4e3098a3aaa
--- /dev/null
+++ b/tags/v_3.062/matlab/EvalWelfare.m
@@ -0,0 +1,105 @@
+function EvalWelfare(vName,pltOpt,NumberOfDraws)
+% stephane.adjemian@ens.fr
+%
+% vName is a string designing the name of the welfare variable in the mod file. 
+%   
+global options_ oo_ lgy_ ys_ fname_ dr_ info
+
+options_.order = 2;
+options_ = set_default_option(options_,'dr_algo',0);
+options_ = set_default_option(options_,'simul_algo',0);
+subindx = subset();
+
+if isempty(NumberOfDraws)
+  B = 500;
+else
+  B = NumberOfDraws; 
+end
+
+% [1] How many mh files and simulations ?
+if options_.mh_nblck == 1
+  files = eval(['dir(''' fname_ '_mh*.mat'');']);
+else% More than one block
+  files = eval(['dir(''' fname_ '_mh*_blck1.mat'');']);
+end
+nn = size(files,1);
+METRO = zeros(nn,3);
+for i = 1:nn
+  file = files(i);
+  eval(['load ' file.name ';'])
+  METRO(i,1) = i-1;
+  METRO(i,2) = size(x2,1);
+  if i>1
+    METRO(i,3) = METRO(i,2)+METRO(i-1,3);
+  else
+    METRO(i,3) = METRO(i,2);
+  end
+end
+TotalNumberOfDraws = METRO(end,3);
+% [2] Take some draws from the metropolis and compute the welfare.
+% [2.1] Set some parameters:
+B = min(B,TotalNumberOfDraws);
+WelfDistribution = zeros(B,1);
+kk = dr_.order_var;
+windx = strmatch(vName,lgy_(kk,:),'exact');
+% [2.2] Get the posterior mean:
+deep = get_posterior_parameters('posterior_mean');
+% [2.3] Compute the posterior distribution of Welfare:
+hfid = waitbar(0,'Posterior welfare distribution...');
+compt = 0;
+ys = ys_;
+for i=1:B
+  linea = 1+floor(rand*TotalNumberOfDraws);
+  tmp = find(METRO(:,3)<linea);
+  if isempty(tmp)
+    FileNumber = 1;
+    linee = linea;
+  else
+    FileNumber = tmp(end)+1;
+    linee = linea-METRO(tmp(end),3);
+  end
+  file = files(FileNumber);
+  eval(['load ' file.name ';'])
+  DEEP = x2(linee,:);
+  deep(subindx) = DEEP(subindx);
+  set_parameters(deep);
+  [dr,info] = resol(ys,0);
+  if ~info(1)
+    ys = dr.ys;
+    WelfDistribution(i) = ys(kk(windx))+.5*dr.ghs2(windx);
+  else
+    WelfDistribution(i) = Inf;
+    compt = compt+1;
+  end
+  waitbar(i/B,hfid);
+end
+close(hfid);
+indx = find(~isinf(WelfDistribution));
+WelfareDistribution = WelfDistribution(indx);
+oo_.Welfare.PosteriorDraws = WelfareDistribution;
+oo_.Welfare.PosteriorMean = mean(WelfareDistribution);
+oo_.Welfare.posteriorStd = std(WelfareDistribution);
+% [3] Non parametric estimation of the posterior density.
+% [3.1] Set some parameters:
+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.
+% [3.2] Compute the optimal bandwidth parameter:
+optimal_bandwidth = mh_optimal_bandwidth(WelfareDistribution,length(indx),bandwidth,kernel_function); 
+% [3.3] Estimation of the posterior density:
+[x1,f1] = kernel_density_estimate(WelfareDistribution,number_of_grid_points,...
+    optimal_bandwidth,kernel_function);
+oo_.Welfare.PosteriorDensity.abscissa = x1;
+oo_.Welfare.PosteriorDensity.density = f1;
+disp(['Percentage of mh-draws violating the B&K conditions: ' num2str(compt/B*100)  '%.'])
+disp(' ')
+% [4] Plot.
+if pltOpt
+  figure('Name','Posterior distribution of the Welfare.')
+  plot(x1,f1,'-k','linewidth',2)
+  axis tight
+  box on
+  xlabel('Welfare')
+  ylabel('Posterior density')
+end
+options_.order = 1;
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/GetPosteriorStatistics.m b/tags/v_3.062/matlab/GetPosteriorStatistics.m
new file mode 100644
index 0000000000000000000000000000000000000000..710d27fa2b0dfc74d189471f0c3ab758e3b9956f
--- /dev/null
+++ b/tags/v_3.062/matlab/GetPosteriorStatistics.m
@@ -0,0 +1,97 @@
+  function [MeanX,MedianX,StdX,DistribX,HPDX] = GetPosteriorStatistics(gend,B,infotype)
+  % stephane.adjemian@gmail.com [05-26-2005]
+  global options_ fname_ lgy_ lgx_ lgy_TeX_ lgx_TeX_ dr_ bayestopt_ oo_
+  
+  deciles = [round(0.1*B) ...
+	     round(0.2*B)...
+	     round(0.3*B)...
+	     round(0.4*B)...
+	     round(0.5*B)...
+	     round(0.6*B)...
+	     round(0.7*B)...
+	     round(0.8*B)...
+	     round(0.9*B)];
+ 
+ tmp = zeros(B,1);
+  
+  if strcmpi(infotype,'SmoothedVariables')
+    PrintOnScreen = 'Smooth variables';
+    NumberOfX = size(lgy_,1);
+    SaveName = 'SmoothedVariables';
+    XNames = lgy_(dr_.order_var,:);
+    NonGenericName = '_smooth';
+    varname = 'smooth';
+  elseif strcmpi(infotype,'SmoothedShocks')
+    PrintOnScreen = 'Smooth structural shocks...';
+    NumberOfX = size(lgx_,1);
+    SaveName = 'SmoothedShocks';
+    XNames = lgx_;
+    NonGenericName = '_innovation';
+    varname = 'innov';
+  elseif strcmpi(infotype,'SmoothedObservationErrors');  
+    PrintOnScreen = 'Smooth measurement error...';
+    NumberOfX = size(options_.varobs,1);
+    SaveName = 'SmoothedMeasurementErrors';
+    XNames = options_.varobs;
+    NonGenericName = '_error';
+    varname = 'error';
+  elseif strcmpi(infotype,'FilteredVariables');  
+    PrintOnScreen = 'Filtered variables...';
+    NumberOfX = size(lgy_,1);
+    SaveName = 'FilteredVariables';
+    XNames = lgy_(dr_.order_var,:);
+    NonGenericName = '_filter';
+    varname = 'filter';
+  end
+  eval(['sfile = size(dir(''' fname_ NonGenericName '*.mat''),1);'])
+  disp(['MH: ' PrintOnScreen '...'])
+  MeanX = zeros(NumberOfX,gend);
+  MedianX = zeros(NumberOfX,gend);
+  StdX = zeros(NumberOfX,gend);
+  DistribX = zeros(NumberOfX,gend,9);
+  HPDX = zeros(NumberOfX,gend,2);
+  for i = 1:NumberOfX
+     for t = 1:gend
+	   StartLine = 0;
+	   for file = 1:sfile;
+	     instr = [fname_ NonGenericName int2str(file)];
+	     eval(['load ' instr]);
+	     eval(['X = stock_' varname ';'])
+	     MeanX(i,t) = MeanX(i,t)+sum(X(i,t,:),3);
+	     DeProfundis = size(X,3);
+	     tmp(StartLine+1:StartLine+DeProfundis) = squeeze(X(i,t,:)); 
+	     StartLine = StartLine+DeProfundis;
+	   end
+	   tmp = sort(tmp);
+	   MedianX(i,t) = tmp(round(B*0.5));
+	   StdX(i,t) = std(tmp);
+	   DistribX(i,t,:) = reshape(tmp(deciles),1,1,9);
+	   tt = floor(options_.mh_conf_sig*B);
+	   a = 1; 
+	   b = tt;
+	   tmp2 = [1;tt;tmp(tt)-tmp(1)];
+	   while b <= B
+	     tmp1 = [a;b;tmp(b)-tmp(a)];
+	     a = a + 1;
+	     b = b + 1;
+	     if tmp1(3,1) < tmp2(3,1)
+	       tmp2 = tmp1;     
+	     end    
+	  end
+	  HPDX(i,t,1) = tmp(tmp2(1,1));
+	  HPDX(i,t,2) = tmp(tmp2(2,1));
+    end
+    disp(['    Variable: ' deblank(XNames(i,:))]);	
+  end
+  clear X;
+  MeanX = MeanX/B;
+  for i=1:NumberOfX
+    eval(['oo_.Posterior' SaveName '.Mean.' deblank(XNames(i,:)) ' = MeanX(i,:)'';']);
+    eval(['oo_.Posterior' SaveName '.Median.' deblank(XNames(i,:)) ' = MedianX(i,:)'';']);
+    eval(['oo_.Posterior' SaveName '.Std.' deblank(XNames(i,:)) ' = StdX(i,:)'';']);
+    eval(['oo_.Posterior' SaveName '.Distribution.' deblank(XNames(i,:)) ' = squeeze(DistribX(i,:,:))'';']);
+    eval(['oo_.Posterior' SaveName '.HPDinf.' deblank(XNames(i,:)) ' = squeeze(HPDX(i,:,1))'';']);
+    eval(['oo_.Posterior' SaveName '.HPDsup.' deblank(XNames(i,:)) ' = squeeze(HPDX(i,:,2))'';']);
+  end
+  disp(['MH: ' PrintOnScreen ', done!'])
+  disp(' ')
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/MakeSmoothVariablesPlots.m b/tags/v_3.062/matlab/MakeSmoothVariablesPlots.m
new file mode 100644
index 0000000000000000000000000000000000000000..878a2ed7fc70ae7ebcc4c6602d7fba475d528a51
--- /dev/null
+++ b/tags/v_3.062/matlab/MakeSmoothVariablesPlots.m
@@ -0,0 +1,292 @@
+ function MakePlots(Type,Distrib,Mean,gend)
+% 
+  global options_ fname_ lgy_ lgx_ lgy_TeX_ lgx_TeX_ dr_ bayestopt_
+  
+  TeX  = options_.TeX;
+  dim  = size(Distrib,3);
+  
+  if strcmpi(Type,'SmoothedVariables')
+    generic = 'SmoothedVariables';
+    figname = 'Smoothed variables';
+    AllNames = lgy_(dr_.order_var,:);
+    if TeX
+      AllTeXNames = lgy_TeX_(dr_.order_var,:);
+    end
+    [nbplt,nr,nc,lr,lc,nstar] = pltorg(size(lgy_,1));
+    numb = size(lgy_,1);
+  elseif strcmpi(Type,'SmoothedShocks')
+    generic = 'SmoothedShocks';
+    figname = 'Smoothed shocks';
+    AllNames = lgx_;
+    if TeX
+      AllTeXNames = lgx_TeX_;
+    end
+    [nbplt,nr,nc,lr,lc,nstar] = pltorg(size(lgx_,1));
+    numb = size(lgx_,1);
+  elseif strcmpi(Type,'SmoothedObservationErrors')
+    generic = 'SmoothedObservationErrors';
+    figname = 'Smoothed observation errors';
+    nvobs = size(options_.varobs,1);
+    numb = 0;
+    index = [];
+    for i=1:nvobs
+      if max(abs(Mean(i,10:end))) > 0.00000001
+	numb = numb + 1;
+	index = cat(1,index,i);
+      end
+    end
+    Distrib = Distrib(index,:,:);
+    Mean = Mean(index,:);
+    [nbplt,nr,nc,lr,lc,nstar] = pltorg(numb);
+    AllNames = options_.varobs(index,:);
+    if TeX
+      AllTeXNames = options_.varobs_TeX(index,:);
+    end
+  elseif strcmpi(Type,'Historical&SmoothedObservableVariables')
+    generic = 'HistoricalAndSmoothedVariables';
+    figname = 'Historical and smoothed observed variables.';
+    numb = size(options_.varobs,1);
+    [nbplt,nr,nc,lr,lc,nstar] = pltorg(numb);
+    AllNames = options_.varobs;
+    if TeX
+      AllTeXNames = options_.varobs_TeX;
+    end
+    Distrib = Distrib(bayestopt_.mf,:);
+  elseif strcmpi(Type,'FilteredVariables')
+    generic = 'FilteredVariables';
+    figname = 'Filtered variables';
+    AllNames = lgy_(dr_.order_var,:);
+    if TeX
+      AllTeXNames = lgy_TeX_(dr_.order_var,:);
+    end
+    [nbplt,nr,nc,lr,lc,nstar] = pltorg(size(lgy_,1));
+    numb = size(lgy_,1);
+  end    
+  
+  if TeX
+    fidTeX = fopen([fname_ '_' generic '.TeX'],'w');
+    fprintf(fidTeX,'%% TeX eps-loader file generated by metropolis.m (Dynare).\n');
+    fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
+    fprintf(fidTeX,' \n');
+  end
+  
+  if nbplt == 1
+    hh = figure('Name',figname);
+    NAMES = [];
+    if TeX, TEXNAMES = [], end
+    for i=1:numb
+      set(0,'CurrentFigure',hh)
+      subplot(nr,nc,i);
+      test = ~(all(all(Distrib(i,:,:)>0)) | all(all(Distrib(i,:,:)<0)));
+      if test & ~strcmpi(Type,'Historical&SmoothedObservableVariables')  
+	plot([1 gend],[0 0],'-r','linewidth',0.5);
+      end
+      hold on
+      for j = 1:min(9,dim)
+	plot(1:gend,Distrib(i,:,j),'-g','linewidth',0.5)
+      end
+      plot(1:gend,Mean(i,:),'-k','linewidth',1)
+      xlim([1 gend]);
+      box on
+      hold off      
+      ih = figure('Visible','off');
+      set(0,'CurrentFigure',ih)
+      if test & ~strcmpi(Type,'Historical&SmoothedObservableVariables') 
+	plot([1 gend],[0 0],'-r','linewidth',0.5);
+      end
+      hold on
+      for j = 1:min(9,dim)
+	plot(1:gend,Distrib(i,:,j),'-g','linewidth',0.5)
+      end
+      plot(1:gend,Mean(i,:),'-k','linewidth',1)
+      xlim([1 gend]);
+      box on
+      hold off
+      name = deblank(AllNames(i,:));
+      NAMES   = strvcat(NAMES,name);
+      if ~isempty(options_.XTick)
+	set(gca,'XTick',options_.XTick)
+	set(gca,'XTickLabel',options_.XTickLabel)
+      end
+      eval(['print -depsc2 ' fname_ '_' generic '_' name]);
+      eval(['print -dpdf ' fname_ '_' generic '_' name]);
+      saveas(ih,[fname_ '_' generic '_' name '.fig']);
+      if TeX
+	texname = deblank(AllTeXNames(i,:));
+	TEXNAMES = strvcat(TEXNAMES,['$' texname '$']);
+      end
+      set(0,'CurrentFigure',hh)
+      title(name,'Interpreter','none')
+      if ~isempty(options_.XTick)
+	set(gca,'XTick',options_.XTick)
+	set(gca,'XTickLabel',options_.XTickLabel)
+      end
+    end
+    eval(['print -depsc2 ' fname_ '_' generic int2str(1)]);
+    eval(['print -dpdf ' fname_ '_' generic int2str(1)]);
+    saveas(hh,[fname_ '_' generic int2str(1) '.fig']);
+    if options_.nograph, close(hh), end
+    if TeX
+      fprintf(fidTeX,'\\begin{figure}[H]\n');
+      for jj = 1:numb
+	fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{%s}\n'],deblank(NAMES(jj,:)),deblank(TEXNAMES(jj,:)));
+      end    
+      fprintf(fidTeX,'\\centering \n');
+      fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_%s%s}\n',fname_,generic,int2str(1));
+      fprintf(fidTeX,'\\caption{%s.}',figname);
+      fprintf(fidTeX,'\\label{Fig:%s:%s}\n',generic,int2str(1));
+      fprintf(fidTeX,'\\end{figure}\n');
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end
+  else
+    for plt = 1:nbplt-1
+      hh = figure('Name',figname);
+      NAMES = [];
+      TEXNAMES = [];
+      for i=1:nstar
+	k = (plt-1)*nstar+i;
+	set(0,'CurrentFigure',hh)
+	subplot(nr,nc,i);
+	test = ~(all(all(Distrib(k,:,:)>0)) | all(all(Distrib(k,:,:)<0))); 
+	if test & ~strcmpi(Type,'Historical&SmoothedObservableVariables')
+	  plot([1 gend],[0 0],'-r','linewidth',0.5);
+	end
+	hold on
+	for j = 1:min(9,dim)
+	  plot(1:gend,Distrib(k,:,j),'-g','linewidth',0.5)
+	end
+	plot(1:gend,Mean(k,:),'-k','linewidth',1)
+	xlim([1 gend]);
+	box on
+	hold off
+	name = deblank(AllNames(k,:));
+	NAMES = strvcat(NAMES,name);
+	ih = figure('Visible','off');
+	set(0,'CurrentFigure',ih)
+	if test & ~strcmpi(Type,'Historical&SmoothedObservableVariables')  
+	  plot([1 gend],[0 0],'-r','linewidth',0.5);
+	end
+	hold on
+	for j = 1:min(9,dim)
+	  plot(1:gend,Distrib(k,:,j),'-g','linewidth',0.5)
+	end
+	plot(1:gend,Mean(k,:),'-k','linewidth',1)
+	xlim([1 gend]);
+	box on
+	hold off
+	if ~isempty(options_.XTick)
+	  set(gca,'XTick',options_.XTick)
+	  set(gca,'XTickLabel',options_.XTickLabel)
+	end
+	eval(['print -depsc2 ' fname_ '_' generic '_' name]);
+	eval(['print -dpdf ' fname_ '_' generic '_' name]);
+	saveas(ih,[fname_ '_' generic '_' name '.fig']);
+	if TeX
+	  texname = deblank(AllTeXNames(k,:));
+	  TEXNAMES = strvcat(TEXNAMES,['$' texname '$']);    
+	end
+	set(0,'CurrentFigure',hh)
+	title(name,'Interpreter','none')
+	if ~isempty(options_.XTick)
+	  set(gca,'XTick',options_.XTick)
+	  set(gca,'XTickLabel',options_.XTickLabel)
+	end
+      end
+      eval(['print -depsc2 ' fname_ '_' generic int2str(plt)]);
+      eval(['print -dpdf ' fname_ '_' generic int2str(plt)]);
+      saveas(hh,[fname_ '_' generic int2str(plt) '.fig']);
+      if options_.nograph, close(hh), end
+      if TeX
+	fprintf(fidTeX,'\\begin{figure}[H]\n');
+	for jj = 1:nstar
+	  fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TEXNAMES(jj,:)));
+	end    
+	fprintf(fidTeX,'\\centering \n');
+	fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_%s%s}\n',fname_,generic,int2str(plt));
+	fprintf(fidTeX,'\\caption{%s.}',figname);
+	fprintf(fidTeX,'\\label{Fig:%s:%s}\n',generic,int2str(plt));
+	fprintf(fidTeX,'\\end{figure}\n');
+	fprintf(fidTeX,' \n');
+      end    
+    end
+    hh = figure('Name',figname);
+    NAMES = [];
+    TEXNAMES = [];
+    for i=1:numb-(nbplt-1)*nstar
+      k = (nbplt-1)*nstar+i;
+      set(0,'CurrentFigure',hh)
+      if lr ~= 0
+	subplot(lr,lc,i);
+      else
+	subplot(nr,nc,i);
+      end
+      test = ~(all(all(Distrib(k,:,:)>0)) | all(all(Distrib(k,:,:)<0)));
+      if test & ~strcmpi(Type,'Historical&SmoothedObservableVariables') 
+	plot([1 gend],[0 0],'-r','linewidth',0.5);
+      end
+      hold on
+      for j = 1:min(9,dim)
+	plot(1:gend,Distrib(k,:,j),'-g','linewidth',0.5)
+      end
+      plot(1:gend,Mean(k,:),'-k','linewidth',1)
+      xlim([1 gend]);
+      box on
+      hold off
+      name = deblank(AllNames(k,:));
+      NAMES    = strvcat(NAMES,name);
+      ih = figure('Visible','off');
+      set(0,'CurrentFigure',ih)
+      if test & ~strcmpi(Type,'Historical&SmoothedObservableVariables')  
+	plot([1 gend],[0 0],'-r','linewidth',0.5);
+      end
+      hold on
+      for j = 1:min(9,dim)
+	plot(1:gend,Distrib(k,:,j),'-g','linewidth',0.5)
+      end
+      plot(1:gend,Mean(k,:),'-k','linewidth',1)
+      xlim([1 gend]);
+      box on
+      hold off
+      if ~isempty(options_.XTick)
+	set(gca,'XTick',options_.XTick)
+	set(gca,'XTickLabel',options_.XTickLabel)
+      end
+      eval(['print -depsc2 ' fname_ '_' generic  '_' name]);
+      eval(['print -dpdf ' fname_ '_' generic '_' name]);
+      saveas(ih,[fname_ '_' generic '_' name '.fig']);
+      if TeX
+	texname  = deblank(AllTeXNames(k,:));
+	TEXNAMES = strvcat(TEXNAMES,['$' texname '$']);
+      end
+      set(0,'CurrentFigure',hh)
+      title(name,'Interpreter','none');
+      if ~isempty(options_.XTick)
+	set(gca,'XTick',options_.XTick)
+	set(gca,'XTickLabel',options_.XTickLabel)
+      end
+    end
+    eval(['print -depsc2 ' fname_ '_' generic int2str(nbplt)]);
+    eval(['print -dpdf ' fname_ '_' generic int2str(nbplt)]);
+    saveas(hh,[fname_ '_' generic int2str(nbplt) '.fig']);
+    if options_.nograph, close(hh), end
+    if TeX
+      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    
+      fprintf(fidTeX,'\\centering \n');
+      fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_%s%s}\n',fname_,generic,int2str(nbplt));
+      fprintf(fidTeX,'\\caption{%s.}',figname);
+      fprintf(fidTeX,'\\label{Fig:%s:%s}\n',generic,int2str(nbplt));
+      fprintf(fidTeX,'\\end{figure}\n');
+      fprintf(fidTeX,'\n');
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end
+  end
+
+
+
+
diff --git a/tags/v_3.062/matlab/VarSampleMoments.m b/tags/v_3.062/matlab/VarSampleMoments.m
new file mode 100644
index 0000000000000000000000000000000000000000..a76761e1024dd24dd4a0eeb39b2c639b686cef6a
--- /dev/null
+++ b/tags/v_3.062/matlab/VarSampleMoments.m
@@ -0,0 +1,57 @@
+function [YtY,XtY,YtX,XtX,Y,X] = VarSampleMoments(FirstObservation,LastObservation,qlag,trend);
+global options_
+
+X = [];
+Y = [];
+YtY = [];
+YtX = [];
+XtY = [];
+XtX = [];
+
+
+if exist(options_.datafile)
+  eval(options_.datafile);
+else
+  eval(['load ' options_.datafile]);
+end
+data = [ ];
+for i=1:size(options_.varobs,1)
+    data = [data eval(deblank(options_.varobs(i,:)))];
+end
+
+if qlag > FirstObservation
+    disp('VarSampleMoments :: not enough data to initialize! Try to increase FirstObservation.')
+    return
+end
+NumberOfObservations = LastObservation-FirstObservation+1;
+NumberOfVariables = size(data,2);
+if trend == -1% No constant
+    X = zeros(NumberOfObservations,NumberOfVariables*qlag);
+elseif trend == 0;% Constant
+    X = zeros(NumberOfObservations,NumberOfVariables*qlag+1);
+    indx = NumberOfVariables*qlag+1;
+elseif trend == 1;% Constant + Trend
+    X = zeros(NumberOfObservations,NumberOfVariables*qlag+2);
+    indx = NumberOfVariables*qlag+1:NumberOfVariables*qlag+2;
+else
+    disp('varols :: trend must be equal to -1,0 or 1!')
+    return
+end
+% I build matrices Y and X  
+Y = data(FirstObservation:LastObservation,:);
+for t=1:NumberOfObservations
+    line = t + FirstObservation-1;
+    for lag = 1:qlag
+        X(t,(lag-1)*NumberOfVariables+1:lag*NumberOfVariables) = data(line-lag,:);
+    end
+    if trend == 0
+        X(t,indx) = 1;
+    elseif trend == 1
+        X(t,indx) = [ 1 , t ];
+    end
+end 
+
+YtY = Y'*Y;
+YtX = Y'*X;
+XtY = X'*Y;
+XtX = X'*X;
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/asamin.dll b/tags/v_3.062/matlab/asamin.dll
new file mode 100755
index 0000000000000000000000000000000000000000..4f0cb237fa1abf2dde685d18f222468d5c3ccbeb
Binary files /dev/null and b/tags/v_3.062/matlab/asamin.dll differ
diff --git a/tags/v_3.062/matlab/asamin.m b/tags/v_3.062/matlab/asamin.m
new file mode 100644
index 0000000000000000000000000000000000000000..813a2749ac63cd0340049aee2fc3d9f8dcb9a161
--- /dev/null
+++ b/tags/v_3.062/matlab/asamin.m
@@ -0,0 +1,160 @@
+%  ASAMIN A gateway function to Adaptive Simulated Annealing (ASA)
+%
+%  ASAMIN is a matlab gateway function to Lester Ingber's Adaptive
+%  Simulated Annealing (ASA)
+%
+%  Copyright (c) 1999-2001  Shinichi Sakata. All Rights Reserved. 
+%
+%  $Id: asamin.m,v 1.1 2004/01/16 10:46:59 michel Exp $
+%
+%  Usage:
+%
+%  asamin ('set')
+%
+%    lists the current value of each option.
+%
+%  asamin ('set', opt_name)
+%
+%    shows the current value of the option given by a character string
+%    opt_name; e.g., 
+%
+%        asamin ('set', 'seed')
+%
+%  asamin ('set', opt_name, opt_value)
+%
+%    set the value opt_value to the option opt_name; e.g.,
+%
+%        asamin ('set', 'seed', 654342)
+%        asamin ('set', 'asa_out_file', 'example.log')
+%
+%  The valid options in these commands are:
+%
+%    rand_seed
+%    test_in_cost_func
+%    use_rejected_cost
+%    asa_out_file
+%    limit_acceptances
+%    limit_generated
+%    limit_invalid
+%    accepted_to_generated_ratio
+%    cost_precision
+%    maximum_cost_repeat
+%    number_cost_samples
+%    temperature_ratio_scale
+%    cost_parameter_scale
+%    temperature_anneal_scale
+%    include_integer_parameters
+%    user_initial_parameters
+%    sequential_parameters
+%    initial_parameter_temperature
+%    acceptance_frequency_modulus
+%    generated_frequency_modulus
+%    reanneal_cost
+%    reanneal_parameters
+%    delta_x
+%
+%    rand_seed is the seed of the random number generation in ASA. 
+%
+%    If test_in_cost_func is set to zero, the cost function should
+%    simply return the value of the objective function. When
+%    test_in_cost_func is set to one, asamin () calls the cost
+%    function with a threshold value as well as the parameter
+%    value. The cost function needs to judge if the value of the cost
+%    function exceeds the threshold as well as compute the value of
+%    the cost function when asamin () requires. (See COST FUNCTION
+%    below for details.)
+%
+%    All other items but use_rejected_cost belong to structure
+%    USER_OPTIONS in ASA. See ASA_README in the ASA package for
+%    details. The default value of use_rejected_cost is zero. If you
+%    set this option to one, ASA uses the current cost value to
+%    compute certain indices, even if the current state is rejected by
+%    the user cost function, provided that the current cost value is
+%    lower than the cost value of the past best state. (See COST
+%    FUNCTION below about the user cost function.)
+%
+%  asamin ('reset')
+%    resets all option values to the hard-coded default values.
+%
+%  [fstar,xstar,grad,hessian,state] = ...
+%     asamin ('minimize', func, xinit, xmin, xmax, xtype,...
+%              parm1, parm2, ...)
+%
+%     minimizes the cost function func (also see COST FUNCTION below).
+%     The argument xinit specifies the initial value of the arguments
+%     of the cost function. Each element of the vectors xmin and xmax
+%     specify the lower and upper bounds of the corresponding
+%     argument.  The vector xtype indicates the types of the
+%     arguments. If xtype(i) is -1 if the i'th argument is real;
+%     xtype(i) is 1 if the i'th argument is integer. If this argument
+%     should be ignored in reannealing, multiply the corresponding
+%     element of xtype by 2 so that the element is 2 or -2. All
+%     parameters following xtype are optional and simply passed to the
+%     cost function each time the cost function is called.
+%
+%     This way of calling asamin returns the following values:
+%
+%     fstar
+%       The value of the objective function at xstar.
+%     xstar
+%       The argument vector at the exit from the ASA routine. If things go
+%       well, xstar should be the minimizer of "func".
+%     grad
+%       The gradient of "func" at xstar.
+%     hessian
+%       The Hessian of "func" at xstar.
+%     state
+%       The vector containing the information on the exit state. 
+%       state(1) is the exit_code, and state(2) is the cost flag. See 
+%       ASA_README for details.
+%
+%
+%     
+%  COST FUNCTION
+%
+%  If test_in_cost_func is set to zero, asamin () calls the "cost
+%  function" (say, cost_func) with one argument, say x (the real cost
+%  function is evaluated at this point). Cost_func is expected to
+%  return the value of the objective function and cost_flag, the
+%  latter of which must be zero if any constraint (if any) is
+%  violated; otherwise one.
+%
+%  When test_in_cost_func is equal to one, asamin () calls the "cost
+%  function" (say, cost_func) with three arguments, say, x (at which
+%  the real cost function is evaluated), critical_cost_value, and
+%  no_test_flag. Asamin expects cost_func to return three scalar
+%  values, say, cost_value, cost_flag, and user_acceptance_flag in the
+%  following manner.
+%   
+%    1. The function cost_func first checks if x satisfies the
+%    constraints of the minimization problem. If any of the
+%    constraints is not satisfied, cost_func sets zero to cost_flag
+%    and return. (user_acceptance_flag and cost_value will not be used
+%    by asamin () in this case.) If all constraints are satisfied, set
+%    one to cost_flag, and proceed to the next step.
+%   
+%    2. If asamin () calls cost_func with no_test_flag==1, cost_func
+%    must compute the value of the cost function, set it to cost_value
+%    and return. When no_test_flag==0, cost_func is expected to judge
+%    if the value of the cost function is greater than
+%    critical_cost_value. If the value of the cost function is found
+%    greater than critical_cost_value, cost_func must set zero to
+%    user_acceptance_flag and return. (asamin () will not use
+%    cost_value in this case.) On the other hand, if the value of the
+%    cost function is found no greater than critical_cost_value,
+%    cost_func must compute the cost function at x, set it to
+%    cost_value, and set one to user_acceptance_flag.
+%   
+%  Remark: To understand the usefulness of test_in_cost_func == 1,
+%  note that it is sometimes easier to check if the value of the cost
+%  function is greater than critical_cost_value than compute the value
+%  of the cost function. For example, suppose that the cost function g
+%  is implicitly defined by an equation f(g(x),x)=0, where f is
+%  strictly increasing in the first argument, and evaluation of g(x)
+%  is computationally expensive (e.g., requiring an iterative method
+%  to find a solution to f(y,x)=0). But we can easily show that
+%  f(critical_cost_value,x) < 0 if and only if g(x) >
+%  critical_cost_value. We can judge if g(x) > critical_cost_value by
+%  computing f(critical_cost_value,x). The value of g(x) is not
+%  necessary.
+%
diff --git a/tags/v_3.062/matlab/beta_rnd.m b/tags/v_3.062/matlab/beta_rnd.m
new file mode 100644
index 0000000000000000000000000000000000000000..18462d1821d5a7a0efe322c597ea1a01472952e1
--- /dev/null
+++ b/tags/v_3.062/matlab/beta_rnd.m
@@ -0,0 +1,34 @@
+function rnd = beta_rnd (n, a, b)
+% PURPOSE: random draws from the beta(a,b) distribution
+%--------------------------------------------------------------
+% USAGE: rnd = beta_rnd(n,a,b)
+% where:   n = size of the vector of draws
+%          a = beta distribution parameter, a = scalar 
+%          b = beta distribution parameter  b = scalar 
+% NOTE: mean = a/(a+b), variance = ab/((a+b)*(a+b)*(a+b+1))
+%--------------------------------------------------------------
+% RETURNS: n-vector of random draws from the beta(a,b) distribution
+%--------------------------------------------------------------
+% SEE ALSO: beta_d, beta_pdf, beta_inv, beta_rnd
+%--------------------------------------------------------------
+
+% written by:
+% James P. LeSage, Dept of Economics
+% University of Toledo
+% 2801 W. Bancroft St,
+% Toledo, OH 43606
+% jlesage@spatial-econometrics.com
+
+   
+  if (nargin ~= 3)
+  error('Wrong # of arguments to beta_rnd');
+  end;
+  
+if any(any((a<=0)|(b<=0)))
+   error('Parameter a or b is nonpositive')
+end
+
+a1n = gamm_rnd(n,a,1);
+a1d = gamm_rnd(n,b,1);
+rnd = a1n./(a1n+a1d);
+
diff --git a/tags/v_3.062/matlab/bfgsi.m b/tags/v_3.062/matlab/bfgsi.m
new file mode 100644
index 0000000000000000000000000000000000000000..be2ef0e4f6833d2814ba8ef3a657d593e0778e7d
--- /dev/null
+++ b/tags/v_3.062/matlab/bfgsi.m
@@ -0,0 +1,25 @@
+function H = bfgsi(H0,dg,dx)
+% H = bfgsi(H0,dg,dx)
+% dg is previous change in gradient; dx is previous change in x;
+% 6/8/93 version that updates inverse hessian instead of hessian
+% itself.
+% Copyright by Christopher Sims 1996.  This material may be freely
+% reproduced and modified.
+if size(dg,2)>1
+   dg=dg';
+end
+if size(dx,2)>1
+   dx=dx';
+end
+Hdg = H0*dg;
+dgdx = dg'*dx;
+if (abs(dgdx) >1e-12)
+   H = H0 + (1+(dg'*Hdg)/dgdx)*(dx*dx')/dgdx - (dx*Hdg'+Hdg*dx')/dgdx;
+else
+   disp('bfgs update failed.')
+   disp(['|dg| = ' num2str(sqrt(dg'*dg)) '|dx| = ' num2str(sqrt(dx'*dx))]);
+   disp(['dg''*dx = ' num2str(dgdx)])
+   disp(['|H*dg| = ' num2str(Hdg'*Hdg)])
+   H=H0;
+end
+save H.dat H
diff --git a/tags/v_3.062/matlab/bicgstab.m b/tags/v_3.062/matlab/bicgstab.m
new file mode 100644
index 0000000000000000000000000000000000000000..9b1b4bd40ec03a1a4b889128dafba8be94b0916b
--- /dev/null
+++ b/tags/v_3.062/matlab/bicgstab.m
@@ -0,0 +1,32 @@
+function [x,status]=bicgstab(func,b,x,tole,kmax,varargin)
+  status = 0;
+  r=b-feval(func,x,varargin{:});
+  rh_0 = r;
+  rh = r;
+  rho_0 = 1;
+  alpha = 1;
+  w = 1;
+  v = 0;
+  p = 0;
+  k = 0;
+  rho_1 = rh_0'*r;
+  tolr = tole*norm(b);
+  
+  while norm(r) > tolr & k < kmax
+    k = k+1;
+    beta = (rho_1/rho_0)*(alpha/w);
+    p = r+beta*(p-w*v);
+    v = feval(func,p,varargin{:});
+    alpha = rho_1/(rh_0'*v);
+    r = r-alpha*v;
+    t = feval(func,r,varargin{:});
+    w = (t'*r)/(t'*t);
+    rho_0 = rho_1;
+    rho_1 = -w*(rh_0'*t);
+    x = x+alpha*p+w*r;
+    r = r-w*t;
+  end
+if k == kmax
+  status = 1;
+  warning(sprintf('BICSTABN didn''t converge after %d iterations: norm(r) = %g',kmax,norm(r)));
+end
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/bksup.m b/tags/v_3.062/matlab/bksup.m
new file mode 100644
index 0000000000000000000000000000000000000000..c46e0e0bf590cc26e1a7be0acc18f3fd7cc31d29
--- /dev/null
+++ b/tags/v_3.062/matlab/bksup.m
@@ -0,0 +1,49 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function d1 = bksupk(ny,fid,jcf,icc1)
+
+global ykmax_ iter_ c ncc
+
+icf = [1:jcf-1] ;
+ir = [(iter_-1)*ny+1:ny*iter_] ;
+irf = icc1+(iter_-1)*ny ;
+d1 = zeros(iter_*ny,1) ;
+
+ofs = (((iter_-1)*ny+1)-1)*ncc*8 ;
+junk = fseek(fid,ofs,-1) ;
+c = fread(fid,[ncc,ny],'float64') ;
+c = c' ;
+
+d1(ir) = c(:,jcf) ;
+ir = ir-ny ;
+
+i = 2 ;
+
+while i <= ykmax_ | i <= iter_
+	irf1 = selif(irf,irf<iter_*ny) ;
+
+	ofs = (((iter_-i)*ny+1)-1)*ncc*8 ;
+	junk = fseek(fid,ofs,-1) ;
+	c = fread(fid,[ncc,ny],'float64') ;
+	c = c' ;
+
+	d1(ir) = c(:,jcf) - c(:,1:size(irf1,1))*d1(irf1) ;
+	ir = ir - ny ;
+	irf = irf - ny ;
+	i = i + 1 ;
+end
+
+while i <= iter_
+
+	ofs = (((iter_-i)*ny+1)-1)*ncc*8 ;
+	junk = fseek(fid,ofs,-1) ;
+	c = fread(fid,[ncc,ny],'float64') ;
+	c = c' ;
+
+	d1(ir) = c(:,jcf)-c(:,icf)*d1(irf) ;
+	ir = ir-ny ;			
+	irf = irf-ny ;
+	i = i+1;
+end
+
+return ;
diff --git a/tags/v_3.062/matlab/bksup1.m b/tags/v_3.062/matlab/bksup1.m
new file mode 100644
index 0000000000000000000000000000000000000000..72baca569c00da3a3093ff7440f15f20adca8a51
--- /dev/null
+++ b/tags/v_3.062/matlab/bksup1.m
@@ -0,0 +1,17 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function d = bksup1(ny,jcf,iyf,c)
+
+global iter_
+
+ir = [(iter_-2)*ny+1:ny+(iter_-2)*ny] ;
+irf = iyf+(iter_-1)*ny ;
+icf = [1:size(iyf,2)] ;
+d = c(:,jcf) ;
+
+for i = 2:iter_
+	d(ir) = c(ir,jcf)-c(ir,icf)*d(irf) ;
+	ir = ir-ny ;
+	irf = irf-ny ;
+end
+
diff --git a/tags/v_3.062/matlab/bksupk.m b/tags/v_3.062/matlab/bksupk.m
new file mode 100644
index 0000000000000000000000000000000000000000..773861f62e8a2e71eb6bda82e5e86b470d4a52c5
--- /dev/null
+++ b/tags/v_3.062/matlab/bksupk.m
@@ -0,0 +1,43 @@
+function d1 = bksupk(ny,fid,jcf,icc1)
+
+global ykmax_ iter_
+
+icf = [1:jcf-1] ;
+ir = [(iter_-1)*ny+1:ny*iter_] ;
+irf = icc1+(iter_-1)*ny ;
+d1 = zeros(iter_*ny,1) ;
+
+ofs = (((iter_-1)*ny+1)-1)*jcf*8 ;
+junk = fseek(fid,ofs,-1) ;
+c = fread(fid,[jcf,ny],'float64')' ;
+
+d1(ir) = c(:,jcf) ;
+ir = ir-ny ;
+
+i = 2 ;
+
+while i <= ykmax_ | i <= iter_
+	irf1 = selif(irf,irf<=iter_*ny) ;
+
+	ofs = (((iter_-i)*ny+1)-1)*jcf*8 ;
+	junk = fseek(fid,ofs,-1) ;
+	c = fread(fid,[jcf,ny],'float64')' ;
+
+	d1(ir) = c(:,jcf) - c(:,1:size(irf1,1))*d1(irf1) ;
+	ir = ir - ny ;
+	irf = irf - ny ;
+	i = i + 1 ;
+end
+
+while i <= iter_
+
+	ofs = (((iter_-i)*ny+1)-1)*jcf*8 ;
+	junk = fseek(fid,ofs,-1) ;
+	c = fread(fid,[jcf,ny],'float64')' ;
+
+	d1(ir) = c(:,jcf)-c(:,icf)*d1(irf) ;
+	ir = ir-ny ;			
+	irf = irf-ny ;
+	i = i+1;
+end
+
diff --git a/tags/v_3.062/matlab/brm.m b/tags/v_3.062/matlab/brm.m
new file mode 100644
index 0000000000000000000000000000000000000000..a36ace354b0385aa0d669cc4c91376068f2296d1
--- /dev/null
+++ b/tags/v_3.062/matlab/brm.m
@@ -0,0 +1,30 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function [e_1, e_2, e_inf]=brm(v,nbr,drop)
+  global y_ iy_ iter_ ykmin_ ykmax_ it_ endo_nbr ex_ fname_
+  
+  i=(iy_ > 0)' ;
+  iyr0 = find(i(:)) ;
+
+  ex_old = ex_;
+  ex_ = ex_(drop+1:end,:);
+  y = y_(:,drop+1:end);
+  y = y(:);
+  
+  iter = iter_ - drop - ykmin_ - ykmax_;
+
+  z = zeros(endo_nbr,iter);
+  fh = str2func([fname_ '_ff']);
+  for it_ = ykmin_+1 : iter+ykmin_
+    z(:,it_) = feval(fh,y(iyr0));
+    iyr0 = iyr0 + endo_nbr;
+  end
+  
+    t1 = z(nbr,:)';
+    t2 = v(drop+1:end-2);
+    t = t1./t2;
+  e_1 = log10(mean(abs(t)));
+  e_2 = log10(var(t));
+  e_inf = log10(max(abs(t)));
+
+  ex_ = ex_old;
diff --git a/tags/v_3.062/matlab/bseastr.m b/tags/v_3.062/matlab/bseastr.m
new file mode 100644
index 0000000000000000000000000000000000000000..5b30f61bc007aeb42f56476bcb24387a8278cc23
--- /dev/null
+++ b/tags/v_3.062/matlab/bseastr.m
@@ -0,0 +1,33 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function x = bseastr(s1,s2)
+
+m = size(s1,1) ;
+x = zeros(m,1) ;
+s1=upper(deblank(s1));
+s2=upper(deblank(s2));
+
+for im = 1:m
+	key = s1(im,:) ;
+	h = size(s2,1) ;
+	l = 1 ;
+	while l <= h
+		mid = round((h+l)/2) ;
+		temp = s2(mid,:) ;
+		if ~ strcmp(key,temp)
+ 			for i = 1:min(length(key),length(temp))
+				if temp(i) > key(i)
+					h = mid - 1 ;
+					break 
+				else
+					l = mid + 1 ;
+					break 
+				end
+			end
+		else
+			x(im) = mid ;
+			break 
+		end
+	end
+end
+
diff --git a/tags/v_3.062/matlab/calib.m b/tags/v_3.062/matlab/calib.m
new file mode 100644
index 0000000000000000000000000000000000000000..aee57e1f70172541e4cd13b55f7795057fac1243
--- /dev/null
+++ b/tags/v_3.062/matlab/calib.m
@@ -0,0 +1,183 @@
+function [Sigma_e_,info] = calib(var_indices,targets,var_weights,nar,cova,Sigma_e_)
+  global ys_ endo_nbr exo_nbr lgy_ lgx_ ykmin_ vx options_
+  
+  ncstr = 0;
+  ni = size(var_indices,1);
+  for i=1:nar+3
+    ncstr = ncstr + size(var_indices{i},1);
+  end
+  if cova
+    if ncstr < exo_nbr*(exo_nbr+1)/2
+      error(['number of preset variances is smaller than number of shock' ...
+	     ' variances and covariances to be estimated !'])
+    end
+  else
+    if ncstr < exo_nbr
+      error(['number of preset variances is smaller than number of shock' ...
+	     ' variances to be estimated !'])
+    end
+  end
+  
+  check_model;
+  
+  % computes approximate solution at order 1
+  [dr_, info] = resol(ys_,0);
+
+  if info(1)
+    print_info(info);
+  end  
+
+  ghx = dr.ghx;
+  ghu = dr.ghu;
+  npred = dr.npred;
+  nstatic = dr.nstatic;
+  kstate = dr.kstate;
+  order = dr.order_var;
+  iv(order) = [1:endo_nbr];
+  iv = iv';
+  nx = size(ghx,2);
+
+  ikx = [nstatic+1:nstatic+npred];
+  
+  A = zeros(nx,nx);
+  A(1:npred,:)=ghx(ikx,:);
+  offset_r = npred;
+  offset_c = 0;
+  i0 = find(kstate(:,2) == ykmin_+1);
+  n0 = size(i0,1);
+  for i=ykmin_:-1:2
+    i1 = find(kstate(:,2) == i);
+    n1 = size(i1,1);
+    j = zeros(n1,1);
+    for j1 = 1:n1
+      j(j1) = find(kstate(i0,1)==kstate(i1(j1),1));
+    end
+    A(offset_r+1:offset_r+n1,offset_c+j)=eye(n1);
+    offset_r = offset_r + n1;
+    offset_c = offset_c + n0;
+    i0 = i1;
+    n0 = n1;
+  end
+  ghu1 = [ghu(ikx,:);zeros(nx-npred,exo_nbr)];
+%  IA = speye(nx*nx)-kron(A,A);
+%  kron_ghu = kron(ghu1,ghu1);
+  
+  % vx1 such that vec(sigma_x) = vx1 * vec(Sigma_e_) (predetermined vars) 
+vx1 = [];
+  % vx1 = IA\kron_ghu;
+  IA = [];
+  kron_ghu = [];
+  
+  % computes required variables and indices among required variables
+  iiy = [];
+  for i=1:nar+3
+    if i ~= 3 & ~isempty(var_indices{i})
+      iiy = union(iiy, iv(var_indices{i}(:,1)));
+    end
+  end
+  if ~isempty(var_indices{2})
+    iiy = union(iiy, iv(var_indices{2}(:,2)));
+  end
+  ny = size(iiy,1);
+
+  for i=1:nar+3
+    if i ~= 3 & ~isempty(var_indices{i})
+      var_indices{i}(:,1) = indnv(iv(var_indices{i}(:,1)),iiy);
+    end
+    if i ~= 2 & i ~= 3 & ~isempty(var_indices{i})
+      var_indices{i} = sub2ind([ny ny],var_indices{i},var_indices{i});
+    end
+  end
+  if ~isempty(var_indices{2})
+    var_indices{2}(:,2) = indnv(iv(var_indices{2}(:,2)),iiy);
+    var_indices{2} = sub2ind([ny ny],var_indices{2}(:,1),var_indices{2}(:,2));
+  end
+  if ~isempty(var_indices{3})
+    var_indices{3} = sub2ind([exo_nbr exo_nbr],var_indices{3}(:,1),var_indices{3}(:,2));
+  end
+  if isempty(Sigma_e_)
+    Sigma_e_ = 0.01*eye(exo_nbr);
+    b = 0.1*ghu1*ghu1';
+  else
+    b = ghu1*Sigma_e_*ghu1';
+    Sigma_e_ = chol(Sigma_e_+1e-14*eye(exo_nbr));
+  end
+  options=optimset('LargeScale','on','MaxFunEvals',20000*ny,'TolX',1e-4, ...
+		   'TolFun',1e-4,'Display','Iter','MaxIter',10000);
+%  [Sigma_e_,f]=fminunc(@calib_obj,Sigma_e_,options,A,ghu1,ghx(iiy,:),ghu(iiy,:),targets,var_weights,var_indices,nar);
+  [Sigma_e_,f]=fmincon(@calib_obj,diag(Sigma_e_).^2,-eye(exo_nbr),zeros(exo_nbr,1),[],[],[],[],[],options,A,ghu1,ghx(iiy,:),ghu(iiy,:),targets,var_weights,var_indices,nar);
+  Sigma_e_ = diag(Sigma_e_);
+  
+  objective = calib_obj2(diag(Sigma_e_),A,ghu1,ghx(iiy,:),ghu(iiy,:), ...
+			 targets,var_weights,var_indices,nar);
+  if ~options_.noprint
+    disp('CALIBRATION')
+    disp('')
+    if ~isempty(var_indices{1})
+      disp(sprintf('%16s %14s %14s %14s %14s','Std. Dev','Target','Obtained','Diff'));
+      str = '   ';
+      for i=1:size(var_indices{1},1)
+	[i1,i2] = ind2sub([ny ny],var_indices{1}(i));
+	str = sprintf('%16s: %14.2f %14.2f %14.2f',lgy_(order(iiy(i1)),:),targets{1}(i),objective{1}(i),objective{1}(i)-targets{1}(i));
+	disp(str);
+      end
+    end
+    if ~isempty(var_indices{2})
+      disp(sprintf('%32s %14s %14s','Correlations','Target','Obtained','Diff'));
+      str = '   ';
+      for i=1:size(var_indices{2},1)
+	[i1,i2]=ind2sub([ny ny],var_indices{2}(i));
+	str = sprintf('%16s,%16s: %14.2f %14.2f %14.2f',lgy_(order(iiy(i1)),:), ...
+		      lgy_(order(iiy(i2)),:),targets{2}(i),objective{2}(i),objective{2}(i)-targets{2}(i));
+	disp(str);
+      end
+    end
+    if ~isempty(var_indices{3})
+      disp(sprintf('%32s %16s %16s','Constrained shocks (co)variances','Target','Obtained'));
+      str = '   ';
+      for i=1:size(var_indices{3},1)
+	[i1,i2]=ind2sub([exo_nbr exo_nbr],var_indices{3}(i));
+	if i1 == i2
+	  str = sprintf('%32s: %16.4f %16.4f',lgx_(order(i1),:), ...
+			targets{3}(i),objective{3}(i));
+	else
+	  str = sprintf('%16s,%16s: %16.4f %16.4f',lgx_(order(i1),:), ...
+			lgx_(order(i2), :),targets{3}(i),objective{3}(i));
+	end
+	disp(str);
+      end
+    end
+    flag = 1;
+    for j=4:nar+3
+      if ~isempty(var_indices{j})
+	if flag
+	  disp(sprintf('%16s %16s %16s','Autocorrelations','Target','Obtained'));
+	  str = '   ';
+	  flag = 0;
+	end
+	for i=1:size(var_indices{j},1)
+	  [i1,i2] = ind2sub([ny ny],var_indices{j}(i));
+	  str = sprintf('%16s(%d): %16.4f %16.4f',lgy_(order(iiy(i1)),:), ...
+			j-3,targets{j}(i),objective{j}(i));
+	  disp(str);
+	end
+      end
+    end    
+    
+    disp('');
+    disp('Calibrated variances')
+    str = '   ';
+    for i=1:exo_nbr
+      str = [str sprintf('%16s',lgx_(i,:))];
+    end
+    disp(str);
+    disp('');
+    str = '      ';
+    for i=1:exo_nbr
+      str = [str sprintf('%16f',Sigma_e_(i,i))];
+    end
+    disp(str);
+  end % end if options_.noprint
+
+  
+  % 10/9/02 MJ
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/calib_obj.m b/tags/v_3.062/matlab/calib_obj.m
new file mode 100644
index 0000000000000000000000000000000000000000..9495c0987c1844bac7187e5797ae74e71390714c
--- /dev/null
+++ b/tags/v_3.062/matlab/calib_obj.m
@@ -0,0 +1,67 @@
+% targets and iy order: 1) variances 2) correlations 
+% 3) constraints on Sigma_e_ itself 4) autocorrelations
+function f=calib_obj(Sigma_e_,A,ghu1,ghx,ghu,targets,var_weights,iy,nar)
+  global vx fold
+  
+  Gamma_y = cell(nar+1,1);
+%  Sigma_e_ = Sigma_e_'*Sigma_e_;
+  Sigma_e_=diag(Sigma_e_);
+  nx = size(ghx,2);
+  b=ghu1*Sigma_e_*ghu1';
+  vx = [];
+  if isempty(vx)
+    vx = lyapunov_symm(A,b);
+  else
+    [vx,status] = bicgstab(@f_var,b(:),vx(:),1e-8,50,A,nx);
+    if status
+      vx = lyapunov_symm(A,b);
+    else
+      vx=reshape(vx,nx,nx);
+    end
+  end
+  Gamma_y{1} = ghx*vx*ghx'+ ghu*Sigma_e_*ghu';
+  f = 0;
+  if ~isempty(targets{1})
+    e = targets{1}-sqrt(Gamma_y{1}(iy{1}));
+    f = e'*(var_weights{1}.*e);
+  end
+
+  sy = sqrt(diag(Gamma_y{1}));
+  sy = sy *sy';
+  if ~isempty(targets{2})
+    e = targets{2}-Gamma_y{1}(iy{2})./(sy(iy{2})+1e-10);
+    f = f+e'*(var_weights{2}.*e);
+  end
+  
+  if ~isempty(targets{3})
+    e = targets{3}-sqrt(Sigma_e_(iy{3}));
+    f = f+e'*(var_weights{3}.*e);
+  end
+  
+  % autocorrelations
+  if nar > 0
+    vxy = (A*vx*ghx'+ghu1*Sigma_e_*ghu');
+    
+    Gamma_y{2} = ghx*vxy./(sy+1e-10);
+    if ~isempty(targets{4})
+      e = targets{4}-Gamma_y{2}(iy{4});
+      f = f+e'*(var_weights{4}.*e);
+    end
+    
+    for i=2:nar
+      vxy = A*vxy;
+      Gamma_y{i+1} = ghx*vxy./(sy+1e-10);
+      if ~isempty(targets{i+3})
+	e = targets{i+3}-Gamma_y{i+1}(iy{i+3});
+	f = f+e'*(var_weights{i+3}.*e);
+      end
+    end
+  end
+  if isempty(fold) | f < 2*fold
+    fold = f;
+    vxold = vx;
+  end
+  % 11/04/02 MJ generalized for correlations, autocorrelations and
+  %             constraints on Sigma_e_
+  % 01/25/03 MJ targets std. dev. instead of variances
+  
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/calib_obj2.m b/tags/v_3.062/matlab/calib_obj2.m
new file mode 100644
index 0000000000000000000000000000000000000000..82c4bee57b36384c06cda905d786554886a72954
--- /dev/null
+++ b/tags/v_3.062/matlab/calib_obj2.m
@@ -0,0 +1,46 @@
+% targets and iy order: 1) variances 2) correlations 
+% 3) constraints on Sigma_e_ itself 4) autocorrelations
+function objective=calib_obj2(Sigma_e_,A,ghu1,ghx,ghu,targets,var_weights,iy,nar)
+  global vx fold
+  
+  objective = cell (nar+3);
+  Gamma_y = cell(nar+1,1);
+  Sigma_e_=diag(Sigma_e_);
+  nx = size(ghx,2);
+  b=ghu1*Sigma_e_*ghu1';
+  vx = lyapunov_symm(A,b);
+  Gamma_y{1} = ghx*vx*ghx'+ ghu*Sigma_e_*ghu';
+  if ~isempty(targets{1})
+    objective{1} = sqrt(Gamma_y{1}(iy{1}));
+  end
+
+  sy = sqrt(diag(Gamma_y{1}));
+  sy = sy *sy';
+  if ~isempty(targets{2})
+    objective{2} = Gamma_y{1}(iy{2})./(sy(iy{2})+1e-10);
+  end
+  
+  if ~isempty(targets{3})
+    objective{3} = Sigma_e_(iy{3});
+  end
+  
+  % autocorrelations
+  if nar > 0
+    vxy = (A*vx*ghx'+ghu1*Sigma_e_*ghu');
+    
+    Gamma_y{2} = ghx*vxy./(sy+1e-10);
+    if ~isempty(targets{4})
+      objective{4} = Gamma_y{2}(iy{4});
+    end
+    
+    for i=2:nar
+      vxy = A*vxy;
+      Gamma_y{i+1} = ghx*vxy./(sy+1e-10);
+      if ~isempty(targets{i+3})
+	objecitve{i+3} = Gamma_y{i+1}(iy{i+3});
+      end
+    end
+  end
+
+  % 11/04/02 MJ generalized for correlations, autocorrelations and
+  %             constraints on Sigma_e_
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/check.m b/tags/v_3.062/matlab/check.m
new file mode 100644
index 0000000000000000000000000000000000000000..3072f2eea850367de45e70bdfc20e01dde366a72
--- /dev/null
+++ b/tags/v_3.062/matlab/check.m
@@ -0,0 +1,69 @@
+% Copyright (C) 2001 Michel Juillard
+%
+
+function result = check
+  global fname_ ys_ eigenvalues_ lambda_ dynatol_ it_ ykmin_ valf_ ex_ ...
+      exe_ xkmin_ xkmax_ options_
+  
+  temp_options = options_;
+  tempex = ex_;
+  if ~valf_
+    ex_ = ones(xkmax_+xkmin_+1,1)*exe_';
+  end
+  
+  options_ = set_default_option(options_,'noprint',0);
+  options_ = set_default_option(options_,'order',1);  
+  options_ = set_default_option(options_,'dr_algo',0);  
+
+  [dr, info] = resol(ys_,1);
+  
+  if info(1) ~= 0 & info(1) ~= 3 & info(1) ~= 4
+    print_info(info);
+  end  
+
+  ex_ = tempex;
+  
+  eigenvalues_ = dr.eigval;
+  nyf = nnz(dr.kstate(:,2)>ykmin_+1);
+  [m_lambda,i]=sort(abs(eigenvalues_));
+  
+  if options_.noprint == 0
+    disp(' ')
+    disp('EIGENVALUES:')
+    disp(sprintf('%16s %16s %16s\n','Modulus','Real','Imaginary'))
+    z=[m_lambda real(eigenvalues_(i)) imag(eigenvalues_(i))]';
+    disp(sprintf('%16.4g %16.4g %16.4g\n',z))
+    options_ = set_default_option(options_,'qz_criterium',1.000001);
+    disp(sprintf('\nThere are %d eigenvalue(s) larger than 1 in modulus ', ...
+		 nnz(abs(eigenvalues_) > options_.qz_criterium)));
+    disp(sprintf('for %d forward-looking variable(s)',nyf));
+    disp(' ')
+    if info(1) == 0
+      if dr.rank == nyf
+	disp('The rank condition is verified.')
+      else
+	disp('The rank conditions ISN''T verified!')
+      end
+      disp(' ')
+    end
+  end
+  
+  % keep lambda_ for backward compatibility
+  lambda_ = eigenvalues_;
+
+  options_ = temp_options;
+  
+  % 2/9/99 MJ: line 15, added test for absence of exogenous variable.
+  % 8/27/2000 MJ: change JACOB call. Added ...,1 to cumsum()
+  % 6/24/01 MJ: added count of abs(eigenvalues) > 1
+  % 2/21/02 MJ: count eigenvalues > 1[+1e-5]
+  % 01/22/03 MJ: warning(warning_state) needs parentheses for Matlab 6.5
+  % 03/20/03 MJ: changed name of global from lambda to lambda_ to avoid
+  %              name conflicts with parameters
+  % 05/21/03 MJ: replace computation by dr1.m and add rank check
+  % 06/05/03 MJ: corrected bug when xkmin_ > 0
+  
+
+
+
+
diff --git a/tags/v_3.062/matlab/check_mh.m b/tags/v_3.062/matlab/check_mh.m
new file mode 100644
index 0000000000000000000000000000000000000000..64b9512e3aeaae5978930e73e03e1df49e79edd2
--- /dev/null
+++ b/tags/v_3.062/matlab/check_mh.m
@@ -0,0 +1,24 @@
+function check_mh(fname)
+  eval(['load ' fname]);
+  nb = size(x3,3);
+  np = size(x2,2);
+  nr = size(x2,1);
+  
+  j1 = ceil(0.5*nr);
+  x = [j1:100:nr];
+  z = [];
+  for i=1:np
+    y1 = zeros(size(x),nb);
+    for k=1:nb
+      for j=1:length(x)
+	y1(j,k) = mean(x2(1:x(j),i,k));
+      end
+    end
+    my_subplot(i,np,4,5,'MH convergence');
+    plot([y1])
+    xmin = min(min(x2(:,i,:)));
+    xmax = max(max(x2(:,i,:)));
+    z = [z; [i sum(sum(x3(:,i,:) < xmin))/nr sum(sum(x3(:,i) > xmax))/nr]];
+  end
+  disp(z)
+     
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/check_model.m b/tags/v_3.062/matlab/check_model.m
new file mode 100644
index 0000000000000000000000000000000000000000..7189ca24884df8875992b2a738bcfa1d04d5b773
--- /dev/null
+++ b/tags/v_3.062/matlab/check_model.m
@@ -0,0 +1,18 @@
+function check_model()
+  global iy_ ykmin_ ykmax_ xkmin_ xkmax_ iy_ exo_det_nbr
+  
+  xlen = xkmin_ + xkmax_ + 1;
+  if ~ iy_(ykmin_+1,:) > 0
+  error ('RESOL: Error in model specification: some variables don"t appear as current') ;
+end
+
+if xlen > 1
+  error (['RESOL: stochastic exogenous variables must appear only at the' ...
+	  ' current period. Use additional endogenous variables']) ;
+end
+
+if (exo_det_nbr > 0) & (ykmin_ > 1 | ykmax_ > 1)
+  error(['Exogenous deterministic variables are currently only allowed in' ...
+	 ' models with leads and lags on only one period'])
+end
+
diff --git a/tags/v_3.062/matlab/cols.m b/tags/v_3.062/matlab/cols.m
new file mode 100644
index 0000000000000000000000000000000000000000..b63a5b4f1f8dd3979487634a51f44483de4eaa61
--- /dev/null
+++ b/tags/v_3.062/matlab/cols.m
@@ -0,0 +1,2 @@
+function nc=cols(x)
+  nc = size(x,2);
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/compdist.m b/tags/v_3.062/matlab/compdist.m
new file mode 100644
index 0000000000000000000000000000000000000000..363b463c0a94109816a8e001bb8b48e0baac5b84
--- /dev/null
+++ b/tags/v_3.062/matlab/compdist.m
@@ -0,0 +1,171 @@
+function compdist(xparam1, x2, pltopt, figurename)
+global bayestopt_  estim_params_ lgx_ lgy_ options_
+
+% NOTE: If pltopt ~= 'All' compdist.m just draws prior densities.  
+
+%% Set density estimation parameters:
+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';     % You can switch to: 'epanechnikov', 'quartic', 'triangle', 
+% 'triweight', 'uniform' or 'cosinus' kernels (iff bandwidth=0, see posterior_density_estimate.m). 
+truncprior = 10^(-3);             
+  
+  
+npar=length(xparam1);
+nruns=length(x2);
+icol=ceil(sqrt(npar));
+iraw=icol;
+if (icol-1)*(icol-2)>=npar
+    iraw = icol-2;
+    icol=icol-1;
+elseif (icol)*(icol-2)>=npar
+    iraw = icol-2;
+elseif icol*(icol-1)>=npar
+    iraw=icol-1;
+end
+
+pmean=bayestopt_.pmean;
+pshape=bayestopt_.pshape; 
+p1 = bayestopt_.p1;
+p2 = bayestopt_.p2;
+p3 = bayestopt_.p3;
+p4 = bayestopt_.p4;
+  
+figure('Name',figurename)
+for i=1:npar;
+  if i<=estim_params_.nvx
+    vname = deblank(lgx_(estim_params_.var_exo(i,1),:));
+    nam=['SE_{',vname,'}'];
+  elseif  i<=(estim_params_.nvx+estim_params_.nvn)
+    deblank(options_.varobs(estim_params_.var_endo(i-estim_params_.nvx,1),:));
+    nam=['SE_{EOBS_',vname,'}'];
+  elseif  i<=(estim_params_.nvx+estim_params_.nvn+estim_params_.ncx)
+    j = i - (estim_params_.nvx+estim_params_.nvn);
+    k1 = estim_params_.corrx(j,1);
+    k2 = estim_params_.corrx(j,2);
+    vname = [deblank(lgx_(k1,:)) ',' deblank(lgx_(k2,:))];
+    nam=['CC_{',vname,'}'];
+  elseif  i<=(estim_params_.nvx+estim_params_.nvn+estim_params_.ncx+ ...
+              estim_params_.ncn)
+    j = i - (estim_params_.nvx+estim_params_.nvn+estim_params_.ncx);
+    k1 = estim_params_.corrn(j,1);
+    k2 = estim_params_.corrn(j,2);
+    vname = [deblank(lgx_(k1,:)) ',' deblank(lgx_(k2,:))];
+    nam=['CC_{EOBS_',vname,'}'];
+  else
+    j = i - (estim_params_.nvx+estim_params_.nvn+estim_params_.ncx+ ...
+      estim_params_.ncn);
+    nam = deblank(estim_params_.param_names(j,:));
+  end
+  subplot(iraw, icol, i);   
+  if strcmpi(pltopt,'all'); % Estimation of the density...
+      [abscissa,ff,h] = posterior_density_estimate(x2(round(options_.mh_drop*nruns):end,i),...
+                      number_of_grid_points,bandwidth,kernel_function);
+      plot(abscissa,ff,'-k','linewidth',2); 
+  end;
+  a = 0;
+  b = 0;
+  if pshape(i) == 1;     %/* BETA Prior */
+      density = inline('((bb-x).^(b-1)).*(x-aa).^(a-1)./(beta(a,b)*(bb-aa)^(a+b-1))','x','a','b','aa','bb');
+      mu = (p1(i)-p3(i))/(p4(i)-p3(i));
+      stdd = p2(i)/(p4(i)-p3(i));
+      a = (1-mu)*mu^2/stdd^2 - mu;
+      b = a*(1/mu - 1);
+      aa = p3(i);
+      bb = p4(i);
+      infbound = qbeta(truncprior,a,b)*(bb-aa)+aa;
+      supbound = qbeta(1-truncprior,a,b)*(bb-aa)+aa;
+      stepsize = (supbound-infbound)/200;
+      abscissa = infbound:stepsize:supbound;
+      f = density(abscissa,a,b,aa,bb);
+      if strcmpi(pltopt,'all');
+          top = max([max(ff);max(f)]);
+      end;
+  elseif pshape(i) == 2; %/* GAMMA PRIOR */
+%      density = inline('((x/b).^(a-1)).*exp(-x/b)*inv(b*gamma(a))','x','a','b');
+      mu = p1(i)-p3(i);
+      b  = p2(i)^2/mu;
+      a  = mu/b;
+      infbound = mj_qgamma(truncprior,a)*b; 
+      supbound = mj_qgamma(1-truncprior,a)*b;
+      stepsize = (supbound-infbound)/200;
+      abscissa = infbound:stepsize:supbound;
+%      f = density(abscissa,a,b);
+      f = exp(lpdfgam(abscissa,a,b));
+      abscissa = abscissa + p3(i);
+      if strcmpi(pltopt,'all');
+          top = max([max(ff);max(f)]);
+      end;
+  elseif pshape(i) == 3; %/* GAUSSIAN PRIOR */
+      density = inline('inv(sqrt(2*pi)*b)*exp(-0.5*((x-a)/b).^2)','x','a','b');
+      a = p1(i);
+      b = p2(i);
+      infbound = qnorm(truncprior,a,b); 
+      supbound = qnorm(1-truncprior,a,b);
+      stepsize = (supbound-infbound)/200;
+      abscissa = infbound:stepsize:supbound;
+      f = density(abscissa,a,b);  
+      if strcmpi(pltopt,'all');
+          top = max([max(ff);max(f)]);
+      end;
+  elseif pshape(i) == 4; %/* INVGAMMA PRIOR type 1 */
+      density = inline('2*inv(gamma(nu/2))*(x.^(-nu-1))*((s/2)^(nu/2)).*exp(-s./(2*x.^2))','x','s','nu');
+      nu = p2(i);
+      s  = p1(i);
+      a  = nu/2;
+      b  = 2/s;
+      infbound = 1/sqrt(mj_qgamma(1-10*truncprior,a)*b); 
+      supbound = 1/sqrt(mj_qgamma(10*truncprior,a)*b);
+      stepsize = (supbound-infbound)/200;
+      abscissa = infbound:stepsize:supbound;
+      f = density(abscissa,s,nu);  
+      if strcmpi(pltopt,'all');
+          top = max([max(ff);max(f)]);
+      end;
+  elseif pshape(i) == 5; %/* UNIFORM PRIOR */
+      density = inline('(x.^0)/(b-a)','x','a','b');
+      a  = p1(i);
+      b  = p2(i);
+      infbound = a; 
+      supbound = b;
+      stepsize = (supbound-infbound)/200;
+      abscissa = infbound:stepsize:supbound;
+      f = density(abscissa,a,b);  
+      if strcmpi(pltopt,'all');
+          top = max([max(ff);max(f)]);
+      end;
+  elseif pshape(i) == 6; %/*  INVGAMMA PRIOR type 2 */        
+      density = inline('inv(gamma(nu/2))*(x.^(-.5(nu+2)))*((s/2)^(nu/2)).*exp(-s./(2*x))','x','s','nu');
+      nu = p2(i);
+      s  = p1(i);
+      a  = nu/2;
+      b  = 2/s;
+      infbound = 1/(qgamma(1-truncprior,a)*b); 
+      supbound = 1/(qgamma(truncprior,a)*b);
+      stepsize = (supbound-infbound)/200;
+      abscissa = infbound:stepsize:supbound;
+      f = density(abscissa,s,nu);  
+      if strcmpi(pltopt,'all');
+          top = max([max(ff);max(f)]);
+      end;
+  end;
+  hold on;
+  k = [1:length(f)];
+  if pshape(i) ~= 5 
+    [junk,k1] = max(f);
+    if k1 == 1 | k1 == length(f)
+      k = find(f < 10);
+    end
+  end
+  hh = plot(abscissa(k),f(k),'-k','linewidth',2);
+  set(hh,'color',[0.7 0.7 0.7]);
+  if strcmpi(pltopt,'all');
+      plot( [xparam1(i) xparam1(i)], [0,top], '--g', 'linewidth', 2);
+  end;
+  title(nam,'Interpreter','none');
+  hold off;
+end;
+drawnow
+
+% 12/01/03 MJ adapted from M. Ratto's version
+% 02/16/04 SA correction to the generalized beta distibution over interval [aa,bb].
diff --git a/tags/v_3.062/matlab/csminit.m b/tags/v_3.062/matlab/csminit.m
new file mode 100644
index 0000000000000000000000000000000000000000..4835b77120629aac90d16ee13fdb904593a2b810
--- /dev/null
+++ b/tags/v_3.062/matlab/csminit.m
@@ -0,0 +1,190 @@
+function [fhat,xhat,fcount,retcode] = csminit(fcn,x0,f0,g0,badg,H0,varargin)
+% [fhat,xhat,fcount,retcode] = csminit(fcn,x0,f0,g0,badg,H0,...
+%                                       P1,P2,P3,P4,P5,P6,P7,P8)
+% retcodes: 0, normal step.  5, largest step still improves too fast.
+% 4,2 back and forth adjustment of stepsize didn't finish.  3, smallest
+% stepsize still improves too slow.  6, no improvement found.  1, zero
+% gradient.
+%---------------------
+% Modified 7/22/96 to omit variable-length P list, for efficiency and compilation.
+% Places where the number of P's need to be altered or the code could be returned to
+% its old form are marked with ARGLIST comments.
+%
+% Fixed 7/17/93 to use inverse-hessian instead of hessian itself in bfgs
+% update.
+%
+% Fixed 7/19/93 to flip eigenvalues of H to get better performance when
+% it's not psd.
+%
+%tailstr = ')';
+%for i=nargin-6:-1:1
+%   tailstr=[ ',P' num2str(i)  tailstr];
+%end
+%ANGLE = .03;
+ANGLE = .005;
+%THETA = .03;
+THETA = .3; %(0<THETA<.5) THETA near .5 makes long line searches, possibly fewer iterations.
+FCHANGE = 1000;
+MINLAMB = 1e-9;
+% fixed 7/15/94
+% MINDX = .0001;
+% MINDX = 1e-6;
+MINDFAC = .01;
+fcount=0;
+lambda=1;
+xhat=x0;
+f=f0;
+fhat=f0;
+g = g0;
+gnorm = norm(g);
+%
+if (gnorm < 1.e-12) & ~badg % put ~badg 8/4/94
+   retcode =1;
+   dxnorm=0;
+   % gradient convergence
+else
+   % with badg true, we don't try to match rate of improvement to directional
+   % derivative.  We're satisfied just to get some improvement in f.
+   %
+   %if(badg)
+   %   dx = -g*FCHANGE/(gnorm*gnorm);
+   %  dxnorm = norm(dx);
+   %  if dxnorm > 1e12
+   %     disp('Bad, small gradient problem.')
+   %     dx = dx*FCHANGE/dxnorm;
+   %   end
+   %else
+   % Gauss-Newton step;
+   %---------- Start of 7/19/93 mod ---------------
+   %[v d] = eig(H0);
+   %toc
+   %d=max(1e-10,abs(diag(d)));
+   %d=abs(diag(d));
+   %dx = -(v.*(ones(size(v,1),1)*d'))*(v'*g);
+%      toc
+   dx = -H0*g;
+%      toc
+   dxnorm = norm(dx);
+   if dxnorm > 1e12
+      disp('Near-singular H problem.')
+      dx = dx*FCHANGE/dxnorm;
+   end
+   dfhat = dx'*g0;
+   %end
+   %
+   %
+   if ~badg
+      % test for alignment of dx with gradient and fix if necessary
+      a = -dfhat/(gnorm*dxnorm);
+      if a<ANGLE
+         dx = dx - (ANGLE*dxnorm/gnorm+dfhat/(gnorm*gnorm))*g;
+         dfhat = dx'*g;
+         dxnorm = norm(dx);
+         disp(sprintf('Correct for low angle: %g',a))
+      end
+   end
+   disp(sprintf('Predicted improvement: %18.9f',-dfhat/2))
+   %
+   % Have OK dx, now adjust length of step (lambda) until min and
+   % max improvement rate criteria are met.
+   done=0;
+   factor=3;
+   shrink=1;
+   lambdaMin=0;
+   lambdaMax=inf;
+   lambdaPeak=0;
+   fPeak=f0;
+   lambdahat=0;
+   while ~done
+      if size(x0,2)>1
+         dxtest=x0+dx'*lambda;
+      else
+         dxtest=x0+dx*lambda;
+      end
+      % home
+      f = eval([fcn '(dxtest,varargin{:})']);
+      %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(sprintf('lambda = %10.5g; f = %20.7f',lambda,f ))
+      %debug
+      %disp(sprintf('Improvement too great? f0-f: %g, criterion: %g',f0-f,-(1-THETA)*dfhat*lambda))
+      if f<fhat
+         fhat=f;
+         xhat=dxtest;
+         lambdahat = lambda;
+      end
+      fcount=fcount+1;
+      shrinkSignal = (~badg & (f0-f < max([-THETA*dfhat*lambda 0]))) | (badg & (f0-f) < 0) ;
+      growSignal = ~badg & ( (lambda > 0)  &  (f0-f > -(1-THETA)*dfhat*lambda) );
+      if  shrinkSignal  &   ( (lambda>lambdaPeak) | (lambda<0) )
+         if (lambda>0) & ((~shrink) | (lambda/factor <= lambdaPeak))
+            shrink=1;
+            factor=factor^.6;
+            while lambda/factor <= lambdaPeak
+               factor=factor^.6;
+            end
+            %if (abs(lambda)*(factor-1)*dxnorm < MINDX) | (abs(lambda)*(factor-1) < MINLAMB)
+            if abs(factor-1)<MINDFAC
+               if abs(lambda)<4
+                  retcode=2;
+               else
+                  retcode=7;
+               end
+               done=1;
+            end
+         end
+         if (lambda<lambdaMax) & (lambda>lambdaPeak)
+            lambdaMax=lambda;
+         end
+         lambda=lambda/factor;
+         if abs(lambda) < MINLAMB
+            if (lambda > 0) & (f0 <= fhat)
+               % try going against gradient, which may be inaccurate
+               lambda = -lambda*factor^6
+            else
+               if lambda < 0
+                  retcode = 6;
+               else
+                  retcode = 3;
+               end
+               done = 1;
+            end
+         end
+      elseif  (growSignal & lambda>0) |  (shrinkSignal & ((lambda <= lambdaPeak) & (lambda>0)))
+         if shrink
+            shrink=0;
+            factor = factor^.6;
+            %if ( abs(lambda)*(factor-1)*dxnorm< MINDX ) | ( abs(lambda)*(factor-1)< MINLAMB)
+            if abs(factor-1)<MINDFAC
+               if abs(lambda)<4
+                  retcode=4;
+               else
+                  retcode=7;
+               end
+               done=1;
+            end
+         end
+         if ( f<fPeak ) & (lambda>0)
+            fPeak=f;
+            lambdaPeak=lambda;
+            if lambdaMax<=lambdaPeak
+               lambdaMax=lambdaPeak*factor*factor;
+            end
+         end
+         lambda=lambda*factor;
+         if abs(lambda) > 1e20;
+            retcode = 5;
+            done =1;
+         end
+      else
+         done=1;
+         if factor < 1.2
+            retcode=7;
+         else
+            retcode=0;
+         end
+      end
+   end
+end
+disp(sprintf('Norm of dx %10.5g', dxnorm))
diff --git a/tags/v_3.062/matlab/csminwel.m b/tags/v_3.062/matlab/csminwel.m
new file mode 100644
index 0000000000000000000000000000000000000000..4caca896b83245307c92c40ba9c236d9c239c76f
--- /dev/null
+++ b/tags/v_3.062/matlab/csminwel.m
@@ -0,0 +1,274 @@
+function [fh,xh,gh,H,itct,fcount,retcodeh] = csminwel(fcn,x0,H0,grad,crit,nit,varargin)
+%[fhat,xhat,ghat,Hhat,itct,fcount,retcodehat] = csminwel(fcn,x0,H0,grad,crit,nit,varargin)
+% fcn:   string naming the objective function to be minimized
+% x0:    initial value of the parameter vector
+% H0:    initial value for the inverse Hessian.  Must be positive definite.
+% grad:  Either a string naming a function that calculates the gradient, or the null matrix.
+%        If it's null, the program calculates a numerical gradient.  In this case fcn must
+%        be written so that it can take a matrix argument and produce a row vector of values.
+% crit:  Convergence criterion.  Iteration will cease when it proves impossible to improve the
+%        function value by more than crit.
+% nit:   Maximum number of iterations.
+% varargin: A list of optional length of additional parameters that get handed off to fcn each
+%        time it is called.
+%        Note that if the program ends abnormally, it is possible to retrieve the current x,
+%        f, and H from the files g1.mat and H.mat that are written at each iteration and at each
+%        hessian update, respectively.  (When the routine hits certain kinds of difficulty, it
+%        write g2.mat and g3.mat as well.  If all were written at about the same time, any of them
+%        may be a decent starting point.  One can also start from the one with best function value.)
+global bayestopt_
+  [nx,no]=size(x0);
+nx=max(nx,no);
+Verbose=1;
+NumGrad= isempty(grad);
+done=0;
+itct=0;
+fcount=0;
+snit=100;
+%tailstr = ')';
+%stailstr = [];
+% Lines below make the number of Pi's optional.  This is inefficient, though, and precludes
+% use of the matlab compiler.  Without them, we use feval and the number of Pi's must be
+% changed with the editor for each application.  Places where this is required are marked
+% with ARGLIST comments
+%for i=nargin-6:-1:1
+%   tailstr=[ ',P' num2str(i)  tailstr];
+%   stailstr=[' P' num2str(i) stailstr];
+%end
+f0 = feval(fcn,x0,varargin{:});
+%ARGLIST
+%f0 = feval(fcn,x0,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,P13);
+% disp('first fcn in csminwel.m ----------------') % Jinill on 9/5/95
+if f0 > 1e50, disp('Bad initial parameter.'), return, end
+if NumGrad
+   if length(grad)==0
+      [g badg] = numgrad(fcn,x0, varargin{:});
+      %ARGLIST
+      %[g badg] = numgrad(fcn,x0,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,P13);
+   else
+      badg=any(find(grad==0));
+      g=grad;
+   end
+   %numgrad(fcn,x0,P1,P2,P3,P4);
+else
+   [g badg] = feval(grad,x0,varargin{:});
+   %ARGLIST
+   %[g badg] = feval(grad,x0,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,P13);
+end
+retcode3=101;
+x=x0;
+f=f0;
+H=H0;
+cliff=0;
+while ~done
+  bayestopt_.penalty = f;
+  g1=[]; g2=[]; g3=[];
+   %addition fj. 7/6/94 for control
+   disp('-----------------')
+   disp('-----------------')
+   %disp('f and x at the beginning of new iteration')
+   disp(sprintf('f at the beginning of new iteration, %20.10f',f))
+   %-----------Comment out this line if the x vector is long----------------
+   %      disp([sprintf('x = ') sprintf('%15.8g %15.8g %15.8g %15.8g\n',x(1:12))]);
+   %-------------------------
+   itct=itct+1;
+   [f1 x1 fc retcode1] = csminit(fcn,x,f,g,badg,H,varargin{:});
+   %ARGLIST
+   %[f1 x1 fc retcode1] = csminit(fcn,x,f,g,badg,H,P1,P2,P3,P4,P5,P6,P7,...
+   %           P8,P9,P10,P11,P12,P13);
+   % itct=itct+1;
+   fcount = fcount+fc;
+   % erased on 8/4/94
+   % if (retcode == 1) | (abs(f1-f) < crit)
+   %    done=1;
+   % end
+   % if itct > nit
+   %    done = 1;
+   %    retcode = -retcode;
+   % end
+   if retcode1 ~= 1
+      if retcode1==2 | retcode1==4
+         wall1=1; badg1=1;
+      else
+         if NumGrad
+            [g1 badg1] = numgrad(fcn, x1,varargin{:});
+            %ARGLIST
+            %[g1 badg1] = numgrad(fcn, x1,P1,P2,P3,P4,P5,P6,P7,P8,P9,...
+            %                P10,P11,P12,P13);
+         else
+            [g1 badg1] = feval(grad,x1,varargin{:});
+            %ARGLIST
+            %[g1 badg1] = feval(grad, x1,P1,P2,P3,P4,P5,P6,P7,P8,P9,...
+            %                P10,P11,P12,P13);
+         end
+         wall1=badg1;
+         % g1
+         save g1 g1 x1 f1 varargin;
+         %ARGLIST
+         %save g1 g1 x1 f1 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13;
+      end
+      if wall1 % & (~done) by Jinill
+         % Bad gradient or back and forth on step length.  Possibly at
+         % cliff edge.  Try perturbing search direction.
+         %
+         %fcliff=fh;xcliff=xh;
+         Hcliff=H+diag(diag(H).*rand(nx,1));
+         disp('Cliff.  Perturbing search direction.')
+         [f2 x2 fc retcode2] = csminit(fcn,x,f,g,badg,Hcliff,varargin{:});
+         %ARGLIST
+         %[f2 x2 fc retcode2] = csminit(fcn,x,f,g,badg,Hcliff,P1,P2,P3,P4,...
+         %     P5,P6,P7,P8,P9,P10,P11,P12,P13);
+         fcount = fcount+fc; % put by Jinill
+         if  f2 < f
+            if retcode2==2 | retcode2==4
+                  wall2=1; badg2=1;
+            else
+               if NumGrad
+                  [g2 badg2] = numgrad(fcn, x2,varargin{:});
+                  %ARGLIST
+                  %[g2 badg2] = numgrad(fcn, x2,P1,P2,P3,P4,P5,P6,P7,P8,...
+                  %      P9,P10,P11,P12,P13);
+               else
+                  [g2 badg2] = feval(grad,x2,varargin{:});
+                  %ARGLIST
+                  %[g2 badg2] = feval(grad,x2,P1,P2,P3,P4,P5,P6,P7,P8,...
+                  %      P9,P10,P11,P12,P13);
+               end
+               wall2=badg2;
+               % g2
+               badg2
+               save g2 g2 x2 f2 varargin
+               %ARGLIST
+               %save g2 g2 x2 f2 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13;
+            end
+            if wall2
+               disp('Cliff again.  Try traversing')
+               if norm(x2-x1) < 1e-13
+                  f3=f; x3=x; badg3=1;retcode3=101;
+               else
+                  gcliff=((f2-f1)/((norm(x2-x1))^2))*(x2-x1);
+                  [f3 x3 fc retcode3] = csminit(fcn,x,f,gcliff,0,eye(nx),varargin{:});
+                  %ARGLIST
+                  %[f3 x3 fc retcode3] = csminit(fcn,x,f,gcliff,0,eye(nx),P1,P2,P3,...
+                  %         P4,P5,P6,P7,P8,...
+                  %      P9,P10,P11,P12,P13);
+                  fcount = fcount+fc; % put by Jinill
+                  if retcode3==2 | retcode3==4
+                     wall3=1; badg3=1;
+                  else
+                     if NumGrad
+                        [g3 badg3] = numgrad(fcn, x3,varargin{:});
+                        %ARGLIST
+                        %[g3 badg3] = numgrad(fcn, x3,P1,P2,P3,P4,P5,P6,P7,P8,...
+                        %                        P9,P10,P11,P12,P13);
+                     else
+                        [g3 badg3] = feval(grad,x3,varargin{:});
+                        %ARGLIST
+                        %[g3 badg3] = feval(grad,x3,P1,P2,P3,P4,P5,P6,P7,P8,...
+                        %                         P9,P10,P11,P12,P13);
+                     end
+                     wall3=badg3;
+                     % g3
+                     badg3
+                     save g3 g3 x3 f3 varargin;
+                     %ARGLIST
+                     %save g3 g3 x3 f3 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13;
+                  end
+               end
+            else
+               f3=f; x3=x; badg3=1; retcode3=101;
+            end
+         else
+            f3=f; x3=x; badg3=1;retcode3=101;
+         end
+      else
+         % normal iteration, no walls, or else we're finished here.
+         f2=f; f3=f; badg2=1; badg3=1; retcode2=101; retcode3=101;
+      end
+   else 
+      f2=f;f3=f;f1=f;retcode2=retcode1;retcode3=retcode1;
+   end
+   %how to pick gh and xh
+   if f3<f & badg3==0
+      ih=3
+      fh=f3;xh=x3;gh=g3;badgh=badg3;retcodeh=retcode3;
+   elseif f2<f & badg2==0
+      ih=2
+      fh=f2;xh=x2;gh=g2;badgh=badg2;retcodeh=retcode2;
+   elseif f1<f & badg1==0
+      ih=1
+      fh=f1;xh=x1;gh=g1;badgh=badg1;retcodeh=retcode1;
+   else
+      [fh,ih] = min([f1,f2,f3]);
+      disp(sprintf('ih = %d',ih))
+      %eval(['xh=x' num2str(ih) ';'])
+      switch ih
+         case 1
+            xh=x1;
+         case 2
+            xh=x2;
+         case 3
+            xh=x3;
+      end %case
+      %eval(['gh=g' num2str(ih) ';'])
+      %eval(['retcodeh=retcode' num2str(ih) ';'])
+      retcodei=[retcode1,retcode2,retcode3];
+      retcodeh=retcodei(ih);
+      if exist('gh')
+         nogh=isempty(gh);
+      else
+         nogh=1;
+      end
+      if nogh
+         if NumGrad
+            [gh badgh] = numgrad(fcn,xh,varargin{:});
+         else
+            [gh badgh] = feval(grad, xh,varargin{:});
+         end
+      end
+      badgh=1;
+   end
+   %end of picking
+   %ih
+   %fh
+   %xh
+   %gh
+   %badgh
+   stuck = (abs(fh-f) < crit);
+   if (~badg)&(~badgh)&(~stuck)
+      H = bfgsi(H,gh-g,xh-x);
+   end
+   if Verbose
+      disp('----')
+      disp(sprintf('Improvement on iteration %d = %18.9f',itct,f-fh))
+   end
+   if Verbose
+      if itct > nit
+         disp('iteration count termination')
+         done = 1;
+      elseif stuck
+         disp('improvement < crit termination')
+         done = 1;
+      end
+      rc=retcodeh;
+      if rc == 1
+         disp('zero gradient')
+      elseif rc == 6
+         disp('smallest step still improving too slow, reversed gradient')
+      elseif rc == 5
+         disp('largest step still improving too fast')
+      elseif (rc == 4) | (rc==2)
+         disp('back and forth on step length never finished')
+      elseif rc == 3
+         disp('smallest step still improving too slow')
+      elseif rc == 7
+         disp('warning: possible inaccuracy in H matrix')
+      end
+   end
+   f=fh;
+   x=xh;
+   g=gh;
+   badg=badgh;
+end
+% what about making an m-file of 10 lines including numgrad.m
+% since it appears three times in csminwel.m
diff --git a/tags/v_3.062/matlab/datatomfile.m b/tags/v_3.062/matlab/datatomfile.m
new file mode 100644
index 0000000000000000000000000000000000000000..dcee78ca4328d2b46331738070c3e976608ad90d
--- /dev/null
+++ b/tags/v_3.062/matlab/datatomfile.m
@@ -0,0 +1,44 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function dynatype (s,var_list)
+% DYNATYPE :	DYNATYPE ( [ 'filename' ] )
+%		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.
+
+global lgy_ lgx_ y_ endo_nbr
+
+%fid=fopen([s,'.m'],'w') ;
+sm=[s,'.m'];
+fid=fopen(sm,'w') ;
+
+n = size(var_list,1);
+if n == 0
+  n = endo_nbr;
+  ivar = [1:n]';
+  var_list = lgy_;
+else
+  ivar=zeros(n,1);
+  for i=1:n
+    i_tmp = strmatch(var_list(i,:),lgy_,'exact');
+    if isempty(i_tmp)
+      error (['One of the specified variables does not exist']) ;
+    else
+      ivar(i) = i_tmp;
+    end
+  end
+end
+
+
+for i = 1:n
+	fprintf(fid,[lgy_(ivar(i),:), '=['],'\n') ;
+	fprintf(fid,'\n') ;
+	fprintf(fid,'%15.8g\n',y_(ivar(i),:)') ;
+   	fprintf(fid,'\n') ;
+   	fprintf(fid,'];\n') ;
+  	fprintf(fid,'\n') ;
+end
+fclose(fid) ;
+
+return ;
diff --git a/tags/v_3.062/matlab/dbeta.m b/tags/v_3.062/matlab/dbeta.m
new file mode 100644
index 0000000000000000000000000000000000000000..36d0c3788844a6ba96c7b099b3cc0750753312e5
--- /dev/null
+++ b/tags/v_3.062/matlab/dbeta.m
@@ -0,0 +1,16 @@
+function d = dbeta(x,a,b)
+%DBETA    The beta density function
+%
+%         f = dbeta(x,a,b)
+
+%       Anders Holtsberg, 18-11-93
+%       Copyright (c) Anders Holtsberg
+
+if any(any((a<=0)|(b<=0)))
+   error('Parameter a or b is nonpositive')
+end
+
+I = find((x<0)|(x>1));
+
+d = x.^(a-1) .* (1-x).^(b-1) ./ beta(a,b);
+d(I) = 0*I;
diff --git a/tags/v_3.062/matlab/dcompare.m b/tags/v_3.062/matlab/dcompare.m
new file mode 100644
index 0000000000000000000000000000000000000000..8544909b437e58061ad70b66c7a1f332f4a91b66
--- /dev/null
+++ b/tags/v_3.062/matlab/dcompare.m
@@ -0,0 +1,42 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function dcompare(s1)
+
+global dsmpl_ iter_
+global nvx nvy x y lag1
+
+ftest(s1,0) ;
+
+i = [lag1(1):size(x,2)-lag1(2)+1]' ;
+
+if size(dsmpl_,1) == 1
+	error(['DSAMPLE not specified.']) ;
+end
+
+if dsmpl_(3) > 0
+	if dsmpl_(3) == 2
+		if dsmpl_(1)<0 | dsmpl_(2)>size(x,2)-lag1(2)
+			error ('Wrong sample.') ;
+		end
+		i = [dsmpl_(1)+lag1(1):dsmpl_(2)+lag1(1)]' ;
+	elseif dsmpl_(3) == 1
+		if dsmpl_(1)>size(x,2)-lag1(2)
+			error ('Wrong sample.') ;
+		end
+		i = [lag1(1):dsmpl_(1)+lag1(1)]' ;
+	end
+end
+
+j = bseastr(nvx,nvy) ;
+
+if stop
+	return ;
+end
+
+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/tags/v_3.062/matlab/dgamma.m b/tags/v_3.062/matlab/dgamma.m
new file mode 100644
index 0000000000000000000000000000000000000000..c94be4e8d7c1a1a8e53944fcea17c22a35096b76
--- /dev/null
+++ b/tags/v_3.062/matlab/dgamma.m
@@ -0,0 +1,15 @@
+function f = dgamma(x,a,b)
+%DGAMMA   The gamma density function
+%
+%         f = dgamma(x,a)
+
+%       Anders Holtsberg, 18-11-93
+%       Copyright (c) Anders Holtsberg
+
+if any(any(a<=0))
+   error('Parameter a is wrong')
+end
+
+f = (x./b) .^ (a-1) .* exp(-x./b) ./ (b.*gamma(a));
+I0 = find(x<0);
+f(I0) = zeros(size(I0));
diff --git a/tags/v_3.062/matlab/diffext.m b/tags/v_3.062/matlab/diffext.m
new file mode 100644
index 0000000000000000000000000000000000000000..26263c23eb82a3d8a9ee02fdfdd134f9e1722518
--- /dev/null
+++ b/tags/v_3.062/matlab/diffext.m
@@ -0,0 +1,74 @@
+function [J] = diffext(f,x,options,varargin)
+%---------------------------------------------------------------------------
+%DIFFEXT   Numerical approximation for hessian.
+%          The method is Richardson`s extrapolation.
+% Sample call
+%   [D,err,relerr,n] = diffext('f',x,delta,toler)
+% Inputs
+%   f        name of the function
+%   x        differentiation point
+%   options  matrix of algorithm parameters
+%   delta    error goal (1e-12)
+%   toler    relative error goal (1e-12)
+% Return
+%   J        Jacobian
+%
+% NUMERICAL METHODS: MATLAB Programs, (c) John H. Mathews 1995
+%
+% Modified F. Collard, August 2001
+%---------------------------------------------------------------------------
+  global gstep_
+  if nargin>3;
+    if ~isempty(options);
+      delta=options(1);
+      toler=options(2);
+    else
+      delta=1e-12;
+      toler=1e-12;
+    end
+  else
+    delta=1e-12;
+    toler=1e-12;
+  end;
+  ff=feval(f,x,varargin{:});
+  nx=size(x,1);
+  nf=size(ff,1);
+  J=zeros(nf,nx);
+  for fi=1:nf;
+    for xi=1:nx;
+      err = 1;
+      relerr = 1;
+      h=max(abs(x(xi)), gstep_)*eps^(1/3) ;
+      dx = zeros(nx,1);
+      dx(xi)=h;      
+      j = 1;
+      fs=feval(f,x+dx,varargin{:});
+      fm=feval(f,x-dx,varargin{:});
+      D(1,1) = (fs(fi) - fm(fi))/(2*h);
+      while relerr>toler & err>delta & j<12
+	h = h/2;
+	dx(xi)=h;      
+	fs=feval(f,x+dx,varargin{:});
+	fm=feval(f,x-dx,varargin{:});
+	D(j+1,1) = (fs(fi) - fm(fi))/(2*h);
+	for k = 1:j,
+	  D(j+1,k+1) = D(j+1,k) + (D(j+1,k)-D(j-1+1,k))/(4^k -1);
+	end
+	err = abs(D(j+1,j+1)-D(j,j));
+	relerr = 2*err/(abs(D(j+1,j+1))+abs(D(j,j))+eps);
+	j = j+1;
+      end
+      n=size(D,1);
+      J(fi,xi)=D(n,n);
+      clear D;
+    end
+  end
+
+% 10/12/2001 MJ modified initial h
+
+
+
+
+
+
+
diff --git a/tags/v_3.062/matlab/disp_dr.m b/tags/v_3.062/matlab/disp_dr.m
new file mode 100644
index 0000000000000000000000000000000000000000..1269d2557cfef5cac529a0db79f860e849bebd67
--- /dev/null
+++ b/tags/v_3.062/matlab/disp_dr.m
@@ -0,0 +1,200 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function disp_dr(dr,order,var_list)
+global lgy_ lgx_ endo_nbr exo_nbr ykmin_
+  
+nx =size(dr.ghx,2);
+nu =size(dr.ghu,2);
+k = find(dr.kstate(:,2) <= ykmin_+1);
+klag = dr.kstate(k,[1 2]);
+
+k1 = dr.order_var;
+
+nvar = size(var_list,1);
+if nvar == 0
+  nvar = length(k1);
+  ivar = [1:nvar];
+else
+  ivar=zeros(nvar,1);
+  for i=1:nvar
+    i_tmp = strmatch(var_list(i,:),lgy_(k1,:),'exact');
+    if isempty(i_tmp)
+      disp(var_list(i,:));
+      error (['One of the variable specified does not exist']) ;
+    else
+      ivar(i) = i_tmp;
+    end
+  end
+end
+disp('POLICY AND TRANSITION FUNCTIONS')
+% variable names
+str = '                        ';
+for i=1:nvar
+  str = [str sprintf('%16s',lgy_(k1(ivar(i)),:))];
+end
+disp(str);
+%
+% constant
+%
+str = 'Constant            ';
+flag = 0;
+for i=1:nvar
+  x = dr.ys(k1(ivar(i)));
+  if order > 1
+    x = x + dr.ghs2(ivar(i))/2;
+  end
+  if abs(x) > 1e-6
+    flag = 1;
+    str = [str sprintf('%16.6f',x)];
+  else
+    str = [str '               0'];
+  end
+end
+if flag
+  disp(str)
+end
+if order > 1
+  str = '(correction)        ';
+  flag = 0;
+  for i=1:nvar
+    x = dr.ghs2(ivar(i))/2;
+    if abs(x) > 1e-6
+      flag = 1;
+      str = [str sprintf('%16.6f',x)];
+    else
+      str = [str '               0'];
+    end
+  end
+  if flag
+    disp(str)
+  end
+end
+%
+% ghx
+%
+for k=1:nx
+  flag = 0;
+  str1 = sprintf('%s(%d)',lgy_(k1(klag(k,1)),:),klag(k,2)-ykmin_-2);
+  str = sprintf('%-20s',str1);
+  for i=1:nvar
+    x = dr.ghx(ivar(i),k);
+    if abs(x) > 1e-6
+      flag = 1;
+      str = [str sprintf('%16.6f',x)];
+    else
+      str = [str '               0'];
+    end
+  end
+  if flag
+    disp(str)
+  end
+end
+%
+% ghu
+%
+for k=1:nu
+  flag = 0;
+  str = sprintf('%-20s',lgx_(k,:));
+  for i=1:nvar
+    x = dr.ghu(ivar(i),k);
+    if abs(x) > 1e-6
+      flag = 1;
+      str = [str sprintf('%16.6f',x)];
+    else
+      str = [str '               0'];
+    end
+  end
+  if flag
+    disp(str)
+  end
+end
+
+if order > 1
+  % ghxx
+  for k = 1:nx
+    for j = 1:k
+      flag = 0;
+      str1 = sprintf('%s(%d),%s(%d)',lgy_(k1(klag(k,1)),:),klag(k,2)-ykmin_-2, ...
+		     lgy_(k1(klag(j,1)),:),klag(j,2)-ykmin_-2);
+      str = sprintf('%-20s',str1);
+      for i=1:nvar
+	if k == j
+	  x = dr.ghxx(ivar(i),(k-1)*nx+j)/2;
+	else
+	  x = dr.ghxx(ivar(i),(k-1)*nx+j);
+	end
+	if abs(x) > 1e-6
+	  flag = 1;
+	  str = [str sprintf('%16.6f',x)];
+	else
+	  str = [str '               0'];
+	end
+      end
+      if flag
+	disp(str)
+      end
+    end
+  end
+  %
+  % ghuu
+  %
+  for k = 1:nu
+    for j = 1:k
+      flag = 0;
+      str = sprintf('%-20s',[lgx_(k,:) ',' lgx_(j,:)] );
+      for i=1:nvar
+	if k == j
+	  x = dr.ghuu(ivar(i),(k-1)*nu+j)/2;
+	else
+	  x = dr.ghuu(ivar(i),(k-1)*nu+j);
+	end
+	if abs(x) > 1e-6
+	  flag = 1;
+	  str = [str sprintf('%16.6f',x)];
+	else
+	  str = [str '               0'];
+	end
+      end
+      if flag
+	disp(str)
+      end
+    end
+  end
+  %
+  % ghxu
+  %
+  for k = 1:nx
+    for j = 1:nu
+      flag = 0;
+      str1 = sprintf('%s(%d),%s',lgy_(k1(klag(k,1)),:),klag(k,2)-ykmin_-2, ...
+		     lgx_(j,:));
+      str = sprintf('%-20s',str1);
+      for i=1:nvar
+	x = dr.ghxu(ivar(i),(k-1)*nu+j);
+	if abs(x) > 1e-6
+	  flag = 1;
+	  str = [str sprintf('%16.6f',x)];
+	else
+	  str = [str '               0'];
+	end
+      end
+      if flag
+	disp(str)
+      end
+    end
+  end
+end
+
+% $$$   dr.ghx
+% $$$   dr.ghu
+% $$$   dr.ghxx
+% $$$   dr.ghuu
+% $$$   dr.ghxu
+
+% 01/08/2001 MJ  added test for order in printing quadratic terms
+% 02/21/2001 MJ pass all variable names through deblank()
+% 02/21/2001 MJ changed from f to g format to write numbers
+% 10/09/2002 MJ corrected error on constant whith subset of variables 
+
+
+
diff --git a/tags/v_3.062/matlab/disp_moments.m b/tags/v_3.062/matlab/disp_moments.m
new file mode 100644
index 0000000000000000000000000000000000000000..9a6eb2a96ddd4d7b9dc3824476f391c8a214aba9
--- /dev/null
+++ b/tags/v_3.062/matlab/disp_moments.m
@@ -0,0 +1,86 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function disp_moments(y,var_list)
+global lgy_ endo_nbr ykmin_ options_ oo_ options_
+  
+warning off
+% Useless ? Already done in stoch_simul...
+nvar = size(var_list,1);
+if nvar == 0
+  nvar = endo_nbr;
+  ivar = [1:nvar]';
+else
+  ivar=zeros(nvar,1);
+  for i=1:nvar
+    i_tmp = strmatch(var_list(i,:),lgy_,'exact');
+    if isempty(i_tmp)
+      error (['One of the variable specified does not exist']) ;
+    else
+      ivar(i) = i_tmp;
+    end
+  end
+end
+  
+y = y(ivar,options_.drop+ykmin_+1:end)';
+
+m = mean(y);
+y = y - repmat(m,size(y,1),1);
+s2 = mean(y.*y);
+s = sqrt(s2);
+oo_.mean = m;
+oo_.var = y'*y/size(y,1);
+
+labels = deblank(lgy_(ivar,:));
+
+if options_.nomoments == 0 & ~options_.noprint
+  z = [ m' s' s2' (mean(y.^3)./s2.^1.5)' (mean(y.^4)./(s2.*s2)-3)' ];
+  title='MOMENTS OF SIMULATED VARIABLES';
+  if options_.hp_filter > 1
+    title = [title ' (HP filter, lambda = ' ...
+	     int2str(options_.hp_filter) ')'];
+  end
+  headers=strvcat('VARIABLE','MEAN','STD. DEV.','VARIANCE','SKEWNESS', ...
+		  'KURTOSIS');
+  table(title,headers,labels,z,size(labels,2)+2,16,6);
+end
+
+if options_.nocorr == 0 & ~options_.noprint
+  corr = (y'*y/size(y,1))./(s'*s);
+  title = 'CORRELATION OF SIMULATED VARIABLES';
+  if options_.hp_filter > 1
+    title = [title ' (HP filter, lambda = ' ...
+	     int2str(options_.hp_filter) ')'];
+  end
+  headers = strvcat('VARIABLE',lgy_(ivar,:));
+  table(title,headers,labels,corr,size(labels,2)+2,8,4);
+end
+  
+ar = options_.ar;
+options_ = set_default_option(options_,'ar',5);
+ar = options_.ar;
+if ar > 0
+  autocorr = [];
+  for i=1:ar
+    oo_.autocorr{i} = y(ar+1:end,:)'*y(ar+1-i:end-i,:)./((size(y,1)-ar)*s'*s);
+    autocorr = [ autocorr diag(oo_.autocorr{i}) ];
+  end
+  if ~options_.noprint
+    title = 'AUTOCORRELATION OF SIMULATED VARIABLES';
+    if options_.hp_filter > 1
+      title = [title ' (HP filter, lambda = ' ...
+	       int2str(options_.hp_filter) ')'];
+    end
+    headers = strvcat('VARIABLE',int2str([1:ar]'));
+    table(title,headers,labels,autocorr,size(labels,2)+2,8,4);
+  end
+end
+  
+  warning on
+% 10/03/02 MJ corrected order std. dev var in printed report.
+% 01/02/03 MJ added correlation and autocorrelation
+% 01/19/03 MJ corrected variable name truncation
+% 02/18/03 MJ added subtitle for HP filter
+% 03/02/03 MJ added ykmin_ to the number of entries of y
+% 04/28/03 MJ modified handling of options_
+% 06/23/03 MJ added warning off
+% 03/04/05 SA added silent mode
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/disp_th_moments.m b/tags/v_3.062/matlab/disp_th_moments.m
new file mode 100644
index 0000000000000000000000000000000000000000..93e8b5485056da902123f2dac2cecd89f48a662b
--- /dev/null
+++ b/tags/v_3.062/matlab/disp_th_moments.m
@@ -0,0 +1,360 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function disp_th_moments(dr,var_list)
+global endo_nbr exo_nbr lgy_ lgx_ Gamma_y lgx_orig_ord_ options_ oo_
+global lgy_TeX_ lgx_TeX_ fname_ options_
+
+TeX = options_.TeX;
+MaxCol = 6;
+
+nvar = size(var_list,1);
+if nvar == 0
+  nvar  = length(dr.order_var);
+  ivar  = transpose(1:nvar);
+  var_list = lgy_;
+else
+  ivar=zeros(nvar,1);
+  if TeX
+    var_listTeX = [];
+  end
+  for i=1:nvar
+    i_tmp = strmatch(var_list(i,:),lgy_,'exact');
+    if isempty(i_tmp)
+      error (['One of the variable specified does not exist']) ;
+    else
+      ivar(i) = i_tmp;
+      if TeX
+	var_listTeX = strvcat(var_listTeX,deblank(lgy_TeX_(i_tmp,:)));
+      end
+    end	
+  end
+end
+
+[Gamma_y,ivar] = th_autocovariances(dr,ivar);
+m = dr.ys(ivar);
+
+i1 = find(abs(diag(Gamma_y{1})) > 1e-12);
+s2 = diag(Gamma_y{1});
+sd = sqrt(s2);
+if options_.order == 2
+  m = m+Gamma_y{options_.ar+3};
+end
+  
+z = [ m sd s2 ];
+oo_.mean = m;
+oo_.var = Gamma_y{1};
+for i=1:options_.ar
+  oo_.autocorr{i}=Gamma_y{i+1};
+end
+
+if TeX
+  filename = [fname_ '_Posterior_ThMoments1.TeX'];
+  fidTeX = fopen(filename,'w');
+  fprintf(fidTeX,'%% TeX-table generated by disp_th_moments (Dynare).\n');
+  fprintf(fidTeX,['%% ' datestr(now,0)]);
+  fprintf(fidTeX,' \n');
+  fprintf(fidTeX,' \n');
+  fprintf(fidTeX,'{\\tiny \n')
+  fprintf(fidTeX,'\\begin{table}\n');
+  fprintf(fidTeX,'\\centering\n');
+  fprintf(fidTeX,'\\begin{tabular}{l|cc} \n');
+  fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+  fprintf(fidTeX,' Variable  & Theoretical expectation & Theoretical variance \\\\ \n');
+  fprintf(fidTeX,'\\hline \\\\ \n');
+  for i=1:nvar
+    fprintf(fidTeX,'$%s$ & %7.3f & %7.3f \\\\ \n',...
+	    deblank(var_listTeX(i,:)),...
+	    m(i),...
+	    oo_.var(i,i));
+  end
+  fprintf(fidTeX,'\\hline\\hline \n');
+  fprintf(fidTeX,'\\end{tabular}\n ');    
+  fprintf(fidTeX,'\\caption{Posterior expectations and variances.}\n ');
+  fprintf(fidTeX,'\\label{Table:Posterior:ThMoments:1}\n');
+  fprintf(fidTeX,'\\end{table}\n');
+  fprintf(fidTeX,'} \n')
+  fprintf(fidTeX,'%% End of TeX file.\n');
+  fclose(fidTeX);
+end
+
+
+lh = size(deblank(lgy_(ivar,:)),2)+2;
+if options_.nomoments == 0
+  if ~options_.noprint
+    title='THEORETICAL MOMENTS';
+    if options_.hp_filter > 1
+      title = [title ' (HP filter, lambda = ' int2str(options_.hp_filter) ')'];
+    end
+    headers=strvcat('VARIABLE','MEAN','STD. DEV.','VARIANCE');
+    table(title,headers,deblank(lgy_(ivar,:)),z,lh,11,4);
+    if exo_nbr > 1
+      disp(' ')
+      title='VARIANCE DECOMPOSITION (in percent)';
+      if options_.hp_filter > 1
+	title = [title ' (HP filter, lambda = ' ...
+		 int2str(options_.hp_filter) ')'];
+      end
+      headers = lgx_;
+      headers(lgx_orig_ord_,:) = headers;
+      headers = strvcat(' ',headers);
+      table(title,headers,deblank(lgy_(ivar(i1),:)),100*Gamma_y{options_.ar+2}(i1,:), ...
+	    lh,8,2);
+    end
+    if TeX
+      PostDeComp = Gamma_y{options_.ar+2};
+      ntabs = ceil(exo_nbr/MaxCol);
+      reste = exo_nbr-(ntabs-1)*MaxCol;
+      TeXheaders(lgx_orig_ord_,:) = lgx_TeX_;
+      filename = [fname_ '_Posterior_ThDeComp.TeX'];
+      fidTeX = fopen(filename,'w');
+      fprintf(fidTeX,'%% TeX-table generated by disp_th_moments (Dynare).\n');
+      fprintf(fidTeX,['%% ' datestr(now,0)]);
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,' \n');
+      for tab = 1:ntabs-1
+	fprintf(fidTeX,'{\\tiny \n')
+	fprintf(fidTeX,'\\begin{table}\n');
+	fprintf(fidTeX,'\\centering\n');
+	fprintf(fidTeX,'\\begin{tabular}{l|cccccc} \n');
+	fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+	fprintf(fidTeX,' Variable  & $%s$ & $%s$ & $%s$ & $%s$ & $%s$ & $%s$ \\\\ \n',...
+		deblank(TeXheaders((tab-1)*MaxCol+1,:)),...
+		deblank(TeXheaders((tab-1)*MaxCol+2,:)),...
+		deblank(TeXheaders((tab-1)*MaxCol+3,:)),...
+		deblank(TeXheaders((tab-1)*MaxCol+4,:)),...
+		deblank(TeXheaders((tab-1)*MaxCol+5,:)),...
+		deblank(TeXheaders((tab-1)*MaxCol+6,:)));
+	fprintf(fidTeX,'\\hline \\\\ \n');
+	for i=1:nvar
+	  fprintf(fidTeX,'$%s$ & %4.2f & %4.2f & %4.2f & %4.2f & %4.2f & %4.2f \\\\ \n',...
+		  deblank(var_listTeX(i,:)),...
+		  PostDeComp(i,(tab-1)*MaxCol+1),...
+		  PostDeComp(i,(tab-1)*MaxCol+2),...
+		  PostDeComp(i,(tab-1)*MaxCol+3),...
+		  PostDeComp(i,(tab-1)*MaxCol+4),...
+		  PostDeComp(i,(tab-1)*MaxCol+5),...
+		  PostDeComp(i,(tab-1)*MaxCol+6));
+	end
+	fprintf(fidTeX,'\\hline\\hline \n');
+	fprintf(fidTeX,'\\end{tabular}\n ');
+	fprintf(fidTeX,'\\caption{Variance decomposition}\n');
+	fprintf(fidTeX,'\\label{Table:Posterior:ThDeComp:%s}\n',int2str(tab));
+	fprintf(fidTeX,'\\end{table}\n');
+	fprintf(fidTeX,'} \n')
+	fprintf(fidTeX,' \n');
+      end
+      if reste == 6
+	fprintf(fidTeX,'{\\tiny \n')
+	fprintf(fidTeX,'\\begin{table}\n');
+	fprintf(fidTeX,'\\centering\n');
+	fprintf(fidTeX,'\\begin{tabular}{l|cccccc} \n');
+	fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+	fprintf(fidTeX,' Variable  & $%s$ & $%s$ & $%s$ & $%s$ & $%s$ & $%s$ \\\\ \n',...
+		deblank(TeXheaders((ntabs-1)*MaxCol+1,:)),...
+		deblank(TeXheaders((ntabs-1)*MaxCol+2,:)),...
+		deblank(TeXheaders((ntabs-1)*MaxCol+3,:)),...
+		deblank(TeXheaders((ntabs-1)*MaxCol+4,:)),...
+		deblank(TeXheaders((ntabs-1)*MaxCol+5,:)),...
+		deblank(TeXheaders((ntabs-1)*MaxCol+6,:)));
+	fprintf(fidTeX,'\\hline \\\\ \n');
+	for i=1:nvar
+	  fprintf(fidTeX,'$%s$ & %4.2f & %4.2f & %4.2f & %4.2f & %4.2f & %4.2f \\\\ \n',...
+		  deblank(var_listTeX(i,:)),...
+		  PostDeComp(i,(ntabs-1)*MaxCol+1),...
+		  PostDeComp(i,(ntabs-1)*MaxCol+2),...
+		  PostDeComp(i,(ntabs-1)*MaxCol+3),...
+		  PostDeComp(i,(ntabs-1)*MaxCol+4),...
+		  PostDeComp(i,(ntabs-1)*MaxCol+5),...
+		  PostDeComp(i,(ntabs-1)*MaxCol+6));
+	end
+	fprintf(fidTeX,'\\hline\\hline \n');
+	fprintf(fidTeX,'\\end{tabular}\n ');    
+	fprintf(fidTeX,'\\caption{Variance decomposition.}\n ');
+	fprintf(fidTeX,'\\label{Table:Posterior:ThDeComp:%s}\n',int2str(ntabs));
+	fprintf(fidTeX,'\\end{table}\n');
+	fprintf(fidTeX,'} \n')
+	fprintf(fidTeX,' \n');
+	fprintf(fidTeX,'%% End Of TeX File.')
+	fclose(fidTeX);
+      elseif reste == 5
+	fprintf(fidTeX,'{\\tiny \n')
+	fprintf(fidTeX,'\\begin{table}\n');
+	fprintf(fidTeX,'\\centering\n');
+	fprintf(fidTeX,'\\begin{tabular}{l|ccccc} \n');
+	fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+	fprintf(fidTeX,' Variable  & $%s$ & $%s$ & $%s$ & $%s$ & $%s$ \\\\ \n',...
+		deblank(TeXheaders((ntabs-1)*MaxCol+1,:)),...
+		deblank(TeXheaders((ntabs-1)*MaxCol+2,:)),...
+		deblank(TeXheaders((ntabs-1)*MaxCol+3,:)),...
+		deblank(TeXheaders((ntabs-1)*MaxCol+4,:)),...
+		deblank(TeXheaders((ntabs-1)*MaxCol+5,:)));
+	fprintf(fidTeX,'\\hline \\\\ \n');
+	for i=1:nvar
+	  fprintf(fidTeX,'$%s$ & %4.2f & %4.2f & %4.2f & %4.2f & %4.2f \\\\ \n',...
+		  deblank(var_listTeX(i,:)),...
+		  PostDeComp(i,(ntabs-1)*MaxCol+1),...
+		  PostDeComp(i,(ntabs-1)*MaxCol+2),...
+		  PostDeComp(i,(ntabs-1)*MaxCol+3),...
+		  PostDeComp(i,(ntabs-1)*MaxCol+4),...
+		  PostDeComp(i,(ntabs-1)*MaxCol+5));
+	end
+	fprintf(fidTeX,'\\hline\\hline \n');
+	fprintf(fidTeX,'\\end{tabular}\n ');    
+	fprintf(fidTeX,'\\caption{Variance decomposition}\n ');
+	fprintf(fidTeX,'\\label{Table:Posterior:ThDeComp:%s}\n',int2str(ntabs));
+	fprintf(fidTeX,'\\end{table}\n');
+	fprintf(fidTeX,'} \n')
+	fprintf(fidTeX,' \n');
+	fprintf(fidTeX,'%% End Of TeX File.')
+	fclose(fidTeX);
+      elseif reste == 4
+	fprintf(fidTeX,'{\\tiny \n')
+	fprintf(fidTeX,'\\begin{table}\n');
+	fprintf(fidTeX,'\\centering\n');
+	fprintf(fidTeX,'\\begin{tabular}{l|cccc} \n');
+	fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+	fprintf(fidTeX,' Variable  & $%s$ & $%s$ & $%s$ & $%s$ \\\\ \n',...
+		deblank(TeXheaders((ntabs-1)*MaxCol+1,:)),...
+		deblank(TeXheaders((ntabs-1)*MaxCol+2,:)),...
+		deblank(TeXheaders((ntabs-1)*MaxCol+3,:)),...
+		deblank(TeXheaders((ntabs-1)*MaxCol+4,:)));
+	fprintf(fidTeX,'\\hline \\\\ \n');
+	for i=1:nvar
+	  fprintf(fidTeX,'$%s$ & %4.2f & %4.2f & %4.2f & %4.2f \\\\ \n',...
+		  deblank(var_listTeX(i,:)),...
+		  PostDeComp(i,(ntabs-1)*MaxCol+1),...
+		  PostDeComp(i,(ntabs-1)*MaxCol+2),...
+		  PostDeComp(i,(ntabs-1)*MaxCol+3),...
+		  PostDeComp(i,(ntabs-1)*MaxCol+4));
+	end
+	fprintf(fidTeX,'\\hline\\hline \n');
+	fprintf(fidTeX,'\\end{tabular}\n ');    
+	fprintf(fidTeX,'\\caption{Variance decomposition}\n ');
+	fprintf(fidTeX,'\\label{Table:Posterior:ThDeComp:%s}\n',int2str(ntabs));
+	fprintf(fidTeX,'\\end{table}\n');
+	fprintf(fidTeX,'} \n')
+	fprintf(fidTeX,' \n');
+	fprintf(fidTeX,'%% End Of TeX File.')
+	fclose(fidTeX);
+      elseif reste == 3
+	fprintf(fidTeX,'{\\tiny \n')
+	fprintf(fidTeX,'\\begin{table}\n');
+	fprintf(fidTeX,'\\centering\n');
+	fprintf(fidTeX,'\\begin{tabular}{l|ccc} \n');
+	fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+	fprintf(fidTeX,' Variable  & $%s$ & $%s$ & $%s$ \\\\ \n',...
+		deblank(TeXheaders((ntabs-1)*MaxCol+1,:)),...
+		deblank(TeXheaders((ntabs-1)*MaxCol+2,:)),...
+		deblank(TeXheaders((ntabs-1)*MaxCol+3,:)));
+	fprintf(fidTeX,'\\hline \\\\ \n');
+	for i=1:nvar
+	  fprintf(fidTeX,'$%s$ & %4.2f & %4.2f & %4.2f \\\\ \n',...
+		  deblank(var_listTeX),...
+		  PostDeComp(i,(ntabs-1)*MaxCol+1),...
+		  PostDeComp(i,(ntabs-1)*MaxCol+2),...
+		  PostDeComp(i,(ntabs-1)*MaxCol+3));
+	end
+	fprintf(fidTeX,'\\hline\\hline \n');
+	fprintf(fidTeX,'\\end{tabular}\n ');    
+	fprintf(fidTeX,'\\caption{Variance decomposition}\n ');
+	fprintf(fidTeX,'\\label{Table:Posterior:ThDeComp:%s}\n',int2str(ntabs));
+	fprintf(fidTeX,'\\end{table}\n');
+	fprintf(fidTeX,'} \n')
+	fprintf(fidTeX,' \n');
+	fprintf(fidTeX,'%% End Of TeX File.')
+	fclose(fidTeX);
+      elseif reste == 2
+	fprintf(fidTeX,'{\\tiny \n')
+	fprintf(fidTeX,'\\begin{table}\n');
+	fprintf(fidTeX,'\\centering\n');
+	fprintf(fidTeX,'\\begin{tabular}{l|cc} \n');
+	fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+	fprintf(fidTeX,' Variable  & $%s$ & $%s$ \\\\ \n',...
+		deblank(TeXheaders((ntabs-1)*MaxCol+1,:)),...
+		deblank(TeXheaders((ntabs-1)*MaxCol+2,:)));
+	fprintf(fidTeX,'\\hline \\\\ \n');
+	for i=1:nvar
+	  fprintf(fidTeX,'$%s$ & %4.2f & %4.2f \\\\ \n',...
+		  deblank(var_listTeX),...
+		  PostDeComp(i,(ntabs-1)*MaxCol+1),...
+		  PostDeComp(i,(ntabs-1)*MaxCol+2));
+	end
+	fprintf(fidTeX,'\\hline\\hline \n');
+	fprintf(fidTeX,'\\end{tabular}\n ');    
+	fprintf(fidTeX,'\\caption{Variance decomposition}\n ');
+	fprintf(fidTeX,'\\label{Table:Posterior:ThDeComp:%s}\n',int2str(ntabs));
+	fprintf(fidTeX,'\\end{table}\n');
+	fprintf(fidTeX,'} \n')
+	fprintf(fidTeX,' \n');
+	fprintf(fidTeX,'%% End Of TeX File.')
+	fclose(fidTeX);
+      elseif reste == 1
+	fprintf(fidTeX,'{\\tiny \n')
+	fprintf(fidTeX,'\\begin{table}\n');
+	fprintf(fidTeX,'\\centering\n');
+	fprintf(fidTeX,'\\begin{tabular}{l|c} \n');
+	fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+	fprintf(fidTeX,' Variable  & $%s$ \\\\ \n',...
+		deblank(TeXheaders((ntabs-1)*MaxCol+1,:)));
+	fprintf(fidTeX,'\\hline \\\\ \n');
+	for i=1:nvar
+	  fprintf(fidTeX,'$%s$ & %4.2f \\\\ \n',...
+		  deblank(var_listTeX),...
+		  PostDeComp(i,(ntabs-1)*MaxCol+1));
+	end
+	fprintf(fidTeX,'\\hline\\hline \n');
+	fprintf(fidTeX,'\\end{tabular}\n ');    
+	fprintf(fidTeX,'\\caption{Variance decomposition}\n ');
+	fprintf(fidTeX,'\\label{Table:Posterior:ThDeComp:%s}\n',int2str(ntabs));
+	fprintf(fidTeX,'\\end{table}\n');
+	fprintf(fidTeX,'} \n')
+	fprintf(fidTeX,' \n');
+	fprintf(fidTeX,'%% End Of TeX File.')
+	fclose(fidTeX);
+      end	
+    end
+  end
+end
+
+if options_.nocorr == 0 & ~options_.noprint
+    disp(' ')
+    title='MATRIX OF CORRELATIONS';
+    if options_.hp_filter > 1
+      title = [title ' (HP filter, lambda = ' int2str(options_.hp_filter) ')'];
+    end
+    labels = deblank(lgy_(ivar,:));
+    headers = strvcat('Variables',labels(i1,:));
+    corr = Gamma_y{1}(i1,i1)./(sd(i1)*sd(i1)');
+    table(title,headers,labels(i1,:),corr,lh,8,4);
+end
+  
+if options_.ar > 0
+  for i=1:options_.ar
+    oo_.autocorr{i} = Gamma_y{i+1};
+  end
+  if ~options_.noprint
+    disp(' ')
+    title='COEFFICIENTS OF AUTOCORRELATION';
+    if options_.hp_filter > 1
+      title = [title ' (HP filter, lambda = ' int2str(options_.hp_filter) ')'];
+    end
+    labels = deblank(lgy_(ivar(i1),:));
+    headers = strvcat('Order ',int2str([1:options_.ar]'));
+    z=[];
+    for i=1:options_.ar
+      z(:,i) = diag(Gamma_y{i+1}(i1,i1));
+    end
+    table(title,headers,labels,z,0,8,4);
+  end
+end
+  
+% 10/09/02 MJ 
+% 10/18/02 MJ added th_autocovariances() and provided for lags on several
+% periods
+% 10/30/02 MJ added correlations and autocorrelations, uses table()
+%             Gamma_y is now a cell array.
+% 02/18/03 MJ added subtitles for HP filter
+% 05/01/03 MJ corrected options_.hp_filter
+% 05/21/03 MJ variance decomposition: test exo_nbr > 1
+% 05/21/03 MJ displays only variables with positive variance
+% 04/03/05 SA added silent mode
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/dlognorm.m b/tags/v_3.062/matlab/dlognorm.m
new file mode 100644
index 0000000000000000000000000000000000000000..4dcfed55083ed40ea72098116f7ecc57faa07512
--- /dev/null
+++ b/tags/v_3.062/matlab/dlognorm.m
@@ -0,0 +1,16 @@
+function f = dlognorm(x,lambda,zeta)
+%DLOGNORM  The log-normal density function
+% 
+%          f = dlognorm(x,lambda,zeta)
+
+%       Copyright (c) Halfdan Grage, Anders Holtsberg
+
+if any(any(zeta<=0))
+   error('Parameter zeta is wrong')
+end
+
+neg = find(x <= 0);
+[n1,n2] = size(neg);
+x(neg) = ones(n1,n2);
+f = dnorm(log(x),lambda,zeta)./x;
+f(neg) = zeros(n1,n2);
diff --git a/tags/v_3.062/matlab/dnorm.m b/tags/v_3.062/matlab/dnorm.m
new file mode 100644
index 0000000000000000000000000000000000000000..53e7974dbac24efddcad0c9b878a0d15b45772b5
--- /dev/null
+++ b/tags/v_3.062/matlab/dnorm.m
@@ -0,0 +1,11 @@
+function  f = dnorm(x,m,s)
+%DNORM 	  The normal density function
+%
+%         f = dnorm(x,Mean,StandardDeviation)
+
+%       Anders Holtsberg, 18-11-93
+%       Copyright (c) Anders Holtsberg
+
+if nargin<3, s=1; end
+if nargin<2, m=0; end
+f = exp(-0.5*((x-m)./s).^2)./(sqrt(2*pi)*s);
diff --git a/tags/v_3.062/matlab/dr1.m b/tags/v_3.062/matlab/dr1.m
new file mode 100644
index 0000000000000000000000000000000000000000..fefc49c4b91135c44ddb87f6f866f97f0d546322
--- /dev/null
+++ b/tags/v_3.062/matlab/dr1.m
@@ -0,0 +1,635 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function [dr,info]=dr1(dr,task)
+
+% info = 1: the model doesn't define current variables uniquely
+% 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
+
+  global jacobia_ iy_ ykmin_ ykmax_ gstep_ exo_nbr exo_det_nbr endo_nbr
+  global ex_ ex_det_ valf_ it_ exe_ exe_det_ xkmin_ xkmax_ stdexo_
+  global fname_ means_ Sigma_e_ lgy_
+  global eigval options_ M_ olr_state_
+
+
+  info = 0;
+  
+  options_ = set_default_option(options_,'loglinear',0);
+  options_ = set_default_option(options_,'noprint',0);
+  options_ = set_default_option(options_,'olr',0);
+  options_ = set_default_option(options_,'olr_beta',1);
+  options_ = set_default_option(options_,'qz_criterium',1.000001);
+
+xlen = xkmax_ + xkmin_ + 1;
+klen = ykmin_ + ykmax_ + 1;
+iyv = iy_';
+iyv = iyv(:);
+iyr0 = find(iyv) ;
+it_ = ykmin_ + 1 ;
+
+if exo_nbr == 0
+  exe_ = [] ;
+end
+
+tempex = ex_;
+
+it_ = ykmin_ + 1;
+if options_.olr
+  z = repmat(zeros(endo_nbr,1),1,klen);
+else
+  z = repmat(dr.ys,1,klen);
+end
+z = z(iyr0) ;
+jacobia_=real(jacob_a('ff1_',[z(:); exe_;exe_det_])) ;
+
+ex_ = tempex ;
+tempex = [];
+
+% expanding system for Optimal Linear Regulator
+if options_.olr
+  bet = options_.olr_beta;
+  jacobia1 = [];
+  n_inst = size(options_.olr_inst,1);
+
+  if ~isfield(olr_state_,'done')
+    olr_state_.done = 1;
+    olr_state_.old_ykmin_ = ykmin_;
+    olr_state_.old_ykmax_ = ykmax_;
+    olr_state_.old_endo_nbr = endo_nbr;
+    olr_state_.old_iy_ = iy_;
+    
+    for i=1:endo_nbr
+      temp = ['mult_' int2str(i)];
+      lgy_ = strvcat(lgy_,temp);
+    end
+    endo_nbr = 2*endo_nbr-n_inst;
+    ykmin_ = max(ykmin_,ykmax_);
+    ykmax_ = ykmin_;
+  end    
+  nj = olr_state_.old_endo_nbr-n_inst;
+  offset_min = ykmin_ - olr_state_.old_ykmin_;
+  offset_max = ykmax_ - olr_state_.old_ykmax_;
+  newiy = zeros(2*ykmin_+1,nj+olr_state_.old_endo_nbr);
+  jacobia_ = jacobia_(1:nj,:);
+  for i=1:2*ykmin_+1
+    if i > offset_min & i <= 2*ykmin_+1-offset_max
+      [junk,k1,k2] = find(olr_state_.old_iy_(i-offset_min,:));
+      if i == ykmin_+1
+	jacobia1 = [jacobia1 [jacobia_(:,k2); 2*options_.olr_w]];
+      else
+	jacobia1 = [jacobia1 [jacobia_(:,k2); ...
+		    zeros(olr_state_.old_endo_nbr,length(k1))]];
+      end
+      newiy(i,k1) = ones(1,length(k1));
+    end
+    i1  = 2*ykmin_+2-i;
+    if i1 <= 2*ykmin_+1-offset_max & i1 > offset_min 
+      [junk,k1,k2] = find(olr_state_.old_iy_(i1-offset_min,:));
+      k3 = find(any(jacobia_(:,k2),2));
+      x = zeros(olr_state_.old_endo_nbr,length(k3));
+      x(k1,:) = bet^(-i1+ykmin_+1)*jacobia_(k3,k2)';
+      jacobia1  = [jacobia1 [zeros(nj,length(k3)); x]];
+      newiy(i,k3+olr_state_.old_endo_nbr) = ones(1,length(k3));
+    end      
+  end
+  jacobia1 = [jacobia1 [jacobia_(:,end-exo_nbr+1:end); ...
+		    zeros(olr_state_.old_endo_nbr, exo_nbr)]];
+  newiy = newiy';
+  newiy = find(newiy(:));
+  iy_ = zeros(endo_nbr*(ykmin_+ykmax_+1),1);
+  iy_(newiy) = [1:length(newiy)]';
+  iy_ =reshape(iy_,endo_nbr,ykmin_+ykmax_+1)';
+  jacobia_ = jacobia1;
+  clear jacobia1
+  % computes steady state
+  resid = feval([fname_ '_fff'],zeros(olr_state_.old_endo_nbr,1));
+  if resid'*resid < 1e-12
+    dr.ys =[dr.ys; zeros(nj,1)];
+  else
+    AA = zeros(endo_nbr,endo_nbr);
+    for i=1:ykmin_+ykmax_+1
+      [junk,k1,k2] = find(iy_(i,:));
+      AA(:,k1) = AA(:,k1)+jacobia_(:,k2);
+    end
+    dr.ys = -AA\[resid; zeros(nj,1)];
+  end
+end
+% end of code section for Optimal Linear Regulator
+
+klen = ykmin_ + ykmax_ + 1;
+dr=set_state_space(dr);
+kstate = dr.kstate;
+kad = dr.kad;
+kae = dr.kae;
+nstatic = dr.nstatic;
+nfwrd = dr.nfwrd;
+npred = dr.npred;
+nboth = dr.nboth;
+order_var = dr.order_var;
+nd = size(kstate,1);
+
+sdyn = endo_nbr - nstatic;
+
+k0 = iy_(ykmin_+1,order_var);
+k1 = iy_(find([1:klen] ~= ykmin_+1),:);
+b = jacobia_(:,k0);
+
+if ykmax_ == 0;  % backward models
+  a = jacobia_(:,nonzeros(k1'));
+  dr.ghx = zeros(size(a));
+  m = 0;
+  for i=ykmin_:-1:1
+    k = nonzeros(iy_(i,order_var));
+    dr.ghx(:,m+[1:length(k)]) = -b\a(:,k);
+    m = m+length(k);
+  end
+  if exo_nbr
+    nz = nnz(iy_);
+    dr.ghu = -b\jacobia_(:,nz+1:end);
+  end
+  dr.eigval = eig(transition_matrix(dr));
+  dr.rank = 0;
+  if any(abs(dr.eigval) > options_.qz_criterium)
+    temp = sort(abs(dr.eigval));
+    nba = nnz(abs(dr.eigval) > options_.qz_criterium);
+    temp = temp(nd-nba+1:nd)-1-options_.qz_criterium;
+    info(1) = 3;
+    info(2) = temp'*temp;
+  end
+  return;
+end
+
+%forward--looking models
+if nstatic > 0
+  [Q,R] = qr(b(:,1:nstatic));
+  aa = Q'*jacobia_;
+else
+  aa = jacobia_;
+end
+a = aa(:,nonzeros(k1'));
+b = aa(:,k0);
+b10 = b(1:nstatic,1:nstatic);
+b11 = b(1:nstatic,nstatic+1:end);
+b2 = b(nstatic+1:end,nstatic+1:end);
+nz = nnz(iy_);
+if exo_nbr
+  fu = aa(:,nz+[1:exo_nbr]);
+end
+clear aa;
+
+% buildind D and E
+d = zeros(nd,nd) ;
+e = d ;
+
+k = find(kstate(:,2) >= ykmin_+2 & kstate(:,3));
+d(1:sdyn,k) = a(nstatic+1:end,kstate(k,3)) ;
+k1 = find(kstate(:,2) == ykmin_+2);
+e(1:sdyn,k1) =  -b2(:,kstate(k1,1)-nstatic);
+k = find(kstate(:,2) <= ykmin_+1 & kstate(:,4));
+e(1:sdyn,k) = -a(nstatic+1:end,kstate(k,4)) ;
+k2 = find(kstate(:,2) == ykmin_+1);
+k2 = k2(~ismember(kstate(k2,1),kstate(k1,1)));
+d(1:sdyn,k2) = b2(:,kstate(k2,1)-nstatic);
+
+if ~isempty(kad)
+  for j = 1:size(kad,1)
+    d(sdyn+j,kad(j)) = 1 ;
+    e(sdyn+j,kae(j)) = 1 ;
+  end
+end
+
+if ~exist('mjdgges')
+  % using Chris Sim's routines
+  use_qzdiv = 1;
+  [ss,tt,qq,w] = qz(e,d);
+  [tt,ss,qq,w] = qzdiv(options_.qz_criterium,tt,ss,qq,w);
+  ss1=diag(ss);
+  tt1=diag(tt);
+  warning_state = warning;
+  warning off;
+  dr.eigval = ss1./tt1 ;
+  warning warning_state;
+  nba = nnz(abs(dr.eigval) > options_.qz_criterium);
+else
+  use_qzdiv = 0;
+  [ss,tt,w,sdim,dr.eigval,info1] = mjdgges(e,d,options_.qz_criterium);
+  if info1
+    info(1) = 2;
+    info(2) = info1;
+    return
+  end
+  nba = nd-sdim;
+end
+
+nyf = sum(kstate(:,2) > ykmin_+1);
+
+if task == 1
+  dr.rank = rank(w(1:nyf,nd-nyf+1:end));
+  dr.eigval = eig(e,d);
+  return
+end
+
+if nba ~= nyf
+  temp = sort(abs(dr.eigval));
+  if nba > nyf
+    temp = temp(nd-nba+1:nd-nyf)-1-options_.qz_criterium;
+    info(1) = 3
+  elseif nba < nyf;
+    temp = temp(nd-nyf+1:nd-nba)-1-options_.qz_criterium;
+    info(1) = 4;
+  end
+  info(2) = temp'*temp;
+  return
+end
+
+np = nd - nyf;
+n2 = np + 1;
+n3 = nyf;
+n4 = n3 + 1;
+% derivatives with respect to dynamic state variables
+% forward variables
+w1 =w(1:n3,n2:nd);
+if condest(w1) > 1e9;
+  info(1) = 5;
+  info(2) = condest(w1);
+  return;
+else
+  gx = -w1'\w(n4:nd,n2:nd)';
+end  
+
+% predetermined variables
+hx = w(1:n3,1:np)'*gx+w(n4:nd,1:np)';
+hx = (tt(1:np,1:np)*hx)\(ss(1:np,1:np)*hx);
+
+k1 = find(kstate(n4:nd,2) == ykmin_+1);
+k2 = find(kstate(1:n3,2) == ykmin_+2);
+dr.ghx = [hx(k1,:); gx(k2(nboth+1:end),:)];
+
+%lead variables actually present in the model
+j3 = nonzeros(kstate(:,3));
+j4  = find(kstate(:,3));
+% derivatives with respect to exogenous variables
+if exo_nbr
+  a1 = b;
+  aa1 = [];
+  if nstatic > 0
+    aa1 = a1(:,1:nstatic);
+  end
+  dr.ghu = -[aa1 a(:,j3)*gx(j4,1:npred)+a1(:,nstatic+1:nstatic+ ...
+						  npred) a1(:,nstatic+npred+1:end)]\fu;
+end
+
+% static variables
+if nstatic > 0
+  temp = -a(1:nstatic,j3)*gx(j4,:)*hx;
+  j5 = find(kstate(n4:nd,4));
+  temp(:,j5) = temp(:,j5)-a(1:nstatic,nonzeros(kstate(:,4)));
+  temp = b10\(temp-b11*dr.ghx);
+  dr.ghx = [temp; dr.ghx];
+  temp = [];
+end
+
+if options_.loglinear == 1
+    k = find(dr.kstate(:,2) <= ykmin_+1);
+    klag = dr.kstate(k,[1 2]);
+    k1 = dr.order_var;
+
+    dr.ghx = repmat(1./dr.ys(k1),1,size(dr.ghx,2)).*dr.ghx.* ...
+	     repmat(dr.ys(k1(klag(:,1)))',size(dr.ghx,1),1);
+    dr.ghu = repmat(1./dr.ys(k1),1,size(dr.ghu,2)).*dr.ghu;
+end
+
+%necessary when using Sims' routines
+if use_qzdiv
+  gx = real(gx);
+  hx = real(hx);
+  dr.ghx = real(dr.ghx);
+  dr.ghu = real(dr.ghu);
+end
+
+%exogenous deterministic variables
+if exo_det_nbr > 0
+  f1 = sparse(jacobia_(:,nonzeros(iy_(ykmin_+2:end,order_var))));
+  f0 = sparse(jacobia_(:,nonzeros(iy_(ykmin_+1,order_var))));
+  fudet = sparse(jacobia_(:,nz+exo_nbr+1:end));
+  M1 = inv(f0+[zeros(endo_nbr,nstatic) f1*gx zeros(endo_nbr,nyf-nboth)]);
+  M2 = M1*f1;
+  dr.ghud = cell(M_.ex_det_length,1);
+  dr.ghud{1} = -M1*fudet;
+  for i = 2:M_.ex_det_length
+    dr.ghud{i} = -M2*dr.ghud{i-1}(end-nyf+1:end,:);
+  end
+end
+
+if options_.order == 1
+  return
+end
+
+% Second order
+tempex = ex_ ;
+
+%hessian = real(hessext('ff1_',[z; exe_]))' ;
+kk = flipud(cumsum(flipud(iy_(ykmin_+1:end,order_var)),1));
+if ykmin_ > 0
+  kk = [cumsum(iy_(1:ykmin_,order_var),1); kk];
+end
+kk = kk';
+kk = find(kk(:));
+nk = size(kk,1)+exo_nbr+exo_det_nbr;
+k1 = iy_(:,order_var);
+k1 = k1';
+k1 = k1(:);
+k1 = k1(kk);
+k2 = find(k1);
+kk1(k1(k2)) = k2;
+kk1 = [kk1 length(k1)+1:length(k1)+exo_nbr+exo_det_nbr];
+kk = reshape([1:nk^2],nk,nk);
+kk1 = kk(kk1,kk1);
+hessian = zeros(endo_nbr,nk^2);
+hessian(:,kk1(:)) = real(hessian_sparse('ff1_',[z; exe_;exe_det_])) ;
+
+ex_ = tempex ;
+clear tempex
+
+n1 = 0;
+n2 = np;
+zx = zeros(np,np);
+zu=zeros(np,exo_nbr);
+for i=2:ykmin_+1
+  k1 = sum(kstate(:,2) == i);
+  zx(n1+1:n1+k1,n2-k1+1:n2)=eye(k1);
+  n1 = n1+k1;
+  n2 = n2-k1;
+end
+kk = flipud(cumsum(flipud(iy_(ykmin_+1:end,order_var)),1));
+k0 = [1:endo_nbr];
+gx1 = dr.ghx;
+hu = dr.ghu(nstatic+[1:npred],:);
+zx = [zx; gx1];
+zu = [zu; dr.ghu];
+for i=1:ykmax_
+  k1 = find(kk(i+1,k0) > 0);
+  zu = [zu; gx1(k1,1:npred)*hu];
+  gx1 = gx1(k1,:)*hx;
+  zx = [zx; gx1];
+  kk = kk(:,k0);
+  k0 = k1;
+end
+zx=[zx; zeros(exo_nbr,np);zeros(exo_det_nbr,np)];
+zu=[zu; eye(exo_nbr);zeros(exo_det_nbr,exo_nbr)];
+[n1,n2] = size(zx);
+if n1*n1*n2*n2 > 1e7
+  rhs = zeros(endo_nbr,n2*n2);
+  k1 = 1;
+  for i1 = 1:n2
+      for i2 = 1:n2
+	rhs(:,k1) = hessian*kron(zx(:,i1),zx(:,i2));
+	k1 = k1 + 1; 
+      end
+  end
+else
+  rhs = hessian*kron(zx,zx);
+end
+rhs = -rhs;
+
+%lhs
+n = endo_nbr+sum(kstate(:,2) > ykmin_+1 & kstate(:,2) < ykmin_+ykmax_+1);
+A = zeros(n,n);
+B = zeros(n,n);
+[junk,k1,k2] = find(iy_(ykmin_+ykmax_+1,order_var));
+gx2 = dr.ghx(k1,:);
+A(1:endo_nbr,1:endo_nbr) = jacobia_(:,iy_(ykmin_+1,order_var));
+A(1:endo_nbr,nstatic+1:nstatic+npred)=...
+    A(1:endo_nbr,nstatic+[1:npred])+jacobia_(:,k2)*gx2(:,1:npred);
+% variables with the highest lead
+k1 = find(kstate(:,2) == ykmin_+ykmax_+1);
+if ykmax_ > 1
+  k2 = find(kstate(:,2) == ykmin_+ykmax_);
+  [junk,junk,k3] = intersect(kstate(k1,1),kstate(k2,1));
+else
+  k2 = [1:endo_nbr];
+  k3 = kstate(k1,1);
+end
+% Jacobian with respect to the variables with the highest lead
+B(1:endo_nbr,end-length(k2)+k3) = jacobia_(:,kstate(k1,3)+endo_nbr);
+offset = endo_nbr;
+k0 = [1:endo_nbr];
+for i=1:ykmax_-1
+  k1 = find(kstate(:,2) == ykmin_+i+1);
+  [k2,junk,k3] = find(kstate(k1,3));
+  A(1:endo_nbr,offset+k2) = jacobia_(:,k3+endo_nbr);
+  n1 = length(k1);
+  A(offset+[1:n1],nstatic+[1:npred]) = -gx(k1,1:npred); 
+  A(offset+[1:n1],offset+[1:n1]) = eye(n1);
+  n0 = length(k0);
+  E = eye(n0);
+  if i == 1
+    [junk,junk,k4]=intersect(kstate(k1,1),[1:endo_nbr]);
+  else
+    [junk,junk,k4]=intersect(kstate(k1,1),kstate(k0,1));
+  end
+  i1 = offset-n0+n1;
+  B(offset+[1:n1],offset-n0+[1:n0]) = -E(k4,:);
+  k0 = k1;
+  offset = offset + n1;
+end
+D = [rhs; zeros(n-endo_nbr,size(rhs,2))];
+if exist('gensylv')
+  C = hx;
+  dr.ghxx = gensylv(2,A,B,C,D);
+else
+  C = kron(hx,hx); 
+  x0 = sylvester3(A,B,C,D);
+  dr.ghxx = sylvester3a(x0,A,B,C,D);
+end
+
+%ghxu
+%rhs
+hu = dr.ghu(nstatic+1:nstatic+npred,:);
+%kk = reshape([1:np*np],np,np);
+%kk = kk(1:npred,1:npred);
+%rhs = -hessian*kron(zx,zu)-f1*dr.ghxx(end-nyf+1:end,kk(:))*kron(hx(1:npred,:),hu(1:npred,:));
+if n1*n1*n2*exo_nbr > 1e7
+  rhs = zeros(endo_nbr,n2*exo_nbr);
+  k1 = 1;
+  for i1 = 1:n2
+      for i2 = 1:exo_nbr
+	rhs(:,k1) = hessian*kron(zx(:,i1),zu(:,i2));
+	k1 = k1 + 1; 
+      end
+  end
+else
+  rhs = hessian*kron(zx,zu);
+end
+nyf1 = sum(kstate(:,2) == ykmin_+2);
+hu1 = [hu;zeros(np-npred,exo_nbr)];
+B1 = [B(1:endo_nbr,:);zeros(size(A,1)-endo_nbr,size(B,2))];
+rhs = -[rhs; zeros(n-endo_nbr,size(rhs,2))]-B1*dr.ghxx*kron(hx,hu1);
+
+%lhs
+dr.ghxu = A\rhs;
+
+%ghuu
+%rhs
+kk = reshape([1:np*np],np,np);
+kk = kk(1:npred,1:npred);
+if n1*n1*exo_nbr*exo_nbr > 1e7
+  rhs = zeros(endo_nbr,exo_nbr*exo_nbr);
+  k1 = 1;
+  for i1 = 1:exo_nbr
+      for i2 = 1:exo_nbr
+	rhs(:,k1) = hessian*kron(zu(:,i1),zu(:,i2));
+	k1 = k1 + 1; 
+      end
+  end
+else
+  rhs = hessian*kron(zu,zu);
+end
+
+rhs = -[rhs; zeros(n-endo_nbr,size(rhs,2))]-B*dr.ghxx*kron(hu1,hu1);
+
+%lhs
+dr.ghuu = A\rhs;
+
+dr.ghxx = dr.ghxx(1:endo_nbr,:);
+dr.ghxu = dr.ghxu(1:endo_nbr,:);
+dr.ghuu = dr.ghuu(1:endo_nbr,:);
+
+
+% dr.ghs2
+% derivatives of F with respect to forward variables
+% reordering predetermined variables in diminishing lag order
+O1 = zeros(endo_nbr,nstatic);
+O2 = zeros(endo_nbr,endo_nbr-nstatic-npred);
+LHS = jacobia_(:,iy_(ykmin_+1,order_var));
+RHS = zeros(endo_nbr,exo_nbr^2);
+kk = find(kstate(:,2) == ykmin_+2);
+gu = dr.ghu; 
+guu = dr.ghuu; 
+Gu = [dr.ghu(nstatic+[1:npred],:); zeros(np-npred,exo_nbr)];
+Guu = [dr.ghuu(nstatic+[1:npred],:); zeros(np-npred,exo_nbr*exo_nbr)];
+E = eye(endo_nbr);
+iy_ordered = flipud(cumsum(flipud(iy_(ykmin_+1:end,order_var)),1));
+if ykmin_ > 0
+  iy_ordered = [cumsum(iy_(1:ykmin_,order_var),1); iy_ordered];
+end
+iy_ordered = iy_ordered';
+iy_ordered = iy_ordered(:);
+k1 = find(iy_ordered);
+iy_ordered(k1) = [1:length(k1)]';
+iy_ordered =reshape(iy_ordered,endo_nbr,ykmin_+ykmax_+1)';
+kh = reshape([1:nk^2],nk,nk);
+kp = sum(kstate(:,2) <= ykmin_+1);
+E1 = [eye(npred); zeros(kp-npred,npred)];
+H = E1;
+hxx = dr.ghxx(nstatic+[1:npred],:);
+for i=1:ykmax_
+  for j=i:ykmax_
+    [junk,k2a,k2] = find(iy_(ykmin_+j+1,order_var));
+    [junk,k3a,k3] = find(iy_ordered(ykmin_+j+1,:));
+    RHS = RHS + jacobia_(:,k2)*guu(k2a,:)+hessian(:,kh(k3,k3))* ...
+	  kron(gu(k3a,:),gu(k3a,:));
+  end
+
+  % LHS
+  [junk,k2a,k2] = find(iy_(ykmin_+i+1,order_var));
+  LHS = LHS + jacobia_(:,k2)*(E(k2a,:)+[O1(k2a,:) dr.ghx(k2a,:)*H O2(k2a,:)]);
+  
+  if i == ykmax_ 
+    break
+  end
+  
+  kk = find(kstate(:,2) == ykmin_+i+1);
+  gu = dr.ghx*Gu;
+  GuGu = kron(Gu,Gu);
+  guu = dr.ghx*Guu+dr.ghxx*GuGu;
+  Gu = hx*Gu;
+  Guu = hx*Guu;
+  Guu(end-npred+1:end,:) = Guu(end-npred+1:end,:) + hxx*GuGu;
+
+  H = E1 + hx*H;
+end
+RHS = RHS*Sigma_e_(:);
+dr.fuu = RHS;
+RHS = -RHS-dr.fbias;
+dr.ghs2 = LHS\RHS;
+
+% deterministic exogenous variables
+if exo_det_nbr > 0
+  hud = dr.ghud{1}(nstatic+1:nstatic+npred,:);
+  zud=[zeros(np,exo_det_nbr);dr.ghud{1};gx(:,1:npred)*hud;zeros(exo_nbr,exo_det_nbr);eye(exo_det_nbr)];
+  R1 = hessian*kron(zx,zud);
+  dr.ghxud = cell(M_.ex_det_length,1);
+  kf = [endo_nbr-nyf+1:endo_nbr];
+  kp = nstatic+[1:npred];
+  dr.ghxud{1} = -M1*(R1+f1*dr.ghxx(kf,:)*kron(dr.ghx(kp,:),dr.ghud{1}(kp,:)));
+  Eud = eye(exo_det_nbr);
+  for i = 2:M_.ex_det_length
+    hudi = dr.ghud{i}(kp,:);
+    zudi=[zeros(np,exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi;zeros(exo_nbr+exo_det_nbr,exo_det_nbr)];
+    R2 = hessian*kron(zx,zudi);
+    dr.ghxud{i} = -M2*(dr.ghxud{i-1}(kf,:)*kron(hx,Eud)+dr.ghxx(kf,:)*kron(dr.ghx(kp,:),dr.ghud{i}(kp,:)))-M1*R2;
+  end
+  R1 = hessian*kron(zu,zud);
+  dr.ghudud = cell(M_.ex_det_length,1);
+  kf = [endo_nbr-nyf+1:endo_nbr];
+
+  dr.ghuud{1} = -M1*(R1+f1*dr.ghxx(kf,:)*kron(dr.ghu(kp,:),dr.ghud{1}(kp,:)));
+  Eud = eye(exo_det_nbr);
+  for i = 2:M_.ex_det_length
+    hudi = dr.ghud{i}(kp,:);
+    zudi=[zeros(np,exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi;zeros(exo_nbr+exo_det_nbr,exo_det_nbr)];
+    R2 = hessian*kron(zu,zudi);
+    dr.ghuud{i} = -M2*dr.ghxud{i-1}(kf,:)*kron(hu,Eud)-M1*R2;
+  end
+  R1 = hessian*kron(zud,zud);
+  dr.ghudud = cell(M_.ex_det_length,M_.ex_det_length);
+  dr.ghudud{1,1} = -M1*R1-M2*dr.ghxx(kf,:)*kron(hud,hud);
+  for i = 2:M_.ex_det_length
+    hudi = dr.ghud{i}(nstatic+1:nstatic+npred,:);
+    zudi=[zeros(np,exo_det_nbr);dr.ghud{i};gx(:,1:npred)*hudi+dr.ghud{i-1}(kf,:);zeros(exo_nbr+exo_det_nbr,exo_det_nbr)];
+    R2 = hessian*kron(zudi,zudi);
+    dr.ghudud{i,i} = -M2*(dr.ghudud{i-1,i-1}(kf,:)+...
+			  2*dr.ghxud{i-1}(kf,:)*kron(hudi,Eud) ...
+			  +dr.ghxx(kf,:)*kron(hudi,hudi))-M1*R2;
+    R2 = hessian*kron(zud,zudi);
+    dr.ghudud{1,i} = -M2*(dr.ghxud{i-1}(kf,:)*kron(hud,Eud)+...
+			  dr.ghxx(kf,:)*kron(hud,hudi))...
+	-M1*R2;
+    for j=2:i-1
+      hudj = dr.ghud{j}(kp,:);
+      zudj=[zeros(np,exo_det_nbr);dr.ghud{j};gx(:,1:npred)*hudj;zeros(exo_nbr+exo_det_nbr,exo_det_nbr)];
+      R2 = hessian*kron(zudj,zudi);
+      dr.ghudud{j,i} = -M2*(dr.ghudud{j-1,i-1}(kf,:)+dr.ghxud{j-1}(kf,:)* ...
+			    kron(hudi,Eud)+dr.ghxud{i-1}(kf,:)* ...
+			    kron(hudj,Eud)+dr.ghxx(kf,:)*kron(hudj,hudi))-M1*R2;
+    end
+    
+  end
+end
+% 01/08/2001 MJ put return on iorder == 1 after defining dr.kstate and dr.kdyn
+% 01/17/2001 MJ added dr.delta_s: correction factor for order = 2
+% 01/21/2001 FC correction of delta_s for more than 1 shock
+% 01/23/2001 MJ suppression of redundant sum() in delta_s formula
+% 02/22/2001 MJ stderr_ replaced by Sigma_e_
+% 08/24/2001 MJ changed the order of the variables, separates static
+%               variables and handles only one instance of variables both
+%               in lead and lag
+% 08/24/2001 MJ added sigma to state variables as in Schmitt-Grohe and
+%               Uribe (2001)
+% 10/20/2002 MJ corrected lags on several periods bug
+% 10/30/2002 MJ corrected lags on several periods bug on static when some
+%               intermediary lags are missing
+% 12/08/2002 MJ uses sylvester3 to solve for dr.ghxx
+% 01/01/2003 MJ added dr.fbias for iterative for dr_algo == 1
+% 02/21/2003 MJ corrected bug for models without lagged variables
+% 03/02/2003 MJ fixed second order for lag on several periods
+% 05/21/2003 MJ add check call argument and make computation for CHECK
+% 06/01/2003 MJ added a test for xkmax_ > 1 and order > 1
+% 08/28/2003 MJ corrected bug in computation of 2nd order (ordering of
+%               forward variable in LHS)
+% 08/29/2003 MJ use Sims routine if mjdgges isn't available
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/dr11.m b/tags/v_3.062/matlab/dr11.m
new file mode 100644
index 0000000000000000000000000000000000000000..743b0aa5ee0f6dc9debde49ea1e9068b614cf8ff
--- /dev/null
+++ b/tags/v_3.062/matlab/dr11.m
@@ -0,0 +1,256 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function dr=dr11(iorder,dr,check)
+
+global jacobia_ iy_ ykmin_ ykmax_ gstep_ exo_nbr endo_nbr
+global ex_ valf_ it_ exe_ xkmin_ xkmax_ ys_ stdexo_
+global fname_ means_ Sigma_e_ lgy_ options_
+global eigval
+% hack for Bayes
+global dr1_test_ bayestopt_
+
+options_ = set_default_option(options_,'loglinear',0);
+
+xlen = xkmax_ + xkmin_ + 1;
+klen = ykmin_ + ykmax_ + 1;
+iyv = iy_';
+iyv = iyv(:);
+iyr0 = find(iyv) ;
+it_ = ykmin_ + 1 ;
+
+
+if exo_nbr == 0
+  exe_ = [] ;
+end
+
+if ~ iy_(ykmin_+1,:) > 0
+  error ('Error in model specification: some variables don"t appear as current') ;
+end
+
+if ~check
+  if xlen > 1
+    error (['SS: stochastic exogenous variables must appear only at the' ...
+	    ' current period. Use additional endogenous variables']) ;
+  end
+end
+  
+if ykmax_ > 1 & iorder > 1
+  error (['Models with leads on more than one period can only be solved' ...
+	  ' at order 1'])
+end
+
+dr=set_state_space(dr);
+kstate = dr.kstate;
+kad = dr.kad;
+kae = dr.kae;
+nstatic = dr.nstatic;
+nfwrd = dr.nfwrd;
+npred = dr.npred;
+nboth = dr.nboth;
+order_var = dr.order_var;
+nd = size(kstate,1);
+
+sdyn = endo_nbr - nstatic;
+
+
+tempex = ex_;
+
+it_ = ykmin_ + 1;
+z = repmat(dr.ys,1,klen);
+z = z(iyr0) ;
+%jacobia_=real(diffext('ff1_',[z; exe_])) ;
+jacobia_=real(jacob_a('ff1_',[z; exe_])) ;
+
+ex_ = tempex ;
+tempex = [];
+
+nz = size(z,1);
+k1 = iy_(find([1:klen] ~= ykmin_+1),:);
+b = jacobia_(:,iy_(ykmin_+1,order_var));
+a = b\jacobia_(:,nonzeros(k1')); 
+if any(isinf(a(:)))
+  dr1_test_(1) = 5;
+  dr1_test_(2) = bayestopt_.penalty;
+end
+if exo_nbr
+  fu = b\jacobia_(:,nz+1:end);
+end
+
+if ykmax_ == 0 & ykmin_ == 1;  % backward model with one lag
+  dr.ghx = -a;
+  dr.ghu = -fu;
+  return;
+elseif ykmax_ == 0 & ykmin_ > 1 % backward model with lags on more than
+			       % one period
+  e = zeros(endo_nbr,nd);				
+  k = find(kstate(:,2) <= ykmin_+1 & kstate(:,4));
+  e(:,k) = -a(:,kstate(k,4)) ;
+  dr.ghx = e;
+  dr.ghu = -fu;
+  return;
+end
+
+% buildind D and E
+d = zeros(nd,nd) ;
+e = d ;
+
+k = find(kstate(:,2) >= ykmin_+2 & kstate(:,3));
+d(1:sdyn,k) = a(nstatic+1:end,kstate(k,3)) ;
+k1 = find(kstate(:,2) == ykmin_+2);
+a1 = eye(sdyn);
+e(1:sdyn,k1) =  -a1(:,kstate(k1,1)-nstatic);
+k = find(kstate(:,2) <= ykmin_+1 & kstate(:,4));
+e(1:sdyn,k) = -a(nstatic+1:end,kstate(k,4)) ;
+k2 = find(kstate(:,2) == ykmin_+1);
+k2 = k2(~ismember(kstate(k2,1),kstate(k1,1)));
+d(1:sdyn,k2) = a1(:,kstate(k2,1)-nstatic);
+
+if ~isempty(kad)
+  for j = 1:size(kad,1)
+    d(sdyn+j,kad(j)) = 1 ;
+    e(sdyn+j,kae(j)) = 1 ;
+  end
+end
+
+options_ = set_default_option(options_,'qz_criterium',1.000001);
+  
+if  ~exist('mjdgges')
+  % using Chris Sim's routines
+  use_qzdiv = 1;
+  [ss,tt,qq,w] = qz(e,d);
+  [tt,ss,qq,w] = qzdiv(options_.qz_criterium,tt,ss,qq,w);
+  ss1=diag(ss);
+  tt1=diag(tt);
+  warning_state = warning;
+  warning off;
+  eigval = ss1./tt1 ;
+  warning warning_state;
+  nba = nnz(abs(eigval) > options_.qz_criterium);
+else
+  use_qzdiv = 0;
+  [ss,tt,w,sdim,eigval,info] = mjdgges(e,d,options_.qz_criterium);
+  if info & info ~= nd+2;
+    error(['ERROR' info ' in MJDGGES.DLL']);
+  end
+  nba = nd-sdim;
+end
+
+nyf = sum(kstate(:,2) > ykmin_+1);
+
+if check
+  dr.rank = rank(w(1:nyf,nd-nyf+1:end));
+  dr.eigval = eigval;
+  return
+end
+
+eigenvalues = sort(eigval);
+
+if nba > nyf;
+%  disp('Instability !');  
+  dr1_test_(1) = 3; %% More eigenvalues superior to unity than forward variables ==> instability.
+  dr1_test_(2) = (abs(eigenvalues(nd-nba+1:nd-nyf))-1-1e-5)'*...
+      (abs(eigenvalues(nd-nba+1:nd-nyf))-1-1e-5);% Distance to Blanchard-Khan conditions (penalty)
+  return
+elseif nba < nyf;
+%  disp('Indeterminacy !');    
+  dr1_test_(1) = 2; %% ==> Indeterminacy. 
+  dr1_test_(2) = (abs(eigenvalues(nd-nyf+1:nd-nba))-1-1e-5)'*...
+      (abs(eigenvalues(nd-nyf+1:nd-nba))-1-1e-5);% Distance to Blanchard-Khan conditions (penality)    
+  %% warning('DR1: Blanchard-Kahn conditions are not satisfied. Run CHECK to learn more!');
+  return
+end
+
+np = nd - nyf;
+n2 = np + 1;
+n3 = nyf;
+n4 = n3 + 1;
+% derivatives with respect to dynamic state variables
+% forward variables
+
+if condest(w(1:n3,n2:nd)) > 1e9
+%  disp('Indeterminacy !!');
+  dr1_test_(1) = 2; 
+  dr1_test_(2) = 1;
+  return
+end
+
+warning_state = warning;
+lastwarn('');
+warning off;
+gx = -w(1:n3,n2:nd)'\w(n4:nd,n2:nd)';
+
+if length(lastwarn) > 0;
+%  disp('Indeterminacy !!');
+  dr1_test_(1) = 2; 
+  dr1_test_(2) = 1;
+  warning(warning_state);
+  return
+end
+
+% predetermined variables
+hx = w(1:n3,1:np)'*gx+w(n4:nd,1:np)';
+hx = (tt(1:np,1:np)*hx)\(ss(1:np,1:np)*hx);
+
+lastwarn('');
+if length(lastwarn) > 0;
+%  disp('Singularity problem in dr11.m');
+  dr1_test_(1) = 2; 
+  dr1_test_(2) = 1;
+  warning(warning_state);
+  return
+end
+
+k1 = find(kstate(n4:nd,2) == ykmin_+1);
+k2 = find(kstate(1:n3,2) == ykmin_+2);
+dr.ghx = [hx(k1,:); gx(k2(nboth+1:end),:)];
+  
+%lead variables actually present in the model
+j3 = nonzeros(kstate(:,3));
+j4  = find(kstate(:,3));
+% derivatives with respect to exogenous variables
+if exo_nbr
+  a1 = eye(endo_nbr);
+  aa1 = [];
+  if nstatic > 0
+    aa1 = a1(:,1:nstatic);
+  end
+  dr.ghu = -[aa1 a(:,j3)*gx(j4,1:npred)+a1(:,nstatic+1:nstatic+ ...
+						  npred) a1(:,nstatic+npred+1:end)]\fu;
+
+
+    lastwarn('');
+    if length(lastwarn) > 0;
+%    disp('Singularity problem in dr11.m');
+        dr1_test_(1) = 2; 
+        dr1_test_(2) = 1;
+        return
+    end
+end
+warning(warning_state);
+
+% static variables
+if nstatic > 0
+  temp = -a(1:nstatic,j3)*gx(j4,:)*hx;
+  j5 = find(kstate(n4:nd,4));
+  temp(:,j5) = temp(:,j5)-a(1:nstatic,nonzeros(kstate(:,4)));
+  dr.ghx = [temp; dr.ghx];
+  temp = [];
+end
+
+if options_.loglinear == 1
+    k = find(dr.kstate(:,2) <= ykmin_+1);
+    klag = dr.kstate(k,[1 2]);
+    k1 = dr.order_var;
+
+    dr.ghx = repmat(1./dr.ys(k1),1,size(dr.ghx,2)).*dr.ghx.* ...
+	     repmat(dr.ys(k1(klag(:,1)))',size(dr.ghx,1),1);
+    dr.ghu = repmat(1./dr.ys(k1),1,size(dr.ghu,2)).*dr.ghu;
+end
+
+% necessary when using Sims' routines
+if use_qzdiv
+  gx = real(gx);
+  hx = real(hx);
+  dr.ghx = real(dr.ghx);
+  dr.ghu = real(dr.ghu);
+end
diff --git a/tags/v_3.062/matlab/dr2.m b/tags/v_3.062/matlab/dr2.m
new file mode 100644
index 0000000000000000000000000000000000000000..e1d6e7c0b7788cc22b34418b53a3714728b742a7
--- /dev/null
+++ b/tags/v_3.062/matlab/dr2.m
@@ -0,0 +1,11 @@
+% Copyright (C) 2001 Michel Juillard
+%
+% function used for dr_algo == 1
+function ghs2=dr2(ys,dr)
+  global fname_
+  
+  dr.ys = ys;
+  fh = str2func([fname_ '_fff']);
+  dr.fbias = 2*feval(fh,dr.ys);
+  dr=dr1(dr,0);
+  ghs2 = dr.ghs2;
diff --git a/tags/v_3.062/matlab/draw_prior_density.m b/tags/v_3.062/matlab/draw_prior_density.m
new file mode 100644
index 0000000000000000000000000000000000000000..1a4fcfbf62ac4e76b2f889f69de0334e6cd40b0f
--- /dev/null
+++ b/tags/v_3.062/matlab/draw_prior_density.m
@@ -0,0 +1,91 @@
+
+function [x,f,abscissa,dens,binf,bsup] = draw_prior_density(indx);
+% stephane.adjemian@cepremap.cnrs.fr [07-15-2004]
+
+global bayestopt_
+
+pmean   = bayestopt_.pmean;
+pshape  = bayestopt_.pshape; 
+p1      = bayestopt_.p1;
+p2      = bayestopt_.p2;
+p3      = bayestopt_.p3;
+p4      = bayestopt_.p4;
+
+truncprior = 10^(-3);
+
+if pshape(indx) == 1     %/* BETA Prior */
+    density = inline('((bb-x).^(b-1)).*(x-aa).^(a-1)./(beta(a,b)*(bb-aa)^(a+b-1))','x','a','b','aa','bb');
+    mu = (p1(indx)-p3(indx))/(p4(indx)-p3(indx));
+    stdd = p2(indx)/(p4(indx)-p3(indx));
+    a = (1-mu)*mu^2/stdd^2 - mu;
+    b = a*(1/mu-1);
+    aa = p3(indx);
+    bb = p4(indx);
+    infbound = qbeta(truncprior,a,b)*(bb-aa)+aa;
+    supbound = qbeta(1-truncprior,a,b)*(bb-aa)+aa;
+    stepsize = (supbound-infbound)/200;
+    abscissa = infbound:stepsize:supbound;
+    dens = density(abscissa,a,b,aa,bb);
+elseif pshape(indx) == 2  %/* GAMMA PRIOR */
+    mu = p1(indx)-p3(indx);
+    b  = p2(indx)^2/mu;
+    a  = mu/b;
+    infbound = mj_qgamma(truncprior,a)*b; 
+    supbound = mj_qgamma(1-truncprior,a)*b;
+    stepsize = (supbound-infbound)/200;
+    abscissa = infbound:stepsize:supbound;
+    dens = exp(lpdfgam(abscissa,a,b));
+    abscissa = abscissa + p3(indx);
+elseif pshape(indx) == 3  %/* GAUSSIAN PRIOR */
+    density = inline('inv(sqrt(2*pi)*b)*exp(-0.5*((x-a)/b).^2)','x','a','b');
+    a = p1(indx);
+    b = p2(indx);
+    infbound = qnorm(truncprior,a,b); 
+    supbound = qnorm(1-truncprior,a,b);
+    stepsize = (supbound-infbound)/200;
+    abscissa = infbound:stepsize:supbound;
+    dens = density(abscissa,a,b);  
+elseif pshape(indx) == 4  %/* INVGAMMA PRIOR type 1 */
+    density = inline('2*inv(gamma(nu/2))*(x.^(-nu-1))*((s/2)^(nu/2)).*exp(-s./(2*x.^2))','x','s','nu');
+    nu = p2(indx);
+    s  = p1(indx);
+    a  = nu/2;
+    b  = 2/s;
+    infbound = 1/sqrt(mj_qgamma(1-10*truncprior,a)*b); 
+    supbound = 1/sqrt(mj_qgamma(10*truncprior,a)*b);
+    stepsize = (supbound-infbound)/200;
+    abscissa = infbound:stepsize:supbound;
+    dens = density(abscissa,s,nu);  
+elseif pshape(indx) == 5  %/* UNIFORM PRIOR */
+    density = inline('(x.^0)/(b-a)','x','a','b');
+    a  = p1(indx);
+    b  = p2(indx);
+    infbound = a; 
+    supbound = b;
+    stepsize = (supbound-infbound)/200;
+    abscissa = infbound:stepsize:supbound;
+    dens = density(abscissa,a,b);  
+elseif pshape(indx) == 6  %/*  INVGAMMA PRIOR type 2 */        
+    density = inline('inv(gamma(nu/2))*(x.^(-.5(nu+2)))*((s/2)^(nu/2)).*exp(-s./(2*x))','x','s','nu');
+    nu = p2(indx);
+    s  = p1(indx);
+    a  = nu/2;
+    b  = 2/s;
+    infbound = 1/(qgamma(1-truncprior,a)*b); 
+    supbound = 1/(qgamma(truncprior,a)*b);
+    stepsize = (supbound-infbound)/200;
+    abscissa = infbound:stepsize:supbound;
+    dens = density(abscissa,s,nu);  
+end 
+
+k = [1:length(dens)];
+if pshape(indx) ~= 5 
+    [junk,k1] = max(dens);
+    if k1 == 1 | k1 == length(dens)
+        k = find(dens < 10);
+    end
+end
+binf = abscissa(k(1));
+bsup = abscissa(k(length(k)));
+x = abscissa(k);
+f = dens(k);
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/dsample.m b/tags/v_3.062/matlab/dsample.m
new file mode 100644
index 0000000000000000000000000000000000000000..1d1dd97812a229fa4f9c6d1de1c793bb35fd4c96
--- /dev/null
+++ b/tags/v_3.062/matlab/dsample.m
@@ -0,0 +1,36 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function dsample(s1,s2)
+% DSAMPLE :	DSAMPLE(d1,d2)
+%		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 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 
+		
+global dsmpl_ iter_
+
+dsmpl_ = zeros(2,1) ;
+
+if s1 > iter_ | s2 > iter_
+  t = ['DYNARE dsample error: one of the arguments is larger than the one' ...
+       ' specified in PERIODS'];
+  error(t);
+end
+
+if nargin == 0
+	dsmpl_(1) = 1 ;
+	dsmpl_(2) = iter_ ;
+elseif nargin == 1
+	dsmpl_(1) = 1 ;
+	dsmpl_(2) = s1 ;
+else
+	dsmpl_(1) = s1 ;
+	dsmpl_(2) = s2 ;
+end
+
+% 02/23/01 MJ added error checking
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/dy_date.m b/tags/v_3.062/matlab/dy_date.m
new file mode 100644
index 0000000000000000000000000000000000000000..b32531a2d13cb9bcb096eb4811fb22758e710c2e
--- /dev/null
+++ b/tags/v_3.062/matlab/dy_date.m
@@ -0,0 +1,6 @@
+function y=dy_date(year,period)
+  global start_date freq_
+  
+  y = freq_*(year-start_date(1))+period-start_date(2)+1;
+  
+  
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/dyn2vec.m b/tags/v_3.062/matlab/dyn2vec.m
new file mode 100644
index 0000000000000000000000000000000000000000..8fd5cb60a846fe031aaba84f8f3089f4c2e16963
--- /dev/null
+++ b/tags/v_3.062/matlab/dyn2vec.m
@@ -0,0 +1,59 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function [z,zss]=dyn2vec(s1,s2);
+
+  global lgy_ lgx_ y_ ys_ ykmin_ xkmin_ ex_ dsmpl_
+
+  if dsmpl_ == 0
+    k = [1:size(y_,2)];
+  else
+    k = [ykmin_+dsmpl_(1):ykmin_+dsmpl_(2)];
+  end
+
+  if nargin == 0
+    if nargout > 0
+      t = ['DYNARE dyn2vec error: the function doesn''t return values when' ...
+	   ' used without input argument'];
+      error(t);
+    end
+    for i=1:size(y_,1)
+      assignin('base',deblank(lgy_(i,:)),y_(i,k)');
+    end
+    return
+  else
+    j = strmatch(s1,lgy_,'exact'); 
+    if ~ isempty(j)
+      z = y_(j,k)';
+    else
+      j = strmatch(s1,lgx_,'exact');
+      if ~ isempty(j)
+	if dsmpl_ == 0
+	  z = ex_(:,j);
+	else
+	  z = ex_(xkmin_+dsmpl_(1):xkmin_+dsmpl_(2));
+	end
+      else
+	t = ['DYNARE dyn2vec error: variable ' deblank(s1(i,:)) ' doesn''t' ...
+	     ' exist.'] ;
+	error (t) ;
+      end
+    end
+  end
+
+  if nargout == 0
+    if nargin == 1
+      assignin('base',s1,z);
+    elseif nargin == 2
+      assignin('base',s2,z);
+    end
+  else
+    zss=ys_(j);
+  end
+  
+% 02/23/01 MJ redone, incorporating FC's improvements
+% 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/tags/v_3.062/matlab/dyn_bvar.m b/tags/v_3.062/matlab/dyn_bvar.m
new file mode 100644
index 0000000000000000000000000000000000000000..cdc2c9caf5fd6013caa20f12ab4bfe7fd1ce4897
--- /dev/null
+++ b/tags/v_3.062/matlab/dyn_bvar.m
@@ -0,0 +1,202 @@
+function dyn_bvar(maxnlags,tau,d,lambda,mu,omega,train,flat,breaks)
+% stephane.adjemian@cepremap.cnrs.fr [21 april, 2004]
+
+
+global options_
+
+eval(options_.datafile);
+dataset = [ ];
+
+for i=1:size(options_.varobs,1)
+    dataset = [dataset eval(deblank(options_.varobs(i,:)))];
+end    
+
+default_nlags  = 8;
+default_const  = 1;
+default_tau    = 3;
+default_d      = 0.5;
+default_lambda = 5;
+default_mu     = 2;
+default_omega  = 1;
+
+if nargin == 0
+    maxnlags =  default_nlags;
+    tau      =  default_tau;
+    d        =  default_d;
+    lambda   =  default_lambda;    
+    mu       =  default_mu;
+    omega    =  default_omega;
+    breaks   = [];
+    train    = [];
+    flat     = 0;
+elseif nargin == 1
+    tau    =  default_tau;
+    d      =  default_d;
+    lambda =  default_lambda;    
+    mu     =  default_mu;
+    omega  =  default_omega;
+    breaks = [];
+    train  = [];
+    flat   = 0;
+elseif nargin == 2
+    if isempty(maxnlags)
+        maxnlags = default_nlags;
+    end   
+    d      =  default_d;
+    lambda =  default_lambda;    
+    mu     =  default_mu;
+    omega  =  default_omega;
+    breaks = [];
+    train  = [];
+    flat   = 0;
+elseif nargin == 3
+    if isempty(maxnlags)
+        maxnlags = default_nlags;
+    end   
+    if isempty(tau)
+        tau = default_tau;
+    end   
+    lambda =  default_lambda;    
+    mu     =  default_mu;
+    omega  =  default_omega;
+    breaks = [];
+    train  = [];
+    flat   = 0;
+elseif nargin == 4
+    if isempty(maxnlags)
+        maxnlags = default_nlags;
+    end   
+    if isempty(tau)
+        tau   = default_tau;
+    end
+    if isempty(d)
+        d     = default_d;
+    end   
+    mu     =  default_mu;
+    omega  =  default_omega;
+    breaks = [];
+    train  = [];
+    flat   = 0;
+elseif nargin == 5
+    if isempty(maxnlags)
+        maxnlags = default_nlags;
+    end   
+    if isempty(tau)
+        tau   = default_tau;
+    end   
+    if isempty(d)
+        d     = default_d;
+    end   
+    if isempty(lambda)
+        lambda =  default_lambda;    
+    end    
+    omega  =  default_omega;
+    breaks = [];
+    train  = [];
+    flat   = 0;
+elseif nargin == 6
+    if isempty(maxnlags)
+        maxnlags = default_nlags;
+    end   
+    if isempty(tau)
+        tau = default_tau;
+    end   
+    if isempty(d)
+        d = default_d;
+    end   
+    if isempty(lambda)
+        lambda = default_lambda;
+    end   
+    if isempty(mu)
+        mu = default_mu;
+    end   
+    train  = [];
+    flat   = 0;
+    breaks = [];
+elseif nargin == 7
+    if isempty(maxnlags)
+        maxnlags = default_nlags;
+    end   
+    if isempty(tau)
+        tau = default_tau;
+    end   
+    if isempty(d)
+        d = default_d;
+    end   
+    if isempty(lambda)
+        lambda = default_lambda;
+    end   
+    if isempty(mu)
+        mu = default_mu;
+    end
+    if isempty(omega)
+        omega = default_omega;
+    end   
+    flat   = 0;
+    breaks = [];
+elseif nargin == 8
+    if isempty(maxnlags)
+        maxnlags = default_nlags;
+    end   
+    if isempty(const)
+        const = default_const;
+    end   
+    if isempty(tau)
+        tau = default_tau;
+    end   
+    if isempty(d)
+        d = default_d;
+    end   
+    if isempty(lambda)
+        lambda = default_lambda;
+    end   
+    if isempty(mu)
+        mu = default_mu;
+    end
+    if isempty(omega)
+        omega = default_omega;
+    end
+    breaks = [];
+    train  = [];
+elseif nargin == 9
+    if isempty(maxnlags)
+        maxnlags = default_nlags;
+    end   
+    if isempty(const)
+        const = default_const;
+    end   
+    if isempty(tau)
+        tau = default_tau;
+    end   
+    if isempty(d)
+        d = default_d;
+    end   
+    if isempty(lambda)
+        lambda = default_lambda;
+    end   
+    if isempty(mu)
+        mu = default_mu;
+    end
+    if isempty(omega)
+        omega = default_omega;
+    end
+    train = [];
+    flat  = 0;
+elseif nargin > 9
+    disp('dyn_bvar :: too many arguments.')
+end
+
+mnprior.tight = tau;
+mnprior.decay = d;
+vprior.sig = std(dataset(options_.first_obs+options_.presample-maxnlags:options_.first_obs+options_.presample-1,:))';
+vprior.w = omega;
+
+
+for lag = 1:maxnlags
+    ydata = dataset(options_.first_obs+options_.presample-lag:options_.first_obs+options_.presample+options_.nobs-1,:);
+    w=mgnldnsty(ydata,lag,ones(options_.nobs+lag,1),breaks,lambda,mu,mnprior,vprior,train,flat);
+    disp(' ')
+    fprintf('The marginal log density of the BVAR(%g) model is equal to %10.4f \n',lag,w);
+    disp(' ')
+end
+
diff --git a/tags/v_3.062/matlab/dyn_bvar2.m b/tags/v_3.062/matlab/dyn_bvar2.m
new file mode 100644
index 0000000000000000000000000000000000000000..356e1fa1847ce734bc43f8bb9a35760457e12932
--- /dev/null
+++ b/tags/v_3.062/matlab/dyn_bvar2.m
@@ -0,0 +1,206 @@
+function dyn_bvar(maxnlags,tau,d,lambda,mu,omega,train,flat,breaks)
+% stephane.adjemian@cepremap.cnrs.fr [22 april, 2004]
+
+
+global options_
+
+eval(options_.datafile);
+dataset = [ ];
+
+for i=1:size(options_.varobs,1)
+    dataset = [dataset eval(deblank(options_.varobs(i,:)))];
+end    
+
+default_nlags  = 8;
+default_const  = 1;
+default_tau    = 3;
+default_d      = 0.5;
+default_lambda = 5;
+default_mu     = 2;
+default_omega  = 1;
+
+if nargin == 0
+    maxnlags =  default_nlags;
+    tau      =  default_tau;
+    d        =  default_d;
+    lambda   =  default_lambda;    
+    mu       =  default_mu;
+    omega    =  default_omega;
+    breaks   = [];
+    train    = [];
+    flat     = 0;
+elseif nargin == 1
+    tau    =  default_tau;
+    d      =  default_d;
+    lambda =  default_lambda;    
+    mu     =  default_mu;
+    omega  =  default_omega;
+    breaks = [];
+    train  = [];
+    flat   = 0;
+elseif nargin == 2
+    if isempty(maxnlags)
+        maxnlags = default_nlags;
+    end   
+    d      =  default_d;
+    lambda =  default_lambda;    
+    mu     =  default_mu;
+    omega  =  default_omega;
+    breaks = [];
+    train  = [];
+    flat   = 0;
+elseif nargin == 3
+    if isempty(maxnlags)
+        maxnlags = default_nlags;
+    end   
+    if isempty(tau)
+        tau = default_tau;
+    end   
+    lambda =  default_lambda;    
+    mu     =  default_mu;
+    omega  =  default_omega;
+    breaks = [];
+    train  = [];
+    flat   = 0;
+elseif nargin == 4
+    if isempty(maxnlags)
+        maxnlags = default_nlags;
+    end   
+    if isempty(tau)
+        tau   = default_tau;
+    end
+    if isempty(d)
+        d     = default_d;
+    end   
+    mu     =  default_mu;
+    omega  =  default_omega;
+    breaks = [];
+    train  = [];
+    flat   = 0;
+elseif nargin == 5
+    if isempty(maxnlags)
+        maxnlags = default_nlags;
+    end   
+    if isempty(tau)
+        tau   = default_tau;
+    end   
+    if isempty(d)
+        d     = default_d;
+    end   
+    if isempty(lambda)
+        lambda =  default_lambda;    
+    end    
+    omega  =  default_omega;
+    breaks = [];
+    train  = [];
+    flat   = 0;
+elseif nargin == 6
+    if isempty(maxnlags)
+        maxnlags = default_nlags;
+    end   
+    if isempty(tau)
+        tau = default_tau;
+    end   
+    if isempty(d)
+        d = default_d;
+    end   
+    if isempty(lambda)
+        lambda = default_lambda;
+    end   
+    if isempty(mu)
+        mu = default_mu;
+    end   
+    train  = [];
+    flat   = 0;
+    breaks = [];
+elseif nargin == 7
+    if isempty(maxnlags)
+        maxnlags = default_nlags;
+    end   
+    if isempty(tau)
+        tau = default_tau;
+    end   
+    if isempty(d)
+        d = default_d;
+    end   
+    if isempty(lambda)
+        lambda = default_lambda;
+    end   
+    if isempty(mu)
+        mu = default_mu;
+    end
+    if isempty(omega)
+        omega = default_omega;
+    end   
+    flat   = 0;
+    breaks = [];
+elseif nargin == 8
+    if isempty(maxnlags)
+        maxnlags = default_nlags;
+    end   
+    if isempty(const)
+        const = default_const;
+    end   
+    if isempty(tau)
+        tau = default_tau;
+    end   
+    if isempty(d)
+        d = default_d;
+    end   
+    if isempty(lambda)
+        lambda = default_lambda;
+    end   
+    if isempty(mu)
+        mu = default_mu;
+    end
+    if isempty(omega)
+        omega = default_omega;
+    end
+    breaks = [];
+    train  = [];
+elseif nargin == 9
+    if isempty(maxnlags)
+        maxnlags = default_nlags;
+    end   
+    if isempty(const)
+        const = default_const;
+    end   
+    if isempty(tau)
+        tau = default_tau;
+    end   
+    if isempty(d)
+        d = default_d;
+    end   
+    if isempty(lambda)
+        lambda = default_lambda;
+    end   
+    if isempty(mu)
+        mu = default_mu;
+    end
+    if isempty(omega)
+        omega = default_omega;
+    end
+    train = [];
+    flat  = 0;
+elseif nargin > 9
+    disp('dyn_bvar :: too many arguments.')
+end
+
+mnprior.tight = tau;
+mnprior.decay = d;
+
+yy = dataset(1:options_.first_obs+options_.presample-1,:);
+bb = inv(yy(1:size(yy,1)-1,:)'*yy(1:size(yy,1)-1,:))*yy(1:size(yy,1)-1,:)'*yy(2:size(yy,1),:);
+rr = yy(2:size(yy,1),:)-yy(1:size(yy,1)-1,:)*bb;
+vprior.sig = sqrt(diag(rr'*rr/(size(yy,1)-1)))';
+vprior.w = omega;
+
+% mgnldnsty(ydata,lags,xdata,breaks,lambda,mu,mnprior,vprior,train,flat)
+
+for lag = 1:maxnlags
+    ydata = dataset(options_.first_obs+options_.presample-lag:options_.first_obs+options_.presample+options_.nobs-1,:);
+    w=mgnldnsty(ydata,lag,ones(options_.nobs+lag,1),breaks,lambda,mu,mnprior,vprior,train,flat);
+    disp(' ')
+    fprintf('The marginal log density of the BVAR(%g) model is equal to %10.4f \n',lag,w);
+    disp(' ')
+end
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/dynare.m b/tags/v_3.062/matlab/dynare.m
new file mode 100644
index 0000000000000000000000000000000000000000..4c3e19471a03dbb05c02b0e6b30cf575e2b5df10
--- /dev/null
+++ b/tags/v_3.062/matlab/dynare.m
@@ -0,0 +1,32 @@
+% Copyright (C) 2001 Michel Juillard
+%
+%	DYNARE ( 'Filename' )
+%	This command runs the .MOD file (or .DYN) specified in Filename.
+%	Filename could be enter with or without the .MOD extension.
+function dynare(fname,varargin)
+
+if ~ isstr(fname)
+	error ('The argument in DYNARE must be a text string.') ;
+end
+
+pathfile = mfilename('fullpath');
+command = [pathfile,'_m ',fname];
+for i=2:nargin
+  command = [command ' ' varargin{i-1}];
+end
+[status, result] = dos (command) ;
+if status
+  error(result)
+end
+
+if ~ isempty(find(abs(fname) == 46))
+	fname = fname(:,1:find(abs(fname) == 46)-1) ;
+end
+
+evalin('base',fname) ;
+
+
+% MJ 2/9/99: replace clear function by clear ff_
+% MJ 4/7/00: change the path of dynare_m
+% MJ 02/26/01: replaced local variable x by fname
+% MJ 09/19/01: evaluates mod script in 'base' workspace
diff --git a/tags/v_3.062/matlab/dynare_estimation.m b/tags/v_3.062/matlab/dynare_estimation.m
new file mode 100644
index 0000000000000000000000000000000000000000..fd6098f679b330f26ec52ae8329e661b01df287a
--- /dev/null
+++ b/tags/v_3.062/matlab/dynare_estimation.m
@@ -0,0 +1,1353 @@
+function dynare_estimation(varlist)
+global options_ bayestopt_ estim_params_ lgy_ lgx_ Sigma_e_ exo_nbr endo_nbr
+global lgy_ lgx_ fname_ oo_  trend_coeff_  iy_ ykmin_ lgx_TeX_ lgy_TeX_
+global dsge_prior_weight ys_
+
+
+
+options_.varlist = varlist;
+
+options_.lgyidx2varobs = zeros(size(lgy_,1),1);
+for i = 1:size(lgy_,1)
+  tmp = strmatch(deblank(lgy_(i,:)),options_.varobs,'exact');
+  if ~isempty(tmp)
+    options_.lgyidx2varobs(i,1) = tmp;
+  end           
+end
+
+options_ = set_default_option(options_,'first_obs',1);
+options_ = set_default_option(options_,'prefilter',0);
+options_ = set_default_option(options_,'presample',0);
+options_ = set_default_option(options_,'lik_algo',1);
+options_ = set_default_option(options_,'lik_init',1);
+options_ = set_default_option(options_,'nograph',0);
+options_ = set_default_option(options_,'mh_conf_sig',0.90);
+options_ = set_default_option(options_,'mh_replic',20000);
+options_ = set_default_option(options_,'mh_drop',0.5);
+options_ = set_default_option(options_,'mh_jscale',0.2);
+options_ = set_default_option(options_,'mh_init_scale',2*options_.mh_jscale);
+options_ = set_default_option(options_,'mode_file','');
+options_ = set_default_option(options_,'mode_compute',4);
+options_ = set_default_option(options_,'mode_check',0);
+options_ = set_default_option(options_,'prior_trunc',1e-10);
+options_ = set_default_option(options_,'load_mh_file',0);
+options_ = set_default_option(options_,'loglinear',0);
+options_ = set_default_option(options_,'unit_root_vars',[]);
+options_ = set_default_option(options_,'XTick',[]);
+options_ = set_default_option(options_,'XTickLabel',[]);
+options_ = set_default_option(options_,'bayesian_irf',0);
+options_ = set_default_option(options_,'bayesian_th_moments',0);
+options_ = set_default_option(options_,'TeX',0);
+options_ = set_default_option(options_,'irf',40);
+options_ = set_default_option(options_,'relative_irf',0);
+options_ = set_default_option(options_,'order',1);
+options_ = set_default_option(options_,'ar',5);
+options_ = set_default_option(options_,'dr_algo',0);
+options_ = set_default_option(options_,'linear',1);
+options_ = set_default_option(options_,'drop',0);
+options_ = set_default_option(options_,'replic',1);
+options_ = set_default_option(options_,'hp_filter',0);
+options_ = set_default_option(options_,'forecast',0);
+options_ = set_default_option(options_,'smoother',0);
+options_ = set_default_option(options_,'moments_varendo',0);
+options_ = set_default_option(options_,'filtered_vars',0);
+options_ = set_default_option(options_,'kalman_algo',1);
+options_ = set_default_option(options_,'kalman_tol',10^(-12));
+options_ = set_default_option(options_,'diffuse_d',[]);
+options_ = set_default_option(options_,'nk',1);
+options_ = set_default_option(options_,'varlag',4);
+options_ = set_default_option(options_,'Opt6Iter',3);
+options_ = set_default_option(options_,'Opt6Numb',40000);
+options_ = set_default_option(options_,'ExcludedParams',[]);
+options_ = set_default_option(options_,'ParamSubSet','All');
+
+optim_options = optimset('display','iter','LargeScale','off',...
+             'MaxFunEvals',100000,'TolFun',1e-8,'TolX',1e-6);
+
+if isfield(options_,'optim_opt')
+  eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']);
+end
+
+n_varobs = size(options_.varobs,1);
+dr = set_state_space([]);
+
+% load data
+rawdata = read_variables(options_.datafile,options_.varobs,[]);
+
+k = [];
+k1 = [];
+for i=1:n_varobs
+  k = [k strmatch(deblank(options_.varobs(i,:)),lgy_(dr.order_var,:), ...
+          'exact')];
+  k1 = [k1 strmatch(deblank(options_.varobs(i,:)),lgy_, 'exact')];
+end
+
+% check initial parameter values and creates bayestopt_
+pnames=['     ';'beta ';'gamm ';'norm ';'invg ';'unif ';'invg2'];
+[xparam1,estim_params_,bayestopt_,lb,ub]=set_prior(estim_params_);
+if any(bayestopt_.pshape > 0)
+  plot_priors
+else
+  options_.mh_replic = 0;
+end
+
+bayestopt_.mf = k;
+bayestopt_.mfys = k1;
+
+% set options for recursive forecast if necessary
+options_ = set_default_option(options_,'nobs',size(rawdata,1)-options_.first_obs+1);
+if options_.nobs(1) == options_.nobs(end) % no recursive estimation
+  options_ = set_default_option(options_,'mh_nblck',2); 
+  options_ = set_default_option(options_,'nodiagnostic',0);
+else
+  options_ = set_default_option(options_,'mh_nblck',1); 
+  options_ = set_default_option(options_,'nodiagnostic',1);
+end
+
+bounds = prior_bounds(bayestopt_);
+bounds(:,1)=max(bounds(:,1),lb);
+bounds(:,2)=min(bounds(:,2),ub);
+if any(xparam1 < bounds(:,1)) | any(xparam1 > bounds(:,2))
+  find(xparam1 < bounds(:,1))
+  find(xparam1 > bounds(:,2))
+  error('Initial parameter values are outside parameter bounds')
+end
+lb = bounds(:,1);
+ub = bounds(:,2);
+bayestopt_.lb = lb;
+bayestopt_.ub = ub;
+
+if isempty(trend_coeff_)
+  bayestopt_.with_trend = 0;
+else
+  bayestopt_.with_trend = 1;
+  bayestopt_.trend_coeff = {};
+  for i=1:n_varobs
+    if i > length(trend_coeff_) | isempty(trend_coeff_{i})
+      bayestopt_.trend_coeff{i} = '0';
+    else
+      bayestopt_.trend_coeff{i} = trend_coeff_{i};
+    end
+  end
+end
+
+bayestopt_.penalty=1e8;             % penalty 
+
+
+nvx = estim_params_.nvx;
+nvn = estim_params_.nvn;
+ncx = estim_params_.ncx;
+ncn = estim_params_.ncn;
+np  = estim_params_.np ;
+nx = nvx+nvn+ncx+ncn+np;
+
+check_model;
+
+%static solver
+if exist([fname_ '_steadystate'])
+  bayestopt_.static_solve = [fname_ '_steadystate'];
+else
+  bayestopt_.static_solve = 'dynare_solve';
+end
+
+% Initialization with unit-root variables
+if ~isempty(options_.unit_root_vars)
+  n_ur = length(options_.unit_root_vars);
+  i_ur = zeros(n_ur,1);
+  for i=1:n_ur
+    i1 = strmatch(options_.unit_root_vars{i},lgy_(dr.order_var,:),'exact');
+    if isempty(i1)
+      error('Undeclared variable in unit_root_vars statement')
+    end
+    i_ur(i) = i1;
+  end
+  i_stable = ones(endo_nbr,1);
+  i_stable(i_ur) = zeros(n_ur,1);
+  i_stable = find(i_stable);
+  if ykmin_ > 1
+    l1 = flipud([cumsum(iy_(1:ykmin_-1,dr.order_var),1);ones(1, ...
+                          endo_nbr)]);
+    n1 = nnz(l1);
+    bayestopt_.Pinf = zeros(n1,n1);
+    l2 = find(l1');
+    l3 = zeros(endo_nbr,ykmin_);
+    l3(i_ur,:) = l1(:,i_ur)';
+    l3 = l3(:);
+    i_ur1 = find(l3(l2));
+    bayestopt_.Pinf(i_ur1,i_ur1) = diag(ones(1,length(i_ur1)));
+    l3 = zeros(endo_nbr,ykmin_);
+    l3(i_stable,:) = l1(:,i_stable)';
+    l3 = l3(:);
+    bayestopt_.i_T_var_stable = find(l3(l2));
+  else
+    n1 = endo_nbr;
+    bayestopt_.Pinf = zeros(n1,n1);
+    bayestopt_.Pinf(i_ur,i_ur) = diag(ones(1,length(i_ur)));
+    l1 = ones(endo_nbr,1);
+    l1(i_ur,:) = zeros(length(i_ur),1);
+    bayestopt_.i_T_var_stable = find(l1);
+  end
+  options_.lik_init = 3;
+else
+  i_stable = [1:endo_nbr]';
+end % if ~isempty(options_.unit_root_vars)
+bayestopt_.i_var_stable = i_stable;
+
+if isempty(options_.datafile)
+  error('ESTIMATION: datafile option is missing')
+end
+
+if isempty(options_.varobs)
+  error('ESTIMATION: VAROBS is missing')
+end
+
+
+% if jscale isn't specified for an estimated parameter, use
+% global option options_.jscale, set to 0.2, by default
+k = find(isnan(bayestopt_.jscale));
+bayestopt_.jscale(k) = options_.mh_jscale;
+
+% transform data 
+if options_.loglinear == 1
+  rawdata = log(rawdata);
+end
+if ~isreal(rawdata)
+  error(['There are complex values in the data. Probably  a wrong' ...
+     ' transformation'])
+end
+
+% load a previous posterior mode if any
+if length(options_.mode_file) > 0
+  eval(['load ' options_.mode_file ';']);
+  if exist('Scale')
+    options_.mh_jscale = Scale;
+    bayestopt_.jscale = ones(length(xparam1),1)*Scale;
+  end
+  if exist('PostMean')
+    MeanPar = PostMean;
+  end  
+end
+
+% compute sample moments if needed (var-dsge)
+if ~isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) | ~isempty(dsge_prior_weight)
+    evalin('base',['[mYY,mXY,mYX,mXX,Ydata,Xdata] = ' ...
+	   'VarSampleMoments(options_.first_obs,options_.first_obs+options_.nobs-1,options_.varlag,-1);'])
+end
+
+iter1 = 1;
+for iter1 = 1:length(options_.nobs)
+  gend = options_.nobs(iter1);
+  if options_.prefilter == 1
+    bayestopt_.mean_varobs = mean(rawdata(options_.first_obs+(0:gend-1),:),1);
+    data = rawdata(options_.first_obs+(0:gend-1),:)'-...
+	   repmat(bayestopt_.mean_varobs',1,gend);
+  else
+    data = rawdata(options_.first_obs+(0:gend-1),:)';
+  end  
+  initial_estimation_checks(xparam1,gend,data);
+  if options_.mode_compute > 0
+    if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+      fh=str2func('DsgeLikelihood');
+    else
+      fh=str2func('DsgeVarLikelihood');        
+    end
+    if options_.mode_compute == 1
+      if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+	[xparam1,fval,exitflag,output,lamdba,grad,hessian_fmincon] = ...
+            fmincon(fh,xparam1,[],[],[],[],lb,ub,[],optim_options,gend,data);
+      else
+	[xparam1,fval,exitflag,output,lamdba,grad,hessian_fmincon] = ...
+            fmincon(fh,xparam1,[],[],[],[],lb,ub,[],optim_options,gend);
+      end
+    elseif options_.mode_compute == 2
+      %   asamin('set','maximum_cost_repeat',0);
+      if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+	[fval,xparam1,grad,hessian_asamin,exitflag] = ...
+	    asamin('minimize','DsgeLikelihood',xparam1,lb,ub,-ones(size(xparam1)),gend,data);   
+      else
+	[fval,xparam1,grad,hessian_asamin,exitflag] = ...
+	    asamin('minimize','DsgeVarLikelihood',xparam1,lb,ub,-ones(size(xparam1)),gend);   
+      end  
+    elseif options_.mode_compute == 3
+      if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+	[xparam1,fval,exitflag] = fminunc(fh,xparam1,optim_options,gend,data);
+      else
+	[xparam1,fval,exitflag] = fminunc(fh,xparam1,optim_options,gend);
+      end  
+    elseif options_.mode_compute == 4
+      H0 = 1e-4*eye(nx);
+      crit = 1e-7;
+      nit = 1000;
+      verbose = 2;
+      if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+	[fval,xparam1,grad,hessian_csminwel,itct,fcount,retcodehat] = ...
+	    csminwel('DsgeLikelihood',xparam1,H0,[],crit,nit,gend,data);
+	disp(sprintf('Objective function at mode: %f',fval))
+	disp(sprintf('Objective function at mode: %f',DsgeLikelihood(xparam1,gend,data)))
+      else
+	[fval,xparam1,grad,hessian_csminwel,itct,fcount,retcodehat] = ...
+	    csminwel('DsgeVarLikelihood',xparam1,H0,[],crit,nit,gend);
+	disp(sprintf('Objective function at mode: %f',fval))
+	disp(sprintf('Objective function at mode: %f',DsgeVarLikelihood(xparam1,gend)))
+      end
+    elseif options_.mode_compute == 5
+      flag = 0;
+      if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+	[xparam1, hh, gg, fval] = newrat('DsgeLikelihood',xparam1,[],[],flag,gend,data);
+	eval(['save ' fname_ '_mode xparam1 hh gg fval;']);
+      else
+	[xparam1, hh, gg, fval] = newrat('DsgeVarLikelihood',xparam1,[],[],flag,gend);
+	eval(['save ' fname_ '_mode xparam1 hh gg fval;']);
+      end
+    elseif options_.mode_compute == 6% New routine!
+      if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+	fval = DsgeLikelihood(xparam1,gend,data);
+      else
+	fval = DsgeVarLikelihood(xparam1,gend);
+      end      
+      OldMode = fval;
+      if ~exist('MeanPar')
+	MeanPar = xparam1;
+      end  
+      for i=1:options_.Opt6Iter
+	if exist('hh')
+	  CovJump = inv(hh);
+	else% The covariance matrix is initialized with the prior
+	  % covariance (a diagonal matrix)
+	  stdev = bayestopt_.pstdev;
+	  indx = find(isinf(stdev));
+	  stdev(indx) = 10*ones(length(indx),1);
+	  CovJump = diag(stdev).^2;
+	end
+	OldPostVar = CovJump;
+	if i == 1;
+	  if options_.Opt6Iter > 1
+	    [xparam1,PostVar,Scale,PostMean] = ...
+		metropolis99(xparam1,gend,data,bounds,options_.Opt6Numb,options_.mh_jscale,'',MeanPar,CovJump);
+	  else
+	    [xparam1,PostVar,Scale,PostMean] = ...
+		metropolis99(xparam1,gend,data,bounds,options_.Opt6Numb,options_.mh_jscale,'LastCall',MeanPar,CovJump);
+	  end
+	  options_.mh_jscale = Scale;
+	  mouvement = max(max(abs(PostVar-OldPostVar)));
+	  if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+	    fval = DsgeLikelihood(xparam1,gend,data);
+	  else
+	    fval = DsgeVarLikelihood(xparam1,gend);
+	  end
+	  disp(['Change in the covariance matrix = ' num2str(mouvement) '.'])
+	  disp(['Mode improvement = ' num2str(abs(OldMode-fval))])
+	  OldMode = fval;
+	else
+	  OldPostVar = PostVar;
+	  if i<options_.Opt6Iter
+	    [xparam1,PostVar,Scale,PostMean] = ...
+		metropolis99(xparam1,gend,data,bounds,options_.Opt6Numb,options_.mh_jscale,'',PostMean,PostVar);
+	  else
+	    [xparam1,PostVar,Scale,PostMean] = ...
+		metropolis99(xparam1,gend,data,bounds,options_.Opt6Numb,options_.mh_jscale,'LastCall',PostMean,PostVar);
+	  end
+	  options_.mh_jscale = Scale;
+	  mouvement = max(max(abs(PostVar-OldPostVar)));
+	  if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+	    fval = DsgeLikelihood(xparam1,gend,data);
+	  else
+	    fval = DsgeVarLikelihood(xparam1,gend);
+	  end
+	  disp(['Change in the covariance matrix = ' num2str(mouvement) '.'])
+	  disp(['Mode improvement = ' num2str(abs(OldMode-fval))])
+	  OldMode = fval;
+	end
+	options_.mh_jscale = Scale;
+	bayestopt_.jscale = ones(length(xparam1),1)*Scale;
+      end
+      hh = inv(PostVar);
+      if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+	fval = DsgeLikelihood(xparam1,gend,data);
+      else
+	fval = DsgeVarLikelihood(xparam1,gend);
+      end
+    end
+    if options_.mode_compute ~= 5 & options_.mode_compute ~= 6 
+      if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+	hh = reshape(hessian('DsgeLikelihood',xparam1,gend,data),nx,nx);
+	eval(['save ' fname_ '_mode xparam1 hh fval;']);
+      else
+	hh = reshape(hessian('DsgeVarLikelihood',xparam1,gend),nx,nx);
+	eval(['save ' fname_ '_mode xparam1 hh fval;']);
+      end
+    end
+    if options_.mode_compute ~= 6
+      eval(['save ' fname_ '_mode xparam1 hh;']);
+    elseif options_.mode_compute == 6
+      eval(['save ' fname_ '_mode xparam1 hh Scale PostMean;']);
+    end
+  end
+
+  if options_.mode_check == 1
+    mode_check(xparam1,0,hh,gend,data,lb,ub);
+  end
+
+  if options_.mode_compute ~= 6
+    hh = generalized_cholesky(hh);
+    invhess = inv(hh);
+  else
+    invhess = PostVar;
+  end
+  stdh = sqrt(diag(invhess));
+  if any(bayestopt_.pshape > 0)
+    disp(' ')
+    disp('RESULTS FROM POSTERIOR MAXIMIZATION')
+    tstath = zeros(nx,1);
+    for i = 1:nx
+      tstath(i) = abs(xparam1(i))/stdh(i);
+    end
+    tit1 = sprintf('%10s %7s %8s %7s %6s %4s %6s\n',' ','prior mean', ...
+           'mode','s.d.','t-stat','prior','pstdev');
+    if np
+      ip = nvx+nvn+ncx+ncn+1;
+      disp('parameters')
+      disp(tit1)
+      for i=1:np
+    disp(sprintf('%12s %7.3f %8.4f %7.4f %7.4f %4s %6.4f', ...
+             deblank(estim_params_.param_names(i,:)), ...
+             bayestopt_.pmean(ip),xparam1(ip),stdh(ip),tstath(ip), ...
+             pnames(bayestopt_.pshape(ip)+1,:), ...
+             bayestopt_.pstdev(ip)));
+    eval(['oo_.posterior_mode.parameters.' deblank(estim_params_.param_names(i,:)) ' = xparam1(ip);']);
+    eval(['oo_.posterior_std.parameters.' deblank(estim_params_.param_names(i,:)) ' = stdh(ip);']); 
+    ip = ip+1;
+      end
+    end
+    if nvx
+      ip = 1;
+      disp('standard deviation of shocks')
+      disp(tit1)
+      for i=1:nvx
+    k = estim_params_.var_exo(i,1);
+        disp(sprintf('%12s %7.3f %8.4f %7.4f %7.4f %4s %6.4f', ...
+             deblank(lgx_(k,:)),bayestopt_.pmean(ip),xparam1(ip), ...
+             stdh(ip),tstath(ip),pnames(bayestopt_.pshape(ip)+1,:), ...
+             bayestopt_.pstdev(ip))); 
+        Sigma_e_(k,k) = xparam1(ip)*xparam1(ip);
+    eval(['oo_.posterior_mode.shocks_std.' deblank(lgx_(k,:)) ' = xparam1(ip);']);
+    eval(['oo_.posterior_std.shocks_std.' deblank(lgx_(k,:)) ' = stdh(ip);']); 
+    ip = ip+1;
+      end
+    end
+    if nvn
+      disp('standard deviation of measurement errors')
+      disp(tit1)
+      ip = nvx+1;
+      for i=1:nvn
+        disp(sprintf('%12s %7.3f %8.4f %7.4f %7.4f %4s %6.4f', ...
+             deblank(options_.varobs(estim_params_.var_endo(i,1),: ...
+                         )),bayestopt_.pmean(ip), ...
+             xparam1(ip),stdh(ip),tstath(ip), ...
+             pnames(bayestopt_.pshape(ip)+1,:), ...
+             bayestopt_.pstdev(ip)));
+    eval(['oo_.posterior_mode.measurement_errors_std.' deblank(options_.varobs(estim_params_.var_endo(i,1),:)) ' = xparam1(ip);']);
+    eval(['oo_.posterior_std.measurement_errors_std.' deblank(options_.varobs(estim_params_.var_endo(i,1),:)) ' = stdh(ip);']); 
+        ip = ip+1;
+      end
+    end
+    if ncx
+      disp('correlation of shocks')
+      disp(tit1)
+      ip = nvx+nvn+1;
+      for i=1:ncx
+    k1 = estim_params_.corrx(i,1);
+        k2 = estim_params_.corrx(i,2);
+        name = [deblank(lgx_(k1,:)) ',' deblank(lgx_(k2,:))];
+        disp(sprintf('%12s %7.3f %8.4f %7.4f %7.4f %4s %6.4f', name, ...
+             bayestopt_.pmean(ip),xparam1(ip),stdh(ip),tstath(ip),  ...
+             pnames(bayestopt_.pshape(ip)+1,:), bayestopt_.pstdev(ip)));
+        Sigma_e_(k1,k2) = xparam1(ip)*sqrt(Sigma_e_(k1,k1)*Sigma_e_(k2,k2));
+        Sigma_e_(k2,k1) = Sigma_e_(k1,k2);
+    eval(['oo_.posterior_mode.shocks_corr.' deblank(lgx_(k1,:)) '_' deblank(lgx_(k2,:)) ' = xparam1(ip);']);
+    eval(['oo_.posterior_std.shocks_corr.' deblank(lgx_(k1,:)) '_' deblank(lgx_(k2,:)) ' = stdh(ip);']); 
+        ip = ip+1;
+      end
+    end
+    if ncn
+      disp('correlation of measurement errors')
+      disp(tit1)
+      ip = nvx+nvn+ncx+1;
+      for i=1:ncn
+        k1 = estim_params_.corrn(i,1);
+        k2 = estim_params_.corrn(i,2);
+        name = [deblank(lgy_(k1,:)) ',' deblank(lgy_(k2,:))];
+        disp(sprintf('%12s %7.3f %8.4f %7.4f %7.4f %4s %6.4f', name, ...
+             bayestopt_.pmean(ip),xparam1(ip),stdh(ip),tstath(ip), ...
+             pnames(bayestopt_.pshape(ip)+1,:), bayestopt_.pstdev(ip)));
+    eval(['oo_.posterior_mode.measurement_errors_corr.' deblank(lgy_(k1,:)) '_' deblank(lgy_(k2,:)) ' = xparam1(ip);']);
+    eval(['oo_.posterior_std.measurement_errors_corr.' deblank(lgy_(k1,:)) '_' deblank(lgy_(k2,:)) ' = stdh(ip);']); 
+    ip = ip+1;
+      end
+    end
+    %%% Laplace approximation to the marginal log density:
+    if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+        md_Laplace = .5*size(xparam1,1)*log(2*pi) + .5*log(det(invhess)) ...
+        - DsgeLikelihood(xparam1,gend,data);
+    else
+        md_Laplace = .5*size(xparam1,1)*log(2*pi) + .5*log(det(invhess)) ...
+        - DsgeVarLikelihood(xparam1,gend);
+    end
+    oo_.MarginalDensity.LaplaceApproximation = md_Laplace;    
+    disp(' ')
+    disp(sprintf('Log data density [Laplace approximation] is %f.',md_Laplace))
+    disp(' ')
+  else
+    disp(' ')
+    disp('RESULTS FROM MAXIMUM LIKELIHOOD')
+    tstath = zeros(nx,1);
+    for i = 1:nx
+      tstath(i) = abs(xparam1(i))/stdh(i);
+    end
+    tit1 = sprintf('%10s %10s %7s %6s\n',' ', ...
+           'Estimate','s.d.','t-stat');
+    if np
+      ip = nvx+nvn+ncx+ncn+1;
+      disp('parameters')
+      disp(tit1)
+      for i=1:np
+        disp(sprintf('%12s %8.4f %7.4f %7.4f', ...
+             deblank(estim_params_.param_names(i,:)), ...
+             xparam1(ip),stdh(ip),tstath(ip)));
+    eval(['oo_.mle_mode.parameters.' deblank(estim_params_.param_names(i,:)) ' = xparam1(ip);']);
+    eval(['oo_.mle_std.parameters.' deblank(estim_params_.param_names(i,:)) ' = stdh(ip);']); 
+        ip = ip+1;
+      end
+    end
+    if nvx
+      ip = 1;
+      disp('standard deviation of shocks')
+      disp(tit1)
+      for i=1:nvx
+    k = estim_params_.var_exo(i,1);
+        disp(sprintf('%12s %8.4f %7.4f %7.4f', ...
+             deblank(lgx_(k,:)),xparam1(ip), ...
+             stdh(ip),tstath(ip)));
+        Sigma_e_(k,k) = xparam1(ip)*xparam1(ip);
+    eval(['oo_.mle_mode.shocks_std.' deblank(lgx_(k,:)) ' = xparam1(ip);']);
+    eval(['oo_.mle_std.shocks_std.' deblank(lgx_(k,:)) ' = stdh(ip);']); 
+    ip = ip+1;
+      end
+    end
+    if nvn
+      disp('standard deviation of measurement errors')
+      disp(tit1)
+      ip = nvx+1;
+      for i=1:nvn
+    disp(sprintf('%12s %8.4f %7.4f %7.4f', ...
+             deblank(options_.varobs(estim_params_.var_endo(i,1),: ...
+                         )), ...
+             xparam1(ip),stdh(ip),tstath(ip)))
+    eval(['oo_.mle_mode.measurement_errors_std.' deblank(options_.varobs(estim_params_.var_endo(i,1),:)) ' = xparam1(ip);']);
+    eval(['oo_.mle_std.measurement_errors_std.' deblank(options_.varobs(estim_params_.var_endo(i,1),:)) ' = stdh(ip);']);      
+    ip = ip+1;
+      end
+    end
+    if ncx
+      disp('correlation of shocks')
+      disp(tit1)
+      ip = nvx+nvn+1;
+      for i=1:ncx
+        k1 = estim_params_.corrx(i,1);
+        k2 = estim_params_.corrx(i,2);
+        name = [deblank(lgx_(k1,:)) ',' deblank(lgx_(k2,:))];
+        disp(sprintf('%12s %8.4f %7.4f %7.4f', name, ...
+             xparam1(ip),stdh(ip),tstath(ip)));
+        Sigma_e_(k1,k2) = xparam1(ip)*sqrt(Sigma_e_(k1,k1)*Sigma_e_(k2,k2));
+        Sigma_e_(k2,k1) = Sigma_e_(k1,k2);
+    eval(['oo_.mle_mode.shocks_corr.' deblank(lgx_(k1,:)) '_' deblank(lgx_(k2,:)) ' = xparam1(ip);']);
+    eval(['oo_.mle_std.shocks_corr.' deblank(lgx_(k1,:)) '_' deblank(lgx_(k2,:)) ' = stdh(ip);']);      
+        ip = ip+1;
+      end
+    end
+    if ncn
+      disp('correlation of measurement errors')
+      disp(tit1)
+      ip = nvx+nvn+ncx+1;
+      for i=1:ncn
+    k1 = estim_params_.corrn(i,1);
+    k2 = estim_params_.corrn(i,2);
+    name = [deblank(lgy_(k1,:)) ',' deblank(lgy_(k2,:))];
+    disp(sprintf('%12s %8.4f %7.4f %7.4f', name, ...
+             xparam1(ip),stdh(ip),tstath(ip)));
+    eval(['oo_.mle_mode.measurement_error_corr.' deblank(lgy_(k1,:)) '_' deblank(lgy_(k2,:)) ' = xparam1(ip);']);
+    eval(['oo_.mle_std.measurement_error_corr.' deblank(lgy_(k1,:)) '_' deblank(lgy_(k2,:)) ' = stdh(ip);']);      
+    ip = ip+1;
+      end
+    end
+  end
+
+  if any(bayestopt_.pshape > 0) & options_.TeX %%%% Bayesian estimation (posterior mode) Latex output
+    if np
+      filename = [fname_ '_Posterior_Mode_1.TeX'];
+      fidTeX = fopen(filename,'w');
+      fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n');
+      fprintf(fidTeX,'%% RESULTS FROM POSTERIOR MAXIMIZATION (parameters)\n');
+      fprintf(fidTeX,['%% ' datestr(now,0)]);
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,'{\\tiny \n')
+      fprintf(fidTeX,'\\begin{table}\n');
+      fprintf(fidTeX,'\\centering\n');
+      fprintf(fidTeX,'\\begin{tabular}{l|lcccc} \n');
+      fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+      fprintf(fidTeX,'  & Prior distribution & Prior mean  & Prior s.d. & Posterior mode & s.d. \\\\ \n');
+      fprintf(fidTeX,'\\hline \\\\ \n');
+      ip = nvx+nvn+ncx+ncn+1;
+      for i=1:np
+    fprintf(fidTeX,'$%s$ & %s & %7.3f & %6.4f & %8.4f & %7.4f \\\\ \n',...
+        deblank(estim_params_.tex(i,:)),...
+        deblank(pnames(bayestopt_.pshape(ip)+1,:)),...
+        bayestopt_.pmean(ip),...
+        estim_params_.param_vals(i,6),...
+        xparam1(ip),...
+        stdh(ip));
+    ip = ip + 1;    
+      end
+      fprintf(fidTeX,'\\hline\\hline \n');
+      fprintf(fidTeX,'\\end{tabular}\n ');    
+      fprintf(fidTeX,'\\caption{Results from posterior parameters (parameters)}\n ');
+      fprintf(fidTeX,'\\label{Table:Posterior:1}\n');
+      fprintf(fidTeX,'\\end{table}\n');
+      fprintf(fidTeX,'} \n')
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end
+    if nvx
+      TeXfile = [fname_ '_Posterior_Mode_2.TeX'];
+      fidTeX = fopen(TeXfile,'w');
+      fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n');
+      fprintf(fidTeX,'%% RESULTS FROM POSTERIOR MAXIMIZATION (standard deviation of structural shocks)\n');
+      fprintf(fidTeX,['%% ' datestr(now,0)]);
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,'{\\tiny \n');
+      fprintf(fidTeX,'\\begin{table}\n');
+      fprintf(fidTeX,'\\centering\n');
+      fprintf(fidTeX,'\\begin{tabular}{l|lcccc} \n');
+      fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+      fprintf(fidTeX,'  & Prior distribution & Prior mean  & Prior s.d. & Posterior mode & s.d. \\\\ \n')
+      fprintf(fidTeX,'\\hline \\\\ \n');
+      ip = 1;
+      for i=1:nvx
+    k = estim_params_.var_exo(i,1);
+    fprintf(fidTeX,[ '$%s$ & %4s & %7.3f & %6.4f & %8.4f & %7.4f \\\\ \n'],...
+        deblank(lgx_TeX_(k,:)),...
+        deblank(pnames(bayestopt_.pshape(ip)+1,:)),...
+        bayestopt_.pmean(ip),...
+        estim_params_.var_exo(i,7),...
+        xparam1(ip), ...
+        stdh(ip)); 
+    ip = ip+1;
+      end
+      fprintf(fidTeX,'\\hline\\hline \n');
+      fprintf(fidTeX,'\\end{tabular}\n ');    
+      fprintf(fidTeX,'\\caption{Results from posterior parameters (standard deviation of structural shocks)}\n ');
+      fprintf(fidTeX,'\\label{Table:Posterior:2}\n');
+      fprintf(fidTeX,'\\end{table}\n');
+      fprintf(fidTeX,'} \n')
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end
+    if nvn
+      TeXfile = [fname_ '_Posterior_Mode_3.TeX'];
+      fidTeX  = fopen(TeXfile,'w');
+      fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n');
+      fprintf(fidTeX,'%% RESULTS FROM POSTERIOR MAXIMIZATION (standard deviation of measurement errors)\n');
+      fprintf(fidTeX,['%% ' datestr(now,0)]);
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,'\\begin{table}\n');
+      fprintf(fidTeX,'\\centering\n');
+      fprintf(fidTeX,'\\begin{tabular}{l|lcccc} \n');
+      fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+      fprintf(fidTeX,'  & Prior distribution & Prior mean  & Prior s.d. &  Posterior mode & s.d. \\\\ \n')
+      fprintf(fidTeX,'\\hline \\\\ \n');
+      ip = nvx+1;
+      for i=1:nvn
+    fprintf(fidTeX,'$%s$ & %4s & %7.3f & %6.4f & %8.4f & %7.4f \\\\ \n',...
+        deblank(options_.varobs_TeX(estim_params_.var_endo(i,1),:)), ...
+        deblank(pnames(bayestopt_.pshape(ip)+1,:)), ...        
+        bayestopt_.pmean(ip), ...
+        estim_params_.var_endo(i,7),...        
+        xparam1(ip),...
+        stdh(ip)); 
+    ip = ip+1;
+      end
+      fprintf(fidTeX,'\\hline\\hline \n');
+      fprintf(fidTeX,'\\end{tabular}\n ');    
+      fprintf(fidTeX,'\\caption{Results from posterior parameters (standard deviation of measurement errors)}\n ');
+      fprintf(fidTeX,'\\label{Table:Posterior:3}\n');
+      fprintf(fidTeX,'\\end{table}\n');
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end
+    if ncx
+      TeXfile = [fname_ '_Posterior_Mode_4.TeX'];
+      fidTeX = fopen(TeXfile,'w');
+      fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n');
+      fprintf(fidTeX,'%% RESULTS FROM POSTERIOR MAXIMIZATION (correlation of structural shocks)\n');
+      fprintf(fidTeX,['%% ' datestr(now,0)]);
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,'\\begin{table}\n');
+      fprintf(fidTeX,'\\centering\n');
+      fprintf(fidTeX,'\\begin{tabular}{l|lcccc} \n');
+      fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+      fprintf(fidTeX,'  & Prior distribution & Prior mean  & Prior s.d. &  Posterior mode & s.d. \\\\ \n')
+      fprintf(fidTeX,'\\hline \\\\ \n');
+      ip = nvx+nvn+1;
+      for i=1:ncx
+    k1 = estim_params_.corrx(i,1);
+    k2 = estim_params_.corrx(i,2);
+    fprintf(fidTeX,[ '$%s$ & %s & %7.3f & %6.4f & %8.4f & %7.4f \\\\ \n'],...
+        [deblank(lgx_TeX_(k1,:)) ',' deblank(lgx_TeX_(k2,:))], ...
+        deblank(pnames(bayestopt_.pshape(ip)+1,:)), ...
+        bayestopt_.pmean(ip), ...
+        estim_params_.corrx(i,8), ...
+        xparam1(ip), ...
+        stdh(ip));
+    ip = ip+1;
+      end
+      fprintf(fidTeX,'\\hline\\hline \n');
+      fprintf(fidTeX,'\\end{tabular}\n ');    
+      fprintf(fidTeX,'\\caption{Results from posterior parameters (correlation of structural shocks)}\n ');
+      fprintf(fidTeX,'\\label{Table:Posterior:4}\n');
+      fprintf(fidTeX,'\\end{table}\n');
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end
+    if ncn
+      TeXfile = [fname_ '_Posterior_Mode_5.TeX'];
+      fidTeX = fopen(TeXfile,'w');
+      fprintf(fidTeX,'%% TeX-table generated by dynare_estimation (Dynare).\n');
+      fprintf(fidTeX,'%% RESULTS FROM POSTERIOR MAXIMIZATION (correlation of measurement errors)\n');
+      fprintf(fidTeX,['%% ' datestr(now,0)]);
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,'\\begin{table}\n');
+      fprintf(fidTeX,'\\centering\n');
+      fprintf(fidTeX,'\\begin{tabular}{l|lcccc} \n');
+      fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+      fprintf(fidTeX,'  & Prior distribution & Prior mean  & Prior s.d. &  Posterior mode & s.d. \\\\ \n')
+      fprintf(fidTeX,'\\hline \\\\ \n');
+      ip = nvx+nvn+ncx+1;
+      for i=1:ncn
+    k1 = estim_params_.corrn(i,1);
+    k2 = estim_params_.corrn(i,2);
+    fprintf(fidTeX,'$%s$ & %s & %7.3f & %6.4f & %8.4f & %7.4f \\\\ \n',...
+        [deblank(lgy_(k1,:)) ',' deblank(lgy_(k2,:))], ...
+        pnames(bayestopt_.pshape(ip)+1,:), ...
+        bayestopt_.pmean(ip), ...
+        estim_params_.corrn(i,8), ...
+        xparam1(ip), ...
+        stdh(ip));
+    ip = ip+1;
+      end
+      fprintf(fidTeX,'\\hline\\hline \n');
+      fprintf(fidTeX,'\\end{tabular}\n ');    
+      fprintf(fidTeX,'\\caption{Results from posterior parameters (correlation of measurement errors)}\n ');
+      fprintf(fidTeX,'\\label{Table:Posterior:5}\n');
+      fprintf(fidTeX,'\\end{table}\n');
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end 
+  end    
+
+
+  if any(bayestopt_.pshape  > 0)  & (options_.mh_replic | options_.load_mh_file)  % not ML estimation
+    bounds = prior_bounds(bayestopt_);
+    bayestopt_.lb = bounds(:,1);
+    bayestopt_.ub = bounds(:,2);
+    if any(xparam1 < bounds(:,1)) | any(xparam1 > bounds(:,2))
+      find(xparam1 < bounds(:,1))
+      find(xparam1 > bounds(:,2))
+      error('Mode values are outside prior bounds. Reduce prior_trunc.')
+    end
+    metropolis(xparam1,invhess,gend,data,rawdata,bounds);
+    get_posterior_parameters('posterior_mean');
+    dr_ = resol(ys_,0);
+  end
+
+  % computes smoothed variables for posterior_mode or posterior_mean, if
+  % metropolis). Except if options_.smoother or recursive forecast
+  
+  if ~options_.smoother & options_.nobs(1) == options_.nobs(end) 
+    [atT,innov,measurement_error,filtered_state_vector,ys,trend_coeff] ...
+	= DsgeSmoother(xparam1,gend,data);
+    for i=1:endo_nbr
+      eval(['oo_.SmoothedVariables.' deblank(lgy_(dr.order_var(i),:)) ' = atT(i,:)'';']);
+      eval(['oo_.FilteredVariables.' deblank(lgy_(dr.order_var(i),:)) ' = filtered_state_vector(i,:)'';']);
+    end
+    [nbplt,nr,nc,lr,lc,nstar] = pltorg(exo_nbr);
+    if options_.TeX
+      fidTeX = fopen([fname_ '_SmoothedShocks.TeX'],'w');
+      fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation.m (Dynare).\n');
+      fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
+      fprintf(fidTeX,' \n');
+    end    
+    if nbplt == 1
+      hh = figure('Name','Smoothed shocks');
+      NAMES = [];
+      if options_.TeX, TeXNAMES = [], end
+      for i=1:exo_nbr
+    subplot(nr,nc,i);
+    plot(1:gend,innov(i,:),'-k','linewidth',1)
+    hold on
+    plot([1 gend],[0 0],'-r','linewidth',.5)
+    hold off
+    xlim([1 gend])
+    name    = deblank(lgx_(i,:));
+    NAMES   = strvcat(NAMES,name);
+    if ~isempty(options_.XTick)
+      set(gca,'XTick',options_.XTick)
+      set(gca,'XTickLabel',options_.XTickLabel)
+    end
+    if options_.TeX
+      texname = lgx_TeX_(i,1);
+      TeXNAMES   = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']);
+    end
+    title(name,'Interpreter','none')
+    eval(['oo_.SmoothedShocks.' deblank(lgx_(i,:)) ' = innov(i,:)'';']);
+      end
+      eval(['print -depsc2 ' fname_ '_SmoothedShocks' int2str(1)]);
+      eval(['print -dpdf ' fname_ '_SmoothedShocks' int2str(1)]);
+      saveas(hh,[fname_ '_SmoothedShocks' int2str(1) '.fig']);
+      if options_.nograph, close(hh), end
+      if options_.TeX
+    fprintf(fidTeX,'\\begin{figure}[H]\n');
+    for jj = 1:exo_nbr
+      fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:)));
+    end    
+    fprintf(fidTeX,'\\centering \n');
+    fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_SmoothedShocks%s}\n',fname_,int2str(1));
+    fprintf(fidTeX,'\\caption{Smoothed shocks.}');
+    fprintf(fidTeX,'\\label{Fig:SmoothedShocks:%s}\n',int2str(1));
+    fprintf(fidTeX,'\\end{figure}\n');
+    fprintf(fidTeX,'\n');
+    fprintf(fidTeX,'%% End of TeX file.\n');
+    fclose(fidTeX);
+      end    
+    else
+      for plt = 1:nbplt-1
+    hh = figure('Name','Smoothed shocks');
+    set(0,'CurrentFigure',hh)
+    NAMES = [];
+    if options_.TeX, TeXNAMES = [], end
+    for i=1:nstar
+      k = (plt-1)*nstar+i;
+      subplot(nr,nc,i);
+      plot([1 gend],[0 0],'-r','linewidth',.5)
+      hold on
+      plot(1:gend,innov(k,:),'-k','linewidth',1)
+      hold off
+      name = deblank(lgx_(k,:));
+      NAMES = strvcat(NAMES,name);
+      if ~isempty(options_.XTick)
+        set(gca,'XTick',options_.XTick)
+        set(gca,'XTickLabel',options_.XTickLabel)
+      end
+      xlim([1 gend])
+      if options_.TeX
+        texname = lgx_TeX_(k,:);
+        TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']);
+      end    
+      title(name,'Interpreter','none')
+      eval(['oo_.SmoothedShocks.' deblank(name) ' = innov(k,:)'';']);
+    end
+    eval(['print -depsc2 ' fname_ '_SmoothedShocks' int2str(plt)]);
+    eval(['print -dpdf ' fname_ '_SmoothedShocks' int2str(plt)]);
+    saveas(hh,[fname_ '_SmoothedShocks' int2str(plt) '.fig']);
+    if options_.nograph, close(hh), end
+    if options_.TeX
+      fprintf(fidTeX,'\\begin{figure}[H]\n');
+      for jj = 1:nstar
+        fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:)));
+      end    
+      fprintf(fidTeX,'\\centering \n');
+      fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_SmoothedShocks%s}\n',fname_,int2str(plt));
+      fprintf(fidTeX,'\\caption{Smoothed shocks.}');
+      fprintf(fidTeX,'\\label{Fig:SmoothedShocks:%s}\n',int2str(plt));
+      fprintf(fidTeX,'\\end{figure}\n');
+      fprintf(fidTeX,'\n');
+    end    
+      end
+      hh = figure('Name','Smoothed shocks');
+      set(0,'CurrentFigure',hh)
+      NAMES = [];
+      if options_.TeX, TeXNAMES = [], end
+      for i=1:exo_nbr-(nbplt-1)*nstar
+    k = (nbplt-1)*nstar+i;
+    if lr ~= 0
+      subplot(lr,lc,i);
+    else
+      subplot(nr,nc,i);
+    end    
+    plot([1 gend],[0 0],'-r','linewidth',0.5)
+    hold on
+    plot(1:gend,innov(k,:),'-k','linewidth',1)
+    hold off
+    name     = deblank(lgx_(k,:));
+    NAMES    = strvcat(NAMES,name);
+    if ~isempty(options_.XTick)
+      set(gca,'XTick',options_.XTick)
+      set(gca,'XTickLabel',options_.XTickLabel)
+    end
+    xlim([1 gend])
+    if options_.TeX
+      texname  = lgx_TeX_(k,:);
+      TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']);
+    end
+    title(name,'Interpreter','none')
+    eval(['oo_.SmoothedShocks.' deblank(name) ' = innov(k,:)'';']);
+      end
+      eval(['print -depsc2 ' fname_ '_SmoothedShocks' int2str(nbplt)]);
+      eval(['print -dpdf ' fname_ '_SmoothedShocks' int2str(nbplt)]);
+      saveas(hh,[fname_ '_SmoothedShocks' int2str(nbplt) '.fig']);
+      if options_.nograph, close(hh), end
+      if options_.TeX
+    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    
+    fprintf(fidTeX,'\\centering \n');
+    fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_SmoothedShocks%s}\n',fname_,int2str(nbplt));
+    fprintf(fidTeX,'\\caption{Smoothed shocks.}');
+    fprintf(fidTeX,'\\label{Fig:SmoothedShocks:%s}\n',int2str(nbplt));
+    fprintf(fidTeX,'\\end{figure}\n');
+    fprintf(fidTeX,'\n');
+    fprintf(fidTeX,'%% End of TeX file.\n');
+    fclose(fidTeX);
+      end    
+    end
+    %%
+    %%  Smooth observational errors...
+    %%
+    yf = zeros(gend,n_varobs);
+    if options_.prefilter == 1
+      yf = atT(bayestopt_.mf,:)+repmat(bayestopt_.mean_varobs',1,gend);
+    elseif options_.loglinear == 1
+      yf = atT(bayestopt_.mf,:)+repmat(log(ys(bayestopt_.mfys)),1,gend)+...
+       trend_coeff*[1:gend];
+    else
+      yf = atT(bayestopt_.mf,:)+repmat(ys(bayestopt_.mfys),1,gend)+...
+       trend_coeff*[1:gend];
+    end
+    if nvn
+      number_of_plots_to_draw = 0;
+      index = [];
+      for i=1:n_varobs
+    if max(abs(measurement_error(10:end))) > 0.000000001
+      number_of_plots_to_draw = number_of_plots_to_draw + 1;
+      index = cat(1,index,i);
+    end
+    eval(['oo_.SmoothedMeasurementErrors.' deblank(options_.varobs(i,:)) ...
+          ' = measurement_error(i,:)'';']);
+      end
+      [nbplt,nr,nc,lr,lc,nstar] = pltorg(number_of_plots_to_draw);
+      if options_.TeX
+    fidTeX = fopen([fname_ '_SmoothedObservationErrors.TeX'],'w');
+    fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation.m (Dynare).\n');
+    fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
+    fprintf(fidTeX,' \n');
+      end    
+      if nbplt == 1
+    hh = figure('Name','Smoothed observation errors');
+    set(0,'CurrentFigure',hh)
+    NAMES = [];
+    if options_.TeX, TeXNAMES = [], end
+    for i=1:number_of_plots_to_draw
+      subplot(nr,nc,i);
+      plot(1:gend,measurement_error(index(i),:),'-k','linewidth',1)
+      hold on
+      plot([1 gend],[0 0],'-r','linewidth',.5)
+      hold off
+      name    = deblank(options_.varobs(index(i),:));
+      NAMES   = strvcat(NAMES,name);
+      if ~isempty(options_.XTick)
+        set(gca,'XTick',options_.XTick)
+        set(gca,'XTickLabel',options_.XTickLabel)
+      end
+      if options_.TeX
+        texname = options_.varobs_TeX(index(i),:);
+        TeXNAMES   = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']);
+      end
+      title(name,'Interpreter','none')
+    end
+    eval(['print -depsc2 ' fname_ '_SmoothedObservationErrors' int2str(1)]);
+    eval(['print -dpdf ' fname_ '_SmoothedObservationErrors' int2str(1)]);
+    saveas(hh,[fname_ '_SmoothedObservationErrors' int2str(1) '.fig']);
+    if options_.nograph, close(hh), end
+    if options_.TeX
+      fprintf(fidTeX,'\\begin{figure}[H]\n');
+      for jj = 1:number_of_plots_to_draw
+        fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:)));
+      end    
+      fprintf(fidTeX,'\\centering \n');
+      fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_SmoothedObservationErrors%s}\n',fname_,int2str(1));
+      fprintf(fidTeX,'\\caption{Smoothed observation errors.}');
+      fprintf(fidTeX,'\\label{Fig:SmoothedObservationErrors:%s',int2str(1));
+      fprintf(fidTeX,'\\end{figure}\n');
+      fprintf(fidTeX,'\n');
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end    
+      else
+    for plt = 1:nbplt-1
+      hh = figure('Name','Smoothed observation errors');
+      set(0,'CurrentFigure',hh)
+      NAMES = [];
+      if options_.TeX, TeXNAMES = [], end
+      for i=1:nstar
+        k = (plt-1)*nstar+i;
+        subplot(nr,nc,i);
+        plot([1 gend],[0 0],'-r','linewidth',.5)
+        hold on
+        plot(1:gend,measurement_error(index(k),:),'-k','linewidth',1)
+        hold off
+        name = deblank(options_.varobs(index(k),:));
+        NAMES = strvcat(NAMES,name);
+        if ~isempty(options_.XTick)
+          set(gca,'XTick',options_.XTick)
+          set(gca,'XTickLabel',options_.XTickLabel)
+        end
+        if options_.TeX
+          texname = options_.varobs_TeX(k,:);
+          TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']);
+        end    
+        title(name,'Interpreter','none')
+      end
+      eval(['print -depsc2 ' fname_ '_SmoothedObservationErrors' int2str(plt)]);
+      eval(['print -dpdf ' fname_ '_SmoothedObservationErrors' int2str(plt)]);
+      saveas(hh,[fname_ '_SmoothedObservationErrors' int2str(plt) '.fig']);
+      if options_.nograph, close(hh), end
+      if options_.TeX
+        fprintf(fidTeX,'\\begin{figure}[H]\n');
+        for jj = 1:nstar
+          fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:)));
+        end    
+        fprintf(fidTeX,'\\centering \n');
+        fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_SmoothedObservationErrors%s}\n',fname_,int2str(plt));
+        fprintf(fidTeX,'\\caption{Smoothed observation errors.}');
+        fprintf(fidTeX,'\\label{Fig:SmoothedObservationErrors:%s}\n',int2str(plt));
+        fprintf(fidTeX,'\\end{figure}\n');
+        fprintf(fidTeX,'\n');
+      end    
+    end
+    hh = figure('Name','Smoothed observation errors');
+    set(0,'CurrentFigure',hh)
+    NAMES = [];
+    if options_.TeX, TeXNAMES = [], end
+    for i=1:number_of_plots_to_draw-(nbplt-1)*nstar
+      k = (nbplt-1)*nstar+i;
+      if lr ~= 0
+        subplot(lr,lc,i);
+      else
+        subplot(nr,nc,i);
+      end    
+      plot([1 gend],[0 0],'-r','linewidth',0.5)
+      hold on
+      plot(1:gend,measurement_error(index(k),:),'-k','linewidth',1)
+      hold off
+      name     = deblank(options_.varobs(index(k),:));
+      NAMES    = strvcat(NAMES,name);
+      if ~isempty(options_.XTick)
+        set(gca,'XTick',options_.XTick)
+        set(gca,'XTickLabel',options_.XTickLabel)
+      end
+      if options_.TeX
+        texname  = options_.varobs_TeX(index(k),:);
+        TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']);
+      end
+      title(name,'Interpreter','none');
+    end
+    eval(['print -depsc2 ' fname_ '_SmoothedObservationErrors' int2str(nbplt)]);
+    eval(['print -dpdf ' fname_ '_SmoothedObservationErrors' int2str(nbplt)]);
+    saveas(hh,[fname_ '_SmoothedObservationErrors' int2str(nbplt) '.fig']);
+    if options_.nograph, close(hh), end
+    if options_.TeX
+      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    
+      fprintf(fidTeX,'\\centering \n');
+      fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_SmoothedObservedErrors%s}\n',fname_,int2str(nbplt));
+      fprintf(fidTeX,'\\caption{Smoothed observed errors.}');
+      fprintf(fidTeX,'\\label{Fig:SmoothedObservedErrors:%s}\n',int2str(nbplt));
+      fprintf(fidTeX,'\\end{figure}\n');
+      fprintf(fidTeX,'\n');
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end    
+      end
+    end 
+    %%
+    %%  Historical and smoothed variabes
+    %%
+    if nvn 
+      [nbplt,nr,nc,lr,lc,nstar] = pltorg(n_varobs);
+      if options_.TeX
+    fidTeX = fopen([fname_ '_HistoricalAndSmoothedVariables.TeX'],'w');
+    fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation.m (Dynare).\n');
+    fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
+    fprintf(fidTeX,' \n');
+      end    
+      if nbplt == 1
+    hh = figure('Name','Historical and smoothed variables');
+    NAMES = [];
+    if options_.TeX, TeXNAMES = [], end
+    for i=1:n_varobs
+      subplot(nr,nc,i);
+      plot(1:gend,yf(i,:),'-r','linewidth',1)
+      hold on
+      plot(1:gend,rawdata(options_.first_obs+(0:gend-1),i),'-k','linewidth',1)
+      hold off
+      name    = deblank(options_.varobs(i,:));
+      NAMES   = strvcat(NAMES,name);
+      if ~isempty(options_.XTick)
+        set(gca,'XTick',options_.XTick)
+        set(gca,'XTickLabel',options_.XTickLabel)
+      end
+      xlim([1 gend])
+      if options_.TeX
+        texname = options_.varobs_TeX(i,1);
+        TeXNAMES   = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']);
+      end
+      title(name,'Interpreter','none')
+    end
+    eval(['print -depsc2 ' fname_ '_HistoricalAndSmoothedVariables' int2str(1)]);
+    eval(['print -dpdf ' fname_ '_HistoricalAndSmoothedVariables' int2str(1)]);
+    saveas(hh,[fname_ '_HistoricalAndSmoothedVariables' int2str(1) '.fig']);
+    if options_.nograph, close(hh), end
+    if options_.TeX
+      fprintf(fidTeX,'\\begin{figure}[H]\n');
+      for jj = 1:n_varobs
+        fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:)));
+      end    
+      fprintf(fidTeX,'\\centering \n');
+      fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_HistoricalAndSmoothedVariables%s}\n',fname_,int2str(1));
+      fprintf(fidTeX,'\\caption{Historical and smoothed variables.}');
+      fprintf(fidTeX,'\\label{Fig:HistoricalAndSmoothedVariables:%s}\n',int2str(1));
+      fprintf(fidTeX,'\\end{figure}\n');
+      fprintf(fidTeX,'\n');
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end    
+      else
+    for plt = 1:nbplt-1
+      hh = figure('Name','Historical and smoothed variables');
+      set(0,'CurrentFigure',hh)
+      NAMES = [];
+      if options_.TeX, TeXNAMES = [], end
+      for i=1:nstar
+        k = (plt-1)*nstar+i;
+        subplot(nr,nc,i);
+        plot(1:gend,yf(k,:),'-r','linewidth',1)
+        hold on
+        plot(1:gend,rawdata(options_.first_obs+(0:gend-1),k),'-k','linewidth',1)
+        hold off
+        name = deblank(options_.varobs(k,:));
+        NAMES = strvcat(NAMES,name);
+        if ~isempty(options_.XTick)
+          set(gca,'XTick',options_.XTick)
+          set(gca,'XTickLabel',options_.XTickLabel)
+        end
+        xlim([1 gend])
+        if options_.TeX
+          texname = options_.varobs_TeX(k,:);
+          TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']);
+        end    
+        title(name,'Interpreter','none')
+      end
+      eval(['print -depsc2 ' fname_ '_HistoricalAndSmoothedVariables' int2str(plt)]);
+      eval(['print -dpdf ' fname_ '_HistoricalAndSmoothedVariables' int2str(plt)]);
+      saveas(hh,[fname_ '_HistoricalAndSmoothedVariables' int2str(plt) '.fig']);
+      if options_.nograph, close(hh), end
+      if options_.TeX
+        fprintf(fidTeX,'\\begin{figure}[H]\n');
+        for jj = 1:nstar
+          fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:)));
+        end    
+        fprintf(fidTeX,'\\centering \n');
+        fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_HistoricalAndSmoothedVariables%s}\n',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    
+    end
+    hh = figure('Name','Historical and smoothed variables');
+    set(0,'CurrentFigure',hh)
+    NAMES = [];
+    if options_.TeX, TeXNAMES = [], end
+    for i=1:n_varobs-(nbplt-1)*nstar
+      k = (nbplt-1)*nstar+i;
+      if lr ~= 0
+        subplot(lr,lc,i);
+      else
+        subplot(nr,nc,i);
+      end    
+      plot(1:gend,yf(k,:),'-r','linewidth',1)
+      hold on
+      plot(1:gend,rawdata(options_.first_obs+(0:gend-1),k),'-k','linewidth',1)
+      hold off
+      name = deblank(options_.varobs(k,:));
+      NAMES    = strvcat(NAMES,name);
+      if ~isempty(options_.XTick)
+        set(gca,'XTick',options_.XTick)
+        set(gca,'XTickLabel',options_.XTickLabel)
+      end
+      xlim([1 gend])
+      if options_.TeX
+        texname  = options_.varobs_TeX(k,:);
+        TeXNAMES = strvcat(TeXNAMES,['$ ' deblank(texname) ' $']);
+      end
+      title(name,'Interpreter','none');
+    end
+    eval(['print -depsc2 ' fname_ '_HistoricalAndSmoothedVariables' int2str(nbplt)]);
+    eval(['print -dpdf ' fname_ '_HistoricalAndSmoothedVariables' int2str(nbplt)]);
+    saveas(hh,[fname_ '_HistoricalAndSmoothedVariables' int2str(nbplt) '.fig']);
+    if options_.nograph, close(hh), end
+    if options_.TeX
+      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    
+      fprintf(fidTeX,'\\centering \n');
+      fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_HistoricalAndSmoothedVariables%s}\n',fname_,int2str(nbplt));
+      fprintf(fidTeX,'\\caption{Historical and smoothed variables.}');
+      fprintf(fidTeX,'\\label{Fig:HistoricalAndSmoothedVariables:%s}\n',int2str(nbplt));
+      fprintf(fidTeX,'\\end{figure}\n');
+      fprintf(fidTeX,'\n');
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end    
+      end % if nbplt == 1
+    end   % if nvn
+  end     % if ~((any(bayestopt_.pshape > 0) & options_.mh_replic) 
+          % | (any(bayestopt_.pshape > 0) & options_.load_mh_file)) | ~options_.smoother  
+
+  if options_.nobs(1) < options_.nobs(end)  % recursive estimation
+    if isempty(varlist)
+      varlist = lgy_;
+    end
+    for i = 1:size(varlist,1)
+      eval(['oo_.RecursiveForecast.Mean.' varlist(i,:) '(' int2str(iter1) ',:) =' ...
+            ' oo_.Forecast.Mean.' varlist(i,:) ';']); 
+      eval(['oo_.RecursiveForecast.Median.' varlist(i,:) '(' int2str(iter1) ',:) =' ...
+            ' oo_.Forecast.Median.' varlist(i,:) ';']); 
+      eval(['oo_.RecursiveForecast.Std.' varlist(i,:) '(' int2str(iter1) ',:) =' ...
+            ' oo_.Forecast.Std.' varlist(i,:) ';']); 
+      eval(['oo_.RecursiveForecast.HPDinf.' varlist(i,:) '(' int2str(iter1) ',:) =' ...
+            ' oo_.Forecast.HPDinf.' varlist(i,:) ';']); 
+      eval(['oo_.RecursiveForecast.HPDsup.' varlist(i,:) '(' int2str(iter1) ',:) =' ...
+            ' oo_.Forecast.HPDsup.' varlist(i,:) ';']); 
+      eval(['oo_.RecursiveForecast.HPDTotalinf.' varlist(i,:) '(' int2str(iter1) ',:) =' ...
+            ' oo_.Forecast.HPDTotalinf.' varlist(i,:) ';']); 
+      eval(['oo_.RecursiveForecast.HPDTotalsup.' varlist(i,:) '(' int2str(iter1) ',:) =' ...
+            ' oo_.Forecast.HPDTotalsup.' varlist(i,:) ';']); 
+    end
+    iter1 = iter1+1;    
+  end
+end        % end for gend=options_.nobs(1):options_.nobs(end)
+
+if options_.nobs(1) < options_.nobs(end) & options_.forecast > 1
+  if isempty(varlist)
+    varlist = lgy_;
+    nvar    = size(lgy_,1);
+    SelecVariables = transpose(1:nvar);
+  else
+    nvar = size(varlist,1);
+    SelecVariables = [];
+    for i=1:nvar
+      if ~isempty(strmatch(varlist(i,:),lgy_,'exact'))
+    SelecVariables = [SelecVariables;strmatch(varlist(i,:),lgy_, ...
+                          'exact')];
+      else
+    error(['Estimation: ' varlist(i,:) ' isn''t an endogenous' ...
+           'variable'])
+      end   
+    end
+    IdObs    = zeros(n_varobs,1);
+    for j=1:n_varobs
+      for i=1:nvar
+    iobs = strmatch(options_.varobs(j,:),varlist,'exact');
+      end
+      if ~isempty(iobs)
+    IdObs(j,1) = iobs;
+      end    
+    end 
+  end
+  k = 3+min(options_.nobs(end)-options_.nobs(1)+options_.forecast, ...
+      size(rawdata,1)-options_.nobs(1));
+  data2 = rawdata(end-k+1:end,:);
+  [nbplt,nr,nc,lr,lc,nstar] = pltorg(nvar);
+  for i = 1:size(varlist,1)
+    if mod(i,nstar) == 1
+      hfig = figure('Name','Out of sample forecasts');
+    end
+    subplot(nr,nc,i)
+    hold on
+    if any(i==IdObs)
+      k2 = find(i==IdObs);
+      if options_.loglinear == 1
+    plot(1:k,exp(data2(end-k+1:end,k2))','-k','linewidth',2);
+      else
+    plot(1:k,data2(k2,end-k+1:end,k2)','-k','linewidth',2);
+      end
+      offsetx = 3;
+    else
+      offsetx = 0;
+    end      
+    for j=1:options_.nobs(end)-options_.nobs(1)+1
+      y = eval(['oo_.RecursiveForecast.Mean.' varlist(i,:) '(j,:)']);
+      y1 = eval(['oo_.RecursiveForecast.HPDinf.' varlist(i,:) '(j,:)']);
+      y2 = eval(['oo_.RecursiveForecast.HPDsup.' varlist(i,:) '(j,:)']);
+      y3 = eval(['oo_.RecursiveForecast.HPDTotalinf.' varlist(i,:) '(j,:)']);
+      y4 = eval(['oo_.RecursiveForecast.HPDTotalsup.' varlist(i,:) '(j,:)']);
+      plot(offsetx+[j:j+options_.forecast-1],y,'-b','linewidth',2)
+      plot(offsetx+[j:j+options_.forecast-1],y1,'--g', ...
+       'linewidth',1.5)
+      plot(offsetx+[j:j+options_.forecast-1],y2,'--g', ...
+       'linewidth',1.5)
+      plot(offsetx+[j:j+options_.forecast-1],y3,'--r', ...
+       'linewidth',1.5)
+      plot(offsetx+[j:j+options_.forecast-1],y4,'--r','linewidth',1.5)
+    end
+%    set(gca,'XTick',offsetx+[1 10 20 30 40 50 60 70 80 90]);
+%    set(gca,'XTickLabel',{'1';'10';'20';'30';'40';'50';'60';'70';'80';'90'});
+    %   xlim([1 options_.forecast+10]);
+    if any(k==IdObs)
+      plot([offsetx+1 offsetx+1],ylim,'-c')
+    end
+    box on
+    title(deblank(varlist(i,:)),'Interpreter','none')
+    hold off
+  end
+end
+
+
+
+
+
+
+
+      
+% SA 07-31-2004     * Added TeX output.
+%                   * Prior plots are done by calling plot_priors.m.
+%                   * All the computations related to the metropolis-hastings are made
+%                   in a new version of metropolis.m.
+%                   * Corrected a bug related to prior's bounds.
+%                   * ...
+%                   * If you do not want to see all the figures generated by dynare, you can use the option
+%                   nograph. The figures will be done and saved in formats eps, pdf and fig (so that you
+%                   should be able to modify the plots within matlab) but each figure will be erased from the
+%                   workspace when completed.
+% SA 08-04-2004     Corrected a bug related to the display of the Smooth shocks and variables plots,
+%                   for ML and posterior mode estimation. 
+% SA 09-03-2004     Compilation of TeX appendix moved to dynare.m.                                                                                                                                                                         h
diff --git a/tags/v_3.062/matlab/dynare_m.exe b/tags/v_3.062/matlab/dynare_m.exe
new file mode 100644
index 0000000000000000000000000000000000000000..e19c15a99b599081fc3fbbbe5b61b9bdd915c83d
Binary files /dev/null and b/tags/v_3.062/matlab/dynare_m.exe differ
diff --git a/tags/v_3.062/matlab/dynare_resolve.m b/tags/v_3.062/matlab/dynare_resolve.m
new file mode 100644
index 0000000000000000000000000000000000000000..2ccfef417336ce30ce6d501c850e74066da53ed6
--- /dev/null
+++ b/tags/v_3.062/matlab/dynare_resolve.m
@@ -0,0 +1,14 @@
+function [A,B,ys,info] = dynare_resolve()
+  global ys_ dr_
+  
+  [dr_,info] = resol(ys_,0);
+  
+  if info(1) > 0
+    A = [];
+    B = [];
+    ys = [];
+    return
+  end
+  
+  [A,B] = kalman_transition_matrix(dr_);
+  ys = dr_.ys;
diff --git a/tags/v_3.062/matlab/dynare_solve.m b/tags/v_3.062/matlab/dynare_solve.m
new file mode 100644
index 0000000000000000000000000000000000000000..1c774421821f81faec5ab8bce521b30ed1c4130b
--- /dev/null
+++ b/tags/v_3.062/matlab/dynare_solve.m
@@ -0,0 +1,85 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function [x,check] = dynare_solve(func,x,varargin)
+  global gstep_ options_ debug_
+  
+  options_ = set_default_option(options_,'solve_algo',2);
+  check = 0;
+  func = str2func(func);
+  if options_.solve_algo == 0
+    if ~isempty(which('fsolve')) & sscanf(version('-release'),'%d') >= 13;
+      options=optimset('fsolve');
+      options.MaxFunEvals = 20000;
+      options.TolFun=1e-8;
+      options.Display = 'off';
+      [x,fval,exitval,output] = fsolve(func,x,options,varargin{:});
+      if exitval > 0
+	check = 0;
+      else
+	check = 1;
+      end
+      return
+    else 
+      options_.solve_algo = 1;
+    end
+  end
+
+  if options_.solve_algo == 1
+    nn = size(x,1) ;
+    [x,check]=solve1(func,x,1:nn,1:nn,varargin{:});
+  elseif options_.solve_algo == 2
+    nn = size(x,1) ;
+    %    tolf = eps^(2/3) ;
+    tolf = 1e-9;
+
+    fjac = zeros(nn,nn) ;
+
+    fvec = feval(func,x,varargin{:});
+
+    i = find(~isfinite(fvec));
+    
+    if ~isempty(i)
+      if debug_
+	disp(['STEADY:  numerical initial values incompatible with the following' ...
+	      ' equations'])
+	disp(i')
+	error('exiting ...')
+      else
+	check = 1;
+	return
+      end
+    end
+    
+    f = 0.5*fvec'*fvec ;
+
+    if max(abs(fvec)) < 0.01*tolf
+      return ;
+    end
+
+    dh = max(abs(x),gstep_*ones(nn,1))*eps^(1/3);
+    for j = 1:nn
+      xdh = x ;
+      xdh(j) = xdh(j)+dh(j) ;
+      fjac(:,j) = (feval(func,xdh,varargin{:}) - fvec)./dh(j) ;
+    end
+
+    [j1,j2,r,s] = dmperm(fjac);
+    
+    for i=length(r)-1:-1:1
+      [x,check]=solve1(func,x,j1(r(i):r(i+1)-1),j2(r(i):r(i+1)-1),varargin{:});
+      if check
+	if debug_
+	  error(sprintf('Solve block = %d check = %d\n',i,check));
+	else
+	  return
+	end
+      end
+    end
+    [x,check]=solve1(func,x,1:nn,1:nn,varargin{:});
+      
+  end
+%    fvec1 = feval(func,x,varargin{:})
+
+  % 08/28/03 MJ add a final call to solve1 for solve_algo == 1 in case
+  %             initvals generates 'false' zeros in the Jacobian
+  
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/dynasave.m b/tags/v_3.062/matlab/dynasave.m
new file mode 100644
index 0000000000000000000000000000000000000000..d4e326e32b08000c7ad93eb570ee8a9024b2cca7
--- /dev/null
+++ b/tags/v_3.062/matlab/dynasave.m
@@ -0,0 +1,37 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function dynasave(s,var_list)
+% DYNASAVE :	DYNASAVE ( [ 'filename' ] )	
+%		This optional command saves the simulation results
+%		in a .MAT file.
+
+  global endo_nbr lgy_ y_
+
+  n = size(var_list,1);
+  if n == 0
+    n = endo_nbr;
+    ivar = [1:n]';
+    var_list = lgy_;
+  else
+    ivar=zeros(n,1);
+    for i=1:n
+      i_tmp = strmatch(var_list(i,:),lgy_,'exact');
+      if isempty(i_tmp)
+	error (['One of the specified variables does not exist']) ;
+      else
+	ivar(i) = i_tmp;
+      end
+    end
+  end
+
+
+%  dyn2vec(var_list(1),var_list(1));
+eval([var_list(1) '=y_(ivar(1),:)'';'])
+eval(['save ' s ' ' var_list(1) ' -mat'])
+  for i = 2:n
+%    dyn2vec(var_list(i),var_list(i));
+    eval([var_list(i) '=y_(ivar(i),:)'';'])
+    eval(['save ' s ' ' var_list(i) ' -append -mat'])
+  end
+
+
diff --git a/tags/v_3.062/matlab/dynatype.m b/tags/v_3.062/matlab/dynatype.m
new file mode 100644
index 0000000000000000000000000000000000000000..531369fa2eb620873ac157cd84585d7b7ed9487b
--- /dev/null
+++ b/tags/v_3.062/matlab/dynatype.m
@@ -0,0 +1,39 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function dynatype (s,var_list)
+% DYNATYPE :	DYNATYPE ( [ 'filename' ] )
+%		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.
+
+global lgy_ lgx_ y_ endo_nbr
+
+fid=fopen(s,'w') ;
+
+n = size(var_list,1);
+if n == 0
+  n = endo_nbr;
+  ivar = [1:n]';
+  var_list = lgy_;
+else
+  ivar=zeros(n,1);
+  for i=1:n
+    i_tmp = strmatch(var_list(i,:),lgy_,'exact');
+    if isempty(i_tmp)
+      error (['One of the specified variables does not exist']) ;
+    else
+      ivar(i) = i_tmp;
+    end
+  end
+end
+
+
+for i = 1:n
+	fprintf(fid,lgy_(ivar(i),:),'\n') ;
+	fprintf(fid,'\n') ;
+	fprintf(fid,'%15.8g\n',y_(ivar(i),:)') ;
+end
+fclose(fid) ;
+
+return ;
diff --git a/tags/v_3.062/matlab/equiv.m b/tags/v_3.062/matlab/equiv.m
new file mode 100644
index 0000000000000000000000000000000000000000..7da01d152548209b770eda87fc0cae308ae4c939
--- /dev/null
+++ b/tags/v_3.062/matlab/equiv.m
@@ -0,0 +1,6 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function y=equiv(x)
+ys_=x;
+taylor;
+y=newt('ff20_',ys_);
diff --git a/tags/v_3.062/matlab/f_var.m b/tags/v_3.062/matlab/f_var.m
new file mode 100644
index 0000000000000000000000000000000000000000..042336fd15bae19e721b8ec9af64423cf96011f3
--- /dev/null
+++ b/tags/v_3.062/matlab/f_var.m
@@ -0,0 +1,4 @@
+function b=f_var(x,a,nx)
+  x=reshape(x,nx,nx);
+  b=x-a*x*a';
+  b=b(:);
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/fbeta.m b/tags/v_3.062/matlab/fbeta.m
new file mode 100644
index 0000000000000000000000000000000000000000..b4b82d2194d9b5552aa769cfb5687cfce154f38a
--- /dev/null
+++ b/tags/v_3.062/matlab/fbeta.m
@@ -0,0 +1,6 @@
+function e = fbeta(p2,p,p1,perc)
+% must restrict p2 such that a>0 and b>0 ....
+  a = (1-p1)*p1^2/p2^2 - p1;
+  b = a*(1/p1 - 1);
+
+  e = p - pbeta(perc,a,b);
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/ff1_.m b/tags/v_3.062/matlab/ff1_.m
new file mode 100644
index 0000000000000000000000000000000000000000..57cbf5b6527f881c9f078d78a1117f4801f6262b
--- /dev/null
+++ b/tags/v_3.062/matlab/ff1_.m
@@ -0,0 +1,15 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function y=ff1_(x)
+global it_ exo_nbr exo_det_nbr ex_ ex_det_ xkmin_ ykmin_ fname_ M_
+
+n1 = size(x,1) - exo_nbr - exo_det_nbr;
+ex_(it_+xkmin_-ykmin_,:) = x(n1+[1:exo_nbr])';
+if M_.ex_det_length > 0
+  ex_det_(it_,:) = x(end-exo_det_nbr+1:end)';
+end
+fh = str2func([fname_ '_ff']);
+y=feval(fh,x(1:n1));
+
+
+
diff --git a/tags/v_3.062/matlab/ff2_.m b/tags/v_3.062/matlab/ff2_.m
new file mode 100644
index 0000000000000000000000000000000000000000..119cf5f77bbf46d92479b96281e20d5fbc39f4ac
--- /dev/null
+++ b/tags/v_3.062/matlab/ff2_.m
@@ -0,0 +1,14 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function y=ff2_(x)
+global np_ endo_nbr nf_ ex_ it_ ykmin_ xkmin_ exo_nbr jp_ jf_ kf_ exe_
+y=zeros(np_+endo_nbr+nf_,1);
+y(1:np_)=x(1:np_);
+ex_(it_-ykmin_+xkmin_,:)=x(np_+1:np_+exo_nbr)';
+y(np_+jp_)=h1_(y(1:np_),ex_(it_-ykmin_+xkmin_,:)');
+y(np_+jf_)=g1_(y(1:np_),ex_(it_-ykmin_+xkmin_,:)');
+y(kf_)=g1_(y(np_+jp_),exe_);
+y=ff_(y);
+
+
+
diff --git a/tags/v_3.062/matlab/ff2a_.m b/tags/v_3.062/matlab/ff2a_.m
new file mode 100644
index 0000000000000000000000000000000000000000..72042518ffb4bd4bdb94ccdd6a4bd599f3e7f942
--- /dev/null
+++ b/tags/v_3.062/matlab/ff2a_.m
@@ -0,0 +1,4 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function z=ff2a_(y,dr)
+  z=fff_(y)+dr.delta_s;
diff --git a/tags/v_3.062/matlab/ff_simul.m b/tags/v_3.062/matlab/ff_simul.m
new file mode 100644
index 0000000000000000000000000000000000000000..880b976b96710b35e5d15d1ada2f979524fdb592
--- /dev/null
+++ b/tags/v_3.062/matlab/ff_simul.m
@@ -0,0 +1,10 @@
+function z=ff_simul(x,y1,m,state,tempu,o1,o2,o3,delta)
+  global fname_ dr_
+
+  fh = str2func([fname_ '_ff']);
+  tempx = [x(dr.order_var(o1:o2))-dr.ys(dr.order_var(o1:o2)); state];
+  tempxx = kron(tempx,tempx);
+  tempxu = kron(tempx,tempu);
+%  y2 = dr.ys(dr.order_var)+dr.ghs2/2+dr.ghx*tempx+dr.ghu*tempu+0.5*(dr.ghxx*tempxx+dr.ghuu*tempuu)+dr.ghxu*tempxu;
+  y2(dr.order_var(o3:end)) = m+dr.ghx(o3:end,:)*tempx+0.5*dr.ghxx(o3:end,:)*tempxx+dr.ghxu(o3:end,:)*tempxu;
+  z=feval(fh,(y1; x; y2))+delta;
diff --git a/tags/v_3.062/matlab/ff_simul1.m b/tags/v_3.062/matlab/ff_simul1.m
new file mode 100644
index 0000000000000000000000000000000000000000..d93084bcae28a0a791f3ad4b1d8bc8ebf46528d8
--- /dev/null
+++ b/tags/v_3.062/matlab/ff_simul1.m
@@ -0,0 +1,7 @@
+function z=ff_simul1(x,y1,m,state,o1,o2,o3,k)
+  global fname_ dr_
+
+  fh = str2func([fname_ '_ff']);
+  tempx = [x(dr_.order_var(o1:o2))-dr_.ys(dr_.order_var(o1:o2)); state];
+  y2 = m+dr_.ghx(o3:end,:)*tempx;
+  z=feval(fh,[y1; x; y2(k)]);
diff --git a/tags/v_3.062/matlab/ff_simul2.m b/tags/v_3.062/matlab/ff_simul2.m
new file mode 100644
index 0000000000000000000000000000000000000000..742727b94fbcc55d1ae00e03c5de1476d2238cb8
--- /dev/null
+++ b/tags/v_3.062/matlab/ff_simul2.m
@@ -0,0 +1,9 @@
+function z=ff_simul2(x,y1,m,state,o1,o2,o3,k)
+  global fname_ dr_
+
+  fh = str2func([fname_ '_ff']);
+  tempx = [x(dr_.order_var(o1:o2))-dr_.ys(dr_.order_var(o1:o2)); state];
+  tempxx = kron(tempx,tempx);
+%  y2 = dr.ys(dr.order_var)+dr.ghs2/2+dr.ghx*tempx+dr.ghu*tempu+0.5*(dr.ghxx*tempxx+dr.ghuu*tempuu)+dr.ghxu*tempxu;
+  y2 = m+dr_.ghx(o3:end,:)*tempx+0.5*dr_.ghxx(o3:end,:)*tempxx;
+  z=feval(fh,[y1; x; y2(k)])+dr_.fuu;
diff --git a/tags/v_3.062/matlab/fff.m b/tags/v_3.062/matlab/fff.m
new file mode 100644
index 0000000000000000000000000000000000000000..38533b5d170a9c87c6cf1866b33ef6a6a9a2a8b4
--- /dev/null
+++ b/tags/v_3.062/matlab/fff.m
@@ -0,0 +1,12 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function x=fff(y)
+
+global ykmin_ ykmax_ iy_
+
+iyr = find(reshape(iy_'>0,(ykmin_+ykmax_+1)*size(iy_,2),1)) ;
+y = kron(ones(ykmin_+ykmax_+1,1),y) ;
+y = y(iyr,:) ;
+x = ff_(y) ;
+
+return ; 
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/ffill.m b/tags/v_3.062/matlab/ffill.m
new file mode 100644
index 0000000000000000000000000000000000000000..c95cf4954da09ddb8593b0efa0a5af7582f87d21
--- /dev/null
+++ b/tags/v_3.062/matlab/ffill.m
@@ -0,0 +1,24 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function [a,b] = ffill(x,ixc,y)
+
+xc = size(x,1) ;
+
+if isempty(y)
+  b = [ixc; 0];
+  a = [x zeros(size(x,1),1)];
+else
+  yc = size(y,1) ;
+  b = [ixc;yc] ;
+
+  if xc > yc
+    a = [x [y;zeros(xc-yc,size(y,2))]] ;
+  elseif yc > xc
+    a = [[x;zeros(yc-xc,size(x,2))] y] ;
+  else
+    a = [x y] ;
+  end
+
+end
+
+% 2001/09/1 MJ corrected for absent lags
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/fgamma.m b/tags/v_3.062/matlab/fgamma.m
new file mode 100644
index 0000000000000000000000000000000000000000..5ed62a90f67b0f2c95be3192f0bc20175a9937b2
--- /dev/null
+++ b/tags/v_3.062/matlab/fgamma.m
@@ -0,0 +1,4 @@
+function e = fgamma(p2,p,p1,perc)
+  b = p2^2/p1;
+  a = p1/b;
+  e = p - pgamma(perc,a,b);
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/figamm.m b/tags/v_3.062/matlab/figamm.m
new file mode 100644
index 0000000000000000000000000000000000000000..067a957b70002ec3dd2be1ea581e0360f085d06a
--- /dev/null
+++ b/tags/v_3.062/matlab/figamm.m
@@ -0,0 +1,2 @@
+function e = figamm(p2,p,p1,perc)
+  e = p - pgamma(1/perc,p2/2,2/p1);
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/fnorm.m b/tags/v_3.062/matlab/fnorm.m
new file mode 100644
index 0000000000000000000000000000000000000000..f842fbc2a859b96f1532d149ac26abf68f0dbbb9
--- /dev/null
+++ b/tags/v_3.062/matlab/fnorm.m
@@ -0,0 +1,2 @@
+function e = fnorm(p2,p,p1,perc)
+  e = p - pnorm(perc,p1,p2);
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/forcst.m b/tags/v_3.062/matlab/forcst.m
new file mode 100644
index 0000000000000000000000000000000000000000..afabf587287890f794b63a0e60b59c20998f679d
--- /dev/null
+++ b/tags/v_3.062/matlab/forcst.m
@@ -0,0 +1,58 @@
+function [yf,var_yf] = forcst(dr,y0,k,var_list)
+  global endo_nbr exo_nbr ykmin_ Sigma_e_ ex_ options_ lgy_
+  
+  options_.periods = k;
+  make_ex_;
+  yf = simult_(y0,dr,ex_(1:k,:),1);
+
+  [A,B] = kalman_transition_matrix(dr);
+  
+  sigma_u = B*Sigma_e_*B';
+  sigma_y = 0;
+  
+  for i=1:k
+    sigma_y = sigma_y+sigma_u;
+    var_yf(i,dr.order_var) = diag(sigma_y(1:endo_nbr,1:endo_nbr))';
+    if i == k
+      break
+    end
+    sigma_u = A*sigma_u*A';
+  end
+
+  nvar = size(var_list,1);
+  if nvar == 0
+    nvar = endo_nbr;
+    ivar = [1:nvar];
+  else
+    ivar=zeros(nvar,1);
+    for i=1:nvar
+      i_tmp = strmatch(var_list(i,:),lgy_,'exact');
+      if isempty(i_tmp)
+	disp(var_list(i,:));
+	error (['One of the variable specified does not exist']) ;
+      else
+	ivar(i) = i_tmp;
+      end
+    end
+  end
+
+  for i=1:nvar
+    my_subplot(i,nvar,2,3,'Forecasts');
+    
+    plot([-ykmin_+1:0],y0(ivar(i),1:ykmin_),'b-',...
+	 [1:k],yf(ivar(i),ykmin_+1:end),'g-',...
+	 [1:k],yf(ivar(i),ykmin_+1:end)'+2*sqrt(var_yf(:,ivar(i))),'g:',...
+	 [1:k],yf(ivar(i),ykmin_+1:end)'-2*sqrt(var_yf(:,ivar(i))),'g:',...
+	 [1 k],repmat(dr.ys(ivar(i)),1,2),'r-');
+    title(lgy_(ivar(i),:));
+  end
+
+
+
+
+
+
+
+
+
+
diff --git a/tags/v_3.062/matlab/forcst2.m b/tags/v_3.062/matlab/forcst2.m
new file mode 100644
index 0000000000000000000000000000000000000000..06c712078d53dedf7cf389c5760db26e190b1aa2
--- /dev/null
+++ b/tags/v_3.062/matlab/forcst2.m
@@ -0,0 +1,44 @@
+function yf=forcst2(y0,horizon,dr,n)
+  global Sigma_e_ endo_nbr exo_nbr options_ ykmin_
+  
+  options_ = set_default_option(options_,'simul_seed',0);
+  order = options_.order;
+  seed = options_.simul_seed;
+
+  k1 = [ykmin_:-1:1];
+  k2 = dr.kstate(find(dr.kstate(:,2) <= ykmin_+1),[1 2]);
+  k2 = k2(:,1)+(ykmin_+1-k2(:,2))*endo_nbr;
+
+  it_ = ykmin_ + 1 ;
+
+  % eliminate shocks with 0 variance
+  i_exo_var = setdiff([1:exo_nbr],find(diag(Sigma_e_) == 0));
+  nxs = length(i_exo_var);
+
+  chol_S = chol(Sigma_e_(i_exo_var,i_exo_var));
+
+  if seed == 0
+    randn('state',sum(100*clock));
+  else
+    randn('state',seed);
+  end
+  
+  if ~isempty(Sigma_e_)
+    e = randn(nxs,n,horizon);
+  end
+  
+  B1 = dr.ghu(:,i_exo_var)*chol_S';
+
+  yf = zeros(endo_nbr,horizon+ykmin_,n);
+  yf(:,1:ykmin_,:,:) = repmat(y0,[1,1,n]);
+  
+  j = ykmin_*endo_nbr;
+  for i=ykmin_+(1:horizon)
+    tempx1 = reshape(yf(:,k1,:),[j,n]);
+    tempx = tempx1(k2,:);
+    yf(:,i,:) = dr.ghx*tempx+B1*squeeze(e(:,:,i-ykmin_));
+    k1 = k1+1;
+  end
+  
+  yf(dr.order_var,:,:) = yf;
+  yf=permute(yf,[2 1 3]);  
diff --git a/tags/v_3.062/matlab/forcst2a.m b/tags/v_3.062/matlab/forcst2a.m
new file mode 100644
index 0000000000000000000000000000000000000000..402210823288d91267057d17503101b747de8f43
--- /dev/null
+++ b/tags/v_3.062/matlab/forcst2a.m
@@ -0,0 +1,23 @@
+function yf=forcst2a(y0,dr,e)
+  global Sigma_e_ endo_nbr exo_nbr options_ ykmin_
+  
+  horizon = size(e,1);
+  options_ = set_default_option(options_,'simul_seed',0);
+  order = options_.order;
+
+  k1 = [ykmin_:-1:1];
+  k2 = dr.kstate(find(dr.kstate(:,2) <= ykmin_+1),[1 2]);
+  k2 = k2(:,1)+(ykmin_+1-k2(:,2))*endo_nbr;
+
+  yf = zeros(horizon+ykmin_,endo_nbr);
+  yf(1:ykmin_,:) = y0';
+  
+  j = ykmin_*endo_nbr;
+  for i=ykmin_+(1:horizon)
+    tempx = yf(k1,:)';
+    yf(i,:) = tempx(k2)'*dr.ghx';
+    k1 = k1+1;
+  end
+  
+   yf(:,dr.order_var) = yf;
+   
diff --git a/tags/v_3.062/matlab/forecast.m b/tags/v_3.062/matlab/forecast.m
new file mode 100644
index 0000000000000000000000000000000000000000..60c3e5a6786365a521935246e671f2585bdec5ee
--- /dev/null
+++ b/tags/v_3.062/matlab/forecast.m
@@ -0,0 +1,45 @@
+% Copyright (C) 2005 Michel Juillard
+%
+function forecast(var_list)
+  global options_ dr_ ys_ endo_nbr exo_nbr exo_det_nbr ykmin_ y_ ex_det_ 
+  global lgy_ lgx_det_ oo_ exe_det_
+  
+  old_options = options_;
+  options_ = set_default_option(options_,'periods',40);
+  if options_.periods == 0
+    options_.periods = 40;
+  end
+  
+  if size(y_,2) < ykmin_
+    y0 = repmat(ys_,ykmin_);
+  else
+    y0 = y_(:,1:ykmin_);
+  end
+  
+  if exo_det_nbr == 0
+    [yf,var_yf] = forcst(dr_,y0,options_.periods,var_list);
+  else
+    if options_.periods > size(ex_det_,1)
+      ex = zeros(options_.periods,exo_nbr);
+      ex_det_ = [ ex_det_; repmat(exe_det_',options_.periods- ...
+				  size(ex_det_,1),1)];
+    elseif options_.periods < size(ex_det_,1)
+      ex = zeros(size(ex_det_,1),exo_nbr); 
+    end
+    [yf,int_width] = simultxdet(y0,dr_,ex,ex_det_,options_.order, ...
+				  var_list);
+  end
+  
+  for i=1:endo_nbr
+    eval(['oo_.forecast.Mean.' lgy_(i,:) '= yf(' int2str(i) ',:)'';']);
+    eval(['oo_.forecast.HPDinf.' lgy_(i,:) '= yf(' int2str(i) ',2:end)''-' ...
+		    ' int_width(:,' int2str(i) ');']);
+    eval(['oo_.forecast.HPDsup.' lgy_(i,:) '= yf(' int2str(i) ',2:end)''+' ...
+		    ' int_width(:,' int2str(i) ');']);
+  end
+
+  for i=1:exo_det_nbr
+    eval(['oo_.forecast.Exogenous.' lgx_det_(i,:) '= ex_det_(:,' int2str(i) ');']);
+  end
+  
+  options_ = old_options;
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/fs_dyn.m b/tags/v_3.062/matlab/fs_dyn.m
new file mode 100644
index 0000000000000000000000000000000000000000..602b8b6ee335c5774f1a812c633477dd55ddebf0
--- /dev/null
+++ b/tags/v_3.062/matlab/fs_dyn.m
@@ -0,0 +1,9 @@
+function fs_dyn(a,b)
+  nu=b;
+  s=b*a^2;
+  mu=sqrt(s/2)*gamma((nu-1)/2)/gamma(nu/2);
+  sigma=sqrt(s/(nu-2)-mu^2);
+
+  disp('     FS to DYNARE conversion for inverse gamma parameters')
+  disp(sprintf('          Frank''s parameters: %f %f',a,b))
+  disp(sprintf('          mu = %f       sigma = %f',mu,sigma))
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/ftest.m b/tags/v_3.062/matlab/ftest.m
new file mode 100644
index 0000000000000000000000000000000000000000..61d380270f80e786000be5407d9b51b29e9e8d64
--- /dev/null
+++ b/tags/v_3.062/matlab/ftest.m
@@ -0,0 +1,69 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function ftest (s1,s2)
+
+global nvx nvy x y lag1
+
+if size(s1,1) ~= 2
+	error ('Sp�cifiez deux fichiers pour la comparaison.') ;
+end
+
+for i = 1:2
+	if ~ isempty(find(abs(s1(i,:)) == 46))
+		error ('Entrez les noms de fichiers sans extensions.') ;
+	end
+end
+
+s1 = [s1 [' ';' ']] ;
+file1 = [s1(1,1:min(find(abs(s1(1,:)) == 32))-1) '.BIN'] ;
+file2 = [s1(2,1:min(find(abs(s1(2,:)) == 32))-1) '.BIN'] ;
+
+fid=fopen(file1,'r') ;
+n1 = fread(fid,1,'int') ;
+n2 = fread(fid,1,'int') ;
+n3 = fread(fid,1,'int') ;
+lag1 = fread(fid,4,'int') ;
+nvx = fread(fid,[n1,n3],'int') ;
+x = fread(fid,[n1,n2],'float64') ;
+fclose(fid) ;
+nvx = setstr(nvx) ;
+
+fid=fopen(file2,'r') ;
+n1 = fread(fid,1,'int') ;
+n2 = fread(fid,1,'int') ;
+n3 = fread(fid,1,'int') ;
+lag2 = fread(fid,4,'int') ;
+nvy = fread(fid,[n1,n3],'int') ;
+y = fread(fid,[n1,n2],'float64') ;
+fclose(fid) ;
+nvy = setstr(nvy) ;
+
+if size(x,1) ~= size(y,1)
+	error ('FTEST: The two files don''t have the same number of variables.');
+end
+
+for i = 1:size(x,1)
+	if ~ strcmp(nvx(i,:),nvy(i,:))
+		error ('FTEST: The two files don''t have the same  variables.') ;	
+	end
+end
+
+if nnz(lag1 - lag2) > 0
+	error ('FTEST: Leads and lags aren''t the same in both files.') ;
+end
+
+j = zeros(size(s2,1),1);
+for i=1:size(s2,1)
+	k = strmatch(s2(i,:),nvx,'exact') ;
+	if isempty(k)
+	  t = ['FTEST: Variable ' s2(i) 'doesn''t exist'] ;
+	  error (t) ;
+	else
+	  j(i) =k;
+	end
+end
+
+y = y(j,:) ;
+x = x(j,:) ;
+
+%06/18/01 MJ replaced beastr by strmatch
diff --git a/tags/v_3.062/matlab/fx_.m b/tags/v_3.062/matlab/fx_.m
new file mode 100644
index 0000000000000000000000000000000000000000..84f4b6370c8dee352fae57b946b873e6827786ef
--- /dev/null
+++ b/tags/v_3.062/matlab/fx_.m
@@ -0,0 +1,10 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function y=fx_(x)
+global ys_ ykmin_ ykmax_ it_ iy_ xkmin_ ex_ fname_
+y=repmat(ys_,ykmin_+ykmax_+1,1);
+iyr0=find(reshape(iy_',size(iy_,1)*size(iy_,2),1));
+y=y(iyr0);
+ex_(it_+xkmin_-ykmin_,:)=x';
+fh = str2func([fname_ '_ff']);
+y=feval(fh,y);
diff --git a/tags/v_3.062/matlab/gamm_rnd.m b/tags/v_3.062/matlab/gamm_rnd.m
new file mode 100644
index 0000000000000000000000000000000000000000..757461bac3dbe83280394cad1da3db852c3f2f9c
--- /dev/null
+++ b/tags/v_3.062/matlab/gamm_rnd.m
@@ -0,0 +1,72 @@
+function gb = gamm_rnd(nrow,m,k)
+% PURPOSE: a matrix of random draws from the gamma distribution
+%---------------------------------------------------
+% USAGE: r = gamm_rnd(n,m,k)
+% where: n = the size of the vector drawn 
+%        m = a parameter such that the mean of the gamma = m/k
+%        k = a parameter such that the variance of the gamma = m/(k^2)
+%        note: m=r/2, k=2 equals chisq r random deviate 
+%---------------------------------------------------
+% RETURNS:
+%        r = an n x 1 vector of random numbers from the gamma distribution      
+% --------------------------------------------------
+% SEE ALSO: gamm_inv, gamm_pdf, gamm_cdf
+%---------------------------------------------------
+% NOTE: written by: Michael Gordy, 15 Sept 1993
+%                   mbgordy@athena.mit.edu
+%---------------------------------------------------
+% REFERENCES: Luc Devroye, Non-Uniform Random Variate Generation, 
+%            New York: Springer Verlag, 1986, ch 9.3-6.
+
+if nargin ~= 3
+error('Wrong # of arguments to gamm_rnd');
+end;
+
+ncol = 1;
+gb=zeros(nrow,ncol);
+if m<=1
+  % Use RGS algorithm by Best, p. 426
+  c=1/m; 
+  t=0.07+0.75*sqrt(1-m);
+  b=1+exp(-t)*m/t;
+  for i1=1:nrow
+    for i2=1:ncol
+       accept=0;
+       while accept==0
+          u=rand; w=rand; v=b*u;
+          if v<=1
+             x=t*(v^c);
+             accept=((w<=((2-x)/(2+x))) | (w<=exp(-x)));
+          else
+             x=-log(c*t*(b-v));
+             y=x/t;
+             accept=(((w*(m+y-m*y))<=1) | (w<=(y^(m-1))));
+          end
+       end
+       gb(i1,i2)=x;
+    end
+  end
+else
+  % Use Best's rejection algorithm XG, p. 410
+  b=m-1;
+  c=3*m-0.75;
+  for i1=1:nrow
+    for i2=1:ncol
+       accept=0;
+       while accept==0
+          u=rand;  v=rand;
+          w=u*(1-u);  y=sqrt(c/w)*(u-0.5);
+          x=b+y;
+          if x >= 0
+             z=64*(w^3)*v*v;
+             accept=(z<=(1-2*y*y/x)) ...
+                    | (log(z)<=(2*(b*log(x/b)-y)));
+          end
+       end
+       gb(i1,i2)=x;
+    end
+  end
+end
+gb=gb/k;    
+    
+
diff --git a/tags/v_3.062/matlab/gcompare.m b/tags/v_3.062/matlab/gcompare.m
new file mode 100644
index 0000000000000000000000000000000000000000..052b5213338a737c9f0abd149b39c71102e47feb
--- /dev/null
+++ b/tags/v_3.062/matlab/gcompare.m
@@ -0,0 +1,41 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function gcompare(s1,s2)
+% 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.
+
+
+global dsmpl_ iter_ ykmin_
+global nvx nvy x y lag1
+
+ftest(s1,s2) ;
+
+ix = [1-lag1(1):size(x,2)-lag1(1)]' ;
+i = [lag1(1):size(ix,1)-lag1(2)+1]' ;
+
+if dsmpl_ == 0
+        i = [ykmin_:size(y,2)]' ;
+else
+	i = [dsmpl_(1):dsmpl_(2)]' ;
+end
+
+for k = 1:size(x,1)
+	figure ;
+	plot (ix(i),x(k,i),ix(i),y(k,i)) ;
+	xlabel (['Periods']) ;
+	title (['Variable ' s2(k,:)]) ;
+	l = min(i) + 1;
+	ll = max(i) - 1 ;
+	text (l,x(k,l),s1(1,:)) ;
+	text (ll,y(k,ll),s1(2,:)) ;
+end
+
+% 06/18/01 MJ corrected treatment of dsmpl_
+% 06/24/01 MJ removed color specification
+
+
+
diff --git a/tags/v_3.062/matlab/generalized_cholesky.m b/tags/v_3.062/matlab/generalized_cholesky.m
new file mode 100644
index 0000000000000000000000000000000000000000..f32f03ef78262487fb3c902bc1148b34f5ed1f35
--- /dev/null
+++ b/tags/v_3.062/matlab/generalized_cholesky.m
@@ -0,0 +1,54 @@
+% proc gmchol(A);
+%    /* calculates the Gill-Murray generalized choleski decomposition */
+%    /* input matrix A must be non-singular and symmetric */
+%    /* Author: Jeff Gill. Part of the Hessian Project. */
+%    local i,j,k,n,sum,R,theta_j,norm_A,phi_j,delta,xi_j,gamm,E,beta_j;
+
+function AA = generalized_cholesky(A);
+
+n = rows(A);
+R = eye(n);
+E = zeros(n,n);
+norm_A = max(sum(abs(A))');
+gamm   = max(abs(diag(A))); 
+delta = max([eps*norm_A;eps]);
+
+for j = 1:n; 
+    theta_j = 0;
+    for i=1:n;
+        somme = 0;
+        for k=1:i-1;	
+	        somme = somme + R(k,i)*R(k,j);
+        end;
+        R(i,j) = (A(i,j) - somme)/R(i,i);
+	    if (A(i,j) -somme) > theta_j;
+	        theta_j = A(i,j) - somme;
+        end;
+	    if i > j;
+	        R(i,j) = 0;
+        end;
+    end;
+    somme = 0;
+    for k=1:j-1;	
+        somme = somme + R(k,j)^2;
+    end;
+    phi_j = A(j,j) - somme;
+    if j+1 <= n;
+        xi_j = max(abs(A((j+1):n,j)));
+    else;
+        xi_j = abs(A(n,j));
+    end;
+    beta_j = sqrt(max([gamm ; (xi_j/n) ; eps]));
+    if all(delta >= [abs(phi_j);((theta_j^2)/(beta_j^2))]);
+        E(j,j) = delta - phi_j;
+    elseif all(abs(phi_j) >= [((delta^2)/(beta_j^2));delta]);
+        E(j,j) = abs(phi_j) - phi_j;
+    elseif all(((theta_j^2)/(beta_j^2)) >= [delta;abs(phi_j)]);
+        E(j,j) = ((theta_j^2)/(beta_j^2)) - phi_j;
+    end;
+    R(j,j) = sqrt(A(j,j) - somme + E(j,j));
+end;
+AA = R'*R;
+
+
+
diff --git a/tags/v_3.062/matlab/generalized_cholesky2.m b/tags/v_3.062/matlab/generalized_cholesky2.m
new file mode 100644
index 0000000000000000000000000000000000000000..c60dd456e066d70038dc7a561d20a2beb97f2848
--- /dev/null
+++ b/tags/v_3.062/matlab/generalized_cholesky2.m
@@ -0,0 +1,122 @@
+% /*
+% **  By Jeff Gill, April 2002.
+% **
+% **  This procedure produces:
+% **
+% **  y = chol(A+E), where E is a diagonal matrix with each element as small
+% **  as possible, and A and E are the same size.  E diagonal values are 
+% **  constrained by iteravely updated Gerschgorin bounds.  
+% **
+% **  REFERENCES:
+% **
+% **  Jeff Gill and Gary King. 1998. "`Hessian not Invertable.' Help!"
+% **  manuscript in progress, Harvard University.
+% **
+% **  Robert B. Schnabel and Elizabeth Eskow. 1990. "A New Modified Cholesky
+% **  Factorization," SIAM Journal of Scientific Statistical Computating,
+% **  11, 6: 1136-58.
+% **
+% **
+% **
+% **  St�phane Adjemian (2003): translation from Gauss to Matlab.  
+% */
+function AA = generalized_cholesky2(A)
+
+n = size(A,1);
+L = zeros(n,n);
+deltaprev = 0;
+gamm = max(abs(diag(A))); 
+tau = eps^(1/3);
+
+if  min(eig(A)) > 0;
+    tau = -1000000;
+end;
+
+norm_A = max(sum(abs(A))');
+gamm = max(abs(diag(A))); 
+delta = max([eps*norm_A;eps]);
+Pprod = eye(n);
+  
+if n > 2; 
+    for k = 1,n-2;
+         if min((diag(A(k+1:n,k+1:n))' - A(k,k+1:n).^2/A(k,k))') < tau*gamm ...
+                & min(eig(A((k+1):n,(k+1):n))) < 0;
+            [tmp,dmax] = max(diag(A(k:n,k:n)));
+            if A(k+dmax-1,k+dmax-1) > A(k,k);
+                P = eye(n);
+                Ptemp = P(k,:); 
+                P(k,:) = P(k+dmax-1,:); 
+                P(k+dmax-1,:) = Ptemp;
+                A = P*A*P;
+                L = P*L*P;
+                Pprod = P*Pprod;
+             end;
+             g = zeros(n-(k-1),1);
+             for i=k:n;  
+                if i == 1;
+	                sum1 = 0;
+                else;
+	                sum1 = sum(abs(A(i,k:(i-1)))');
+	            end;
+                if i == n;
+	                sum2 = 0;
+                else;
+                    sum2 = sum(abs(A((i+1):n,i)));
+	            end; 
+                g(i-k+1) = A(i,i) - sum1 - sum2;
+             end; 
+             [tmp,gmax] = max(g);
+             if gmax ~= k;
+                P = eye(n);
+                Ptemp  = P(k,:); 
+                P(k,:) = P(k+dmax-1,:); 
+                P(k+dmax-1,:) = Ptemp;
+                A = P*A*P;
+                L = P*L*P;
+                Pprod = P*Pprod;
+             end; 
+             normj = sum(abs(A(k+1:n,k)));
+             delta = max([0;deltaprev;-A(k,k)+normj;-A(k,k)+tau*gamm]);
+             if delta > 0;
+               A(k,k) = A(k,k) + delta;
+               deltaprev = delta;
+             end;
+         end; 
+         A(k,k) = sqrt(A(k,k));
+         L(k,k) = A(k,k); 
+         for i=k+1:n; 
+            if L(k,k) > eps; 
+                A(i,k) = A(i,k)/L(k,k); 
+            end;
+	        L(i,k) = A(i,k);
+            A(i,k+1:i) = A(i,k+1:i) - L(i,k)*L(k+1:i,k)';
+            if A(i,i) < 0; 
+                A(i,i) = 0; 
+            end;
+         end;
+    end;
+end;
+A(n-1,n) = A(n,n-1);
+eigvals  = eig(A(n-1:n,n-1:n));
+dlist    = [ 0 ; deltaprev ;...
+        -min(eigvals)+tau*max((inv(1-tau)*max(eigvals)-min(eigvals))|gamm) ]; 
+if dlist(1) > dlist(2); 
+    delta = dlist(1);   
+else;
+    delta = dlist(2);
+end;
+if delta < dlist(3);
+    delta = dlist(3);
+end;
+if delta > 0;
+    A(n-1,n-1) = A(n-1,n-1) + delta;
+    A(n,n) = A(n,n) + delta;
+    deltaprev = delta;
+end;
+A(n-1,n-1) = sqrt(A(n-1,n-1));
+L(n-1,n-1) = A(n-1,n-1);
+A(n,n-1) = A(n,n-1)/L(n-1,n-1);
+L(n,n-1) = A(n,n-1);
+A(n,n) = sqrt(A(n,n) - L(n,(n-1))^2);
+L(n,n) = A(n,n);
+AA = Pprod'*L'*Pprod';
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/gensylv.dll b/tags/v_3.062/matlab/gensylv.dll
new file mode 100755
index 0000000000000000000000000000000000000000..72754a104aa749503d1108677334bce6f588704d
Binary files /dev/null and b/tags/v_3.062/matlab/gensylv.dll differ
diff --git a/tags/v_3.062/matlab/get_posterior_parameters.m b/tags/v_3.062/matlab/get_posterior_parameters.m
new file mode 100644
index 0000000000000000000000000000000000000000..1f51ce6983eec1364afd0b9a8638bd4876247aa1
--- /dev/null
+++ b/tags/v_3.062/matlab/get_posterior_parameters.m
@@ -0,0 +1,56 @@
+function xparam=get_posterior_parameters(type)
+  global estim_params_ oo_ Sigma_e_ lgx_ options_
+  
+  nvx = estim_params_.nvx;
+  nvn = estim_params_.nvn;
+  ncx = estim_params_.ncx;
+  ncn = estim_params_.ncn;
+  np  = estim_params_.np;
+  
+  xparam = zeros(nvx+nvn+ncx+ncn+np,1);
+  
+  m = 1;
+  for i=1:nvx
+    k1 = estim_params_.var_exo(i,1);
+    name1 = deblank(lgx_(k1,:));
+    xparam(m) = eval(['oo_.' type '.shocks_std.' name1]);
+    Sigma_e_(k1,k1) = xparam(m)^2;
+    m = m+1;
+  end
+  
+  for i=1:nvn
+    k1 = estim_params_.var_endo(i,1);
+    name1 = deblank(options_.varobs(k1,:));
+    xparam(m) = eval(['oo_.' type '.measurement_errors_std.' name1]);
+    m = m+1;
+  end
+  
+  for i=1:ncx
+    k1 = estim_params_.var_exo(i,1);
+    k2 = estim_params_.var_exo(i,1);
+    name1 = deblank(lgx_(k1,:));
+    name2 = deblank(lgx_(k2,:));
+    xparam(m) = eval(['oo_.' type '.shocks_corr.' name1 '_' name2]);
+    Sigma_e_(k1,k2) = xparam(m);
+    Sigma_e_(k2,k1) = xparam(m);
+    m = m+1;
+  end
+  
+  for i=1:ncn
+    k1 = estim_params_.var_endo(i,1);
+    k2 = estim_params_.var_endo(i,1);
+    name1 = deblank(options_.varobs(k1,:));
+    name2 = deblank(options_.varobs(k2,:));
+    xparam(m) = eval(['oo_.' type '.measurement_errors_corr.' name1 '_' name2]);
+    m = m+1;
+  end
+
+  for i=1:np
+    name1 = deblank(estim_params_.param_names(i,:));
+    xparam(m) = eval(['oo_.' type '.parameters.' name1]);
+    assignin('base',name1,xparam(m));
+    m = m+1;
+  end
+  
+
+  
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/get_the_name.m b/tags/v_3.062/matlab/get_the_name.m
new file mode 100644
index 0000000000000000000000000000000000000000..df70a381f8e8218887919236acd34febfd4c1ca9
--- /dev/null
+++ b/tags/v_3.062/matlab/get_the_name.m
@@ -0,0 +1,59 @@
+function [nam,texnam] = get_the_name(k,TeX)
+% stephane.adjemian@cepremap.cnrs.fr [07-13-2004]
+global lgx_ lgy_ lgx_TeX_ estim_params_ options_
+
+nam = [];
+texnam = [];
+
+if k <= estim_params_.nvx
+    vname = deblank(lgx_(estim_params_.var_exo(k,1),:));
+    nam=['SE_',vname];
+    if TeX
+      %        tname  = deblank(lgx_TeX_(estim_params_.var_exo(k,1),:));
+      tname = vname;
+      texnam = ['$ SE_{' tname '} $'];
+    end
+elseif  k <= (estim_params_.nvx+estim_params_.nvn)
+    vname = deblank(options_.varobs(estim_params_.var_endo(k-estim_params_.nvx,1),:));
+    nam=['SE_EOBS_',vname];
+    if TeX
+      %  tname  =
+      %  deblank(options_.TeX_varobs(estim_params_.var_endo(k-estim_params_.nvx,1),:));
+      tname = vname;
+        texnam = ['$ SE_{' tname '} $'];
+    end
+elseif  k <= (estim_params_.nvx+estim_params_.nvn+estim_params_.ncx)
+    jj = k - (estim_params_.nvx+estim_params_.nvn);
+    k1 = estim_params_.corrx(jj,1);
+    k2 = estim_params_.corrx(jj,2);
+    vname = [deblank(lgx_(k1,:)) '_' deblank(lgx_(k2,:))];
+    nam=['CC_',vname];
+    if TeX
+        % tname  = [deblank(lgx_TeX_(k1,:)) ',' deblank(lgx_TeX_(k2,:))];
+	tname = vname;
+        texnam = ['$ CC_{' tname '} $'];
+    end
+elseif  k <= (estim_params_.nvx+estim_params_.nvn+estim_params_.ncx+ ...
+		            estim_params_.ncn)
+    jj = k - (estim_params_.nvx+estim_params_.nvn+estim_params_.ncx);
+    k1 = estim_params_.corrn(jj,1);
+    k2 = estim_params_.corrn(jj,2);
+    vname = [deblank(lgy_(k1,:)) '_' deblank(lgy_(k2,:))];
+    nam=['CC_EOBS_' vname];
+    if TeX
+        % tname  = [deblank(lgy_TeX_(k1,:)) ',' deblank(lgy_TeX_(k2,:))];
+	tname = vname;
+        texnam =['$ CC_{' tname '} $'];
+    end
+else
+    jj = k - (estim_params_.nvx+estim_params_.nvn+estim_params_.ncx+estim_params_.ncn); 
+    nam = deblank(estim_params_.param_names(jj,:));
+    if TeX
+        % texnam = ['$ '  deblank(estim_params_.tex(jj,:))  ' $'];
+        texnam = nam;
+    end    
+end
+
+
+% SA 07-15-2004 Added TeX names.
+% SA 12-02-2004 Changed non-TeX names format.
diff --git a/tags/v_3.062/matlab/hessext.m b/tags/v_3.062/matlab/hessext.m
new file mode 100644
index 0000000000000000000000000000000000000000..2b49ce8bd05ae9b47b26fd997d27e6f737dea2f5
--- /dev/null
+++ b/tags/v_3.062/matlab/hessext.m
@@ -0,0 +1,86 @@
+function [H] = hessext(f,x,options,varargin)
+%---------------------------------------------------------------------------
+%HESSEXT   Numerical approximation for hessian.
+%          The method is Richardson`s extrapolation.
+% Sample call
+%   [H] = hessext(f,x,options,varargin)
+% Inputs
+%   f        name of the function
+%   x        differentiation point
+%   options  matrix of algorithm parameters
+%   delta    error goal (1e-12)
+%   toler    relative error goal (1e-12)
+% Return
+%   J        Jacobian
+%
+% NUMERICAL METHODS: MATLAB Programs, (c) John H. Mathews 1995
+%
+% Modified F. Collard, August 2001
+%---------------------------------------------------------------------------
+  if nargin>3;
+    if ~isempty(options);
+      delta=options(1);
+      toler=options(2);
+    else
+      delta=1e-12;
+      toler=1e-9;
+    end
+  else
+    delta=1e-12;
+    toler=1e-9;
+  end;
+  ff=feval(f,x,varargin{:});
+  nx=size(x,1);
+  nf=size(ff,1);
+  H=sparse(nx*nx,nf);
+  for fi=1:nf;
+    for xi=1:nx;
+      for xj=xi:nx;
+	err = 1;
+	relerr = 1;
+	h = 0.997;
+	dx = zeros(nx,1);
+	dy = zeros(nx,1);
+	dx(xi)=h;      
+	dy(xj)=h;      
+	j = 1;
+	fss=feval(f,x+dx+dy,varargin{:});
+	fsm=feval(f,x+dx-dy,varargin{:});
+	fms=feval(f,x-dx+dy,varargin{:});
+	fmm=feval(f,x-dx-dy,varargin{:});
+	D(1,1) = (fss(fi) -fsm(fi)-fms(fi)+ fmm(fi))/(4*h*h);
+	while relerr>toler & err>delta
+	  h = h/2;
+	  dx = zeros(nx,1);
+	  dy = zeros(nx,1);
+	  dx(xi)=h;      
+	  dy(xj)=h;      
+	  fss=feval(f,x+dx+dy,varargin{:});
+	  fsm=feval(f,x+dx-dy,varargin{:});
+	  fms=feval(f,x-dx+dy,varargin{:});
+	  fmm=feval(f,x-dx-dy,varargin{:});
+	  D(j+1,1) = (fss(fi) -fsm(fi)-fms(fi)+ fmm(fi))/(4*h*h);
+	  for k = 1:j,
+	    D(j+1,k+1) = D(j+1,k) + (D(j+1,k)-D(j,k))/(4^k -1);
+	  end
+	  err = abs(D(j+1,j+1)-D(j,j));
+	  relerr = 2*err/(abs(D(j+1,j+1))+abs(D(j,j))+eps);
+	  j = j+1;
+	  if j == 20
+	    error(sprintf('Hessian evalutation didn''t converge. Equation %d, variables %d %d, relerr %e',fi,xi,xj,relerr))
+	  end
+	end
+	n=size(D,1);
+	H((xi-1)*nx+xj,fi)=D(n,n);
+	H((xj-1)*nx+xi,fi)=D(n,n);
+	D=0;
+      end
+    end
+  end
+
+% 10/12/2001 MJ modified initial h
+
+
+
+
+
diff --git a/tags/v_3.062/matlab/hessian.m b/tags/v_3.062/matlab/hessian.m
new file mode 100644
index 0000000000000000000000000000000000000000..911a8e25f96bad8e5df3c4ced72b006649c8265c
--- /dev/null
+++ b/tags/v_3.062/matlab/hessian.m
@@ -0,0 +1 @@
+% Copyright (C) 2001 Michel Juillard
%
% computes second order partial derivatives
% uses Abramowitz and Stegun (1965) formulas 25.3.24 and 25.3.27 p. 884
function hessian_mat = hessian(func,x,varargin)
global gstep_

func = str2func(func);
n=size(x,1);
%h1=max(abs(x),gstep_*ones(n,1))*eps^(1/3);
h1=max(abs(x),sqrt(gstep_)*ones(n,1))*eps^(1/6);
h_1=h1;
xh1=x+h1;
h1=xh1-x;
xh1=x-h_1;
h_1=x-xh1;
xh1=x;

f0=feval(func,x,varargin{:});
f1=zeros(size(f0,1),n);
f_1=f1;

for i=1:n
    xh1(i)=x(i)+h1(i);
    f1(:,i)=feval(func,xh1,varargin{:});
    xh1(i)=x(i)-h_1(i);
    f_1(:,i)=feval(func,xh1,varargin{:});
    xh1(i)=x(i);
    i=i+1;
end
xh_1=xh1;
hessian_mat = zeros(size(f0,1),n*n);
for i=1:n
    if i > 1
        k=[i:n:n*(i-1)];
        hessian_mat(:,(i-1)*n+1:(i-1)*n+i-1)=hessian_mat(:,k);
    end 
    hessian_mat(:,(i-1)*n+i)=(f1(:,i)+f_1(:,i)-2*f0)./(h1(i)*h_1(i));
    temp=f1+f_1-f0*ones(1,n);
        for j=i+1:n
        xh1(i)=x(i)+h1(i);
        xh1(j)=x(j)+h_1(j);
        xh_1(i)=x(i)-h1(i);
        xh_1(j)=x(j)-h_1(j);
        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));
        xh1(i)=x(i);
        xh1(j)=x(j);
        xh_1(i)=x(i);
        xh_1(j)=x(j);
        j=j+1;
    end
    i=i+1;
end

% 11/25/03 SA Created from Hessian_sparse (removed sparse)
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/hessian2.m b/tags/v_3.062/matlab/hessian2.m
new file mode 100644
index 0000000000000000000000000000000000000000..4589fc7d6781a25d41588196f376b5c002a01a14
--- /dev/null
+++ b/tags/v_3.062/matlab/hessian2.m
@@ -0,0 +1,511 @@
+function hessian2(xparam1,gend,data)
+% source Schorfheide
+%/* filename:    lbdhess.g
+%** description: The program computes the hessianfit at the posterior mode 
+%** created:     05/05/00
+%/******************************************************** 
+%/* Compute hessianfit, element by element, fine tune with dxscale
+%   Compute hessianfit for two step-seize (dx) and take average to prevent singularity  
+%/******************************************************** 
+npara = length(xparam1);
+para = xparam1;
+ndx = 1;%6
+%dx =  exp(-seqa(6,2,ndx));
+%dx =  exp([-6:-2:-16]);
+dx =  exp([-10]);
+hessianfit = zeros( npara, npara );
+gradx = zeros(ndx,1);
+grady = zeros(ndx,1);
+gradxy = zeros(ndx,1);
+hessdiag = zeros(ndx,1);
+dxscale = ones(npara,1);
+%  dxscale(5,1)=10;
+%  dxscale(13,1)=10;
+%  dxscale(17,1)=10;
+%  dxscale(8,1)=.10;
+%  dxscale(11,1)=.10;
+%  dxscale(31,1)=.10;
+  
+
+%/* Compute Diagonal elements first
+%*/
+seli = 1;
+fx  = mj_optmumlik(para,gend,data,1);
+%do until seli > npara;
+while seli <= npara;
+%     locate 1,1;
+%     "hessianfit Element    (" seli seli ")";
+     i=1;
+     while i <= ndx;
+      paradx = para;
+      parady = para;
+      paradx(seli) = paradx(seli) + dx(i)*dxscale(seli);
+      parady(seli) = parady(seli) - dx(i)*dxscale(seli);
+      paradxdy = paradx;
+      paradxdy(seli) = paradxdy(seli) - dx(i)*dxscale(seli);
+%     fx  = optmumlik20(para,q,h2,aa,mf,gitno,gst,gobs,gend,gstart,nlags,rawdata,lpd);
+fdx  = mj_optmumlik(paradx,gend,data,1);
+%      fdx  = optmumlik20(paradx,q,h2,aa,mf,gitno,gst,gobs,gend,gstart,nlags,rawdata,lpd);
+fdy  = mj_optmumlik(parady,gend,data,1);
+   %   fdy  = optmumlik20(parady,q,h2,aa,mf,gitno,gst,gobs,gend,gstart,nlags,rawdata,lpd);
+%     fdxdy  = optmumlik20(paradxdy,q,h2,aa,mf,gitno,gst,gobs,gend,gstart,nlags,rawdata,lpd);
+      fdxdy  = fx;
+      gradx(i) = -( fx - fdx )/ (dx(i)*dxscale(seli));
+      grady(i) = ( fx - fdy )/ (dx(i)*dxscale(seli));
+      gradxy(i) = -(fx -fdxdy)/ sqrt( (dx(i)*dxscale(seli))^2 + (dx(i)*dxscale(seli))^2 );
+      hessdiag(i) = -( 2*fx - fdx - fdy)/(dx(i)*dxscale(seli))^2; 
+      hessdiag(i) = -( fx - fdx - fdy + fdxdy )/(dx(i)*dx(i)*dxscale(seli)*dxscale(seli));
+      i = i+1;
+  end;
+%     "Values";
+%     -hessdiag';
+     hessianfit(seli,seli) = -1*(hessdiag(1));
+%     hessianfit(seli,seli) = -0.5*(hessdiag(3)+hessdiag(4));
+%     locate 6,1;
+%     "Value Used:" hessianfit[seli,seli];
+   seli = seli+1
+end;
+
+diag(hessianfit)
+
+%/* Now compute off-diagonal elements
+%** Make sure that correlations are between -1 and 1
+%** errorij contains the index of elements that are invalid
+%*/
+errorij = [ 0 0 0];
+
+seli = 1;
+for seli = 1:npara;
+%   selj = seli+1;
+   for selj =seli+1:npara;
+       disp([seli selj]);
+%     locate 1,1;
+%     "hessianfit Element    (" seli selj ")";
+     i=1;
+     while i <= ndx;
+      paradx = para;
+      parady = para;
+      paradx(seli) = paradx(seli) + dx(i)*dxscale(seli);
+      parady(selj) = parady(selj) - dx(i)*dxscale(selj);
+      paradxdy = paradx;
+      paradxdy(selj) = paradxdy(selj) - dx(i)*dxscale(selj);
+%      fx  = optmumlik20(para,q,h2,aa,mf,gitno,gst,gobs,gend,gstart,nlags,rawdata,lpd);
+fdx  = mj_optmumlik(paradx,gend,data,1);
+%      fdx  = optmumlik20(paradx,q,h2,aa,mf,gitno,gst,gobs,gend,gstart,nlags,rawdata,lpd);
+fdy  = mj_optmumlik(parady,gend,data,1);
+%      fdy  = optmumlik20(parady,q,h2,aa,mf,gitno,gst,gobs,gend,gstart,nlags,rawdata,lpd);
+fdy  = mj_optmumlik(paradxdy,gend,data,1);
+%      fdxdy  = optmumlik20(paradxdy,q,h2,aa,mf,gitno,gst,gobs,gend,gstart,nlags,rawdata,lpd);
+      gradx(i) = -( fx - fdx )/ (dx(i)*dxscale(seli));
+      grady(i) = ( fx - fdy )/ (dx(i)*dxscale(selj));
+      gradxy(i) = -(fx -fdxdy)/ sqrt( (dx(i)*dxscale(selj))^2 + (dx(i)*dxscale(seli))^2 );
+      hessdiag(i) = -( 2*fx - fdx - fdy)/(dx(i)*dxscale(seli))^2; 
+      hessdiag(i) = -( fx - fdx - fdy + fdxdy )/(dx(i)*dx(i)*dxscale(seli)*dxscale(selj));
+      i = i+1;
+     end;
+%     "Values";
+%     -hessdiag';
+
+%     hessianfit(seli,selj) = -0.5*(hessdiag(3)+hessdiag(4));
+     hessianfit(seli,selj) = -1*(hessdiag(1));
+     
+     if ( hessianfit(seli,seli) == 0 ) | (hessianfit(selj,selj) == 0);
+        corrij = 0;
+     else;
+        corrij = hessianfit(seli,selj)/sqrt(hessianfit(seli,seli)*hessianfit(selj,selj));
+    end;
+
+     if (corrij < -1) | (corrij > 1);
+        hessianfit(seli,selj)=0;
+        errorij = [ errorij [seli selj corrij] ];
+    end;   
+     hessianfit(selj,seli) = hessianfit(seli,selj);
+
+%     locate 6,1;
+%     "Value Used: " hessianfit[seli,selj];
+%     "Correlation:" corrij;
+%     "Number of Errors:" rows(errorij)-1;
+%     selj=selj+1;
+ end;
+%   seli = seli+1;
+end;
+
+%cls;
+disp('Errors')
+disp(errorij);
+
+
+%/*******************************************************************************
+
+bbbb=xparam1;
+%  func =fval;
+%  grad=grad;
+%  retcode=exitflag
+  opfhessfit = (-hessianfit);
+  invhess=inv(opfhessfit);
+  stdh=sqrt(diag(invhess));
+  pr =length(xparam1);
+  tstath=zeros(pr,1);
+  i = 1; while i <= pr ; %do until i>pr;
+    tstath(i)=abs(bbbb(i))/stdh(i);
+  i=i+1; end ; %endo;
+%tstath
+%  print "t-stats. from the Hessian";
+  disp('print "t-stats. from the Hessian" ') ;
+ disp([xparam1 stdh tstath]);   
+
+bbbb=xparam1;
+%  func =fval;
+%  grad=grad;
+%  retcode=exitflag
+ % opfhessfit = (-hessianfit);
+ % invhess=inv(opfhessfit*.5+opfhess*.5);
+ % stdh=sqrt(diag(invhess));
+ % pr =length(xparam1);
+ % tstath=zeros(pr,1);
+ % i = 1; while i <= pr ; %do until i>pr;
+ %   tstath(i)=abs(bbbb(i))/stdh(i);
+ % i=i+1; end ; %endo;
+%tstath
+%  print "t-stats. from the Hessian";
+ % disp('print "t-stats. from the Hessian" ') ;
+% disp([xparam1 stdh tstath]);   
+
+%opfhessfit = -hessianfit*.5+opfhess*.5;
+hessian=opfhessfit;
+
+
+
+return;
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+npara = length(xparam1);
+para = xparam1;
+ndx = 1;%6
+%dx =  exp(-seqa(6,2,ndx));
+%dx =  exp([-6:-2:-16]);
+dx =  exp([-10]);
+hessianfit = zeros( npara, npara );
+gradx = zeros(ndx,1);
+grady = zeros(ndx,1);
+gradxy = zeros(ndx,1);
+hessdiag = zeros(ndx,1);
+dxscale = ones(npara,1);
+
+
+%/* Compute Diagonal elements first
+%*/
+seli = 1;
+%do until seli > npara;
+while seli <= npara;
+%     locate 1,1;
+%     "hessianfit Element    (" seli seli ")";
+     i=1;
+     while i <= ndx;
+      paradx = para;
+      parady = para;
+      paradx(seli) = paradx(seli) + dx(i)*dxscale(seli);
+      parady(seli) = parady(seli) - dx(i)*dxscale(seli);
+      paradxdy = paradx;
+      paradxdy(seli) = paradxdy(seli) - dx(i)*dxscale(seli);
+      fx  = optmumlik20(para,q,h2,aa,mf,gitno,gst,gobs,gend,gstart,nlags,rawdata,lpd);
+      fdx  = optmumlik20(paradx,q,h2,aa,mf,gitno,gst,gobs,gend,gstart,nlags,rawdata,lpd);
+      fdy  = optmumlik20(parady,q,h2,aa,mf,gitno,gst,gobs,gend,gstart,nlags,rawdata,lpd);
+      fdxdy  = optmumlik20(paradxdy,q,h2,aa,mf,gitno,gst,gobs,gend,gstart,nlags,rawdata,lpd);
+      gradx(i) = -( fx - fdx )/ (dx(i)*dxscale(seli));
+      grady(i) = ( fx - fdy )/ (dx(i)*dxscale(seli));
+      gradxy(i) = -(fx -fdxdy)/ sqrt( (dx(i)*dxscale(seli))^2 + (dx(i)*dxscale(seli))^2 );
+      hessdiag(i) = -( 2*fx - fdx - fdy)/(dx(i)*dxscale(seli))^2; 
+      hessdiag(i) = -( fx - fdx - fdy + fdxdy )/(dx(i)*dx(i)*dxscale(seli)*dxscale(seli));
+      i = i+1;
+  end;
+%     "Values";
+%     -hessdiag';
+     hessianfit(seli,seli) = -1*(hessdiag(1));
+%     hessianfit(seli,seli) = -0.5*(hessdiag(3)+hessdiag(4));
+%     locate 6,1;
+%     "Value Used:" hessianfit[seli,seli];
+   seli = seli+1;
+end;
+
+%/* Now compute off-diagonal elements
+%** Make sure that correlations are between -1 and 1
+%** errorij contains the index of elements that are invalid
+%*/
+errorij = [ 0 0 0];
+
+seli = 1;
+for seli = 1:npara;
+   selj = seli+1
+   while selj <= npara;
+%     locate 1,1;
+%     "hessianfit Element    (" seli selj ")";
+     i=1;
+     while i <= ndx;
+      paradx = para;
+      parady = para;
+      paradx(seli) = paradx(seli) + dx(i)*dxscale(seli);
+      parady(selj) = parady(selj) - dx(i)*dxscale(selj);
+      paradxdy = paradx;
+      paradxdy(selj) = paradxdy(selj) - dx(i)*dxscale(selj);
+      fx  = optmumlik20(para,q,h2,aa,mf,gitno,gst,gobs,gend,gstart,nlags,rawdata,lpd);
+      fdx  = optmumlik20(paradx,q,h2,aa,mf,gitno,gst,gobs,gend,gstart,nlags,rawdata,lpd);
+      fdy  = optmumlik20(parady,q,h2,aa,mf,gitno,gst,gobs,gend,gstart,nlags,rawdata,lpd);
+      fdxdy  = optmumlik20(paradxdy,q,h2,aa,mf,gitno,gst,gobs,gend,gstart,nlags,rawdata,lpd);
+      gradx(i) = -( fx - fdx )/ (dx(i)*dxscale(seli));
+      grady(i) = ( fx - fdy )/ (dx(i)*dxscale(selj));
+      gradxy(i) = -(fx -fdxdy)/ sqrt( (dx(i)*dxscale(selj))^2 + (dx(i)*dxscale(seli))^2 );
+      hessdiag(i) = -( 2*fx - fdx - fdy)/(dx(i)*dxscale(seli))^2; 
+      hessdiag(i) = -( fx - fdx - fdy + fdxdy )/(dx(i)*dx(i)*dxscale(seli)*dxscale(selj));
+      i = i+1
+  end;
+%     "Values";
+%     -hessdiag';
+
+%     hessianfit(seli,selj) = -0.5*(hessdiag(3)+hessdiag(4));
+     hessianfit(seli,selj) = -1*(hessdiag(1));
+     
+     if ( hessianfit(seli,seli) == 0 ) or (hessianfit(selj,selj) == 0);
+        corrij = 0;
+     else;
+        corrij = hessianfit(seli,selj)/sqrt(hessianfit(seli,seli)*hessianfit(selj,selj));
+    end;
+
+     if (corrij < -1) or (corrij > 1);
+        hessianfit(seli,selj)=0;
+        errorij = [ errorij [seli selj corrij] ];
+    end;   
+     hessianfit(selj,seli) = hessianfit(seli,selj);
+
+%     locate 6,1;
+%     "Value Used: " hessianfit[seli,selj];
+%     "Correlation:" corrij;
+%     "Number of Errors:" rows(errorij)-1;
+     selj=selj+1
+ end;
+%   seli = seli+1;
+end;
+
+%cls;
+disp('Errors')
+disp(errorij);
+
+
+%/*******************************************************************************
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+%new;
+%closeall;
+%library user, pgraph, lbdlib;
+%format /mb1 /ros 16,8;
+%cls;
+
+%/******************************************************** 
+%**      Estimate the DSGE Model
+%**      Models: 1 = RBC
+%**              2 = LBD
+%**              3 = LBD + Effort
+ 
+%mspec  = 3;
+%mprior = 2;
+%npara  = 12;
+
+%/******************************************************** 
+%** Import data on output growth and inflation: series (nobs,2)
+%** observations from 1954:III to 1997:IV: 
+%**
+%** YY is composed of gdpq_cld and blsh_cl
+%*/
+%#include c:\projects\active\persist\Gauss\prog_t03\loaddata.g
+%loadm path = ^lpath para_names;
+%
+%/******************************************************** 
+%** Load Posterior Mode Estimates
+
+%lpara = lpath $+ "\\" $+ lmodel $+ lprior $+ "mode";
+%open fhpara = ^lpara for read;
+%para = readr(fhpara,npara);
+%closeall fhpara;
+
+%"Parameter   | Estimate ";
+%outmat = para_names'~para;
+%let mask[1,2] = 0 1;
+%%let fmt[2,3] =
+%   "-*.*s " 10 4
+%   "*.*lf " 10 4;
+%d = printfm(outmat,(0 ~ 1),fmt);
+
+%"";
+%"Prior*Likelihood at Mode";
+%fcn(para);
+%"Press Key to Continue";
+%k = keyw;
+%cls;
+% $$$  
+% $$$ /*
+% $$$ goto evalhess;
+% $$$ */
+% $$$ 
+% $$$ 
+% $$$ 
+% $$$ 
+% $$$ 
+% $$$ 
+% $$$ 
+% $$$ 
+% $$$ 
+% $$$ 
+% $$$ 
+% $$$ 
+% $$$ 
+% $$$ 
+% $$$ 
+% $$$ /* Initialize Output files
+% $$$ */
+% $$$ ohess = lpath $+ "\\" $+ lmodel $+ lprior $+ "hess";
+% $$$ create fhhess=^ohess with hess, npara, 8;
+% $$$ wr    = writer(fhhess,hessianfit[1:npara,1:npara]);
+% $$$ closeall fhhess;
+% $$$    
+% $$$ 
+% $$$ 
+% $$$ 
+% $$$ /* Load hessianfit, compute penalty
+% $$$ */
+% $$$ evalhess:
+% $$$ 
+% $$$ lhess = lpath $+ "\\" $+ lmodel $+ lprior $+ "hess";
+% $$$ open fhhess = ^lhess for read;
+% $$$ HHm   = readr( fhhess,npara );
+% $$$ closeall fhhess;
+% $$$ 
+% $$$ /* hessianfit is of reduced rank. Keep zero rows and columns and do SVD
+% $$$ */
+% $$$ if mspec == 1;
+% $$$    rankHHm = 9;
+% $$$ elseif mspec == 2;
+% $$$    rankHHm = 11;
+% $$$ else;
+% $$$    rankHHm = 12;
+% $$$ endif;
+% $$$ 
+% $$$ /* Create Inverse by Singular Value Decomposition
+% $$$ */
+% $$$ {u , s, v} = svd1(HHM);
+% $$$ invHHMdet = 1;
+% $$$ 
+% $$$ i = 1;
+% $$$ do until i > npara;
+% $$$    if i > rankHHM;
+% $$$       s[i,i] = 0;
+% $$$    else;
+% $$$       s[i,i]    = 1/s[i,i];
+% $$$       invHHMdet = invHHMdet*s[i,i];
+% $$$    endif;
+% $$$    i = i+1;
+% $$$ endo;
+% $$$ 
+% $$$ invHHM  = u*s*u';
+% $$$ sigmult = u*sqrt(s);
+% $$$ 
+% $$$ "Determinant of minus hessianfit";
+% $$$ invHHMdet;
+% $$$ "sqrt(Diagonal of Inverse hessianfit)";
+% $$$ sqrt(diag(invHHM));
+% $$$ 
+% $$$ "Post Mode Penalty";
+% $$$ penalt = (rankHHM/2)*ln(2*pi) + 0.5*ln(invHHMdet);
+% $$$ penalt;
+% $$$ 
+% $$$ /* Initialize Output files
+% $$$ */
+% $$$ omult = lpath $+ "\\" $+ lmodel $+ lprior $+ "mult";
+% $$$ create fhmult=^omult with MULT, npara, 8;
+% $$$ wr = writer(fhmult,sigmult);
+% $$$ 
+% $$$ closeall fhmult;
+% $$$ end;
+% $$$ 
+% $$$ 
+% $$$ %/****************************************************/
+% $$$ %/*                 PROCEDURES                       */
+% $$$ %/****************************************************/
+% $$$ 
+% $$$ 
+% $$$ %proc (1) = fcn(para);
+% $$$ %local lnpY, lnprio1, lnprio2, obsmean, obsvar;
+% $$$ 
+% $$$ %{lnpy, obsmean, obsvar} = evallbd( para,mspec,T0,YY);
+% $$$ 
+% $$$ %/* Evaluate the Prior density
+% $$$       
+% $$$ %  lnprio1 = priodens( para, pmean, pstdd, pshape);
+% $$$ %  lnprio2 = priomuphi( para );
+% $$$ 
+% $$$ %retp(real(lnpY+lnprio1+lnprio2));  
+% $$$ %endp;
+% $$$ 
+% $$$ /***************************************************************************
+% $$$ */
+% $$$ 
+% $$$ proc (1) = priomuphi(para);
+% $$$ local muphi, lnprio;
+% $$$ muphi = para[7:8];
+% $$$ if mspec > 1;
+% $$$    lnprio = -ln(2*pi) - 0.5*ln(det(muphi_v0))
+% $$$             - 0.5*(muphi - muphi_m0)'*inv(muphi_v0)*(muphi - muphi_m0);
+% $$$ else;
+% $$$    lnprio = 0;
+% $$$ endif;
+% $$$ retp(lnprio);
+% $$$ endp;
+% $$$ 
+% $$$ 
+% $$$ 
diff --git a/tags/v_3.062/matlab/hessian_sparse.m b/tags/v_3.062/matlab/hessian_sparse.m
new file mode 100644
index 0000000000000000000000000000000000000000..6f26a0b6a060509502fe9cc4d131438f4b603ce7
--- /dev/null
+++ b/tags/v_3.062/matlab/hessian_sparse.m
@@ -0,0 +1 @@
+% Copyright (C) 2001 Michel Juillard
%
% computes second order partial derivatives
% uses Abramowitz and Stegun (1965) formulas 25.3.24 and 25.3.27 p. 884
function hessian_mat = hessian_sparse(func,x,varargin)
global gstep_

func = str2func(func);
n=size(x,1);
%h1=max(abs(x),gstep_*ones(n,1))*eps^(1/3);
h1=max(abs(x),sqrt(gstep_)*ones(n,1))*eps^(1/6);
h_1=h1;
xh1=x+h1;
h1=xh1-x;
xh1=x-h_1;
h_1=x-xh1;
xh1=x;

f0=feval(func,x,varargin{:});
nf = size(f0,1);
f1=zeros(nf,n);
f_1=f1;

for i=1:n
    xh1(i)=x(i)+h1(i);
    f1(:,i)=feval(func,xh1,varargin{:});
    xh1(i)=x(i)-h_1(i);
    f_1(:,i)=feval(func,xh1,varargin{:});
    xh1(i)=x(i);
    i=i+1;
end
xh_1=xh1;
hessian_mat = spalloc(nf,n*n,3*nf*n);
for i=1:n
    if i > 1
        k=[i:n:n*(i-1)];
        hessian_mat(:,(i-1)*n+1:(i-1)*n+i-1)=hessian_mat(:,k);
    end 
    hessian_mat(:,(i-1)*n+i)=sparse((f1(:,i)+f_1(:,i)-2*f0)./(h1(i)*h_1(i)));
    temp=f1+f_1-f0*ones(1,n);
        for j=i+1:n
        xh1(i)=x(i)+h1(i);
        xh1(j)=x(j)+h_1(j);
        xh_1(i)=x(i)-h1(i);
        xh_1(j)=x(j)-h_1(j);
        hessian_mat(:,(i-1)*n+j)=sparse(-(-feval(func,xh1,varargin{:})-feval(func,xh_1,varargin{:})+temp(:,i)+temp(:,j))./(2*h1(i)*h_1(j)));
        xh1(i)=x(i);
        xh1(j)=x(j);
        xh_1(i)=x(i);
        xh_1(j)=x(j);
        j=j+1;
    end
    i=i+1;
end

% 10/03/02 MJ used the 7 points formula
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/hpfast.m b/tags/v_3.062/matlab/hpfast.m
new file mode 100644
index 0000000000000000000000000000000000000000..e93fa16f450480bc97a1712e9e6c39fd7f23d462
--- /dev/null
+++ b/tags/v_3.062/matlab/hpfast.m
@@ -0,0 +1,106 @@
+% Copyright (C) 2001 Michel Juillard
+%
+% Fast hpfiltering:
+%
+% [c,t]=hpfast(y,lambda)
+%
+% Inputs:
+%
+% y: 			vector (nx1) containing the series you wish to filter
+% lambda:	smoothing parameter (default: quarterly 1600)
+%
+% Outputs:
+% 
+% c:			Cyclical component (deviations from trend)
+%	t:			Trend component
+%
+function [d,t]=hpfast(y,s)
+if nargin<2;
+  s = 1600;
+end;
+iopt 	= 0;
+y			= y(:);
+n 		= length(y);
+d1		= zeros(n,1);
+t			= zeros(n,1);
+
+v = zeros(3*n,6);
+if iopt ~= 1,
+  ss=s;
+  nn=n;
+  v11=1;
+  v22=1;
+  v12=0;
+  for i=3:n;
+    x=v11;
+    z=v12;
+    v11=1/s + 4*(x-z) + v22;
+    v12=2*x - z;
+    v22=x;
+    det1=v11*v22-v12*v12;
+    v(i,1)=v22/det1;
+    v(i,3)=v11/det1;
+    v(i,2)=-v12/det1;
+    x=v11+1;
+    z=v11;
+    v11=v11-v11*v11/x;
+    v22=v22-v12*v12/x;
+    v12=v12-z*v12/x;
+  end;
+end;
+%
+%  Forward pass 
+%
+m1=y(2);
+m2=y(1);
+for i=3:n;
+  x=m1;
+  m1=2*m1-m2;
+  m2=x;
+  t(i-1,1)= v(i,1)*m1 + v(i,2)*m2;
+  d1(i-1,1)=v(i,2)*m1+v(i,3)*m2;
+  det1=v(i,1)*v(i,3)-v(i,2)*v(i,2);
+  v11=v(i,3)/det1;
+  v12=-v(i,2)/det1;
+  z=(y(i)-m1)/(v11+1);
+  m1=m1+v11*z;
+  m2=m2+v12*z;
+end
+t(n,1)=m1;
+t(n-1,1)=m2;
+%
+% Backward pass
+%
+m1=y(n-1);
+m2=y(n);
+for i=n-2:-1:1;
+  i1=i+1;
+  ib=n-i+1;
+  x=m1;
+  m1=2*m1 - m2;
+  m2=x;
+%
+% Combine info for y(.lt.i) with info for y(.ge.i)
+%
+  if i > 2;
+    e1=v(ib,3)*m2+v(ib,2)*m1+t(i,1);
+    e2=v(ib,2)*m2+v(ib,1)*m1+d1(i,1);
+    b11=v(ib,3)+v(i1,1);
+    b12=v(ib,2)+v(i1,2);
+    b22=v(ib,1)+v(i1,3);
+    det1=b11*b22-b12*b12;
+    t(i,1)=(-b12*e1+b11*e2)/det1;
+  end
+%
+% End of combining
+%
+	det1=v(ib,1)*v(ib,3)-v(ib,2)*v(ib,2);
+	v11=v(ib,3)/det1;
+  v12=-v(ib,2)/det1;
+  z=(y(i)-m1)/(v11+1);
+  m1=m1+v11*z;
+  m2=m2+v12*z;
+end
+t(1,1)=m1;
+t(2,1)=m2;
+d=y-t;
diff --git a/tags/v_3.062/matlab/indnv.m b/tags/v_3.062/matlab/indnv.m
new file mode 100644
index 0000000000000000000000000000000000000000..9419ed7085e8fc6440099de4614ec477b801a93f
--- /dev/null
+++ b/tags/v_3.062/matlab/indnv.m
@@ -0,0 +1,17 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function a=indnv(x,y)
+
+a = zeros(size(x)) ;
+
+for i = 1:size(x,1)
+  j = find( x(i) == y );
+  if isempty(j)
+    a(i) = NaN;
+  else
+    a(i) = j;
+  end
+end
+
+
+
diff --git a/tags/v_3.062/matlab/initial_estimation_checks.m b/tags/v_3.062/matlab/initial_estimation_checks.m
new file mode 100644
index 0000000000000000000000000000000000000000..b244e1a5ff90a74456bab4187610a2be30d4cce1
--- /dev/null
+++ b/tags/v_3.062/matlab/initial_estimation_checks.m
@@ -0,0 +1,26 @@
+function initial_estimation_checks(xparam1,gend,data)
+global bayestopt_ estim_params_ exo_nbr dsge_prior_weight
+  
+nv = size(data,1);
+  
+if nv > exo_nbr + estim_params_.nvn
+  error(['Estimation can''t take place because there are less shocks than' ...
+     'observed variables'])
+end
+  
+r = rank(data);
+if r < nv
+  error(['Estimation can''t take place because the data are perfectly' ...
+     ' correlated']);
+end
+
+if ~isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) | ~isempty(dsge_prior_weight)
+  [fval,cost_flag,ys,trend_coeff,info] = DsgeVarLikelihood(xparam1,gend);
+else
+  [fval,cost_flag,ys,trend_coeff,info] = DsgeLikelihood(xparam1,gend,data);
+end
+
+if info(1) > 0
+  disp('Error in computing likelihood for initial parameter values')
+  print_info(info)
+end
diff --git a/tags/v_3.062/matlab/initvalf_.m b/tags/v_3.062/matlab/initvalf_.m
new file mode 100644
index 0000000000000000000000000000000000000000..37c8d980202e3d8285862e8221bf3da2720f9f16
--- /dev/null
+++ b/tags/v_3.062/matlab/initvalf_.m
@@ -0,0 +1,103 @@
+function initvalf_(fname,period,varargin)
+  global lgy_ lgx_ lgr_ y_ ex_ valf_ ykmin_ xkmin_ ykmax_ xkmax_ iter_ ...
+      y_start_date ex_start_date freq_ start_date
+
+  if ~isempty(strfind(upper(fname),'.XLS'))
+    [data,names_v]=xlsread(fname);
+  else
+    load(fname);
+  end
+  
+  if length(period) == 2
+    period = dy_date(period(1),period(2));
+  end
+  
+  if period - max(ykmin_,xkmin_) < 0
+    error(['INITVALF_: not enough data points in database for number of' ...
+	   ' lags. Start later!'])
+  end
+  
+  if nargin > 2
+    if strcmp(upper(varargin{1}),'SERIES')
+      series = 1 ;
+    elseif strcmp(upper(varargin{1}),'MAT')
+      series = 0 ;
+    else
+      error(['INITVALF: unknown option ' varargin{1}])
+    end
+  else
+    series = 0 ;
+  end
+  
+  y1 = floor((period-ykmin_)/freq_);
+  p1 = period-ykmin_-freq_*y1;
+  y_start_date(2) = start_date(2) + p1-1;
+  if y_start_date(2) > freq_
+    y_start_date(2) = y_start_date(2) - freq_;
+    y1 = y1 + 1;
+  end
+  y_start_date(1) = start_date(1)+y1;
+  
+  y1 = floor((period-xkmin_)/freq_);
+  p1 = period-xkmin_-freq_*y1;
+  ex_start_date(2) = start_date(2) + p1-1;
+  if y_start_date(2) > freq_
+    ex_start_date(2) = ex_start_date(2) - freq_;
+    y1 = y1 + 1;
+  end
+  ex_start_date(1) = start_date(1)+y1;
+  
+  clear y1, p1;
+  
+  valf_ = 1;
+  y_ = [];
+  ex_ = [];
+  
+  for i=1:size(lgy_,1)
+    if series == 1
+      x = eval([lgy_(i,:) '(period-ykmin_:period+iter_+ykmax_-1);']);
+      y_ = [y_; x'];
+    else
+      k = strmatch(upper(lgy_(i,:)),names_v,'exact');
+      if isempty(k)
+	error(['INITVALF: ' lgy_(i,:) ' not found'])
+      end
+      x = data(:,k);
+      y_ = [y_; x(period-ykmin_:period+iter_+ykmax_-1)']; 
+    end
+  end
+  
+  for i=1:size(lgx_,1)
+    if series == 1
+      x = eval([lgx_(i,:) '(period-xkmin_:period+iter_+xkmax_-1);']);
+      ex_ = [ex_ x];
+    else
+      k = strmatch(upper(lgx_(i,:)),names_v,'exact');
+      if isempty(k)
+	error(['INITVALF: ' lgx_(i,:) ' not found'])
+      end
+      x = data(:,k);
+      ex_ = [ex_ x(period-xkmin_:period+iter_+xkmax_-1)]; 
+    end
+  end
+    
+% $$$   if any(isnan(y_(:,1))) | any(isnan(ex_(1,:)))
+% $$$     error('INITVALF: missing value in first period')
+% $$$   end
+% $$$   
+% $$$   if any(isnan(y_(:,end))) | any(isnan(ex_(end,:)))
+% $$$     error('INITVALF: missing value in last period')
+% $$$   end
+  
+% 8/23/01 MJ changed argument 'FILE' to 'MAT'
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tags/v_3.062/matlab/inverse_gamma_specification.m b/tags/v_3.062/matlab/inverse_gamma_specification.m
new file mode 100644
index 0000000000000000000000000000000000000000..5c847387201443324c7562838da615c24f388c1b
--- /dev/null
+++ b/tags/v_3.062/matlab/inverse_gamma_specification.m
@@ -0,0 +1,50 @@
+function [s,nu] = inverse_gamma_specification(mu,sigma,type)
+%
+% mu    --> expectation
+% sigma --> standard deviation
+% type = 1 --> Inverse Gamma 1
+% type = 2 --> Inverse Gamma 2
+%
+% stephane.adjemian@cepremap.cnrs.fr [01/14/2004]
+
+
+sigma2 = sigma^2;
+mu2 = mu^2;
+
+if type == 2;       % Inverse Gamma 2   
+   nu   = 2*(2+mu2/sigma2);
+   s    = 2*mu*(1+mu2/sigma2);
+elseif type == 1;   % Inverse Gamma 1 
+    if sigma2 < Inf;
+      nu = sqrt(2*(2+mu2/sigma2));
+      nu2 = 2*nu;
+      nu1 = 2;
+      err = 2*mu2*gamma(nu/2)^2-(sigma2+mu2)*(nu-2)*gamma((nu-1)/2)^2;
+      while abs(nu2-nu1) > 1e-12
+	if err > 0
+	  nu1 = nu;
+	  if nu < nu2
+	    nu = nu2;
+	  else
+	    nu = 2*nu;
+	    nu2 = nu;
+	  end
+	else
+	  nu2 = nu;
+	end
+	nu =  (nu1+nu2)/2;
+	err = 2*mu2*gamma(nu/2)^2-(sigma2+mu2)*(nu-2)*gamma((nu-1)/2)^2;
+      end
+      s = (sigma2+mu2)*(nu-2);
+    else;
+        nu  = 2;
+        s   = 2*mu2/pi;
+    end;   
+else;
+   s  = -1;
+   nu = -1;
+end;
+
+% 01/18/2004 MJ replaced fsolve with secant
+%               suppressed chck
+%	        changed order of output parameters
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/irf.m b/tags/v_3.062/matlab/irf.m
new file mode 100644
index 0000000000000000000000000000000000000000..aaea7433ae528a4cb67d2dc939001bd67439d720
--- /dev/null
+++ b/tags/v_3.062/matlab/irf.m
@@ -0,0 +1,42 @@
+function y_=irf(dr, e1, long_, drop_, replic, iorder)
+  global lgy_ ykmin_ endo_nbr exo_nbr exe_ ykmin_ xkmin_ Sigma_e_ iter_ lgx_
+
+  old_iter = iter_;
+  iter_ = long_;
+  
+  temps = repmat(dr.ys,1,ykmin_);
+
+  y_	= 0;
+  if iorder == 1
+    iter_ = long_;
+    y1_ = repmat(dr.ys,1,iter_);
+    ex2_ = zeros(iter_,exo_nbr);
+    ex2_(1,:) = e1';
+    y2_ = simult_(repmat(dr.ys,1,ykmin_),dr,ex2_,iorder);
+    y_ = y2_(:,ykmin_+1:end)-y1_;
+  else
+    % eliminate shocks with 0 variance
+    i_exo_var = setdiff([1:exo_nbr],find(diag(Sigma_e_) == 0));
+    nxs = length(i_exo_var);
+    ex1_ = zeros(long_+drop_+xkmin_,exo_nbr);
+    ex2_ = ex1_;
+    chol_S = chol(Sigma_e_(i_exo_var,i_exo_var));
+
+    for j = 1: replic
+      randn('seed',j);
+      ex1_(:,i_exo_var) = randn(long_+drop_+xkmin_,nxs)*chol_S;
+      ex2_ = ex1_;
+      ex2_(drop_+1,:) = ex2_(drop_+1,:)+e1';   
+      y1_ = simult_(repmat(dr.ys,1,ykmin_),dr,ex1_,iorder);
+      y2_ = simult_(repmat(dr.ys,1,ykmin_),dr,ex2_,iorder);
+      y_ = y_+(y2_(:,ykmin_+drop_+1:end)-y1_(:,ykmin_+drop_+1:end));
+    end
+    y_=y_/replic;
+  end
+  iter_ = old_iter;
+
+% 01/18/02 MJ corrected for many lags
+% 03/11/22 MJ input is now entire shock vector e1 (for orthogonalized
+%              IRFs)
+
+
diff --git a/tags/v_3.062/matlab/jacob.m b/tags/v_3.062/matlab/jacob.m
new file mode 100644
index 0000000000000000000000000000000000000000..84f2f02825f8b0fb8d24d70bfade1485f0254740
--- /dev/null
+++ b/tags/v_3.062/matlab/jacob.m
@@ -0,0 +1,21 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function jacob(func,z)
+		
+global d1_ jacobia_ gstep_
+
+func = str2func(func);
+z = reshape(z,max(size(z)),1) ;
+d1_ = feval(func,z) ;
+nz = size(z,1) ;
+jacobia_ = zeros(size(d1_,1),nz) ;
+dh = max(abs(z), gstep_*ones(nz,1))*eps^(1/3) ;
+xdh = z ;
+for j = 1:nz
+	xdh(j) = xdh(j)+dh(j) ;
+	h = xdh(j)-z(j) ;
+	jacobia_(:,j) = ((feval(func,xdh)-d1_)/h) ;
+	xdh(j) = z(j) ;
+end
+
+% 8/27/2000 modified with function name MJ
diff --git a/tags/v_3.062/matlab/jacob2.m b/tags/v_3.062/matlab/jacob2.m
new file mode 100644
index 0000000000000000000000000000000000000000..08df299499ad6aea997564da153ed5f79c7afb3d
--- /dev/null
+++ b/tags/v_3.062/matlab/jacob2.m
@@ -0,0 +1,56 @@
+% Copyright (C) 2001 Michel Juillard
+%
+% computes second order partial derivatives
+% uses Abramowitz and Stegun (1965) formulas 25.3.24 and 25.3.27 p. 884
+function jacob2_=jacob2(func,x)
+global gstep_
+
+func = str2func(func);
+n=size(x,1);
+%h1=max(abs(x),gstep_*ones(n,1))*eps^(1/3);
+h1=max(abs(x),sqrt(gstep_)*ones(n,1))*eps^(1/6);
+h_1=h1;
+xh1=x+h1;
+h1=xh1-x;
+xh1=x-h_1;
+h_1=x-xh1;
+xh1=x;
+
+f0=feval(func,x);
+f1=zeros(size(f0,1),n);
+f_1=f1;
+
+for i=1:n
+	xh1(i)=x(i)+h1(i);
+	f1(:,i)=feval(func,xh1);
+	xh1(i)=x(i)-h_1(i);
+	f_1(:,i)=feval(func,xh1);
+	xh1(i)=x(i);
+	i=i+1;
+end
+xh_1=xh1;
+jacob2_=spalloc(size(f0,1),n*n,3*n);
+for i=1:n
+	if i > 1
+		k=[i:n:n*(i-1)];
+		jacob2_(:,(i-1)*n+1:(i-1)*n+i-1)=jacob2_(:,k);
+	end	
+	jacob2_(:,(i-1)*n+i)=sparse((f1(:,i)+f_1(:,i)-2*f0)./(h1(i)*h_1(i)));
+	temp=f1+f_1-f0*ones(1,n);
+        for j=i+1:n
+		xh1(i)=x(i)+h1(i);
+		xh1(j)=x(j)+h_1(j);
+		xh_1(i)=x(i)-h1(i);
+		xh_1(j)=x(j)-h_1(j);
+		jacob2_(:,(i-1)*n+j)=sparse(-(-feval(func,xh1)-feval(func,xh_1)+temp(:,i)+temp(:,j))./(2*h1(i)*h_1(j)));
+		xh1(i)=x(i);
+		xh1(j)=x(j);
+		xh_1(i)=x(i);
+		xh_1(j)=x(j);
+		j=j+1;
+	end
+	i=i+1;
+end
+
+% 10/03/02 MJ used the 7 points formula
+
diff --git a/tags/v_3.062/matlab/jacob_a.m b/tags/v_3.062/matlab/jacob_a.m
new file mode 100644
index 0000000000000000000000000000000000000000..a07cfc9c6e68e420baa6070400167075323d57b8
--- /dev/null
+++ b/tags/v_3.062/matlab/jacob_a.m
@@ -0,0 +1,26 @@
+% Copyright (C) 2001 Michel Juillard
+%
+% symmetric formula to compute the Jacobian
+%
+function jacobia_=jacob_a(func,z)
+		
+global d1_ gstep_
+
+func = str2func(func);
+z = reshape(z,max(size(z)),1) ;
+d1_ = feval(func,z) ;
+nz = size(z,1) ;
+jacobia_ = zeros(size(d1_,1),nz) ;
+dh = max(abs(z), gstep_*ones(nz,1))*eps^(1/3) ;
+xdh1 = z ;
+xdh2 = z ;
+for j = 1:nz
+	xdh1(j) = z(j)-dh(j) ;
+	xdh2(j) = z(j)+dh(j) ;
+	h = xdh2(j)-xdh1(j) ;
+	jacobia_(:,j) = ((feval(func,xdh2)-feval(func,xdh1))/h) ;
+	xdh1(j) = z(j) ;
+	xdh2(j) = z(j) ;
+end
+
+% 10/03/02 MJ creation
diff --git a/tags/v_3.062/matlab/kalman_transition_matrix.m b/tags/v_3.062/matlab/kalman_transition_matrix.m
new file mode 100644
index 0000000000000000000000000000000000000000..1cbc37ea0d699af1b1971d6760a6748cb5732c75
--- /dev/null
+++ b/tags/v_3.062/matlab/kalman_transition_matrix.m
@@ -0,0 +1,32 @@
+% makes transition matrices out of ghx and ghu for Kalman filter
+% still needs to eliminate unobserved static variables
+% order of variables s p b f p_1
+
+function [A,B] = kalman_transition_matrix(dr)
+  global ykmin_ exo_nbr 
+  nx = size(dr.ghx,2)+dr.nfwrd+dr.nstatic;
+  kstate = dr.kstate;
+  ikx = [dr.nstatic+1:dr.nstatic+dr.npred];
+  
+  A = zeros(nx,nx);
+  k0 = kstate(find(kstate(:,2) <= ykmin_+1),:);
+  i0 = find(k0(:,2) == ykmin_+1);
+  n0 = size(dr.ghx,1);
+  A(1:n0,dr.nstatic+1:dr.nstatic+dr.npred) = dr.ghx(:,1:dr.npred);
+  A(1:n0,dr.nstatic+dr.npred+dr.nfwrd+1:end) = dr.ghx(:,dr.npred+1:end);
+  B = zeros(nx,exo_nbr);
+  B(1:n0,:) = dr.ghu;
+  offset_col = dr.nstatic;
+  for i=ykmin_:-1:2
+    i1 = find(k0(:,2) == i);
+    n1 = size(i1,1);
+    j = zeros(n1,1);
+    for j1 = 1:n1
+      j(j1) = find(k0(i0,1)==k0(i1(j1),1));
+    end
+    if i == ykmin_-1
+      offset_col = dr.nstatic+dr.nfwrd;
+    end
+    A(n0+i1-dr.npred,offset_col+i0(j))=eye(n1);
+    i0 = i1;
+  end
diff --git a/tags/v_3.062/matlab/kernel_density_estimate.m b/tags/v_3.062/matlab/kernel_density_estimate.m
new file mode 100644
index 0000000000000000000000000000000000000000..aeb1e9e94b33a3119de8df1874c73b62f51092b6
--- /dev/null
+++ b/tags/v_3.062/matlab/kernel_density_estimate.m
@@ -0,0 +1,58 @@
+function [abscissa,f] = kernel_density_estimate(data,number_of_grid_points,bandwidth,kernel_function) 
+%%  This function aims at estimating a continuous density. A kernel density 
+%%  estimator is used (see Silverman [1986]). 
+%% 
+%%  * Silverman [1986], "Density estimation for statistics and data analysis". 
+%%
+%%  The code is adapted from Anders Holtsberg's matlab toolbox (stixbox). 
+%%
+%%  stephane.adjemian@cepremap.cnrs.fr [07/16/2004]. 
+
+if size(data,2) > 1 & size(data,1) == 1 
+    data = transpose(data); 
+elseif size(data,2)>1 & size(data,1)>1 
+    error('kernel_density_estimate :: data must be a one dimensional array.'); 
+end
+test = log(number_of_grid_points)/log(2);
+if (abs(test-round(test)) > 10^(-12))
+    error('kernel_density_estimate :: The number of grid points must be a power of 2.');
+end
+
+n = size(data,1); 
+
+
+%% KERNEL SPECIFICATION...
+if strcmpi(kernel_function,'gaussian') 
+    k    = inline('inv(sqrt(2*pi))*exp(-0.5*x.^2)'); 
+elseif strcmpi(kernel_function,'uniform') 
+    k    = inline('0.5*(abs(x) <= 1)'); 
+elseif strcmpi(kernel_function,'triangle') 
+    k    = inline('(1-abs(x)).*(abs(x) <= 1)'); 
+elseif strcmpi(kernel_function,'epanechnikov') 
+    k    = inline('0.75*(1-x.^2).*(abs(x) <= 1)'); 
+elseif strcmpi(kernel_function,'quartic') 
+    k    = inline('0.9375*((1-x.^2).^2).*(abs(x) <= 1)'); 
+elseif strcmpi(kernel_function,'triweight') 
+    k    = inline('1.09375*((1-x.^2).^3).*(abs(x) <= 1)'); 
+elseif strcmpi(kernel_function,'cosinus') 
+    k    = inline('(pi/4)*cos((pi/2)*x).*(abs(x) <= 1)'); 
+end     
+
+
+%% COMPUTE DENSITY ESTIMATE... Gaussian kernel should be used (FFT).
+a  = min(data) - (max(data)-min(data))/3;
+b  = max(data) + (max(data)-min(data))/3;
+abscissa = linspace(a,b,number_of_grid_points)';
+d  = abscissa(2)-abscissa(1); 
+xi = zeros(number_of_grid_points,1);
+xa = (data-a)/(b-a)*number_of_grid_points; 
+for i = 1:n;
+    indx = floor(xa(i));
+    temp = xa(i)-indx;
+    xi(indx+[1 2]) = xi(indx+[1 2]) + [1-temp,temp]';
+end;    
+xk = [-number_of_grid_points:number_of_grid_points-1]'*d;
+kk = k(xk/bandwidth);
+kk = kk / (sum(kk)*d*n);
+f = ifft(fft(fftshift(kk)).*fft([xi ;zeros(size(xi))]));
+f = real(f(1:number_of_grid_points));
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/linear.m b/tags/v_3.062/matlab/linear.m
new file mode 100644
index 0000000000000000000000000000000000000000..e34f39b6380f302fca7c94b19215e32217172165
--- /dev/null
+++ b/tags/v_3.062/matlab/linear.m
@@ -0,0 +1,87 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function linear(x)
+%	LINEAR : LINEAR (x,'filename')
+
+global iy_ ykmin_ ykmax_ xkmin_ xkmax_ jacobia_
+global lgy_ lgx_ iter_ fname_
+
+x = reshape(x,max(size(x)),1) ;
+xx = x ;
+nn = size(iy_,2) ;
+nv = max(iy_(size(iy_,1),:)) ;
+indic = zeros(0,0) ;
+
+if size(x,1) == nv
+	r = find(reshape(iy_'>0,(ykmin_+ykmax_+1)*nn,1)) ;
+	n = abs(lgy_) ;
+	n = kron(ones(ykmin_+ykmax_+1,1),n) ;
+	n = setstr(n(r,:)) ;
+	m = [-ykmin_:ykmax_]'*ones(1,nn) ;
+	m = reshape(m',(ykmin_+ykmax_+1)*nn,1) ;
+	m = m(r) ;
+elseif size(x,1) == nn
+	l = iy_>0 ;
+	l = l.*kron(ones(size(iy_,1),1),[1:nn]) ;
+	i = nonzeros(reshape(iy_,size(iy_,1)*nn,1)) ;
+	j = nonzeros(reshape(l,size(iy_,1)*nn,1)) ;
+	s = ones(1,max(iy_(size(iy_,1),:))) ;
+	indic = sparse(i,j,s,nv,nn) ;
+	x = indic*x ;
+	n = lgy_ ;
+	m = zeros(nn,1) ;
+else
+	error ('Wrong number of arguments in LINEAR.') ;
+end
+
+jacob([fname_ '_ff'],x) ;
+
+if ~ isempty(indic)
+	jacobia_=jacobia_*indic ;
+	clear indic ;
+end
+
+fprintf (1,'Periods  :  ') ;
+fprintf (1,'%4g \n',iter_) ;
+fprintf (1,'Endogenous variables : ') ; fprintf (1,'\n') ;
+fprintf (1,lgy_) ;
+fprintf (1,'\n') ;
+fprintf (1,'Exogenous variables : ') ; fprintf (1,'\n') ;
+fprintf (1,lgx_) ;
+fprintf (1,'\n') ;
+fprintf (1,'Linearization around :') ;
+fprintf (1,'\n') ;
+
+for i = 1:size(n,1) ;
+	fprintf (1,n(i,:)) ; fprintf (1,'(%1g)',m(i)) ;
+	fprintf (1,' = %15.6f \n',xx(i)) ;
+end
+
+fprintf (1,'\n') ;
+
+for i = 1:size(jacobia_,1)
+	for j = 1:size(jacobia_,2)
+		if jacobia_(i,j) ~= 0
+			if jacobia_(i,j) == 1
+				if j == 1
+					fprintf (1,n(j,:)) ; fprintf (1,'(%1g)',m(j)) ;
+				else
+					fprintf (1, ' + ') ; fprintf (1,n(j,:)) ; fprintf (1,'(%1g)',m(j)) ;
+				end
+			elseif jacobia_(i,j) == -1
+				fprintf (1,' - ') ; fprintf (1,n(j,:)) ; fprintf (1,'(%1g)',m(j)) ;
+			elseif jacobia_(i,j) > 0
+				if j>1, fprintf (1,' + ') ; end
+				fprintf (1,'%15.6g',jacobia_(i,j)) ;
+				fprintf (1,'*') ; fprintf (1,n(j,:)) ; fprintf (1,'(%1g)',m(j)) ;
+			else
+				fprintf (1,'%15.6g',jacobia_(i,j)) ;
+				fprintf (1,'*') ; fprintf (1,n(j,:)) ; fprintf (1,'(%1g)',m(j)) ;
+			
+			end
+		end
+	end
+	fprintf (1,'\n') ;
+end
+
+return ;
diff --git a/tags/v_3.062/matlab/list_variables.m b/tags/v_3.062/matlab/list_variables.m
new file mode 100644
index 0000000000000000000000000000000000000000..08fd8f21fc40a0421e59ca240e224436cd9ea510
--- /dev/null
+++ b/tags/v_3.062/matlab/list_variables.m
@@ -0,0 +1,34 @@
+function list_variables()
+  global lgy_ iy_ ykmin_ ykmax_ endo_nbr
+  
+  ipred = find(sum(iy_(1:ykmin_,:),1))';
+  ifwrd = find(sum(iy_(ykmin_+2:end,:),1))';
+  iboth = intersect(ipred,ifwrd);
+  istatic = setdiff([1:endo_nbr]',union(ipred,ifwrd));
+  disp('Purely predetermined variables')
+  ipred1 = setdiff(ipred,iboth);
+  if isempty(ipred1)
+    disp('    none')
+  else
+    disp(lgy_(ipred1,:))
+  end
+  disp('Purely forward-looking variables')
+  ifwrd1 = setdiff(ifwrd,iboth);
+  if isempty(ifwrd1)
+    disp('    none')
+  else
+    disp(lgy_(ifwrd1,:))
+  end
+  disp('Variables that are both forward-looking and predetermined')
+  if isempty(iboth)
+    disp('    none')
+  else
+    disp(lgy_(iboth,:))
+  end
+  disp('Static variables')
+  if isempty(istatic)
+    disp('    none')
+  else
+    disp(lgy_(istatic,:))
+  end
+  
diff --git a/tags/v_3.062/matlab/lnsrch.m b/tags/v_3.062/matlab/lnsrch.m
new file mode 100644
index 0000000000000000000000000000000000000000..11efadc0928fa87fb1cbf61c76a1b9bd6754eb17
--- /dev/null
+++ b/tags/v_3.062/matlab/lnsrch.m
@@ -0,0 +1,86 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function [x,f,fvec,check]=lnsrch(xold,fold,g,p,stpmax,func,varargin)
+
+  alf = 1e-4 ;
+  tolx = 3.7e-11 ;
+  alam = 1;
+  
+  nn = size(xold,1) ;
+  summ = sqrt(sum(p.*p)) ;
+  if ~isfinite(summ)
+    error(['Some element of Newton direction isn''t finite. Jacobian maybe' ...
+	   ' singular or there is a problem with initial values'])
+  end
+  
+  if summ > stpmax
+    p=p.*stpmax/summ ;
+  end
+
+  slope = g'*p ;
+  
+  test = max(abs(p)'./max([abs(xold)';ones(1,nn)])) ;
+  alamin = tolx/test ;
+
+  if alamin > 0.1
+    alamin = 0.1;
+  end
+  
+  while 1
+    if alam < alamin
+      check = 1 ;
+      return
+    end
+    
+    x = xold + (alam*p) ;
+    fvec = feval(func,x,varargin{:}) ;
+    f = 0.5*fvec'*fvec ;
+
+    if any(isnan(fvec))
+      alam = alam/2 ;
+      alam2 = alam ;
+      f2 = f ;
+      fold2 = fold ;
+    else
+
+      if f <= fold+alf*alam*slope
+	check = 0;
+	break ;
+      else
+	if alam == 1
+	  tmplam = -slope/(2*(f-fold-slope)) ;
+	else
+	  rhs1 = f-fold-alam*slope ;
+	  rhs2 = f2-fold2-alam2*slope ;
+	  a = (rhs1/(alam^2)-rhs2/(alam2^2))/(alam-alam2) ;
+	  b = (-alam2*rhs1/(alam^2)+alam*rhs2/(alam2^2))/(alam-alam2) ;
+	  if a == 0
+	    tmplam = -slope/(2*b) ;
+	  else
+	    disc = (b^2)-3*a*slope ;
+
+	    if disc < 0
+	      error ('Roundoff problem in nlsearch') ;
+	    else
+	      tmplam = (-b+sqrt(disc))/(3*a) ;
+	    end
+
+	  end
+
+	  if tmplam > 0.5*alam
+	    tmplam = 0.5*alam;
+	  end
+
+	end
+
+	alam2 = alam ;
+	f2 = f ;
+	fold2 = fold ;
+	alam = max([tmplam;(0.1*alam)]) ;
+      end
+    end
+  end
+
+% 01/14/01 MJ lnsearch is now a separate function
+% 01/12/03 MJ check for finite summ to avoid infinite loop when Jacobian
+%             is singular or model is denormalized
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/lnsrch1.m b/tags/v_3.062/matlab/lnsrch1.m
new file mode 100644
index 0000000000000000000000000000000000000000..1f7e7e2854f75f75c587aab02fcac15fc9f1080f
--- /dev/null
+++ b/tags/v_3.062/matlab/lnsrch1.m
@@ -0,0 +1,95 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function [x,f,fvec,check]=lnsrch(xold,fold,g,p,stpmax,func,j1,j2,varargin)
+
+  x = [];
+  f = [];
+  fvec = [];
+  alf = 1e-4 ;
+  tolx = 3.7e-11 ;
+  alam = 1;
+  
+  x = xold;
+  nn = length(j2);
+  summ = sqrt(sum(p.*p)) ;
+  if ~isfinite(summ)
+    warning(['Some element of Newton direction isn''t finite. Jacobian maybe' ...
+	   ' singular or there is a problem with initial values'])
+    check = 1;
+    return
+  end
+  
+  if summ > stpmax
+    p=p.*stpmax/summ ;
+  end
+
+  slope = g'*p ;
+  
+  test = max(abs(p)'./max([abs(xold(j2))';ones(1,nn)])) ;
+  alamin = tolx/test ;
+
+  if alamin > 0.1
+    alamin = 0.1;
+  end
+  
+  while 1
+    if alam < alamin
+      check = 1 ;
+      return
+    end
+    
+    x(j2) = xold(j2) + (alam*p) ;
+    fvec = feval(func,x,varargin{:}) ;
+    fvec = fvec(j1);
+    f = 0.5*fvec'*fvec ;
+
+    if any(isnan(fvec))
+      alam = alam/2 ;
+      alam2 = alam ;
+      f2 = f ;
+      fold2 = fold ;
+    else
+
+      if f <= fold+alf*alam*slope
+	check = 0;
+	break ;
+      else
+	if alam == 1
+	  tmplam = -slope/(2*(f-fold-slope)) ;
+	else
+	  rhs1 = f-fold-alam*slope ;
+	  rhs2 = f2-fold2-alam2*slope ;
+	  a = (rhs1/(alam^2)-rhs2/(alam2^2))/(alam-alam2) ;
+	  b = (-alam2*rhs1/(alam^2)+alam*rhs2/(alam2^2))/(alam-alam2) ;
+	  if a == 0
+	    tmplam = -slope/(2*b) ;
+	  else
+	    disc = (b^2)-3*a*slope ;
+
+	    if disc < 0
+	      warning ('Roundoff problem in nlsearch') ;
+	      check = 1;
+	      return
+	    else
+	      tmplam = (-b+sqrt(disc))/(3*a) ;
+	    end
+
+	  end
+
+	  if tmplam > 0.5*alam
+	    tmplam = 0.5*alam;
+	  end
+
+	end
+
+	alam2 = alam ;
+	f2 = f ;
+	fold2 = fold ;
+	alam = max([tmplam;(0.1*alam)]) ;
+      end
+    end
+  end
+
+% 01/14/01 MJ lnsearch is now a separate function
+% 01/12/03 MJ check for finite summ to avoid infinite loop when Jacobian
+%             is singular or model is denormalized
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/lpdfbeta.m b/tags/v_3.062/matlab/lpdfbeta.m
new file mode 100644
index 0000000000000000000000000000000000000000..46106ca265bbceca542bbeb8d2b0f54beb30a317
--- /dev/null
+++ b/tags/v_3.062/matlab/lpdfbeta.m
@@ -0,0 +1,7 @@
+function ldens = lpdfbeta(x,a,b);
+% log BETA PDF
+  ldens = gammaln(a+b) - gammaln(a) - gammaln(b) + (a-1)*log(x) + (b-1)*log(1-x);
+
+% 10/11/03 MJ adapted from a GAUSS version by F. Schorfheide, translated
+%             to Matlab by R. Wouters.  
+%             use Matlab gammaln instead of lngam
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/lpdfgam.m b/tags/v_3.062/matlab/lpdfgam.m
new file mode 100644
index 0000000000000000000000000000000000000000..67e781d99df5369a53b455e5bec73075caba92e2
--- /dev/null
+++ b/tags/v_3.062/matlab/lpdfgam.m
@@ -0,0 +1,7 @@
+function  ldens = lpdfgam(x,a,b);
+% log GAMMA PDF 
+  ldens = -gammaln(a) -a*log(b)+ (a-1)*log(x) -x/b ;
+
+% 10/11/03  MJ adapted from an earlier GAUSS version by F. Schorfeide,
+%              translated to MATLAB by R. Wouters  
+%              use MATLAB gammaln rather than lngam
diff --git a/tags/v_3.062/matlab/lpdfgbeta.m b/tags/v_3.062/matlab/lpdfgbeta.m
new file mode 100644
index 0000000000000000000000000000000000000000..f1ba841e45c564a0ee75427bb8a982fb2b5d7b33
--- /dev/null
+++ b/tags/v_3.062/matlab/lpdfgbeta.m
@@ -0,0 +1,7 @@
+function ldens = lpdfgbeta(x,a,b,aa,bb);
+% log (generalized) BETA PDF 
+ldens = -betaln(a,b) + (a-1)*log(x-aa) + (b-1)*log(bb-x) - (a+b-1)*log(bb-aa);
+%gammaln(a+b) - gammaln(a) - gammaln(b)
+%betaln(a,b)
+%pause
+% 02/16/04 SA Interval [aa,bb] is the support of the probability density function. 
diff --git a/tags/v_3.062/matlab/lpdfig.m b/tags/v_3.062/matlab/lpdfig.m
new file mode 100644
index 0000000000000000000000000000000000000000..8365ffa5a067c37412d35c0da0b9419ccc4b5e2f
--- /dev/null
+++ b/tags/v_3.062/matlab/lpdfig.m
@@ -0,0 +1,8 @@
+function ldens = lpdfig(x,a,b)
+% log INVERSE GAMMA
+   ldens = log(2) - gammaln(b/2) + (b/2).*log(a/2) - ( (b+1)/2 ).*log(x.^2) - a./(2*x.^2);
+
+% 10/11/03 MJ adapted from an earlier GAUSS version by F. Schorfeide,
+%             then translated to Matlab by R. Wouters
+%             uses Matlab gammaln rather than lngam
+% 12/01/03 MJ modified according to MR suggestion
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/lpdfig1.m b/tags/v_3.062/matlab/lpdfig1.m
new file mode 100644
index 0000000000000000000000000000000000000000..8375dbe755dc9857b7ce8f79498104f542a71924
--- /dev/null
+++ b/tags/v_3.062/matlab/lpdfig1.m
@@ -0,0 +1,12 @@
+function ldens = lpdfig1(x,s,nu)
+% log INVERSE GAMMA (type 1)
+%
+% X ~ IG1(s,nu)
+% 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.
+%
+% stephane.adjemian@cepremap.cnrs.fr [01/16/2004]
+
+ldens = log(2) - gammaln(nu/2) - (nu/2).*log(2/s) - (nu+1)*log(x) - .5*s./(x.^2);
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/lpdfig2.m b/tags/v_3.062/matlab/lpdfig2.m
new file mode 100644
index 0000000000000000000000000000000000000000..8030683cd1c795fc2f60aff597cf9c78ada49b52
--- /dev/null
+++ b/tags/v_3.062/matlab/lpdfig2.m
@@ -0,0 +1,12 @@
+function ldens = lpdfig2(x,s,nu)
+% log INVERSE GAMMA (type 2)
+%
+% X ~ IG2(s,nu)
+% 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.
+%
+% stephane.adjemian@cepremap.cnrs.fr [01/16/2004]
+
+ldens = - gammaln(nu/2) - (nu/2)*log(2/s) - .5*(nu+2)*log(x) -.5*s./x;
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/lpdfnorm.m b/tags/v_3.062/matlab/lpdfnorm.m
new file mode 100644
index 0000000000000000000000000000000000000000..a7d690fbe94d6f07a106db8a4cc7997ee5ad0078
--- /dev/null
+++ b/tags/v_3.062/matlab/lpdfnorm.m
@@ -0,0 +1,9 @@
+function  f = lpdfnorm(x,m,s)
+%LPDFNORM The log of the normal density function
+%
+%         f = lpdfnorm(x,Mean,StandardDeviation)
+
+if nargin<3, s=1; end
+if nargin<2, m=0; end
+f = -log(s)-log(2*pi)/2-((x-m)./s).^2/2;
+
diff --git a/tags/v_3.062/matlab/lyapunov_symm.m b/tags/v_3.062/matlab/lyapunov_symm.m
new file mode 100644
index 0000000000000000000000000000000000000000..1294bf3619f21de0d10fccf07ec5b31a8f2704ff
--- /dev/null
+++ b/tags/v_3.062/matlab/lyapunov_symm.m
@@ -0,0 +1,49 @@
+% solves x-a*x*a'=b for b (and then x) symmetrical
+function [x,info]=lyapunov_symm(a,b)
+  info = 0;
+  n = size(b,1);
+  if n == 1
+    x=b/(1-a*a);
+    return
+  end
+  x=zeros(n,n);
+  [u,t]=schur(a);
+  b=u'*b*u;
+  for i=n:-1:2
+    if t(i,i-1) == 0
+      if i == n
+	c = zeros(n,1);
+      else
+	c = t(1:i,:)*(x(:,i+1:end)*t(i,i+1:end)')+...
+	    t(i,i)*t(1:i,i+1:end)*x(i+1:end,i);
+      end
+      q = eye(i)-t(1:i,1:i)*t(i,i);
+      x(1:i,i) = q\(b(1:i,i)+c);
+      x(i,1:i-1) = x(1:i-1,i)';
+    else
+      if i == n
+	c = zeros(n,1);
+	c1 = zeros(n,1);
+      else
+	c = t(1:i,:)*(x(:,i+1:end)*t(i,i+1:end)')+...
+	    t(i,i)*t(1:i,i+1:end)*x(i+1:end,i)+...
+	    t(i,i-1)*t(1:i,i+1:end)*x(i+1:end,i-1);
+	c1 = t(1:i,:)*(x(:,i+1:end)*t(i-1,i+1:end)')+...
+	     t(i-1,i-1)*t(1:i,i+1:end)*x(i+1:end,i-1)+...
+	     t(i-1,i)*t(1:i,i+1:end)*x(i+1:end,i);
+      end
+      q = [eye(i)-t(1:i,1:i)*t(i,i) -t(1:i,1:i)*t(i,i-1);...
+	   -t(1:i,1:i)*t(i-1,i) eye(i)-t(1:i,1:i)*t(i-1,i-1)];
+      z =  q\[b(1:i,i)+c;b(1:i,i-1)+c1];
+      x(1:i,i) = z(1:i);
+      x(1:i,i-1) = z(i+1:end);
+      x(i,1:i-1)=x(1:i-1,i)';
+      x(i-1,1:i-2)=x(1:i-2,i-1)';
+      i = i - 1;
+    end
+  end
+  if i == 2
+    c = t(1,:)*(x(:,2:end)*t(1,2:end)')+t(1,1)*t(1,2:end)*x(2:end,1);
+    x(1,1)=(b(1,1)+c)/(1-t(1,1)*t(1,1));
+  end
+  x=u*x*u';
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/make_ex_.m b/tags/v_3.062/matlab/make_ex_.m
new file mode 100644
index 0000000000000000000000000000000000000000..d4c28a19aae151df493c7b94a733d72b124cf9c8
--- /dev/null
+++ b/tags/v_3.062/matlab/make_ex_.m
@@ -0,0 +1,64 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function make_ex_
+  global exe_ ex_ ex0_ xkmin_ xkmax_ exo_nbr options_ exe_det_ ex_det_ ...
+      exo_det_nbr ex_det0_ ykmin_ ykmax_
+  
+  options_ = set_default_option(options_,'periods',0);
+  
+  if isempty(exe_)
+    exe_ = zeros(exo_nbr,1);
+  end
+  
+  if exo_det_nbr > 1 & isempty(exe_det_)
+    exe_det_ = zeros(exo_det_nbr,1);
+  end
+  
+  if isempty(ex_)
+    if isempty(ex0_)
+      ex_ = [ones(xkmin_+options_.periods+xkmax_,1)*exe_'];
+    else
+      ex_ = [ones(xkmin_,1)*ex0_';ones(options_.periods+xkmax_,1)*exe_'];
+    end
+  elseif size(ex_,2) < length(exe_)
+    k = size(ex_,2)+1:length(exe_)
+    if isempty(ex0_)
+      ex_ = [ex_ ones(xkmin_+size(ex_,1)+xkmax_,1)*exe_(k)'];
+    else
+      ex_ = [ex_ [ones(xkmin_,1)*ex0_(k)'; ones(size(ex_,1)-xkmin_+xkmax_, ...
+						1)*exe_(k)']];
+    end
+  elseif size(ex_,1) < xkmin_+xkmax_+options_.periods
+    if isempty(ex0_)
+      ex_ = [ex_; ones(xkmin_+options_.periods+xkmax_-size(ex_,1),1)*exe_'];
+    else
+      ex_ = [ones(xkmin_,1)*ex0_'; ex_; ones(options_.periods+xkmax_-size(ex_, ...
+						  1),1)*exe_'];
+    end
+  end
+  
+  if exo_det_nbr > 0
+    if isempty(ex_det_)
+      if isempty(ex_det0_)
+	ex_det_ = [ones(ykmin_+options_.periods+ykmax_,1)*exe_det_'];
+      else
+	ex_det_ = [ones(ykmin_,1)*ex_det0_';ones(options_.periods+ykmax_,1)*exe_det_'];
+      end
+    elseif size(ex_det_,2) < length(exe_det_)
+      k = size(ex_det_,2)+1:length(exe_det_)
+      if isempty(ex_det0_)
+	ex_det_ = [ex_det_ ones(ykmin_+size(ex_det_,1)+ykmax_,1)*exe_det_(k)'];
+      else
+	ex_det_ = [ex_det_ [ones(ykmin_,1)*ex_det0_(k)'; ones(size(ex_det_,1)-ykmin_+ykmax_, ...
+						  1)*exe_det_(k)']];
+      end
+    elseif size(ex_det_,1) < ykmin_+ykmax_+options_.periods
+      if isempty(ex_det0_)
+	ex_det_ = [ex_det_; ones(ykmin_+options_.periods+ykmax_-size(ex_det_,1),1)*exe_det_'];
+      else
+	ex_det_ = [ones(ykmin_,1)*ex_det0_'; ex_det_; ones(options_.periods+ykmax_-size(ex_det_, ...
+						  1),1)*exe_det_'];
+      end
+    end
+  end
+	     
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/make_y_.m b/tags/v_3.062/matlab/make_y_.m
new file mode 100644
index 0000000000000000000000000000000000000000..21cd0104d0868a9e84d6683667077e4de86216ed
--- /dev/null
+++ b/tags/v_3.062/matlab/make_y_.m
@@ -0,0 +1,36 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function make_y_
+  global ys_ y_ ys0_ ykmin_ ykmax_ endo_nbr options_
+  
+  options_ = set_default_option(options_,'periods',0);
+  
+  if isempty(ys_)
+    ys_ = ones(endo_nbr,1);
+  end
+  
+  
+  if isempty(y_)
+    if isempty(ys0_)
+      y_ = [ys_*ones(1,ykmin_+options_.periods+ykmax_)];
+    else
+      y_ = [ys0_*ones(1,ykmin_);ys_*ones(1,options_.periods+ykmax_)];
+    end
+  elseif size(y_,1) < length(ys_)
+    k = size(y_,1)+1:length(ys_)
+    if isempty(ys0_)
+      y_ = [y_; ys_(k)*ones(1,ykmin_+size(y_,1)+ykmax_)];
+    else
+      y_ = [y_; [ys0_(k)*ones(1,ykmin_); ys_(k)*ones(1,size(y_,2)-ykmin_+ ...
+						     ykmax_)]];
+    end
+  elseif size(y_,2) < ykmin_+ykmax_+options_.periods
+    if isempty(ys0_)
+      y_ = [y_ ys_*ones(1,ykmin_+options_.periods+ykmax_-size(y_,2),1)];
+    else
+      y_ = [ys0_*ones(1,ykmin_) y_  ys_*ones(1,options_.periods+ykmax_-size(y_, ...
+						  2))];
+    end
+  end
+    
+	     
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/marginal_density.m b/tags/v_3.062/matlab/marginal_density.m
new file mode 100644
index 0000000000000000000000000000000000000000..ce178c7c006a82ff8b03cc897684e3056ffdb828
--- /dev/null
+++ b/tags/v_3.062/matlab/marginal_density.m
@@ -0,0 +1,48 @@
+function marginal = marginal_density(x2,logpost2)
+global fname_ options_
+
+nruns = size(x2,1);
+nblck = size(x2,3);
+npara = size(x2,2);
+
+B = 1;
+T = nruns-round(options_.mh_drop*nruns)+1;
+N = T*nblck;
+simulations = zeros(N,npara);
+lposterior   = zeros(N,1);
+
+while B <= nblck;
+    simulations((B-1)*T+1:B*T,:) = x2(round(options_.mh_drop*nruns):nruns,:,B);
+    lposterior((B-1)*T+1:B*T) = logpost2(round(options_.mh_drop*nruns):nruns,B);
+    B = B + 1;
+end;    
+
+lpost_mode = max(lposterior);
+
+MU = mean(simulations)';
+SIGMA = zeros(npara,npara);
+for i=1:N;
+    SIGMA = SIGMA + (simulations(i,:)'-MU)*(simulations(i,:)'-MU)';
+end;
+SIGMA = SIGMA/N;
+
+DetSIGMA = det(SIGMA);
+InvSIGMA = inv(SIGMA);
+marginal = [];
+
+for p = 0.1:0.1:0.9;
+    critval = qchisq(p,npara);
+    tmp = 0;
+    for i = 1:N;
+        deviation  = (simulations(i,:)-MU')*InvSIGMA*((simulations(i,:)-MU'))';
+        if deviation <= critval;
+	  lftheta = -log(p)-(npara*log(2*pi)+log(DetSIGMA)+deviation)/2;
+	  tmp = tmp + exp(lftheta - lposterior(i)+lpost_mode);
+        end;    
+    end;
+    marginal = cat(1,marginal,[p,lpost_mode-log(tmp/N)]); 
+end;    
+    
+
+
+
diff --git a/tags/v_3.062/matlab/matrictint.m b/tags/v_3.062/matlab/matrictint.m
new file mode 100644
index 0000000000000000000000000000000000000000..eb95193c8444578a22e842c37ed0df92ad152b85
--- /dev/null
+++ b/tags/v_3.062/matlab/matrictint.m
@@ -0,0 +1,35 @@
+function w=matrictint(S,XXi,T)
+%function w=matrictint(S,XXi,T)
+%  S:  usually sample cross product matrix of LS residuals
+% XXi:  inv(X'X) matrix for rhs variables
+%  T:  number of observations
+%  w:  log of integrated posterior for SUR or RF VAR with det(Sigma)^(-(m+1)/2) Jeffreys-like prior
+%  To get the log of the integral of the likelihood for a VAR with T observations, 
+%   k rhs variables in each equation, and m equations, set T=T-m-1 and subtract .5*m*(m+1)*log(2*pi).
+% We are integrating the exponential of -.5*T*m*log(2*pi)-.5*(T+m+1)*log(det(Sigma))-.5*trace(Sigma\S(beta)).
+k=size(XXi,1);
+m=size(S,1);
+[cx,p]=chol(XXi);
+[cs,q]=chol(S);
+%cx=cschol(XXi);
+%cs=cschol(S);
+if any(diag(cx)<100*eps)
+    error('singular XXi')
+end
+if any(diag(cs<100*eps))
+    error('singular S')
+end
+w=(-T+k+(m-1)/2)*m*.5*log(pi)-(T-k)*sum(log(diag(cs)))+m*sum(log(diag(cx)))+ggammaln(m,(T-k)/2);
+
+function lgg=ggammaln(m,ndf)
+%function gg=ggamma(m,ndf)
+% From 8.2.22 on p.427 of Box and Tiao, this is the log of generalized
+% gamma divided by gamma(.5)^(.5*m*(m-1))
+if ndf<=(m-1)/2
+    error('too few df in ggammaln')
+else
+    %lgg=.5*m*(m-1)*gammaln(.5); % normalizing factor not used in Wishart integral
+    garg=ndf+.5*(0:-1:1-m);
+    lgg=sum(gammaln(garg));
+end
+    
diff --git a/tags/v_3.062/matlab/mcmc_diagnostic.m b/tags/v_3.062/matlab/mcmc_diagnostic.m
new file mode 100644
index 0000000000000000000000000000000000000000..9216d49104856b517d853fa3094a0b08f757a139
--- /dev/null
+++ b/tags/v_3.062/matlab/mcmc_diagnostic.m
@@ -0,0 +1,172 @@
+function mcmc_diagnostic(x2)
+% 
+% See S. Brooks and Gelman [1998, Journal ]
+%
+
+global estim_params_ lgx_ options_
+
+nblck = size(x2,3);
+npar  = size(x2,2);
+nruns = size(x2,1)
+
+origin = 1000;
+step_size = 100;
+
+det_W = zeros(nruns,1);
+det_B = zeros(nruns,1);
+det_V = zeros(nruns,1);
+R     = zeros(nruns,1);
+ligne = 0;
+
+for iter = origin:step_size:nruns;
+    ligne = ligne + 1; 
+    W = zeros(npar,npar);
+    B = zeros(npar,npar);
+    linea = ceil(0.5*iter);
+    n = iter-linea+1;
+    muB = mean(mean(x2(linea:iter,:,:),3),1)';  
+    for j = 1:nblck;
+        muW  = mean(x2(linea:iter,:,j))';
+        B = B + (muW-muB)*(muW-muB)';
+        for t = linea:iter;
+            W = W + (x2(t,:,j)'-muW)*(x2(t,:,j)-muW');     
+        end;    
+    end;
+    W = inv(nblck*(n-1))*W;
+    B = n*inv(nblck-1)*B;
+    V = inv(n)*(n-1)*W + (1+inv(nblck))*B/n;
+    det_W(ligne,1) = det(W);
+    det_B(ligne,1) = det(B);
+    det_V(ligne,1) = det(V);
+    lambda = max(eig(inv(n*W)*B));
+    R(ligne,1) = (n-1)/n + lambda*(nblck+1)/nblck;
+end;    
+
+det_W = det_W(1:ligne,1);
+det_V = det_V(1:ligne,1);
+R     = R(1:ligne,1);
+
+figure('Name','MCMC multivariate diagnostic');
+subplot(2,1,1);
+plot(origin:step_size:nruns,R,'-k','linewidth',2);
+subplot(2,1,2);
+plot(origin:step_size:nruns,det_W,'--r','linewidth',2);
+hold on;
+plot(origin:step_size:nruns,det_V,'--b','linewidth',2);
+hold off;
+
+
+[R_interval,R_c1,R_c2] = mcmcdiags(x2,0.2,3,4,origin,step_size);
+pages = floor(npar/4);
+k = 0;
+
+% pages
+for i = 1:pages;
+    figure('Name','MCMC univariate diagnostic');
+    boxplot = 1;
+    for j = 1:4;
+        k = k+1;
+        if k <= estim_params_.nvx;
+            vname = deblank(lgx_(estim_params_.var_exo(k,1),:));
+            nam=['SE_{',vname,'}'];
+        elseif  k <= (estim_params_.nvx+estim_params_.nvn);
+            vname = deblank(options_.varobs(estim_params_.var_endo(k-estim_params_.nvx,1),:));
+            nam=['SE_{EOBS_',vname,'}'];
+        elseif  k <= (estim_params_.nvx+estim_params_.nvn+estim_params_.ncx);
+            jj = k - (estim_params_.nvx+estim_params_.nvn);
+            k1 = estim_params_.corrx(jj,1);
+            k2 = estim_params_.corrx(jj,2);
+            vname = [deblank(lgx_(k1,:)) ',' deblank(lgx_(k2,:))];
+            nam=['CC_{',vname,'}'];
+        elseif  k <= (estim_params_.nvx+estim_params_.nvn+estim_params_.ncx+ ...
+		estim_params_.ncn)
+            jj = k - (estim_params_.nvx+estim_params_.nvn+estim_params_.ncx);
+            k1 = estim_params_.corrn(jj,1);
+            k2 = estim_params_.corrn(jj,2);
+            vname = [deblank(lgx_(k1,:)) ',' deblank(lgx_(k2,:))];
+            nam=['CC_{EOBS_',vname,'}'];
+        else
+            jj = k - (estim_params_.nvx+estim_params_.nvn+estim_params_.ncx+estim_params_.ncn);
+            nam = deblank(estim_params_.param_names(jj,:));
+        end
+        xx = origin:step_size:nruns;
+        for crit = 1:3;
+            if crit == 1;
+                plt1 = R_interval(:,k,1);
+                plt2 = R_interval(:,k,2);
+                namnam  = [nam , ', R_{interval}']; 
+            elseif crit == 2;
+                plt1 = R_c1(:,k,1);
+                plt2 = R_c1(:,k,2);
+                namnam  = [nam , ', R_{c1}'];
+            elseif crit == 3;    
+                plt1 = R_c2(:,k,1);
+                plt2 = R_c2(:,k,2);
+                namnam  = [nam , ', R_{c2}'];
+            end;
+            subplot(4,3,boxplot);
+            plot(xx,plt1,'-b');
+            hold on;
+            plot(xx,plt2,'-r');
+            hold off;
+            title(namnam,'Interpreter','none');
+            boxplot = boxplot + 1;
+        end;
+    end;
+end;
+reste = npar-k;
+figure('Name','MCMC univariate diagnostic');
+boxplot = 1;
+for j = 1:reste;
+    k = k+1;
+    if k <= estim_params_.nvx;
+        vname = deblank(lgx_(estim_params_.var_exo(k,1),:));
+        nam=['SE_{',vname,'}'];
+    elseif  k <= (estim_params_.nvx+estim_params_.nvn);
+        vname = deblank(options_.varobs(estim_params_.var_endo(k-estim_params_.nvx,1),:));
+        nam=['SE_{EOBS_',vname,'}'];
+    elseif  k <= (estim_params_.nvx+estim_params_.nvn+estim_params_.ncx);
+        jj = k - (estim_params_.nvx+estim_params_.nvn);
+        k1 = estim_params_.corrx(jj,1);
+        k2 = estim_params_.corrx(jj,2);
+        vname = [deblank(lgx_(k1,:)) ',' deblank(lgx_(k2,:))];
+        nam=['CC_{',vname,'}'];
+    elseif  k <= (estim_params_.nvx+estim_params_.nvn+estim_params_.ncx+ ...
+		estim_params_.ncn)
+        jj = k - (estim_params_.nvx+estim_params_.nvn+estim_params_.ncx);
+        k1 = estim_params_.corrn(jj,1);
+        k2 = estim_params_.corrn(jj,2);
+        vname = [deblank(lgx_(k1,:)) ',' deblank(lgx_(k2,:))];
+        nam = ['CC_{EOBS_',vname,'}'];
+    else
+        jj = k - (estim_params_.nvx+estim_params_.nvn+estim_params_.ncx+estim_params_.ncn);
+        nam = deblank(estim_params_.param_names(jj,:));
+    end
+    xx = origin:step_size:nruns;
+    for crit = 1:3;
+        if crit == 1;
+            plt1 = R_interval(:,k,1);
+            plt2 = R_interval(:,k,2);
+            namnam  = [nam , ', R_{interval}']; 
+        elseif crit == 2;
+            plt1 = R_c1(:,k,1);
+            plt2 = R_c1(:,k,2);
+            namnam  = [nam , ', R_{c1}'];
+        elseif crit == 3;    
+            plt1 = R_c2(:,k,1);
+            plt2 = R_c2(:,k,2);
+            namnam  = [nam , ', R_{c2}'];
+        end;
+        subplot(reste,3,boxplot);
+        plot(xx,plt1,'-b');
+        hold on;
+        plot(xx,plt2,'-r');
+        hold off;
+        title(namnam,'Interpreter','none');
+        boxplot = boxplot + 1;
+    end;
+end;    
+    
+    
+    
+
diff --git a/tags/v_3.062/matlab/mcmcdiags.m b/tags/v_3.062/matlab/mcmcdiags.m
new file mode 100644
index 0000000000000000000000000000000000000000..9b896f604fb0ffab1bf33659040d666f239eb0d0
--- /dev/null
+++ b/tags/v_3.062/matlab/mcmcdiags.m
@@ -0,0 +1,114 @@
+function [R_interval,R_c1,R_c2] = mcmcdiags(x2,alpha,c1,c2,origin,step_size);
+% This function computes univariate mcmc diagnostics. See S. Brooks and A.
+% Gelman "General Methods for Monitoring Convergence of Iterative
+% Simulations".
+% 
+% stephane.adjemian@cepremap.cnrs.fr [01/05/2004] 
+
+global fname_
+
+
+f1 = [fname_ '_MH_diagnostics_1'];
+f2 = [fname_ '_MH_diagnostics_2'];
+
+
+npar  = size(x2,2);  
+nruns = size(x2,1);
+nblck = size(x2,3);
+ligne = 0;
+LIGNE = 0;
+
+R_interval = zeros(nruns,npar,2);
+MU1   = zeros(1,npar,nblck);
+
+BigArray  = cat(2,x2,zeros(nruns,npar,nblck));
+for i = 1:npar;
+    for j = 1:nblck;
+        [tmp,indx] = sort(BigArray(:,i,j));
+        BigArray(:,i,j) = tmp;
+        BigArray(:,i+npar,j) = indx;
+    end;
+end;
+save(f1,'BigArray');
+clear BigArray;
+BigMatrix = zeros(nruns*nblck,2*npar);
+tmp = (1:nruns)';
+for i=1:npar;
+    for j=1:nblck;
+        BigMatrix((j-1)*nruns+1:j*nruns,i) = x2(:,i,j);
+        BigMatrix((j-1)*nruns+1:j*nruns,npar+i) = tmp;
+    end;
+    pmt = sortrows([BigMatrix(:,i),BigMatrix(:,npar+i)],1);
+    BigMatrix(:,i) = pmt(:,1);
+    BigMatrix(:,npar+i) = pmt(:,2);    
+end;   
+save(f2,'BigMatrix');
+clear BigMatrix;
+
+load(f2);
+for iter  =  origin:step_size:nruns;
+    ligne = ligne + 1;
+    linea = ceil(0.5*iter);
+    n = iter-linea+1;
+    cinf = round(nblck*n*alpha/2);
+    csup = round(nblck*n*(1-alpha/2));
+    for i=1:npar;
+        linie = find(BigMatrix(:,npar+i) >= linea & ...
+            BigMatrix(:,npar+i)<=iter);
+        tmp = BigMatrix(linie,i); 
+        R_interval(ligne,i,1) = tmp(csup)-tmp(cinf);
+    end;
+end;
+clear BigMatrix;LIGNE = ligne;ligne = 0;
+R_interval = R_interval(1:LIGNE,:,:);
+load(f1);
+for iter  = origin:step_size:nruns;
+    ligne = ligne+1;
+    linea = ceil(0.5*iter);
+    n = iter-linea+1;
+    cinf = round(n*alpha/2);
+    csup = round(n*(1-alpha/2));
+    for i=1:npar;
+        for j=1:nblck;
+            linie = find(BigArray(:,npar+i,j) >= linea & ...
+                BigArray(:,npar+i,j)<=iter);
+            tmp = BigArray(linie,i,j); 
+            R_interval(ligne,i,2) = tmp(csup)-tmp(cinf);
+        end;    
+    end;
+end;
+clear BigArray;ligne = 0;
+
+R_c1 = zeros(LIGNE,npar,2);
+R_c2 = zeros(LIGNE,npar,2);
+
+for iter  = origin:step_size:nruns;
+    ligne  = ligne + 1; 
+    linea  = ceil(0.5*iter);
+    n      = iter-linea+1;
+    selvec = linea:iter;
+    MEAN1  = zeros(n,npar,nblck);
+    MEAN2  = zeros(n,npar,nblck);
+    tmp = x2(selvec,:,:);                    
+    mu1 = mean(mean(tmp,3),1);
+    mu2 = mean(tmp,1);
+    for j=1:nblck;
+        MU1(1,:,j) = mu1;
+    end;    
+    for t = 1:n;
+        MEAN1(t,:,:) = MU1;
+        MEAN2(t,:,:) = mu2;
+    end;    
+    R_c1(ligne,:,1) = sum(sum(abs(tmp-MEAN1).^c1,3),1)/(nblck*n-1);
+    R_c2(ligne,:,1) = sum(sum(abs(tmp-MEAN1).^c2,3),1)/(nblck*n-1);
+    R_c1(ligne,:,2) = sum(sum(abs(tmp-MEAN2).^c1,3),1)/(nblck*(n-1));
+    R_c2(ligne,:,2) = sum(sum(abs(tmp-MEAN2).^c2,3),1)/(nblck*(n-1));
+end;    
+
+R_c1 = R_c1.^(1/c1);
+R_c2 = R_c2.^(1/c2);
+
+delete([f1 '.mat'])
+delete([f2 '.mat'])
+
+% 2004/1/12 SA corrected bug line 59
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/mcompare.m b/tags/v_3.062/matlab/mcompare.m
new file mode 100644
index 0000000000000000000000000000000000000000..b5b8d13bc2cad3cb2c9acf934028b27e9d87a968
--- /dev/null
+++ b/tags/v_3.062/matlab/mcompare.m
@@ -0,0 +1,54 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function mcompare(s1,s2)
+% MCOMPARE :	MCOMPARE ( [ 'file1' ; 'file2' ] , [ 'var1' ; 'var2' ...] )	
+%		This optional command plots the relative differences between
+%		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
+%		is equal to the difference between the two simulation reported
+%		to the first one. If, for a given variable, zero is one of the
+%		value of the base simulation, the absolute difference is ploted
+%		instead of the relative one.
+
+global dsmpl_ iter_
+global nvx nvy x y lag1
+
+ftest(s1,s2) ;
+
+ix = [1-lag1(1):size(x,2)-lag1(1)]' ;
+i = [lag1(1):size(ix,1)-lag1(2)+1]' ;
+
+if size(dsmpl_,1) == 1
+	error(['DSAMPLE not specified.']) ;
+end
+
+if dsmpl_(3) > 0
+	if dsmpl_(3) == 2
+		if dsmpl_(1)<0 | dsmpl_(2)>size(x,2)-lag1(2)
+			error ('Wrong sample.') ;
+		end
+		i = [dsmpl_(1)+lag1(1):dsmpl_(2)+lag1(1)]' ;
+	elseif dsmpl_(3) == 1
+		if dsmpl_(1)>size(x,2)-lag1(2)
+			error ('Wrong sample.') ;
+		end
+		i = [lag1(1):dsmpl_(1)+lag1(1)]' ;
+	end
+end
+
+for k = 1:size(x,1)
+	figure ;
+	x1 = x(k,i) ;
+	y1 = y(k,i) ;
+	if nnz(x1) < length(x1)
+		plot(ix(i),(y1-x1)) ;
+	else
+		plot(ix(i),(y1-x1)./x1) ;
+	end
+	xlabel(['Periods']) ;
+	title(['Variable ' s2(k)]) ;
+end
+
+return ;
diff --git a/tags/v_3.062/matlab/metropolis.m b/tags/v_3.062/matlab/metropolis.m
new file mode 100644
index 0000000000000000000000000000000000000000..7e28c970f0a49a96e09d2bcf1fffdd3d8e3effa9
--- /dev/null
+++ b/tags/v_3.062/matlab/metropolis.m
@@ -0,0 +1,3932 @@
+function metropolis(xparam1,vv,gend,data,rawdata,mh_bounds)
+% stephane.adjemian@cepremap.cnrs.fr [07-31-2004]
+% Adapted from an older version of metropolis.m 
+
+  global bayestopt_ exo_nbr dr_ estim_params_ Sigma_e_ options_ xparam_test
+  global lgy_ lgx_ fname_ ys_ xkmin_ xkmax_ ykmin_ ykmax_ endo_nbr
+  global oo_ lgx_orig_ord_ lgy_TeX_ lgx_TeX_
+  global dsge_prior_weight
+
+  TeX       = options_.TeX;
+  nruns     = options_.mh_replic;
+  truns     = options_.mh_replic*options_.mh_nblck;
+  nblck     = options_.mh_nblck;
+  nvx       = estim_params_.nvx;
+  nvn       = estim_params_.nvn;
+  ncx       = estim_params_.ncx;
+  ncn       = estim_params_.ncn;
+  np        = estim_params_.np ;
+  nx        = nvx+nvn+ncx+ncn+np;
+  npar      = length(xparam1);
+  nvobs     = size(options_.varobs,1);
+  horizon = options_.forecast;
+
+  % options_.load_mh_file = -1;
+  
+
+  %% Determine the value of MAX_nruns, MAX_nforc, MAX_nsmoo and MAX_ninno values
+  MaxNumberOfBytes = 1000000;%% This value should be adjusted
+  MAX_nruns = ceil(MaxNumberOfBytes/(npar+2)/8);
+  MAX_nforc = ceil(MaxNumberOfBytes/((options_.forecast+ykmin_)*length(ys_))/8);
+  MAX_nsmoo = ceil(MaxNumberOfBytes/((endo_nbr)*gend)/8);
+  MAX_ninno = ceil(MaxNumberOfBytes/(exo_nbr*gend)/8);
+  MAX_nerro = ceil(MaxNumberOfBytes/(size(options_.varobs,1)*gend)/8);
+  MAX_nfilt = ceil(MaxNumberOfBytes/((endo_nbr)*gend)/8);
+  if options_.bayesian_irf
+    MAX_nirfs_dsge = ceil(MaxNumberOfBytes/(options_.irf*length(ys_)*exo_nbr)/8);
+    if ~isempty(dsge_prior_weight)
+      MAX_nirfs_dsgevar = ceil(MaxNumberOfBytes/(options_.irf*nvobs*exo_nbr)/8)
+    end
+  end
+  MAX_nthm1 = ceil(MaxNumberOfBytes/(length(ys_)*8));
+  MAX_nthm2 = ceil(MaxNumberOfBytes/(length(ys_)*length(ys_)*8));
+  MAX_nthm3 = ceil(MaxNumberOfBytes/(length(ys_)*exo_nbr*8));
+  MAX_nthm4 = ceil(MaxNumberOfBytes/(length(ys_)*options_.ar*8));
+
+  d     = chol(vv);
+  options_.lik_algo = 1;
+
+  if nruns
+    if options_.load_mh_file == 0
+      % Delete old mh files...
+      if nblck > 1
+	disp('MH: Multiple chains mode.')
+      else
+	disp('MH: One Chain mode.')
+      end
+      files = eval(['dir(''' fname_ '_mh*.mat'');']);
+      if length(files)
+	delete([fname_ '_mh*.mat']);
+	disp('MH: Old _mh files succesfully erased!')
+      end   
+      nops = 0;         % Number Of Past Simulations.
+      lfile = -1;       % Index for the last mh file.
+      if nblck > 1
+	disp('MH: Searching for initial values...')
+	ix2 = zeros(1,npar,nblck);
+	ilogpo2 = zeros(1,nblck);
+	for j=1:nblck
+	  validate  = 0;
+	  init_iter = 0;
+	  trial     = 1;
+	  while validate == 0 & trial <= 10 
+	    candidate = options_.mh_init_scale*randn(1,npar)*d + transpose(xparam1);
+	    if all(candidate' > mh_bounds(:,1)) & all(candidate' < mh_bounds(:,2)) 
+	      ix2(1,:,j) = candidate;
+	      if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+                ilogpo2(1,j) = -DsgeLikelihood(ix2(1,:,j)',gend,data);
+	      else
+                ilogpo2(1,j) = -DsgeVarLikelihood(ix2(1,:,j)',gend);
+	      end
+	      j = j+1;
+	      validate = 1;
+	    end
+	    init_iter = init_iter + 1;
+	    if init_iter > 100 & validate == 0
+	      disp(['MH: I couldn''t get a valid initial value in 100 trials.'])
+	      disp(['MH: You should Reduce mh_init_scale...'])
+	      disp(sprintf('MH: Parameter mh_init_scale is equal to %f.',options_.mh_init_scale))
+	      options_.mh_init_scale = input('MH: Enter a new value...  ');
+	      trial = trial+1;
+	    end
+	  end
+	  if trial > 10 & ~validate
+	    error(['MH: I''m unable to find a starting value for block ' int2str(j)]);
+	  end
+	end
+	disp('MH: Initial values found!')
+	disp(' ')
+      else
+	candidate = transpose(xparam1);
+	if all(candidate' > mh_bounds(:,1)) & all(candidate' < mh_bounds(:,2)) 
+	  ix2 = candidate;
+	  if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+	    ilogpo2 = -DsgeLikelihood(ix2',gend,data);
+	  else
+	    ilogpo2 = -DsgeVarLikelihood(ix2',gend);
+	  end
+	  disp('MH: Initialization at the posterior mode.')
+	  disp(' ')
+	else
+	  disp('MH: Initialization failed...')
+	  error('MH: The posterior mode lies outside the prior bounds.')
+	end
+      end
+      save([fname_ '_MhInitialization'],'ix2','ilogpo2');
+    elseif options_.load_mh_file == 1
+      disp('MH: I''m loading past metropolis-hastings simulations...')
+      if nblck>1
+	files = eval(['dir(''' fname_ '_mh*_blck*.mat'');']);
+	bfiles = eval(['dir(''' fname_ '_mh0_blck*.mat'');']);
+	lfile = length(files)/length(bfiles)-1;
+      else
+	files = eval(['dir(''' fname_ '_mh*.mat'');']);
+	bfiles = 1;
+	ifiles = eval(['dir(''' fname_ '_MhInitialization.mat'');']);
+	if isempty(ifiles)
+	  lfile = length(files)-1;
+	else
+	  lfile = length(files)-2;
+	end
+      end
+      if ~length(files)
+	error('MH: FAILURE :: there is no MH file to load here!')    
+      end
+      past_number_of_blocks = length(bfiles);
+      if length(bfiles)>0 & past_number_of_blocks ~= nblck
+	disp('MH: The specified number of blocks doesn''t match with the previous number of blocks!')
+	disp(['MH: You declared ' int2str(nblck) ' blocks, but the previous number of blocks was ' int2str(past_number_of_blocks) '.'])
+	disp(['MH: I will run the Metropolis-Hastings with ' int2str(past_number_of_blocks) ' blocks.' ])
+	nblck = past_number_of_blocks;
+	options_.mh_nblck = nblck;
+      end
+      %lfile = length(files)/nblck-1;
+      if nblck == 1
+	instr = [fname_ '_mh' int2str(lfile)];
+	eval(['load ' instr]);
+	clear post2;
+	nops = size(logpo2,1);  
+	ix2 = x2(nops,:);   
+	ilogpo2 = logpo2(nops);
+	clear x2  logpo2;     
+	for file = 0:lfile-1
+	  instr = [fname_ '_mh' int2str(file)];
+	  eval(['load ' instr]);
+	  clear post2 x2;
+	  nops = nops + size(logpo2,1);
+	end
+      else 
+	for b = 1:nblck
+	  instr = [fname_ '_mh' int2str(lfile) '_blck' int2str(b)];
+	  eval(['load ' instr]);
+	  clear post2;
+	  nops = length(logpo2);
+	  ix2(1,:,b) = x2(nops,:);  
+	  ilogpo2(b) = logpo2(nops);
+	  clear x2  logpo2;     
+	end
+	for file = 0:lfile-1
+	  instr = [fname_ '_mh' int2str(file) '_blck1'];
+	  eval(['load ' instr]);
+	  clear post2 x2;
+	  nops = nops + length(logpo2);
+	  clear logpo2;
+	end
+      end
+      % nops is the Number Of Past Simulations. 
+      disp(['MH: ... It''s done. I''ve loaded ' int2str(nops) 'simulations.'])
+      disp(' ')
+    elseif options_.load_mh_file == -1%%% Not ready...
+      instr = [fname_ '_MhInitialization'];
+      eval(['load ' instr]);
+      nblck = length(ilogpo2);
+      options_.mh_nblck = nblck;
+      % Count the total number of saved mh files
+      AllMhFiles = eval(['dir(''' fname_ '_mh*_blck*.mat'');']);
+      TotalNumberOfMhFiles = length(AllMhFiles);
+      % Count the number of saved mh files per block
+      NumberOfMhFilesPerBlock = zeros(nblck,1); 
+      for i = 1:nblck
+	BlckMhFiles = eval(['dir(''' fname_ '_mh*_blck' int2str(i) '.mat'');']);
+	NumberOfMhFilesPerBlock(i) = length(BlckMhFiles);
+      end
+      NumberOfMhFilesPerBlock
+      return
+    end    
+    isux = 0; 
+    if nblck == 1
+      hh   = waitbar(0,'Please wait... Metropolis-Hastings...');
+      set(hh,'Name','Metropolis-Hastings')
+      if nruns <= MAX_nruns
+	x2 = zeros(nruns,npar); 
+	x2(1,:) = ix2(1,:);
+	logpo2 = zeros(nruns,1);    
+	logpo2(1) = ilogpo2;    
+      else
+	x2 = zeros(MAX_nruns,npar);
+	x2(1,:) = ix2(1,:);
+	logpo2 = zeros(MAX_nruns,1);
+	logpo2(1) = ilogpo2;
+      end
+      irun = ~options_.load_mh_file;    %%%% irun=0 <-- previous files are loaded
+      rruns = nruns-irun;
+      j=1;
+      while j<=rruns
+	irun = irun + 1;
+	if irun <= MAX_nruns
+	  par = randn(1,npar)*d;
+	  par = par.*bayestopt_.jscale' + ix2;  
+	  if all(transpose(par) > mh_bounds(:,1)) & all(transpose(par) < mh_bounds(:,2))
+	    if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+	      logpost = -DsgeLikelihood(transpose(par),gend,data);
+	    else
+	      logpost = -DsgeVarLikelihood(transpose(par),gend);
+	    end
+	  else
+	    logpost = -inf;
+	  end    
+	  if logpost > -inf & log(rand) < logpost - ilogpo2
+	    x2(irun,:) = par; 
+	    ix2 = par;
+	    logpo2(irun) = logpost; 
+	    ilogpo2 = logpost;
+	    isux = isux + 1;
+	  else    
+	    x2(irun,:) = ix2;
+	    logpo2(irun) = ilogpo2;
+	  end   
+	  prtfrc = j/nruns;
+	  waitbar(prtfrc,hh,sprintf('%f done, acceptation rate %f',prtfrc,isux/j));
+	else
+	  post2 = exp(logpo2);
+	  save([fname_ '_mh' int2str(lfile+1)],'x2','logpo2','post2');
+	  clear x2 logpo2 post2;
+	  x2 = zeros(MAX_nruns,npar);
+	  logpo2 = zeros(MAX_nruns,1);
+	  lfile = lfile + 1;
+	  irun = 0;
+	  j = j - 1;
+	end
+	j = j + 1;
+      end
+      if nruns <= MAX_nruns
+	post2 = exp(logpo2);
+	save([fname_ '_mh' int2str(lfile+1)],'x2','logpo2','post2');
+	clear post2 x2 logpo2;
+      elseif irun <= MAX_nruns    
+	x2 = x2(1:irun,:);
+	logpo2 = logpo2(1:irun,1); 
+	post2 = exp(logpo2);
+	save([fname_ '_mh' int2str(lfile+1)],'x2','logpo2','post2');
+	clear post2 x2 logpo2;
+      end
+      close(hh)
+      disp(sprintf('Acceptation rate : %f',isux/nruns))
+    else
+      disp('Acceptation rates :')
+      for b=1:nblck
+	hh   = waitbar(0,'Please wait... Metropolis-Hastings...');
+	set(hh,'Name',['Metropolis-Hastings, Block ',int2str(b)]);
+	if nruns <= MAX_nruns
+	  x2 = zeros(nruns,npar);   
+	  x2(1,:) = ix2(1,:,b);
+	  logpo2 = zeros(nruns,1);  
+	  logpo2(1) = ilogpo2(1,b); 
+	else
+	  x2 = zeros(MAX_nruns,npar);
+	  x2(1,:) = ix2(1,:,b);
+	  logpo2 = zeros(MAX_nruns,1);
+	  logpo2(1) = ilogpo2(1,b);
+	end 
+	irun  = ~options_.load_mh_file; % Previous files are loaded <-- irun=0
+	rruns = nruns-irun;
+	isav = 0;
+	isux = 0;
+	j = 1;
+	while j <= rruns
+	  irun = irun + 1;
+	  if irun <= MAX_nruns
+	    par = randn(1,npar)*d;
+	    par = par.*transpose(bayestopt_.jscale) + ix2(1,:,b);  
+	    if all(transpose(par) > mh_bounds(:,1)) & all(transpose(par) < mh_bounds(:,2))
+	      if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+		logpost = -DsgeLikelihood(transpose(par),gend,data);
+	      else
+		logpost = -DsgeVarLikelihood(transpose(par),gend);
+	      end
+	    else
+	      logpost = -inf;
+	    end    
+	    if logpost > -inf & log(rand) < logpost - ilogpo2(1,b)
+	      x2(irun,:) = par; 
+	      ix2(1,:,b) = par;
+	      logpo2(irun) = logpost; 
+	      ilogpo2(1,b) = logpost;
+	      isux = isux + 1;
+	    else    
+	      x2(irun,:) = ix2(1,:,b);
+	      logpo2(irun) = ilogpo2(1,b);
+	    end 
+	    prtfrc = j/nruns;
+	    waitbar(prtfrc,hh,sprintf('%f done, acceptation rate %f',prtfrc,isux/j));
+	  else
+	    post2 = exp(logpo2);
+	    save([fname_ '_mh' int2str(lfile+1+isav) '_blck' int2str(b)],'x2','logpo2','post2');
+	    clear post2;
+	    x2 = zeros(MAX_nruns,npar);
+	    logpo2 = zeros(MAX_nruns,1);
+	    isav = isav + 1;
+	    irun = 0;
+	    j=j-1;
+	  end
+	  j = j+1; 
+	end
+	if nruns <= MAX_nruns
+	  post2 = exp(logpo2);
+	  save([fname_ '_mh' int2str(lfile+isav+1) '_blck' int2str(b)],'x2','logpo2','post2');
+	  clear post2 x2 logpo2;
+	elseif irun <= MAX_nruns    
+	  x2 = x2(1:irun,:);
+	  logpo2 = logpo2(1:irun,1); 
+	  post2 = exp(logpo2);
+	  save([fname_ '_mh' int2str(lfile+isav+1) '_blck' int2str(b)],'x2','logpo2','post2');
+	  clear post2 x2 logpo2;
+	end
+	disp(sprintf('Block %d: %f',b,isux/nruns))
+	close(hh)
+      end
+    end
+    disp(' ')
+    disp(['MH: Total number of iterations       : ' int2str(nops+nruns) '.'])
+  end %end if nruns
+  if nblck == 1
+    files = eval(['dir(''' fname_ '_mh*.mat'');']);
+    nfile = length(files)-2;
+    number_of_simulations_per_file = zeros(nfile+1,1);
+    instr = [fname_ '_mh' int2str(0)];
+    eval(['load ' instr]);
+    clear x2 post2;
+    number_of_simulations_per_file(1) = length(logpo2);
+    if nfile >= 1
+      for file = 1:nfile
+	instr = [fname_ '_mh' int2str(file)];
+	eval(['load ' instr]);
+	clear post2 x2;
+	number_of_simulations_per_file(file+1) = length(logpo2);
+      end
+    end
+    clear logpo2;
+    if ~nruns
+      tmp  = cumsum(number_of_simulations_per_file);
+      nops = tmp(nfile+1); clear tmp;
+    end
+  else
+    files = eval(['dir(''' fname_ '_mh*_blck1.mat'');']);   
+    nfile = length(files)-1;
+    number_of_simulations_per_file = zeros(nfile+1,1);
+    instr = [fname_ '_mh' int2str(0) '_blck' int2str(1)];
+    eval(['load ' instr]);
+    clear x2 post2;
+    number_of_simulations_per_file(1) = length(logpo2);
+    if nfile >= 1
+      for file = 1:nfile
+	instr = [fname_ '_mh' int2str(file) '_blck1'];
+	eval(['load ' instr]);
+	clear post2 x2;
+	number_of_simulations_per_file(file+1) = length(logpo2);
+      end
+    end
+    clear logpo2;
+    if ~nruns
+      tmp  = cumsum(number_of_simulations_per_file);
+      nops = tmp(nfile+1); clear tmp;
+      bfiles = eval(['dir(''' fname_ '_mh0_blck*.mat'');']);
+      past_number_of_blocks = length(bfiles);
+      if past_number_of_blocks ~= nblck
+	nblck = past_number_of_blocks;
+	options_.mh_nblck = nblck;
+      end
+    end
+  end
+  cumulated_number_of_simulations_per_file = cumsum(number_of_simulations_per_file);
+  disp(['MH: Number of mh files             : ' int2str(nfile+1) ' per block.'])
+  disp(['MH: Total number of generated files    : ' int2str((nfile+1)*nblck) '.'])
+  disp(['MH: Total number of iterations         : ' int2str(nops+nruns) '.'])
+  disp('MH: Number of simulations per file: ')
+  for i=0:nfile
+    disp(sprintf('    The number of simulations in file %d is: %d.',i,number_of_simulations_per_file(i+1)))
+  end
+  disp(' ')
+  nsim = nops+nruns;
+  %
+  %%
+  %%%
+  %%%%
+  %%%%% MCMC convergence diagnostics
+  %%%%
+  %%%
+  %%
+  %
+  origin = 1000;
+  if ~options_.nodiagnostic & nblck > 1 & nsim > origin
+    %%
+    %%  Univariate diagnostic : Brooks and Gelman (1998).
+    %%
+    step_size   = ceil((nsim-origin)/100);  % So that the computational time does not 
+    ALPHA       = 0.2;                      % increase too much with the number of simulations. 
+    time = 1:nsim;
+    xx = origin:step_size:nsim;
+    number_of_lines = length(xx);
+    tmp = zeros(nsim*nblck,3);
+    UDIAG = zeros(number_of_lines,6,npar);
+    if nsim < origin
+      error('MH: The number of simulations is to small to compute the MCMC convergence diagnostics.')
+    end
+    if TeX
+      fidTeX = fopen([fname_ '_UnivariateDiagnostics.TeX'],'w');
+      fprintf(fidTeX,'%% TeX eps-loader file generated by metropolis.m (Dynare).\n');
+      fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
+      fprintf(fidTeX,' \n');
+    end
+    disp('MH: Univariate convergence diagnostic, Brooks and Gelman (1998):')
+    for j=1:npar
+      fprintf('    Parameter %d...  ',j);
+      for b = 1:nblck
+    startline = 0;
+    for n = 0:nfile
+      instr = [fname_ '_mh' int2str(n) '_blck' int2str(b)];
+      eval(['load ' instr]);
+      clear logpo2 post2;
+      tmp((b-1)*nsim+startline+1:(b-1)*nsim+cumulated_number_of_simulations_per_file(n+1),1) = x2(:,j);
+      clear x2;
+      startline = startline+number_of_simulations_per_file(n+1);
+    end 
+      end
+      tmp(:,2) = kron(transpose(1:nblck),ones(nsim,1));
+      tmp(:,3) = kron(ones(nblck,1),transpose(time)); 
+      tmp = sortrows(tmp,1);
+      ligne   = 0;
+      for iter  = origin:step_size:nsim
+    ligne = ligne+1;
+    linea = ceil(0.5*iter);
+    n     = iter-linea+1;
+    cinf  = round(n*ALPHA/2);
+    csup  = round(n*(1-ALPHA/2));
+    CINF  = round(nblck*n*ALPHA/2);
+    CSUP  = round(nblck*n*(1-ALPHA/2));
+    temp  = tmp(find((tmp(:,3)>=linea) & (tmp(:,3)<=iter)),1:2);
+    UDIAG(ligne,1,j) = temp(CSUP,1)-temp(CINF,1);
+    moyenne = mean(temp(:,1));%% Pooled mean.
+    UDIAG(ligne,3,j) = sum((temp(:,1)-moyenne).^2)/(nblck*n-1);
+    UDIAG(ligne,5,j) = sum(abs(temp(:,1)-moyenne).^3)/(nblck*n-1);
+    for i=1:nblck
+      pmet = temp(find(temp(:,2)==i));
+      UDIAG(ligne,2,j) = UDIAG(ligne,2,j) + pmet(csup,1)-pmet(cinf,1);
+      moyenne = mean(pmet,1); %% Within mean. 
+      UDIAG(ligne,4,j) = UDIAG(ligne,4,j) + sum((pmet(:,1)-moyenne).^2)/(n-1);
+      UDIAG(ligne,6,j) = UDIAG(ligne,6,j) + sum(abs(pmet(:,1)-moyenne).^3)/(n-1);
+    end
+      end
+      fprintf('Done! \n');
+    end
+    UDIAG(:,[2 4 6],:) = UDIAG(:,[2 4 6],:)/nblck;
+    disp(' ')
+    clear pmet temp moyenne CSUP CINF csup cinf n linea iter tmp;    
+    pages = floor(npar/3);
+    k = 0;  
+    for i = 1:pages
+      h = figure('Name','MCMC univariate diagnostic (Brooks and Gelman,1998)');
+      boxplot = 1;
+      if TeX
+    NAMES = [];
+    TEXNAMES = [];
+      end
+      for j = 1:3 % Loop over parameters
+    k = k+1;
+    [nam,namtex] = get_the_name(k,TeX);
+    for crit = 1:3% Loop over criteria
+      if crit == 1
+        plt1 = UDIAG(:,1,k);
+        plt2 = UDIAG(:,2,k);
+        namnam  = [nam , ' (Interval)']; 
+      elseif crit == 2
+        plt1 = UDIAG(:,3,k);
+        plt2 = UDIAG(:,4,k);
+        namnam  = [nam , ' (m2)'];
+      elseif crit == 3    
+        plt1 = UDIAG(:,5,k);
+        plt2 = UDIAG(:,6,k);
+        namnam  = [nam , ' (m3)'];
+      end
+      if TeX
+        NAMES = strvcat(NAMES,deblank(namnam));
+        TEXNAMES = strvcat(TEXNAMES,deblank(namtex));
+      end
+      subplot(3,3,boxplot);
+      plot(xx,plt1,'-b');     % Pooled
+      hold on;
+      plot(xx,plt2,'-r');     % Within (mean)
+      hold off;
+      xlim([xx(1) xx(number_of_lines)])
+      title(namnam,'Interpreter','none')
+      boxplot = boxplot + 1;
+    end
+      end
+      eval(['print -depsc2 ' fname_ '_udiag' int2str(i)]);
+      eval(['print -dpdf ' fname_ '_udiag' int2str(i)]);
+      saveas(h,[fname_ '_udiag' int2str(i) '.fig']);
+      if options_.nograph, close(h), end
+      if TeX
+    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    
+    fprintf(fidTeX,'\\centering \n');
+    fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_udiag%s}\n',fname_,int2str(i));
+    fprintf(fidTeX,'\\caption{Univariate convergence diagnostics for the Metropolis-Hastings.\n');
+    fprintf(fidTeX,'The first, second and third columns are respectively the criteria based on\n');
+    fprintf(fidTeX,'the eighty percent interval, the second and third moments.}');
+    fprintf(fidTeX,'\\label{Fig:UnivariateDiagnostics:%s}\n',int2str(i));
+    fprintf(fidTeX,'\\end{figure}\n');
+    fprintf(fidTeX,'\n');
+      end
+    end
+    reste = npar-k;
+    if reste
+      if reste == 1
+    nr = 3;
+    nc = 1;
+      elseif reste == 2;
+    nr = 2;
+    nc = 3;
+      end
+      if TeX
+    NAMES = [];
+    TEXNAMES = [];
+      end
+      h = figure('Name','MCMC univariate diagnostic (Brooks and Gelman, 1998)');
+      boxplot = 1;
+      for j = 1:reste
+    k = k+1;
+    [nam,namtex] = get_the_name(k,TeX);
+    for crit = 1:3
+      if crit == 1
+        plt1 = UDIAG(:,1,k);
+        plt2 = UDIAG(:,2,k);
+        namnam  = [nam , ' (Interval)']; 
+      elseif crit == 2
+        plt1 = UDIAG(:,3,k);
+        plt2 = UDIAG(:,4,k);
+        namnam  = [nam , ' (m2)'];
+      elseif crit == 3    
+        plt1 = UDIAG(:,5,k);
+        plt2 = UDIAG(:,6,k);
+        namnam  = [nam , ' (m3)'];
+      end
+      if TeX
+        NAMES = strvcat(NAMES,deblank(namnam));
+        TEXNAMES = strvcat(TEXNAMES,deblank(namtex));
+      end
+      subplot(nr,nc,boxplot);
+      plot(xx,plt1,'-b');                   % Pooled
+      hold on;
+      plot(xx,plt2,'-r');                   % Within (mean)
+      hold off;
+      xlim([xx(1) xx(number_of_lines)]);
+      title(namnam,'Interpreter','none');
+      boxplot = boxplot + 1;
+    end
+      end
+      eval(['print -depsc2 ' fname_ '_udiag' int2str(pages+1)]);
+      eval(['print -dpdf ' fname_ '_udiag' int2str(pages+1)]);
+      saveas(h,[fname_ '_udiag' int2str(pages+1) '.fig']);
+      if options_.nograph, close(h), end
+      if TeX
+    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    
+    fprintf(fidTeX,'\\centering \n');
+    fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_udiag%s}\n',fname_,int2str(pages+1));
+    if reste == 2
+      fprintf(fidTeX,'\\caption{Univariate convergence diagnostics for the Metropolis-Hastings.\n');
+      fprintf(fidTeX,'The first, second and third columns are respectively the criteria based on\n');
+      fprintf(fidTeX,'the eighty percent interval, the second and third moments.}');
+    elseif reste == 1
+      fprintf(fidTeX,'\\caption{Univariate convergence diagnostics for the Metropolis-Hastings.\n');
+      fprintf(fidTeX,'The first, second and third rows are respectively the criteria based on\n');
+      fprintf(fidTeX,'the eighty percent interval, the second and third moments.}');
+    end
+    fprintf(fidTeX,'\\label{Fig:UnivariateDiagnostics:%s}\n',int2str(pages+1));
+    fprintf(fidTeX,'\\end{figure}\n');
+    fprintf(fidTeX,'\n');
+    fprintf(fidTeX,'% End Of TeX file.');
+    fclose(fidTeX);
+      end
+    end % if reste > 0
+    clear UDIAG;
+    %%
+    %% Multivariate diagnostic.
+    %%
+    if TeX
+      fidTeX = fopen([fname_ '_MultivariateDiagnostics.TeX'],'w');
+      fprintf(fidTeX,'%% TeX eps-loader file generated by metropolis.m (Dynare).\n');
+      fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
+      fprintf(fidTeX,' \n');
+      NAMES = [];
+    end
+    tmp = zeros(nsim*nblck,3);
+    MDIAG = zeros(number_of_lines,6);
+    for b = 1:nblck
+      startline = 0;
+      for n = 0:nfile
+    instr = [fname_ '_mh' int2str(n) '_blck' int2str(b)];
+    eval(['load ' instr]);
+    clear x2 post2;
+    tmp((b-1)*nsim+startline+1:(b-1)*nsim+cumulated_number_of_simulations_per_file(n+1),1) = logpo2;
+    startline = startline+number_of_simulations_per_file(n+1);
+      end   
+    end
+    clear logpo2;
+    tmp(:,2) = kron(transpose(1:nblck),ones(nsim,1));
+    tmp(:,3) = kron(ones(nblck,1),transpose(time)); 
+    tmp = sortrows(tmp,1);
+    ligne   = 0;
+    for iter  = origin:step_size:nsim
+      ligne = ligne+1;
+      linea = ceil(0.5*iter);
+      n     = iter-linea+1;
+      cinf  = round(n*ALPHA/2);
+      csup  = round(n*(1-ALPHA/2));
+      CINF  = round(nblck*n*ALPHA/2);
+      CSUP  = round(nblck*n*(1-ALPHA/2));
+      temp  = tmp(find((tmp(:,3)>=linea) & (tmp(:,3)<=iter)),1:2);
+      MDIAG(ligne,1) = temp(CSUP,1)-temp(CINF,1);
+      moyenne = mean(temp(:,1));%% Pooled mean.
+      MDIAG(ligne,3) = sum((temp(:,1)-moyenne).^2)/(nblck*n-1);
+      MDIAG(ligne,5) = sum(abs(temp(:,1)-moyenne).^3)/(nblck*n-1);
+      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. 
+	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;  
+    h = figure('Name','Multivatiate diagnostic');
+    boxplot = 1;
+    for crit = 1:3
+      if crit == 1
+	plt1 = MDIAG(:,1);
+	plt2 = MDIAG(:,2);
+	namnam  = 'Interval'; 
+      elseif crit == 2
+	plt1 = MDIAG(:,3);
+	plt2 = MDIAG(:,4);
+	namnam  = 'm2';
+      elseif crit == 3    
+	plt1 = MDIAG(:,5);
+	plt2 = MDIAG(:,6);
+	namnam  = 'm3';
+      end
+      if TeX
+	NAMES = strvcat(NAMES,namnam);
+      end
+      subplot(3,1,boxplot);
+      plot(xx,plt1,'-b');  % Pooled
+      hold on
+      plot(xx,plt2,'-r');  % Within (mean)
+      hold off
+      xlim([xx(1) xx(number_of_lines)])
+      title(namnam,'Interpreter','none');
+      boxplot = boxplot + 1;
+    end
+    eval(['print -depsc2 ' fname_ '_mdiag']);
+    eval(['print -dpdf ' fname_ '_mdiag']);
+    saveas(h,[fname_ '_mdiag.fig']);
+    if options_.nograph, close(h), end
+    if TeX
+      fprintf(fidTeX,'\\begin{figure}[H]\n');
+      for jj = 1:3
+	fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),' ');
+      end    
+      fprintf(fidTeX,'\\centering \n');
+      fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_mdiag}\n',fname_);
+      fprintf(fidTeX,'\\caption{Multivariate convergence diagnostics for the Metropolis-Hastings.\n');
+      fprintf(fidTeX,'The first, second and third rows are respectively the criteria based on\n');
+      fprintf(fidTeX,'the eighty percent interval, the second and third moments. The different \n');
+      fprintf(fidTeX,'parameters are aggregated using the posterior kernel.}');
+      fprintf(fidTeX,'\\label{Fig:MultivariateDiagnostics}\n');
+      fprintf(fidTeX,'\\end{figure}\n');
+      fprintf(fidTeX,'\n');
+      fprintf(fidTeX,'% End Of TeX file.');
+      fclose(fidTeX);
+    end
+  end % End of if ~options_.nodiagnostic
+  %%
+  %% Now i discard some simulations...
+  %%
+  trun = cumulated_number_of_simulations_per_file(nfile+1);
+  irun = floor(options_.mh_drop*trun)+1;
+  ffil = 0;       % The first MH file we have to read...
+  ifil = irun;    % and the first line we have to read in this file.
+  for ffil = 0:nfile
+    if irun <= cumulated_number_of_simulations_per_file(ffil+1)
+      break
+    end
+    ifil = ifil-number_of_simulations_per_file(ffil+1);
+  end
+  trun = trun-irun+1;
+  fprintf('MH: I''ll use mh-files %d to %d.\n',ffil,nfile);
+  fprintf('MH: In mh-file number %d i''ll start at line %d.\n',ffil,ifil);
+  fprintf('MH: Finally the total number of simulations is %d.\n',trun);
+  disp(' ');
+  %
+  %%
+  %%%
+  %%%%
+  %%%%% Modified harmonic mean
+  %%%%
+  %%%
+  %%
+  %
+  fprintf('MH: I''m computing the posterior mean... ');
+  MU = zeros(1,npar);
+  lpost_mode = -Inf;
+  for  b = 1:nblck
+    if nblck > 1
+      instr = [fname_ '_mh' int2str(ffil) '_blck' int2str(b)];
+    else
+      instr = [fname_ '_mh' int2str(ffil)];
+    end
+    eval(['load ' instr]); clear post2;
+    MU(1,:) = MU(1,:) + sum(x2(ifil:end,:),1);
+    lpost_mode = max(lpost_mode,max(logpo2(ifil:end,1)));
+  end
+  for n = ffil+1:nfile
+    for b = 1:nblck
+      if nblck > 1
+	instr = [fname_ '_mh' int2str(n) '_blck' int2str(b)];
+      else
+	instr = [fname_ '_mh' int2str(n)];
+      end
+      eval(['load ' instr]);
+      clear post2;
+      MU(1,:) = MU(1,:) + sum(x2,1);
+      lpost_mode = max(lpost_mode,max(logpo2));
+    end
+  end
+  clear x2 logpo2;
+  MU = MU/(trun*nblck);
+  fprintf(' Done!\n');
+  fprintf('MH: I''m computing the posterior covariance matrix... ');
+  SIGMA = zeros(npar,npar);
+  for b = 1:nblck
+    if nblck > 1
+      instr = [fname_ '_mh' int2str(ffil) '_blck' int2str(b)];
+    else
+      instr = [fname_ '_mh' int2str(ffil)];
+    end  
+    eval(['load ' instr]);
+    clear post2 logpo2;
+    SIGMA = SIGMA + transpose(x2(ifil:end,:)-ones(size(x2(ifil:end,:),1),1)*MU)*...
+	    (x2(ifil:end,:)-ones(size(x2(ifil:end,:),1),1)*MU);
+  end               
+  for n = ffil+1:nfile
+    for b = 1:nblck
+      if nblck > 1
+	instr = [fname_ '_mh' int2str(n) '_blck' int2str(b)];
+      else
+	instr = [fname_ '_mh' int2str(n)];
+      end
+      eval(['load ' instr]);
+      clear post2 logpo2;
+      SIGMA = SIGMA + transpose(x2-ones(size(x2,1),1)*MU)*(x2-ones(size(x2,1),1)*MU);
+    end             
+  end
+  clear x2;
+  SIGMA =  SIGMA/(trun*nblck);%<=== Variance of the parameters (ok!)
+  fprintf(' Done!\n');
+  disp(' ');
+  disp('MH: I''m computing the posterior log marginale density (modified harmonic mean)... ');
+  detSIGMA = det(SIGMA);
+  invSIGMA = inv(SIGMA);
+  marginal = zeros(9,2);
+  linee = 0;
+  check_coverage  = 1;
+  increase        = 1;
+  while check_coverage
+    for p = 0.1:0.1:0.9;
+      critval = qchisq(p,npar);
+      tmp = 0;
+      for k = ffil:nfile
+    inst = [fname_ '_mh' int2str(k)];
+    if k == ffil
+      i1 = ifil;
+    else
+      i1 = 1;
+    end
+    EndOfFile = number_of_simulations_per_file(k+1);
+    for b=1:nblck
+      if nblck > 1
+        instr = [inst '_blck' int2str(b)];
+      else
+        instr = inst;
+      end  
+      load(instr,'x2','logpo2');
+      for i = i1:EndOfFile
+        deviation  = (x2(i,:)-MU)*invSIGMA*(x2(i,:)-MU)';
+        if deviation <= critval
+          lftheta = -log(p)-(npar*log(2*pi)+log(detSIGMA)+deviation)/2;
+          tmp = tmp + exp(lftheta - logpo2(i)+lpost_mode);
+        end
+      end
+    end 
+      end
+      clear x2 logpo2;
+      linee = linee + 1;    
+      marginal(linee,:) = [p,lpost_mode-log(tmp/(trun*nblck))];
+    end
+    if abs((marginal(9,2)-marginal(1,2))/marginal(9,2)) > 0.01 | isinf(marginal(1,2))
+      if increase == 1
+	disp('MH: The support of the weighting density function is not large enough...')
+	disp('MH: I increase the variance of this distribution.')
+	increase = 1.2*increase;
+	invSIGMA = inv(SIGMA*increase);
+	detSIGMA = det(SIGMA*increase);
+	linee    = 0;   
+      else
+	disp('MH: Let me try again.')
+	increase = 1.2*increase;
+	invSIGMA = inv(SIGMA*increase);
+	detSIGMA = det(SIGMA*increase);
+	linee    = 0;
+	if increase > 20
+	  check_coverage = 0;
+	  clear invSIGMA detSIGMA increase;
+	  disp('MH: There''s probably a problem with the modified harmonic mean estimator.')    
+	end    
+      end    
+    else
+      check_coverage = 0;
+      clear invSIGMA detSIGMA increase;
+      disp('MH: Modified harmonic mean estimator, done!')
+    end
+  end
+  %
+  %%
+  %%%
+  %%%%
+  %%%%% Highest Probability Intervals (coverage is given by options_.mh_conf_sig)
+  %%%%
+  %%%
+  %%
+  %
+  disp(' ')
+  fprintf('MH: I''m computing the Highest Probability Intervals... ');
+  post_mean = transpose(MU);
+  n = trun*nblck;
+  n1    = round((1-options_.mh_conf_sig)*n);
+  k = zeros(n1,1);
+  tmp = zeros(n,1);
+  if nblck == 1
+    for i = 1:npar
+      EndOfFile = number_of_simulations_per_file(ffil+1)-ifil+1;
+      instr = [fname_ '_mh' int2str(ffil)];
+      eval(['load ' instr]);
+      clear post2 logpo2;
+      tmp(1:EndOfFile) = x2(ifil:end,i);
+      OldEndOfFile = EndOfFile;
+      for f = ffil+1:nfile
+	NewEndOfFile = number_of_simulations_per_file(f+1);
+	instr = [fname_ '_mh' int2str(f)];
+	eval(['load ' instr]);
+	clear post2 logpo2;
+	tmp(OldEndOfFile+1:OldEndOfFile+NewEndOfFile) = x2(:,i);
+	OldEndOfFile = OldEndOfFile + NewEndOfFile;
+      end
+      clear x2;
+      tmp = sort(tmp);
+      j2 = n-n1;
+      for j1 = 1:n1
+	k(j1) = tmp(j2)-tmp(j1);
+	j2 = j2 + 1;
+      end
+      [kmin,k1] = min(k);
+      min_interval(i,:) = [tmp(k1) tmp(k1)+kmin];
+    end
+    clear tmp;
+  else
+    for i = 1:npar
+      EndOfFile = number_of_simulations_per_file(ffil+1)-ifil+1;
+      NewStartLine = 0;
+      inst = [fname_ '_mh' int2str(ffil)];
+      for b = 1:nblck
+	instr = [inst '_blck' int2str(b)];
+	eval(['load ' instr]);
+	clear post2 logpo2;
+	tmp(NewStartLine+1:NewStartLine+EndOfFile,1) = x2(ifil:end,i);
+	NewStartLine = NewStartLine + EndOfFile;
+      end
+      for f = ffil+1:nfile
+	EndOfFile = number_of_simulations_per_file(f+1);
+	inst = [fname_ '_mh' int2str(f)];
+	for B = 1:nblck
+	  instr = [inst '_blck' int2str(b)];
+	  eval(['load ' instr]);
+	  clear post2 logpo2;
+	  tmp(NewStartLine+1:NewStartLine+EndOfFile,1) = x2(:,i);
+	  NewStartLine = NewStartLine + EndOfFile;
+	end
+      end
+      clear x2;
+      tmp = sort(tmp);
+      j2 = n-n1;
+      for j1 = 1:n1
+	k(j1) = tmp(j2)-tmp(j1);
+	j2 = j2 + 1;
+      end
+      [kmin,k1] = min(k);
+      min_interval(i,:) = [tmp(k1) tmp(k1)+kmin];
+    end
+    clear tmp;
+  end
+  fprintf(' Done!\n');
+  %
+  %%
+  %%%
+  %%%%
+  %%%%% Print results
+  %%%%
+  %%%
+  %%
+  %%
+  %% [1] On screen
+  %%
+  disp(' ');
+  disp(' ')
+  marginal
+  disp(' ')
+  disp(' ')
+  disp('ESTIMATION RESULTS')
+  disp(' ')
+  disp(sprintf('Log data density is %f.',mean(marginal(:,2))))
+  oo_.MarginalDensity.ModifiedHarmonicMean = mean(marginal(:,2));
+  pnames=['     ';'beta ';'gamm ';'norm ';'invg ';'unif ';'invg2'];
+  tit2 = sprintf('%10s %7s %10s %14s %4s %6s\n',' ','prior mean', ...
+         'post. mean','conf. interval','prior','pstdev');
+  ip = nvx+nvn+ncx+ncn+1;
+  if np
+    disp(' ')
+    disp('parameters')
+    disp(tit2)
+    for i=1:np
+      disp(sprintf('%12s %7.3f %8.4f %7.4f %7.4f %4s %6.4f', ...
+           deblank(estim_params_.param_names(i,:)), ...
+           bayestopt_.pmean(ip),post_mean(ip),min_interval(ip,:), ...
+           pnames(bayestopt_.pshape(ip)+1,:), ...
+           bayestopt_.pstdev(ip)));
+      eval(['oo_.posterior_mean.parameters.' deblank(estim_params_.param_names(i,:)) ' = post_mean(ip);']);
+      eval(['oo_.posterior_hpdinf.parameters.' deblank(estim_params_.param_names(i,:)) ' = min_interval(ip,1);']); 
+      eval(['oo_.posterior_hpdsup.parameters.' deblank(estim_params_.param_names(i,:)) ' = min_interval(ip,2);']);
+      ip = ip+1;
+    end
+  end
+  if nvx
+    ip = 1;
+    disp(' ')
+    disp('standard deviation of shocks')
+    disp(tit2)
+    for i=1:nvx
+      k = estim_params_.var_exo(i,1);
+      disp(sprintf('%12s %7.3f %8.4f %7.4f %7.4f %4s %6.4f', ...
+           deblank(lgx_(k,:)),bayestopt_.pmean(ip),post_mean(ip), ...
+           min_interval(ip,:),pnames(bayestopt_.pshape(ip)+1,:), ...
+           bayestopt_.pstdev(ip))); 
+      Sigma_e_(k,k) = post_mean(ip)*post_mean(ip);
+      eval(['oo_.posterior_mean.shocks_std.' deblank(lgx_(k,:)) ' = post_mean(ip);']);
+      eval(['oo_.posterior_hpdinf.shocks_std.' deblank(lgx_(k,:)) ' = min_interval(ip,1);']); 
+      eval(['oo_.posterior_hpdsup.shocks_std.' deblank(lgx_(k,:)) ' = min_interval(ip,2);']);
+      ip = ip+1;
+    end
+  end
+  if nvn
+    disp(' ')
+    disp('standard deviation of measurement errors')
+    disp(tit2)
+    ip = nvx+1;
+    for i=1:nvn
+      disp(sprintf('%12s %7.3f %8.4f %7.4f %7.4f %4s %6.4f', ...
+           deblank(options_.varobs(estim_params_.var_endo(i,1),:)),...
+           bayestopt_.pmean(ip), ...
+           post_mean(ip),min_interval(ip,:), ...
+           pnames(bayestopt_.pshape(ip)+1,:), ...
+           bayestopt_.pstdev(ip)));
+      eval(['oo_.posterior_mean.measurement_errors_std.' deblank(options_.varobs(estim_params_.var_endo(i,1),:)) ' = post_mean(ip);']);
+      eval(['oo_.posterior_hpdinf.measurement_errors_std.' deblank(options_.varobs(estim_params_.var_endo(i,1),:)) ' = min_interval(ip,1);']); 
+      eval(['oo_.posterior_hpdsup.measurement_errors_std.' deblank(options_.varobs(estim_params_.var_endo(i,1),:)) ' = min_interval(ip,2);']);            
+      ip = ip+1;
+    end
+  end
+  if ncx
+    disp(' ')
+    disp('correlation of shocks')
+    disp(tit2)
+    ip = nvx+nvn+1;
+    for i=1:ncx
+      k1 = estim_params_.corrx(i,1);
+      k2 = estim_params_.corrx(i,2);
+      name = [deblank(lgx_(k1,:)) ',' deblank(lgx_(k2,:))];
+      disp(sprintf('%12s %7.3f %8.4f %7.4f %7.4f %4s %6.4f', name, ...
+           bayestopt_.pmean(ip),post_mean(ip),min_interval(ip,:), ...
+           pnames(bayestopt_.pshape(ip)+1,:), ...
+           bayestopt_.pstdev(ip)));
+      eval(['oo_.posterior_mean.shocks_corr.' deblank(lgx_(k1,:)) '_' deblank(lgx_(k2,:)) ' = post_mean(ip);']);
+      eval(['oo_.posterior_hpdinf.shocks_corr.' deblank(lgx_(k1,:)) '_' deblank(lgx_(k2,:)) ' = min_interval(ip,1);']); 
+      eval(['oo_.posterior_hpdsup.shocks_corr.' deblank(lgx_(k1,:)) '_' deblank(lgx_(k2,:)) ' = min_interval(ip,2);']);      
+      Sigma_e_(k1,k2) = post_mean(ip)*sqrt(Sigma_e_(k1,k1)*Sigma_e_(k2,k2));
+      Sigma_e_(k2,k1) = Sigma_e_(k1,k2);
+      ip = ip+1;
+    end
+  end
+  if ncn
+    disp(' ')
+    disp('correlation of measurement errors')
+    disp(tit2)
+    ip = nvx+nvn+ncx+1;
+    for i=1:ncn
+      k1 = estim_params_.corrn(i,1);
+      k2 = estim_params_.corrn(i,2);
+      name = [deblank(lgy_(k1,:)) ',' deblank(lgy_(k2,:))];
+      disp(sprintf('%12s %7.3f %8.4f %7.4f %7.4f %4s %6.4f', name, ...
+           bayestopt_.pmean(ip),post_mean(ip),min_interval(ip,:), ...
+           pnames(bayestopt_.pshape(ip)+1,:), ...
+           bayestopt_.pstdev(ip))); 
+      eval(['oo_.posterior_mean.measurement_errors_corr.' deblank(lgy_(k1,:)) '_' deblank(lgy_(k2,:)) ' = post_mean(ip);']);
+      eval(['oo_.posterior_hpdinf.measurement_errors_corr.' deblank(lgy_(k1,:)) '_' deblank(lgy_(k2,:)) ' = min_interval(ip,1);']); 
+      eval(['oo_.posterior_hpdsup.measurement_errors_corr.' deblank(lgy_(k1,:)) '_' deblank(lgy_(k2,:)) ' = min_interval(ip,2);']);      
+      ip = ip+1;
+    end
+  end
+  %%
+  %% [1] In a TeX file
+  %%
+  if TeX 
+    if np
+      ip = nvx+nvn+ncx+ncn+1;
+      fidTeX = fopen([fname_ '_MH_Posterior_1.TeX'],'w');
+      fprintf(fidTeX,'%% TeX-table generated by metropolis.m (Dynare).\n');
+      fprintf(fidTeX,'%% RESULTS FROM METROPOLIS HASTINGS (parameters)\n');
+      fprintf(fidTeX,['%% ' datestr(now,0)]);
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,'{\\tiny \n');
+      fprintf(fidTeX,'\\begin{table}\n');
+      fprintf(fidTeX,'\\centering\n');
+      fprintf(fidTeX,'\\begin{tabular}{l|lccccc} \n');
+      fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+      fprintf(fidTeX,'  & Prior distribution & Prior mean  & Prior s.d. & Post. mean & HPD inf & HPD sup  \\\\ \n');
+      fprintf(fidTeX,'\\hline \\\\ \n');
+      for i=1:np
+	fprintf(fidTeX,' $%s$ & %s & %7.3f & %6.4f & %8.4f & %7.4f & %7.4f \\\\ \n',...
+		deblank(estim_params_.tex(i,:)), ...
+		deblank(pnames(bayestopt_.pshape(ip)+1,:)), ...
+		bayestopt_.pmean(ip), ...
+		bayestopt_.pstdev(ip), ...
+		post_mean(ip), ...
+		min_interval(ip,1), ...
+		min_interval(ip,2));
+	ip = ip+1;
+      end   
+      fprintf(fidTeX,'\\hline\\hline \n');
+      fprintf(fidTeX,'\\end{tabular}\n ');    
+      fprintf(fidTeX,'\\caption{Results from Metropolis Hastings (parameters)}\n ');
+      fprintf(fidTeX,'\\label{Table:MhPosterior:1}\n');
+      fprintf(fidTeX,'\\end{table}\n');
+      fprintf(fidTeX,'} \n');
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end
+    if nvx
+      ip = 1;
+      fidTeX = fopen([fname_ '_MH_Posterior_2.TeX'],'w');
+      fprintf(fidTeX,'%% TeX-table generated by metropolis.m (Dynare).\n');
+      fprintf(fidTeX,'%% RESULTS FROM METROPOLIS HASTINGS (standard deviation of structural shocks)\n');
+      fprintf(fidTeX,['%% ' datestr(now,0)]);
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,'{\\tiny \n');
+      fprintf(fidTeX,'\\begin{table}\n');
+      fprintf(fidTeX,'\\centering\n');
+      fprintf(fidTeX,'\\begin{tabular}{l|lccccc} \n');
+      fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+      fprintf(fidTeX,'  & Prior distribution & Prior mean  & Prior s.d. & Post. mean & HPD inf & HPD sup  \\\\ \n');
+      fprintf(fidTeX,'\\hline \\\\ \n');
+      for i=1:nvx
+	k = estim_params_.var_exo(i,1);
+	fprintf(fidTeX,' $%s$ & %s & %7.3f & %6.4f & %8.4f & %7.4f & %7.4f \\\\ \n',...
+		deblank(lgx_TeX_(k,:)),...
+		deblank(pnames(bayestopt_.pshape(ip)+1,:)), ...
+		bayestopt_.pmean(ip), ...
+		bayestopt_.pstdev(ip), ...
+		post_mean(ip), ...
+		min_interval(ip,1), ...
+		min_interval(ip,1));
+	ip = ip+1;
+      end
+      fprintf(fidTeX,'\\hline\\hline \n');
+      fprintf(fidTeX,'\\end{tabular}\n ');    
+      fprintf(fidTeX,'\\caption{Results from Metropolis Hastings (standard deviation of structural shocks)}\n ');
+      fprintf(fidTeX,'\\label{Table:MhPosterior:2}\n');
+      fprintf(fidTeX,'\\end{table}\n');
+      fprintf(fidTeX,'} \n');
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end
+    if nvn
+      ip = nvx+1;
+      fidTeX = fopen([fname_ '_MH_Posterior_3.TeX'],'w');
+      fprintf(fidTeX,'%% TeX-table generated by metropolis.m (Dynare).\n');
+      fprintf(fidTeX,'%% RESULTS FROM METROPOLIS HASTINGS (standard deviation of measurement errors)\n');
+      fprintf(fidTeX,['%% ' datestr(now,0)]);
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,'{\\tiny \n');
+      fprintf(fidTeX,'\\begin{table}\n');
+      fprintf(fidTeX,'\\centering\n');
+      fprintf(fidTeX,'\\begin{tabular}{l|lccccc} \n');
+      fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+      fprintf(fidTeX,'  & Prior distribution & Prior mean  & Prior s.d. & Post. mean & HPD inf & HPD sup  \\\\ \n');
+      fprintf(fidTeX,'\\hline \\\\ \n');
+      for i=1:nvn
+	fprintf(fidTeX,' $%s$ & %s & %7.3f & %6.4f & %8.4f & %7.4f & %7.4f \\\\ \n',...
+		deblank(options_.varobs_TeX(estim_params_.var_endo(i,1),:)), ...
+		deblank(pnames(bayestopt_.pshape(ip)+1,:)), ...
+		bayestopt_.pmean(ip), ...
+		bayestopt_.pstdev(ip), ...
+		post_mean(ip), ...
+		min_interval(ip,1), ...
+		min_interval(ip,2));
+	p = ip+1;
+      end
+      fprintf(fidTeX,'\\hline\\hline \n');
+      fprintf(fidTeX,'\\end{tabular}\n ');    
+      fprintf(fidTeX,'\\caption{Results from Metropolis Hastings (standard deviation of measurement errors)}\n ');
+      fprintf(fidTeX,'\\label{Table:MhPosterior:3}\n');
+      fprintf(fidTeX,'\\end{table}\n');
+      fprintf(fidTeX,'} \n');
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end
+    if ncx
+      ip = nvx+nvn+1;
+      fidTeX = fopen([fname_ '_MH_Posterior_4.TeX'],'w');
+      fprintf(fidTeX,'%% TeX-table generated by metropolis.m (Dynare).\n');
+      fprintf(fidTeX,'%% RESULTS FROM METROPOLIS HASTINGS (correlation of structural shocks)\n');
+      fprintf(fidTeX,['%% ' datestr(now,0)]);
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,'{\\tiny \n');
+      fprintf(fidTeX,'\\begin{table}\n');
+      fprintf(fidTeX,'\\centering\n');
+      fprintf(fidTeX,'\\begin{tabular}{l|lccccc} \n');
+      fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+      fprintf(fidTeX,'  & Prior distribution & Prior mean  & Prior s.d. & Post. mean & HPD inf & HPD sup  \\\\ \n');
+      fprintf(fidTeX,'\\hline \\\\ \n');
+      for i=1:ncx
+	k1 = estim_params_.corrx(i,1);
+	k2 = estim_params_.corrx(i,2);
+	name = [deblank(lgx_TeX_(k1,:)) ',' deblank(lgx_TeX_(k2,:))];
+	fprintf(fidTeX,' $%s$ & %s & %7.3f & %6.4f & %8.4f & %7.4f & %7.4f \\\\ \n',...
+		name, ...
+		deblank(pnames(bayestopt_.pshape(ip)+1,:)), ...
+		bayestopt_.pmean(ip), ...
+		bayestopt_.pstdev(ip), ...
+		post_mean(ip), ...
+		min_interval(ip,1), ...
+		min_interval(ip,2));
+	ip = ip+1;
+      end
+      fprintf(fidTeX,'\\hline\\hline \n');
+      fprintf(fidTeX,'\\end{tabular}\n ');    
+      fprintf(fidTeX,'\\caption{Results from Metropolis Hastings (correlation of structural shocks)}\n ');
+      fprintf(fidTeX,'\\label{Table:MhPosterior:4}\n');
+      fprintf(fidTeX,'\\end{table}\n');
+      fprintf(fidTeX,'} \n');
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end
+    if ncn
+      ip = nvx+nvn+ncx+1;
+      fidTeX = fopen([fname_ '_MH_Posterior_5.TeX'],'w');
+      fprintf(fidTeX,'%% TeX-table generated by metropolis.m (Dynare).\n');
+      fprintf(fidTeX,'%% RESULTS FROM METROPOLIS HASTINGS (correlation of measurement errors)\n');
+      fprintf(fidTeX,['%% ' datestr(now,0)]);
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,'{\\tiny \n');
+      fprintf(fidTeX,'\\begin{table}\n');
+      fprintf(fidTeX,'\\centering\n');
+      fprintf(fidTeX,'\\begin{tabular}{l|lccccc} \n');
+      fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+      fprintf(fidTeX,'  & Prior distribution & Prior mean  & Prior s.d. & Post. mean & HPD inf & HPD sup  \\\\ \n');
+      fprintf(fidTeX,'\\hline \\\\ \n');
+      for i=1:ncn
+	k1 = estim_params_.corrn(i,1);
+	k2 = estim_params_.corrn(i,2);
+	name = [deblank(lgy_TeX_(k1,:)) ',' deblank(lgy_TeX_(k2,:))];
+	fprintf(fidTeX,' $%s$ & %s & %7.3f & %6.4f & %8.4f & %7.4f & %7.4f \\\\ \n',...
+		name, ...
+		deblank(pnames(bayestopt_.pshape(ip)+1,:)), ...
+		bayestopt_.pmean(ip), ...
+		bayestopt_.pstdev(ip), ...
+		post_mean(ip), ...
+		min_interval(ip,1), ...
+		min_interval(ip,2));
+	ip = ip+1;
+      end
+      fprintf(fidTeX,'\\hline\\hline \n');
+      fprintf(fidTeX,'\\end{tabular}\n ');    
+      fprintf(fidTeX,'\\caption{Results from Metropolis Hastings (correlation of structural shocks)}\n ');
+      fprintf(fidTeX,'\\label{Table:MhPosterior:5}\n');
+      fprintf(fidTeX,'\\end{table}\n');
+      fprintf(fidTeX,'} \n');
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end
+  end % if TeX
+  %                                                               
+  %%                                                              
+  %%%                                                             
+  %%%%                                                            
+  %%%%% Plot posterior distributions
+  %%%%                                                            
+  %%%                                                             
+  %%                                                              
+  %                                                               
+  figurename = 'Priors and posteriors';
+  if TeX    
+    fidTeX = fopen([fname_ '_PriorsAndPosteriors.TeX'],'w');
+    fprintf(fidTeX,'%% TeX eps-loader file generated by metropolis.m (Dynare).\n');
+    fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
+    fprintf(fidTeX,' \n');
+  end
+  [nbplt,nr,nc,lr,lc,nstar] = pltorg(npar);
+  if nbplt == 1
+    h1 = figure('Name',figurename);
+    if TeX
+      TeXNAMES = [];
+    end    
+    NAMES    = []; 
+    for i=1:npar
+      [borneinf,bornesup,x1,x2,f1,f2,top,nam,texnam] = ...
+      posterior_distribution(i,nfile,ffil,ifil,...
+                 nblck,n,number_of_simulations_per_file,TeX);
+      eval(['oo_.posterior_density.' deblank(nam) ' = [x1,f1];']);
+      eval(['oo_.prior_density.' deblank(nam) ' = [x2,f2];']); 
+      if TeX
+	TeXNAMES = strvcat(TeXNAMES,texnam);
+      end    
+      NAMES = strvcat(NAMES,nam);
+      subplot(nr,nc,i);
+      hh = plot(x2,f2,'-k','linewidth',2);
+      set(hh,'color',[0.7 0.7 0.7]);
+      hold on;
+      plot(x1,f1,'-k','linewidth',2);
+      plot( [xparam1(i) xparam1(i)], [0,1.1*top], '--g', 'linewidth', 2);
+      box on;
+      axis([borneinf bornesup 0 1.1*top]);
+      title(nam,'Interpreter','none');
+      hold off;
+      drawnow
+    end
+    eval(['print -depsc2 ' fname_ '_PriorsAndPosteriors' int2str(1)]);
+    eval(['print -dpdf ' fname_ '_PriorsAndPosteriors' int2str(1)]);
+    saveas(h1,[fname_ '_PriorsAndPosteriors' int2str(1) '.fig']);
+    if TeX
+      fprintf(fidTeX,'\\begin{figure}[H]\n');
+      for jj = 1:npar
+	fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:)));
+      end    
+      fprintf(fidTeX,'\\centering\n');
+      fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_PriorsAndPosteriors%s}\n',fname_,int2str(1));
+      fprintf(fidTeX,'\\caption{Priors and posteriors.}');
+      fprintf(fidTeX,'\\label{Fig:PriorsAndPosteriors:%s}\n',int2str(1));
+      fprintf(fidTeX,'\\end{figure}\n');
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end
+    if options_.nograph, close(h1), end
+  else
+    for plt = 1:nbplt-1
+      hplt = figure('Name',figurename);
+      if TeX
+	TeXNAMES = [];
+      end    
+      NAMES    = []; 
+      for index=1:nstar
+	names = [];
+	i = (plt-1)*nstar + index;
+	[borneinf,bornesup,x1,x2,f1,f2,top,nam,texnam] = ...
+	    posterior_distribution(i,nfile,ffil,ifil,...
+				   nblck,n,number_of_simulations_per_file,TeX);
+	eval(['oo_.posterior_density.' deblank(nam) ' = [x1,f1];']);
+	eval(['oo_.prior_density.' deblank(nam) ' = [x2,f2];']);                     
+	if TeX
+	  TeXNAMES = strvcat(TeXNAMES,texnam);
+	end    
+	NAMES = strvcat(NAMES,nam);
+	subplot(nr,nc,index);
+	hh = plot(x2,f2,'-k','linewidth',2);
+	set(hh,'color',[0.7 0.7 0.7]);
+	hold on;
+	plot(x1,f1,'-k','linewidth',2);
+	plot( [xparam1(i) xparam1(i)], [0,1.1*top], '--g', 'linewidth', 2);
+	box on;
+	axis([borneinf bornesup 0 1.1*top]);
+	title(nam,'Interpreter','none');
+	hold off;
+	drawnow;
+      end  % index=1:nstar
+      eval(['print -depsc2 ' fname_ '_PriorsAndPosteriors' int2str(plt)]);
+      eval(['print -dpdf ' fname_ '_PriorsAndPosteriors' int2str(plt)]);
+      saveas(hplt,[fname_ '_PriorsAndPosteriors' int2str(plt) '.fig']);
+      if TeX
+	fprintf(fidTeX,'\\begin{figure}[H]\n');
+	for jj = 1:nstar
+	  fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:)));
+	end    
+	fprintf(fidTeX,'\\centering\n');
+	fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_PriorsAndPosteriors%s}\n',fname_,int2str(plt));
+	fprintf(fidTeX,'\\caption{Priors and posteriors.}');
+	fprintf(fidTeX,'\\label{Fig:PriorsAndPosteriors:%s}\n',int2str(plt));
+	fprintf(fidTeX,'\\end{figure}\n');
+	fprintf(fidTeX,' \n');
+      end    
+      if options_.nograph, close(hplt), end
+    end % plt = 1:nbplt-1
+    hplt = figure('Name',figurename);
+    if TeX
+      TeXNAMES = [];
+    end    
+    NAMES    = []; 
+    for index=1:npar-(nbplt-1)*nstar
+      i = (nbplt-1)*nstar +  index;
+      [borneinf,bornesup,x1,x2,f1,f2,top,nam,texnam] = ...
+	  posterior_distribution(i,nfile,ffil,ifil,...
+				 nblck,n,number_of_simulations_per_file,TeX);
+      eval(['oo_.posterior_density.' deblank(nam) ' = [x1,f1];']);
+      eval(['oo_.prior_density.' deblank(nam) ' = [x2,f2];']);             
+      if TeX
+	TeXNAMES = strvcat(TeXNAMES,texnam);
+      end
+      NAMES = strvcat(NAMES,nam);
+      if lr
+	subplot(lc,lr,index);
+      else
+	subplot(nr,nc,index);
+      end    
+      hh = plot(x2,f2,'-k','linewidth',2);
+      set(hh,'color',[0.7 0.7 0.7]);
+      hold on;
+      plot(x1,f1,'-k','linewidth',2);
+      plot( [xparam1(i) xparam1(i)], [0,1.1*top], '--g', 'linewidth', 2);
+      box on;
+      axis([borneinf bornesup 0 1.1*top]);
+      title(nam,'Interpreter','none');
+      hold off;
+      drawnow;
+    end  % index=1:npar-(nbplt-1)*nstar
+    eval(['print -depsc2 ' fname_ '_PriorsAndPosteriors' int2str(nbplt)]);
+    eval(['print -dpdf ' fname_ '_PriorsAndPosteriors' int2str(nbplt)]);
+    saveas(hplt,[fname_ '_PriorsAndPosteriors' int2str(nbplt) '.fig']);
+    if TeX
+      fprintf(fidTeX,'\\begin{figure}[H]\n');
+      for jj = 1:npar-(nbplt-1)*nstar
+	fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:)));
+      end    
+      fprintf(fidTeX,'\\centering\n');
+      fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_PriorsAndPosteriors%s}\n',fname_,int2str(nbplt));
+      fprintf(fidTeX,'\\caption{Priors and posteriors.}');
+      fprintf(fidTeX,'\\label{Fig:PriorsAndPosteriors:%s}\n',int2str(nbplt));
+      fprintf(fidTeX,'\\end{figure}\n');
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end
+    if options_.nograph, close(hplt), end
+  end
+  %                                                               
+  %%                                                              
+  %%%                                                             
+  %%%%                                                            
+  %%%%% Je (re)fais mes comptes... I should be able to skip this part (already done) 
+  %%%%                                                            
+  %%%                                                             
+  %%                                                              
+  %                                                               
+  FLN = zeros(nfile-ffil+1,3);% Describes the number of lines in each file
+  if nblck == 1
+    instr1 = [fname_ '_mh'];
+    instr2 = '';
+  else  % I only consider draws from the first chain. This is correct
+    % if and only if the metropolis-hastings did converge.
+    instr1 = [fname_ '_mh'];
+    instr2 = '_blck1';
+  end   
+  eval(['load ' instr1 int2str(ffil) instr2]);
+  clear post2 x2;
+  FLN(1,1) = ffil;                            % File number   
+  FLN(1,2) = size(logpo2(ifil:end,:),1);      % Number of simulations in this file (density) 
+  FLN(1,3) = FLN(1,2);                        % Cumulative Distribution Function
+  if nfile-ffil+1>1
+    linee = 1;
+    for n = ffil+1:nfile
+      linee = linee+1;
+      instr = [instr1 int2str(n) instr2];
+      eval(['load ' instr]);
+      clear post2 x2;
+      FLN(linee,1) = n;
+      FLN(linee,2) = size(logpo2,1);
+      FLN(linee,3) = FLN(linee-1,3) + FLN(linee,2);  
+    end
+    clear logpo2
+    nruns = FLN(linee,3);
+  else
+    nruns = FLN(1,3);    
+  end
+  FLN(:,3) = FLN(:,3)/nruns;% I'm scaling the CDF
+  nvar     = endo_nbr;
+  B        = min(500,nruns);
+  deciles = [round(0.1*B) ...
+	     round(0.2*B)...
+	     round(0.3*B)...
+	     round(0.4*B)...
+	     round(0.5*B)...
+	     round(0.6*B)...
+	     round(0.7*B)...
+	     round(0.8*B)...
+	     round(0.9*B)];
+  %                                                               
+  %%                                                              
+  %%%                                                             
+  %%%%                                                            
+  %%%%% SDGE-based forecasts, smooth and filtered variables, IRFs and theoretical moments 
+  %%%%                                                            
+  %%%                                                             
+  %%                                                              
+  %                                                               
+  if options_.forecast | options_.smoother | options_.filtered_vars
+    deep = MU;
+    subindx = subset();
+    % [1] I delete some old files...    
+    disp(' ')
+    disp(' ')
+    if options_.forecast
+      files = eval(['dir(''' fname_ '_forecast*.mat'');']);
+      if length(files)
+	delete([fname_ '_forecast*.mat']);
+	disp(['MH: Old ' fname_ '_forecast files deleted! '])
+      end
+    end
+    if options_.smoother        
+      files = eval(['dir(''' fname_ '_smooth*.mat'');']);
+      if length(files)
+	delete([fname_ '_smooth*.mat']);
+	disp(['MH: Old ' fname_ '_smooth files deleted! '])
+      end
+      files = eval(['dir(''' fname_ '_innovation*.mat'');']);
+      if length(files)
+	delete([fname_ '_innovation*.mat']);
+	disp(['MH: Old ' fname_ '_innovation files deleted! '])
+      end
+      files = eval(['dir(''' fname_ '_error*.mat'');']);
+      if length(files)
+	delete([fname_ '_error*.mat']);
+	disp(['MH: Old ' fname_ '_error files deleted! '])
+      end
+    end
+    if options_.filtered_vars
+      files = eval(['dir(''' fname_ '_filter*.mat'');']);     
+      if length(files)                                        
+	delete([fname_ '_filter*.mat']);                    
+	disp(['MH: Old ' fname_ '_filter files deleted! ']) 
+      end                                                         
+    end
+    disp(' ')
+    disp(' ')
+    % [2] Initialization...    
+    ex_      = zeros(horizon+xkmin_+xkmax_,exo_nbr);
+    yyyy     = zeros(nvar,ykmin_);
+    IdObs    = bayestopt_.mfys;
+    if options_.forecast 
+      if B <= MAX_nforc
+	stock_forcst = zeros(options_.forecast+ykmin_,nvar,B);
+	stock_forcst1 = zeros(options_.forecast+ykmin_,nvar,B);
+      else
+	stock_forcst = zeros(options_.forecast+ykmin_,nvar,MAX_nforc);
+	stock_forcst1 = zeros(options_.forecast+ykmin_,nvar,MAX_nforc);
+      end
+    end 
+    if options_.smoother
+      if B <= MAX_nsmoo
+	stock_smooth = zeros(endo_nbr,gend,B);
+      else
+	stock_smooth = zeros(endo_nbr,gend,MAX_nsmoo);
+      end
+      if B <= MAX_ninno 
+	stock_innov  = zeros(exo_nbr,gend,B);
+      else
+	stock_innov  = zeros(exo_nbr,gend,MAX_ninno);
+      end
+      if nvn & B <= MAX_nerro
+	%stock_error = zeros(gend,nvobs,B);
+	stock_error = zeros(nvobs,gend,B);
+      else nvn & B > MAX_nerro
+	%stock_error = zeros(gend,nvobs,MAX_nerro);
+	stock_error = zeros(nvobs,gend,MAX_nerro);
+      end
+    end
+    if options_.filtered_vars
+      if B <= MAX_nfilt
+	stock_filter = zeros(endo_nbr,gend+1,B);
+      else
+	stock_filter = zeros(endo_nbr,gend+1,MAX_nfilt);
+      end
+    end
+    h = waitbar(0,'SDGE model based forecasts...');
+    % [3]   CoRe    
+    % [3.1] First we consider the case with measurement error
+    if nvn
+      % [3.1.1] More than one _mh file 
+      if nfile-ffil+1>1			
+	if options_.forecast
+	  sfil_forc = 0;
+	  irun_forc = 0;  			
+	end
+	if options_.smoother
+	  sfil_smoo = 0;
+	  sfil_inno = 0;
+	  sfil_erro = 0;
+	  irun_smoo = 0;
+	  irun_inno = 0;
+	  irun_erro = 0;
+	end
+	if options_.filtered_vars
+	  sfil_filt = 0;
+	  irun_filt = 0;  			
+	end
+	% [3.1.1.1] Loop in the metropolis
+	for b = 1:B;
+	  if options_.forecast
+	    irun_forc = irun_forc+1;
+	  end
+	  if options_.smoother
+	    irun_smoo = irun_smoo+1;
+	    irun_inno = irun_inno+1;
+	    irun_erro = irun_erro+1;
+	  end
+	  if options_.filtered_vars
+	    irun_filt = irun_filt+1;  			
+	  end    			
+	  % FIRST, I choose an _mh file (where the posterior distribution is stored)
+	  choose_an_mh_file = rand;
+	  mh_file_number = FLN(find(choose_an_mh_file>=FLN(:,3)),1);
+	  if isempty(mh_file_number)
+	    mh_file_number = ffil;
+	  else    
+	    mh_file_number = mh_file_number(1);
+	  end    
+	  eval(['load ' instr1 int2str(mh_file_number) instr2]);
+	  clear post2 logpo2;
+	  % SECOND, I choose a vector of structural parameters (a line in the _mh file) 
+	  DEEP  = x2(floor(rand*FLN(find(mh_file_number == FLN(:,1)),2))+1,:);
+	  deep(subindx) = DEEP(subindx);
+	  % THIRD, I estimate the smooth and filtered variables. I need the smoothed variables
+	  % to estimate the state of the model at the end of the sample. 
+	  [atT,innov,obs_err,filtered_state_vector,ys,trend_coeff] = DsgeSmoother(transpose(deep),gend,data);
+	  % FOURTH, smoothed and filtered variables are saved if needed
+	  if options_.smoother
+	    if irun_erro < MAX_nerro
+	      stock_error(:,:,irun_erro) = obs_err;
+	    else
+	      stock_error(:,:,irun_erro) = obs_err;
+	      sfil_erro = sfil_erro + 1;
+	      instr = [fname_ '_error' int2str(sfil_erro) ' stock_error;'];
+	      eval(['save ' instr]);
+	      irun_erro = 0;
+	      stock_error  = zeros(gend,nvobs,MAX_nerro);
+	    end
+	    if irun_smoo < MAX_nsmoo
+	      stock_smooth(:,:,irun_smoo) = atT(1:endo_nbr,1:gend);
+	    else
+	      stock_smooth(:,:,irun_smoo) = atT(1:endo_nbr,1:gend);
+	      sfil_smoo = sfil_smoo + 1;
+	      instr = [fname_ '_smooth' int2str(sfil_smoo) ' stock_smooth;'];
+	      eval(['save ' instr]);
+	      irun_smoo = 0;
+	      stock_smooth = ...
+		  zeros(endo_nbr,gend,MAX_nsmoo);
+	    end	
+	    if irun_inno < MAX_ninno
+	      stock_innov(:,:,irun_inno) = innov;
+	    else
+	      stock_innov(:,:,irun_inno) = innov;
+	      sfil_inno = sfil_inno + 1;
+	      instr = [fname_ '_innovation' int2str(sfil_inno) ' stock_innov;'];
+	      eval(['save ' instr]);
+	      irun_inno = 0;
+	      stock_innov  = zeros(exo_nbr,gend,MAX_ninno);
+	    end	
+	  end
+	  if options_.filtered_vars
+	    if irun_filt < MAX_nfilt
+	      stock_filter(:,:,irun_filt) = filtered_state_vector;
+	    else
+	      stock_filter(:,:,irun_filt) = filtered_state_vector;
+	      sfil_filt = sfil_filt + 1;
+	      instr = [fname_ '_filter' int2str(sfil_filt) ' stock_filter;'];
+	      eval(['save ' instr]);
+	      irun_filt = 0;
+	      stock_filter = ...
+		  zeros(endo_nbr,gend+1,MAX_nfilt);
+	    end	
+	  end    			
+	  if options_.forecast
+	    % FIFTH, I update variable dr_ 
+	    dr_ = resol(ys_,0);
+	    % SIXTH, I do and save the forecasts (for all the endogenous variables)
+	    % The state of the economy at the end of the sample 
+	    % depends on the structural parameters.	    
+	    yyyy(:,1:ykmin_) = atT(1:endo_nbr,size(atT,2)-ykmin_+1:size(atT,2));
+	    yf = forcst2a(yyyy,dr_,ex_);
+	    if options_.prefilter == 1
+	      yf(:,IdObs) = yf(:,IdObs)+repmat(bayestopt_.mean_varobs', ...
+					       horizon+ykmin_,1);
+	    end
+	    yf(:,IdObs) = yf(:,IdObs)+(gend+[1-ykmin_:horizon]')*trend_coeff';
+	    if options_.loglinear == 1
+	      yf = yf+repmat(log(ys'),horizon+ykmin_,1);
+	      yf = exp(yf);
+	    else
+	      yf = yf+repmat(ys',horizon+ykmin_,1);
+	    end
+	    stock_forcst(:,:,irun_forc) = yf;
+	    yf1 = forcst2(yyyy,horizon,dr_,1);
+	    if options_.prefilter == 1
+	      yf1(:,IdObs,:) = yf1(:,IdObs,:)+ ...
+		  repmat(bayestopt_.mean_varobs',[horizon+ykmin_,1,1]);
+	    end
+	    yf1(:,IdObs,:) = yf1(:,IdObs,:)+repmat((gend+[1-ykmin_:horizon]')* ...
+		trend_coeff',[1,1,1]);
+	    if options_.loglinear == 1
+	      yf1 = yf1 + repmat(log(ys'),[horizon+ykmin_,1,1]);
+	      yf1 = exp(yf1);
+	    else
+	      yf1 = yf1 + repmat(ys',[horizon+ykmin_,1,1]);
+	    end
+	    stock_forcst1(:,:,irun_forc) = yf1;
+	    if irun_forc == MAX_nforc
+	      sfil_forc = sfil_forc + 1;
+	      save([fname_ '_forecast' int2str(sfil_forc)],'stock_forcst','stock_forcst1');
+	      irun_forc = 0;
+	      stock_forcst = zeros(horizon+ykmin_,nvar,MAX_nforc);
+	      stock_forcst1 = zeros(horizon+ykmin_,nvar,MAX_nforc);
+	    end
+	  end		
+	  waitbar(b/B,h);    
+	end % of loop [3.1.1.1]
+	if options_.smoother
+	  if irun_smoo
+	    stock_smooth = stock_smooth(:,:,1:irun_smoo);
+	    sfil_smoo = sfil_smoo + 1;
+	    instr = [fname_ '_smooth' int2str(sfil_smoo) ' stock_smooth;'];
+	    eval(['save ' instr]);
+	  end
+	  clear stock_smooth;
+	  if irun_inno
+	    stock_innov = stock_innov(:,:,1:irun_inno);
+	    sfil_inno = sfil_inno + 1;
+	    instr = [fname_ '_innovation' int2str(sfil_inno) ' stock_innov;'];
+	    eval(['save ' instr]);
+	  end
+	  clear stock_innov;
+	  if irun_erro
+	    stock_error = stock_error(:,:,1:irun_erro);
+	    sfil_erro = sfil_erro + 1;
+	    instr = [fname_ '_error' int2str(sfil_erro) ' stock_error;'];
+	    eval(['save ' instr]);
+	  end
+	  clear stock_error;
+	end
+	if options_.forecast	
+	  if irun_forc
+	    stock_forcst = stock_forcst(:,:,1:irun_forc);  
+	    stock_forcst1 = stock_forcst1(:,:,1:irun_forc);  
+	    sfil_forc = sfil_forc + 1;
+	    save([fname_ '_forecast' int2str(sfil_forc)],'stock_forcst','stock_forcst1');
+	  end
+	  clear stock_forcst stock_forcst1
+	end
+	if options_.filtered_vars	
+	  if irun_filt
+	    stock_filter = stock_filter(:,:,1:irun_filt);
+	    sfil_filt = sfil_filt + 1;
+	    instr = [fname_ '_filter' int2str(sfil_filt) ' stock_filter;'];
+	    eval(['save ' instr]);
+	  end
+	  clear stock_filter;
+	end
+      else % [3.1.2] Just one _mh file
+	if options_.forecast
+	  sfil_forc = 0;
+	  irun_forc = 0;  			
+	end
+	if options_.smoother
+	  sfil_smoo = 0;
+	  sfil_inno = 0;
+	  sfil_erro = 0;
+	  irun_smoo = 0;
+	  irun_inno = 0;
+	  irun_erro = 0;
+	end
+	if options_.filtered_vars
+	  sfil_filt = 0;
+	  irun_filt = 0;  			
+	end
+	eval(['load ' instr1 int2str(ffil) instr2]);
+	NumberOfSimulations = length(logpo2);
+	clear post2 logpo2;
+	for b = 1:B;
+	  if options_.forecast
+	    irun_forc = irun_forc+1;
+	  end
+	  if options_.smoother
+	    irun_smoo = irun_smoo+1;
+	    irun_inno = irun_inno+1;
+	    irun_erro = irun_erro+1;
+	  end
+	  if options_.filtered_vars
+	    irun_filt = irun_filt+1;            
+	  end
+	  DEEP  = x2(floor(rand*NumberOfSimulations)+1,:); 
+	  deep(subindx) = DEEP(subindx);
+	  [atT,innov,obs_err,filtered_state_vector,ys,trend_coeff] = DsgeSmoother(transpose(deep),gend,data);
+	  if options_.smoother
+	    if irun_erro < MAX_nerro
+	      stock_error(:,:,irun_erro) = obs_err;
+	    else
+	      stock_error(:,:,irun_erro) = obs_err;
+	      sfil_erro = sfil_erro + 1;
+	      instr = [fname_ '_error' int2str(sfil_erro) ' stock_error;'];
+	      eval(['save ' instr]);
+	      irun_erro = 0;
+	      stock_error  = zeros(gend,nvobs,MAX_nerro);
+	    end
+	    if irun_smoo < MAX_nsmoo
+	      stock_smooth(:,:,irun_smoo) = atT(1:endo_nbr,1:gend);
+	    else
+	      stock_smooth(:,:,irun_smoo) = atT(1:endo_nbr,1:gend);
+	      sfil_smoo = sfil_smoo + 1;
+	      instr = [fname_ '_smooth' int2str(sfil_smoo) ' stock_smooth;'];
+	      eval(['save ' instr]);
+	      irun_smoo = 0;
+	      stock_smooth = ...
+		  zeros(endo_nbr,gend,MAX_nsmoo);
+	    end 
+	    if irun_inno < MAX_ninno
+	      stock_innov(:,:,irun_inno) = innov;
+	    else
+	      stock_innov(:,:,irun_inno) = innov;
+	      sfil_inno = sfil_inno + 1;
+	      instr = [fname_ '_innovation' int2str(sfil_inno) ' stock_innov;'];
+	      eval(['save ' instr]);
+	      irun_inno = 0;
+	      stock_innov  = zeros(exo_nbr,gend,MAX_ninno);
+	    end
+	  end
+	  if options_.filtered_vars
+	    if irun_filt < MAX_nfilt                                             
+	      stock_filter(:,:,irun_filt) = filtered_state_vector;             
+	    else                                                                 
+	      stock_filter(:,:,irun_filt) = filtered_state_vector;             
+	      sfil_filt = sfil_filt + 1;                                       
+	      instr = [fname_ '_filter' int2str(sfil_filt) ' stock_filter;'];  
+	      eval(['save ' instr]);                                           
+	      irun_filt = 0;                                                   
+	      stock_filter = ...                                               
+		  zeros(endo_nbr,gend+1,MAX_nfilt);     
+	    end                                                                  
+	  end
+	  if options_.forecast
+	    dr_ = resol(ys_,0);
+	    yyyy(:,1:ykmin_) = atT(1:endo_nbr,size(atT,2)-ykmin_+1:size(atT,2));
+	    yf = forcst2a(yyyy,dr_,ex_);
+	    if options_.prefilter == 1
+	      yf(:,IdObs) = yf(:,IdObs)+repmat(bayestopt_.mean_varobs', ...
+					       horizon+ykmin_,1);
+	    end
+	    yf(:,IdObs) = yf(:,IdObs)+(gend+[1-ykmin_:horizon]')*trend_coeff';
+	    if options_.loglinear == 1
+	      yf = yf+repmat(log(ys'),horizon+ykmin_,1);
+	      yf = exp(yf);
+	    else
+	      yf = yf+repmat(ys',horizon+ykmin_,1);
+	    end
+	    stock_forcst(:,:,irun_forc) = yf;
+	    yf1 = forcst2(yyyy,horizon,dr_,1);
+	    if options_.prefilter == 1
+	      yf1(:,IdObs,:) = yf1(:,IdObs,:)+ ...
+		  repmat(bayestopt_.mean_varobs',[horizon+ykmin_,1,1]);
+	    end
+	    yf1(:,IdObs,:) = yf1(:,IdObs,:)+repmat((gend+[1-ykmin_:horizon]')* ...
+						   trend_coeff',[1,1,1]);
+	    if options_.loglinear == 1
+	      yf1 = yf1 + repmat(log(ys'),[horizon+ykmin_,1,1]);
+	      yf1 = exp(yf1);
+	    else
+	      yf1 = yf1 + repmat(ys',[horizon+ykmin_,1,1]);
+	    end
+	    stock_forcst1(:,:,irun_forc) = yf1;
+	    if irun_forc == MAX_nforc
+	      sfil_forc = sfil_forc + 1;
+	      save([fname_ '_forecast' int2str(sfil_forc)],'stock_forcst','stock_forcst1');
+	      irun_forc = 0;
+	      stock_forcst = zeros(horizon+ykmin_,nvar,MAX_nforc);
+	      stock_forcst1 = zeros(horizon+ykmin_,nvar,MAX_nforc);
+	    end
+	  end   
+	  waitbar(b/B,h);    
+	end % of the loop over the metropolis simulations
+	if options_.smoother
+	  if irun_smoo
+	    stock_smooth = stock_smooth(:,:,1:irun_smoo);
+	    sfil_smoo = sfil_smoo + 1;
+	    instr = [fname_ '_smooth' int2str(sfil_smoo) ' stock_smooth;'];
+	    eval(['save ' instr]);
+	  end
+	  clear stock_smooth;
+	  if irun_inno
+	    stock_innov = stock_innov(:,:,1:irun_inno);
+	    sfil_inno = sfil_inno + 1;
+	    instr = [fname_ '_innovation' int2str(sfil_inno) ' stock_innov;'];
+	    eval(['save ' instr]);
+	  end
+	  clear stock_innov;
+	  if irun_erro
+	    stock_error = stock_error(:,:,1:irun_erro);
+	    sfil_erro = sfil_erro + 1;
+	    instr = [fname_ '_error' int2str(sfil_erro) ' stock_error;'];
+	    eval(['save ' instr]);
+	  end
+	  clear stock_error;
+	end
+	if options_.forecast    
+	  if irun_forc
+	    stock_forcst = stock_forcst(:,:,1:irun_forc);  
+	    stock_forcst1 = stock_forcst1(:,:,1:irun_forc);  
+	    sfil_forc = sfil_forc + 1;
+	    save([fname_ '_forecast' int2str(sfil_forc)],'stock_forcst','stock_forcst1');
+	  end
+	  clear stock_forcst stock_forcst1
+	end
+	if options_.filtered_vars
+	  if irun_filt
+	    stock_filter = stock_filter(:,:,1:irun_filt);
+	    sfil_filt = sfil_filt + 1;
+	    instr = [fname_ '_filter' int2str(sfil_filt) ' stock_filter;'];
+	    eval(['save ' instr]);
+	  end
+	  clear stock_filter;           
+	end
+      end
+    else % [3.2]    Second we consider the case without measurement error
+      if nfile-ffil+1>1
+	if options_.forecast
+	  sfil_forc = 0;
+	  irun_forc = 0;  			
+	end
+	if options_.smoother
+	  sfil_smoo = 0;
+	  sfil_inno = 0;
+	  sfil_erro = 0;
+	  irun_smoo = 0;
+	  irun_inno = 0;
+	  irun_erro = 0;
+	end
+	if options_.filtered_vars
+	  sfil_filt = 0;
+	  irun_filt = 0;  			
+	end
+	for b = 1:B;
+	  if options_.forecast
+	    irun_forc = irun_forc+1;
+	  end
+	  if options_.smoother
+	    irun_smoo = irun_smoo+1;
+	    irun_inno = irun_inno+1;
+	    irun_erro = irun_erro+1;
+	  end
+	  if options_.filtered_vars
+	    irun_filt = irun_filt+1;  			
+	  end	    
+	  choose_an_mh_file = rand;
+	  mh_file_number = FLN(find(choose_an_mh_file>=FLN(:,3)),1);
+	  if isempty(mh_file_number)
+	    mh_file_number = ffil;
+	  else    
+	    mh_file_number = mh_file_number(1);
+	  end    
+	  eval(['load ' instr1 int2str(mh_file_number) instr2]);
+	  clear post2 logpo2;
+	  DEEP  = x2(floor(rand*FLN(find(mh_file_number == FLN(:,1)),2))+1,:);
+	  deep(subindx) = DEEP(subindx);
+	  [atT,innov,obs_err,filtered_state_vector,ys,trend_coeff] = DsgeSmoother(transpose(deep),gend,data);
+	  if options_.smoother
+	    %if irun_erro < MAX_nerro
+	    %	stock_error(:,:,irun_erro) = obs_err;
+	    %else
+	    %	stock_error(:,:,irun_erro) = obs_err;
+	    %	instr = [fname_ '_error' int2str(sfil_erro) ' stock_error;'];
+	    %	eval(['save ' instr]);
+	    %	sfil_erro = sfil_erro + 1;
+	    %	irun_erro = 0;
+	    %	stock_error  = zeros(gend,nvobs,MAX_nerro);
+	    %end
+	    if irun_smoo < MAX_nsmoo
+	      stock_smooth(:,:,irun_smoo) = atT(1:endo_nbr,1:gend);
+	      if options_.prefilter == 1
+		stock_smooth(bayestopt_.mf,:,irun_smoo) = atT(bayestopt_.mf,:)+repmat(bayestopt_.mean_varobs',1,gend);
+	      elseif options_.loglinear == 1
+		stock_smooth(bayestopt_.mf,:,irun_smoo) = atT(bayestopt_.mf,:)+...
+		    repmat(log(ys(bayestopt_.mfys)),1,gend)+...
+		     trend_coeff*[1:gend];
+	      else
+		stock_smooth(bayestopt_.mf,:,irun_smoo) = atT(bayestopt_.mf,:)+...
+		    repmat(ys(bayestopt_.mfys),1,gend)+...
+		     trend_coeff*[1:gend];
+	      end
+	    else
+	      stock_smooth(:,:,irun_smoo) = atT(1:endo_nbr,1:gend);
+	      if options_.prefilter == 1
+		stock_smooth(bayestopt_.mf,:,irun_smoo) = atT(bayestopt_.mf,:)+repmat(bayestopt_.mean_varobs',1,gend);
+	      elseif options_.loglinear == 1
+		stock_smooth(bayestopt_.mf,:,irun_smoo) = atT(bayestopt_.mf,:)+...
+		    repmat(log(ys(bayestopt_.mfys)),1,gend)+...
+		     trend_coeff*[1:gend];
+	      else
+		stock_smooth(bayestopt_.mf,:,irun_smoo) = atT(bayestopt_.mf,:)+...
+		    repmat(ys(bayestopt_.mfys),1,gend)+...
+		     trend_coeff*[1:gend];
+	      end
+	      sfil_smoo = sfil_smoo + 1;
+	      instr = [fname_ '_smooth' int2str(sfil_smoo) ' stock_smooth;'];
+	      eval(['save ' instr]);
+	      irun_smoo = 0;
+	      stock_smooth = ...
+		zeros(endo_nbr,gend,MAX_nsmoo);
+	    end	
+	    if irun_inno < MAX_ninno
+	      stock_innov(:,:,irun_inno) = innov;
+	    else
+	      stock_innov(:,:,irun_inno) = innov;
+	      sfil_inno = sfil_inno + 1;
+	      instr = [fname_ '_innovation' int2str(sfil_inno) ' stock_innov;'];
+	      eval(['save ' instr]);
+	      irun_inno = 0;
+	      stock_innov  = zeros(exo_nbr,gend,MAX_ninno);
+	    end	
+	  end
+	  if options_.filtered_vars
+	    if irun_filt < MAX_nfilt
+	      stock_filter(:,:,irun_filt) = filtered_state_vector;
+	    else
+	      stock_filter(:,:,irun_filt) = filtered_state_vector;
+	      sfil_filt = sfil_filt + 1;
+	      instr = [fname_ '_filter' int2str(sfil_filt) ' stock_filter;'];
+	      eval(['save ' instr]);
+	      irun_filt = 0;
+	      stock_filter = ...
+		 zeros(endo_nbr,gend+1,MAX_nfilt);
+	    end
+	  end
+	  if options_.forecast	    
+	    dr_ = resol(ys_,0);
+	    for j = 1:nvar 
+	      yyyy(j,1:ykmin_) = atT(j,size(atT,2)-ykmin_+1:size(atT,2));
+	    end
+	    yf = forcst2a(yyyy,dr_,ex_);
+	    if options_.prefilter == 1
+	      yf(:,IdObs) = yf(:,IdObs)+repmat(bayestopt_.mean_varobs', ...
+					       horizon+ykmin_,1);
+	    end
+	    yf(:,IdObs) = yf(:,IdObs)+(gend+[1-ykmin_:horizon]')*trend_coeff';
+	    if options_.loglinear == 1
+	      yf = yf+repmat(log(ys'),horizon+ykmin_,1);
+	      yf = exp(yf);
+	    else
+	      yf = yf+repmat(ys',horizon+ykmin_,1);
+	    end
+	    stock_forcst(:,:,irun_forc) = yf;
+	    yf1 = forcst2(yyyy,horizon,dr_,1);
+	    if options_.prefilter == 1
+	      yf1(:,IdObs,:) = yf1(:,IdObs,:)+ ...
+		  repmat(bayestopt_.mean_varobs',[horizon+ykmin_,1,1]);
+	    end
+	    yf1(:,IdObs,:) = yf1(:,IdObs,:)+repmat((gend+[1-ykmin_:horizon]')* ...
+		trend_coeff',[1,1,1]);
+	    if options_.loglinear == 1
+	      yf1 = yf1 + repmat(log(ys'),[horizon+ykmin_,1,1]);
+	      yf1 = exp(yf1);
+	    else
+	      yf1 = yf1 + repmat(ys',[horizon+ykmin_,1,1]);
+	    end
+	    stock_forcst1(:,:,irun_forc) = yf1;
+	    if irun_forc == MAX_nforc
+	      sfil_forc = sfil_forc + 1;
+	      save([fname_ '_forecast' int2str(sfil_forc)],'stock_forcst','stock_forcst1');
+	      irun_forc = 0;
+	      stock_forcst = zeros(horizon+ykmin_,nvar,MAX_nforc);
+	      stock_forcst1 = zeros(horizon+ykmin_,nvar,MAX_nforc);
+	    end
+	  end
+	  waitbar(b/B,h);    
+	end
+	if options_.smoother
+	  if irun_smoo
+	    stock_smooth = stock_smooth(:,:,1:irun_smoo);
+	    sfil_smoo = sfil_smoo + 1;
+	    instr = [fname_ '_smooth' int2str(sfil_smoo) ' stock_smooth;'];
+	    eval(['save ' instr]);
+	  end
+	  clear stock_smooth;
+	  if irun_inno
+	    stock_innov = stock_innov(:,:,1:irun_inno);
+	    sfil_inno = sfil_inno + 1;
+	    instr = [fname_ '_innovation' int2str(sfil_inno) ' stock_innov;'];
+	    eval(['save ' instr]);
+	  end
+	  clear stock_innov;
+	end
+	if options_.forecast	
+	  if irun_forc
+	    stock_forcst = stock_forcst(:,:,1:irun_forc);  
+	    stock_forcst1 = stock_forcst1(:,:,1:irun_forc);  
+	    sfil_forc = sfil_forc + 1;
+	    save([fname_ '_forecast' int2str(sfil_forc)],'stock_forcst','stock_forcst1');
+	  end
+	  clear stock_forcst stock_forcst1
+	end
+	if options_.filtered_vars	
+	  if irun_filt
+	    stock_filter = stock_filter(:,:,1:irun_filt);
+	    sfil_filt = sfil_filt + 1;
+	    instr = [fname_ '_filter' int2str(sfil_filt) ' stock_filter;'];
+	    eval(['save ' instr]);
+	  end
+	  clear stock_filter;
+	end
+      else % just one _mh file
+	if options_.forecast
+	  sfil_forc = 0;
+	  irun_forc = 0;  			
+	end
+	if options_.smoother
+	  sfil_smoo = 0;
+	  sfil_inno = 0;
+	  %sfil_erro = 1;
+	  irun_smoo = 0;
+	  irun_inno = 0;
+	  %irun_erro = 0;
+	end
+	if options_.filtered_vars
+	  sfil_filt = 0;
+	  irun_filt = 0;  			
+	end	  		
+	eval(['load ' instr1 int2str(ffil) instr2]);
+	NumberOfSimulations = length(logpo2);
+	clear post2 logpo2;
+	for b = 1:B;
+	  if options_.forecast
+	    irun_forc = irun_forc+1;
+	  end
+	  if options_.smoother
+	    irun_smoo = irun_smoo+1;
+	    irun_inno = irun_inno+1;
+	    %irun_erro = irun_erro+1;
+	  end
+	  if options_.filtered_vars
+	    irun_filt = irun_filt+1;  			
+	  end	    
+	  DEEP  = x2(floor(rand*NumberOfSimulations)+1,:); 
+	  deep(subindx) = DEEP(subindx);
+	  [atT,innov,obs_err,filtered_state_vector,ys,trend_coeff] = DsgeSmoother(deep',gend,data);
+           % removing lagged variables when ykmin_ > 1
+           filtered_state_vector = filtered_state_vector(1:endo_nbr,:);
+	  if options_.smoother
+	    if irun_smoo < MAX_nsmoo
+	      stock_smooth(:,:,irun_smoo) = atT(1:endo_nbr,1:gend);
+	      if options_.prefilter == 1
+		stock_smooth(bayestopt_.mf,:,irun_smoo) = atT(bayestopt_.mf,:)+repmat(bayestopt_.mean_varobs',1,gend);
+	      elseif options_.loglinear == 1
+		stock_smooth(bayestopt_.mf,:,irun_smoo) = atT(bayestopt_.mf,:)+...
+		    repmat(log(ys(bayestopt_.mfys)),1,gend)+...
+		     trend_coeff*[1:gend];
+	      else
+		stock_smooth(bayestopt_.mf,:,irun_smoo) = atT(bayestopt_.mf,:)+...
+		    repmat(ys(bayestopt_.mfys),1,gend)+...
+		     trend_coeff*[1:gend];
+	      end
+	    else
+	      stock_smooth(:,:,irun_smoo) = atT(1:endo_nbr,1:gend);
+	      if options_.prefilter == 1
+		stock_smooth(bayestopt_.mf,:,irun_smoo) = atT(bayestopt_.mf,:)+repmat(bayestopt_.mean_varobs',1,gend);
+	      elseif options_.loglinear == 1
+		stock_smooth(bayestopt_.mf,:,irun_smoo) = atT(bayestopt_.mf,:)+...
+		    repmat(log(ys(bayestopt_.mfys)),1,gend)+...
+		     trend_coeff*[1:gend];
+	      else
+		stock_smooth(bayestopt_.mf,:,irun_smoo) = atT(bayestopt_.mf,:)+...
+		    repmat(ys(bayestopt_.mfys),1,gend)+...
+		     trend_coeff*[1:gend];
+	      end
+	      sfil_smoo = sfil_smoo + 1;
+	      instr = [fname_ '_smooth' int2str(sfil_smoo) ' stock_smooth;'];
+	      eval(['save ' instr]);
+	      irun_smoo = 0;
+	      stock_smooth = ...
+		  zeros(endo_nbr,gend,MAX_nsmoo);
+	    end	
+	    if irun_inno < MAX_ninno
+	      stock_innov(:,:,irun_inno) = innov;
+	    else
+	      stock_innov(:,:,irun_inno) = innov;
+	      sfil_inno = sfil_inno + 1;
+	      instr = [fname_ '_innovation' int2str(sfil_inno) ' stock_innov;'];
+	      eval(['save ' instr]);
+	      irun_inno = 0;
+	      stock_innov  = zeros(exo_nbr,gend,MAX_ninno);
+	    end	
+	  end
+	  if options_.filtered_vars
+	    if irun_filt < MAX_nfilt
+	      stock_filter(:,:,irun_filt) = filtered_state_vector;
+	    else
+	      stock_filter(:,:,irun_filt) = filtered_state_vector;
+	      sfil_filt = sfil_filt + 1;
+	      instr = [fname_ '_filter' int2str(sfil_filt) ' stock_filter;'];
+	      eval(['save ' instr]);
+	      irun_filt = 0;
+	      stock_filter = ...
+		  zeros(endo_nbr,gend+1,MAX_nfilt);
+	    end	
+	  end    			
+	  if options_.forecast	    
+	    dr_ = resol(ys_,0);
+	    yyyy(:,1:ykmin_) = atT(1:endo_nbr,size(atT,2)-ykmin_+1:size(atT,2));
+	    yf = forcst2a(yyyy,dr_,ex_);
+	    if options_.prefilter == 1
+	      yf(:,IdObs) = yf(:,IdObs)+repmat(bayestopt_.mean_varobs', ...
+					       horizon+ykmin_,1);
+	    end
+	    yf(:,IdObs) = yf(:,IdObs)+(gend+[1-ykmin_:horizon]')*trend_coeff';
+	    if options_.loglinear == 1
+	      yf = yf+repmat(log(ys'),horizon+ykmin_,1);
+	      yf = exp(yf);
+	    else
+	      yf = yf+repmat(ys',horizon+ykmin_,1);
+	    end
+	    stock_forcst(:,:,irun_forc) = yf;
+	    yf1 = forcst2(yyyy,horizon,dr_,1);
+	    if options_.prefilter == 1
+	      yf1(:,IdObs,:) = yf1(:,IdObs,:)+ ...
+		  repmat(bayestopt_.mean_varobs',[horizon+ykmin_,1,1]);
+	    end
+	    yf1(:,IdObs,:) = yf1(:,IdObs,:)+repmat((gend+[1-ykmin_:horizon]')* ...
+						   trend_coeff',[1,1,1]);
+	    if options_.loglinear == 1
+	      yf1 = yf1 + repmat(log(ys'),[horizon+ykmin_,1,1]);
+	      yf1 = exp(yf1);
+	    else
+	      yf1 = yf1 + repmat(ys',[horizon+ykmin_,1,1]);
+	    end
+	    stock_forcst1(:,:,irun_forc) = yf1;
+	    if irun_forc == MAX_nforc
+	      sfil_forc = sfil_forc + 1;
+	      save([fname_ '_forecast' int2str(sfil_forc)],'stock_forcst','stock_forcst1');
+	      irun_forc = 0;
+	      stock_forcst = zeros(horizon+ykmin_,nvar,MAX_nforc);
+	      stock_forcst1 = zeros(horizon+ykmin_,nvar,MAX_nforc);
+	    end
+	  end   
+	  waitbar(b/B,h);    
+	end
+	if options_.smoother
+	  if irun_smoo
+	    stock_smooth = stock_smooth(:,:,1:irun_smoo);
+	    sfil_smoo = sfil_smoo + 1;
+	    instr = [fname_ '_smooth' int2str(sfil_smoo) ' stock_smooth;'];
+	    eval(['save ' instr]);
+	  end
+	  clear stock_smooth;
+	  if irun_inno
+	    stock_innov = stock_innov(:,:,1:irun_inno);
+	    sfil_inno = sfil_inno + 1;
+	    instr = [fname_ '_innovation' int2str(sfil_inno) ' stock_innov;'];
+	    eval(['save ' instr]);
+	  end
+	  clear stock_innov;
+	end
+	if options_.forecast    
+	  if irun_forc
+	    stock_forcst = stock_forcst(:,:,1:irun_forc);  
+	    stock_forcst1 = stock_forcst1(:,:,1:irun_forc);  
+	    sfil_forc = sfil_forc + 1;
+	    save([fname_ '_forecast' int2str(sfil_forc)],'stock_forcst','stock_forcst1');
+	  end
+	  clear stock_forcst stock_forcst1
+	end
+	if options_.filtered_vars   
+	  if irun_filt
+	    stock_filter = stock_filter(:,:,1:irun_filt);
+	    sfil_filt = sfil_filt + 1;
+	    instr = [fname_ '_filter' int2str(sfil_filt) ' stock_filter;'];
+	    eval(['save ' instr]);
+	  end
+	  clear stock_filter;
+	end   
+      end
+    end
+    close(h);
+  end
+  %%
+  %% Only a subset of variables may be treated    
+  %%
+  varlist = options_.varlist;
+  if isempty(varlist)
+    varlist = lgy_;
+    nvar    = size(lgy_,1);
+    SelecVariables = transpose(1:nvar);
+  else
+    nvar = size(varlist,1);
+    SelecVariables = [];
+    for i=1:nvar
+      if ~isempty(strmatch(varlist(i,:),lgy_,'exact'))
+    SelecVariables = [SelecVariables;strmatch(varlist(i,:),lgy_,'exact')];
+      end   
+    end
+    IdObs    = zeros(nvobs,1);
+    for j=1:nvobs
+      for i=1:nvar
+    iobs = strmatch(options_.varobs(j,:),varlist,'exact');
+      end
+      if ~isempty(iobs)
+    IdObs(j,1) = iobs;
+      end    
+    end 
+  end
+  if TeX
+    varlist_TeX = [];
+    for i=1:nvar
+      varlist_TeX = strvcat(varlist_TeX,lgy_TeX_(SelecVariables(i),:));
+    end
+  end
+  %%                                    %%
+  %% Now I treat the forecasts (plots)  %%   
+  %%                                    %%
+  if options_.forecast
+    tmp = zeros(B,1);
+    tmp_big = zeros(B,1);
+    fprintf('MH: Out of sample forecasts...\n');
+    MeanForecast = zeros(options_.forecast,nvar);
+    MedianForecast = zeros(options_.forecast,nvar);
+    StdForecast = zeros(options_.forecast,nvar);
+    HPD   = zeros(options_.forecast,nvar,2);
+    StdForecast_total = zeros(options_.forecast,nvar);
+    HPD_total   = zeros(options_.forecast,nvar,2);
+    for step = 1:options_.forecast % ... Suffering is one very long moment.
+      truestep = step+ykmin_;
+      for i = 1:nvar;
+	StartLine = 0;
+	StartLine1 = 0;
+	for file = 1:sfil_forc;
+	  load([fname_ '_forecast' int2str(file)]);
+	  MeanForecast(step,i) = MeanForecast(step,i)+sum(stock_forcst(truestep,SelecVariables(i),:),3);
+	  DeProfundis = size(stock_forcst,3); 
+	  DeProfundis1 = size(stock_forcst1,3); 
+	  tmp(StartLine+1:StartLine+DeProfundis) = squeeze(stock_forcst(truestep,SelecVariables(i),:)); 
+	  tmp_big(StartLine1+1:StartLine1+DeProfundis1) = squeeze(stock_forcst1(truestep,SelecVariables(i),:)); 
+	  StartLine = StartLine+DeProfundis;
+	  StartLine1 = StartLine1+DeProfundis1;
+	end
+	tmp = sort(tmp);
+	tmp_big = sort(tmp_big);
+	MedianForecast(step,i) = tmp(round(B*0.5));
+	StdForecast(step,i) = std(tmp);
+	StdForecast_total(step,i) = std(tmp_big);
+	t = floor(options_.mh_conf_sig*B);
+	a = 1; 
+	b = t;
+	tmp2 = [1;t;tmp(t)-tmp(1)];
+	while b <= B
+	  tmp1 = [a;b;tmp(b)-tmp(a)];
+	  a = a + 1;
+	  b = b + 1;
+	  if tmp1(3) < tmp2(3)
+	    tmp2 = tmp1;     
+	  end    
+	end
+	HPD(step,i,1) = tmp(tmp2(1));
+	HPD(step,i,2) = tmp(tmp2(2));
+	t = floor(options_.mh_conf_sig*B);
+	a = 1; 
+	b = t;
+	tmp2_big = [1;t;tmp_big(t)-tmp_big(1)];
+	while b <= B
+	  tmp1_big = [a;b;tmp_big(b)-tmp_big(a)];
+	  a = a + 1;
+	  b = b + 1;
+	  if tmp1_big(3) < tmp2_big(3)
+	    tmp2_big = tmp1_big;     
+	  end    
+	end
+	HPD_total(step,i,1) = tmp_big(tmp2_big(1));
+	HPD_total(step,i,2) = tmp_big(tmp2_big(2));
+      end
+      disp(['    Period = ' int2str(step)]);
+    end
+    MeanForecast = MeanForecast/B;
+    [nbplt,nr,nc,lr,lc,nstar] = pltorg(nvar);
+    if TeX
+      fidTeX = fopen([fname_ '_BayesianForecasts.TeX'],'w');
+      fprintf(fidTeX,'%% TeX eps-loader file generated by metropolis.m (Dynare).\n');
+      fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
+      fprintf(fidTeX,' \n');
+      NAMES = [];
+      TEXNAMES = [];
+    end    
+    for plt = 1:nbplt
+      if TeX
+    NAMES = [];
+    TEXNAMES = [];
+      end
+      hfig = figure('Name','Out of sample forecasts');
+      for i = 1:nstar
+    k = (plt-1)*nstar+i;
+    if k > nvar
+      break
+    end
+    subplot(nr,nc,i)
+    hold on
+    if any(k==IdObs)
+      idx = find(k==IdObs);
+      if options_.loglinear == 1
+        plot(1:10+options_.forecast,...
+             [exp(data(idx,size(data,2)-10+1:end))';...
+              MeanForecast(:,k)],'-b','linewidth',2)
+      else
+        plot(1:10+options_.forecast,...
+             [data(idx,size(data,2)-10+1:end)';...
+              MeanForecast(:,k)],'-b','linewidth',2)
+      end
+      offsetx = 10;
+    else
+      plot(1:options_.forecast,MeanForecast(:,k),'-b', ...
+         'linewidth',2)
+      offsetx = 0;
+    end   
+    plot(offsetx+[1:options_.forecast],HPD(:,k,1),'--g', ...
+         'linewidth',1.5)
+    plot(offsetx+[1:options_.forecast],HPD(:,k,2),'--g', ...
+         'linewidth',1.5)
+    plot(offsetx+[1:options_.forecast],HPD_total(:,k,1),'--r', ...
+         'linewidth',1.5)
+    plot(offsetx+[1:options_.forecast],HPD_total(:,k,2),'--r','linewidth',1.5)
+    set(gca,'XTick',offsetx+[1 10 20 30 40 50 60 70 80 90]);
+    set(gca,'XTickLabel',{'1';'10';'20';'30';'40';'50';'60';'70';'80';'90'});
+    %   xlim([1 options_.forecast+10]);
+    if any(k==IdObs)
+      plot([11 11],ylim,'-c')
+    end
+    box on
+    title(deblank(varlist(k,:)),'Interpreter','none')
+    hold off
+    eval(['oo_.Forecast.Mean.' deblank(varlist(k,:)) ' = MeanForecast(:,k)'';']);
+    eval(['oo_.Forecast.Median.' deblank(varlist(k,:)) ' = MedianForecast(:,k)'';']);
+    eval(['oo_.Forecast.Std.' deblank(varlist(k,:)) ' = StdForecast(:,k)'';']);
+    eval(['oo_.Forecast.HPDinf.' deblank(varlist(k,:)) ' = squeeze(HPD(:,k,1))'';']);
+    eval(['oo_.Forecast.HPDsup.' deblank(varlist(k,:)) ' = squeeze(HPD(:,k,2))'';']);
+    eval(['oo_.Forecast.HPDTotalinf.' deblank(varlist(k,:)) ' = squeeze(HPD_total(:,k,1))'';']);
+    eval(['oo_.Forecast.HPDTotalsup.' deblank(varlist(k,:)) ' = squeeze(HPD_total(:,k,2))'';']);
+    if TeX
+      NAMES = strvcat(NAMES,deblank(varlist(k,:)));
+      TEXNAMES = strvcat(TEXNAMES,['$ ' deblank(varlist_TeX(k,:)) ' $']);
+    end
+      end
+      eval(['print -depsc2 ' fname_ '_Forecasts' int2str(plt)]);
+      eval(['print -dpdf ' fname_ '_Forecasts' int2str(plt)]);
+      saveas(hfig,[fname_ '_Forecasts' int2str(plt) '.fig']);
+      if options_.nograph, close(hfig), end
+      if TeX
+    fprintf(fidTeX,'\\begin{figure}[H]\n');
+    for jj = 1:nstar
+      fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TEXNAMES(jj,:)));
+    end    
+    fprintf(fidTeX,'\\centering \n');
+    fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_Forecasts%s}\n',fname_,int2str(plt));
+    fprintf(fidTeX,'\\caption{DSGE posterior mean forecats with HPD intervals.}');
+    fprintf(fidTeX,'\\label{Fig:Forecasts:%s}\n',int2str(plt));
+    fprintf(fidTeX,'\\end{figure}\n');
+    fprintf(fidTeX,' \n');
+      end
+    end
+    fprintf('MH: Out of sample forecasts, done!\n')
+    disp(' ')
+  end
+  %%
+  %% Smooth variables and Filtered variables (all endogenous variables are considered here)        
+  %%
+  if options_.smoother
+    [MeanSmooth,MedianSmooth,StdSmooth,DistribSmooth,HPDSmooth] = GetPosteriorStatistics(gend,B,'SmoothedVariables');    
+    [MeanInnov,MedianInnov,StdInnov,DistribInnov,HPDInnov] = GetPosteriorStatistics(gend,B,'SmoothedShocks');
+    if nvn
+      [MeanError,MedianError,StdError,DistribError,HPDError] = GetPosteriorStatistics(gend,B,'SmoothedObservationErrors');
+    end
+    %%
+    %% Now I plot the smooth -structural- shocks
+    %%
+    MakeSmoothVariablesPlots('SmoothedShocks',DistribInnov,MeanInnov,gend)
+    %%
+    %% Smoothed variables (observed and unobserved)
+    %%
+    MakeSmoothVariablesPlots('SmoothedVariables',DistribSmooth,MeanSmooth,gend)
+    %%
+    %% Smoothed observation error
+    %%
+    if nvn
+      MakeSmoothVariablesPlots('SmoothedObservationErrors',DistribError,MeanError,gend)
+      %%
+      %% Historical and smoothed variabes
+      %%
+      MakeSmoothVariablesPlots('Historical&SmoothedObservableVariables',...
+                   MeanSmooth,rawdata(options_.first_obs+(0:gend-1),:),gend)
+    end  
+    %%
+    %%
+    %%
+  end % options_.smoother
+  if options_.filtered_vars % Filtered variables.
+    [MeanFilter,MedianFilter,StdFilter,DistribFilter,HPDFilter] = GetPosteriorStatistics(gend,B,'FilteredVariables');
+    MakeSmoothVariablesPlots('FilteredVariables',DistribFilter,MeanFilter,gend)
+  end          
+  %%
+  %%    Posterior IRFs. Instead of displaying the IRFs associated to the posterior mean
+  %%    of the structural parameters (by calling stoch_simul after estimation), 
+  %%    metropolis.m will display the posterior mean of the IRFs and the deciles of 
+  %%    the IRFs' posterior distribution. All the results are saved in the global 
+  %%    structure oo_ (posterior medians, posterior standard deviations and posterior HPD   
+  %%    intervals are also computed and saved).
+  %%
+  if options_.bayesian_irf
+    deep = MU;
+    subindx = subset();
+    nirfs = options_.irf;
+    if ~isempty(dsge_prior_weight)
+      files = eval(['dir(''' fname_ '_irf_dsgevar*.mat'');']);     
+      if length(files)                                        
+	delete([fname_ '_irf_dsgevar*.mat']);                    
+	disp(['MH: Old ' fname_ '_irf_dsgevar files deleted! ']) 
+      end
+      files = eval(['dir(''' fname_ '_irf_dsge*.mat'');']);     
+      if length(files)                                        
+	delete([fname_ '_irf_dsge*.mat']);                    
+	disp(['MH: Old ' fname_ '_irf_dsge files deleted! ']) 
+      end
+    else
+      files = eval(['dir(''' fname_ '_irf_dsge*.mat'');']);     
+      if length(files)                                        
+	delete([fname_ '_irf_dsge*.mat']);                    
+	disp(['MH: Old ' fname_ '_irf_dsge files deleted! ']) 
+      end      
+    end    
+    if B <= MAX_nirfs_dsge
+      stock_irf_dsge = zeros(nirfs,size(lgy_,1),exo_nbr,B);
+    elseif nvn & B > MAX_nirfs
+      stock_irf_dsge = zeros(nirfs,size(lgy_,1),exo_nbr,MAX_nirfs_dsge);
+    end
+    if ~isempty(dsge_prior_weight)
+      if B <= MAX_nirfs_dsgevar
+	stock_irf_dsgevar = zeros(nirfs,nvobs,exo_nbr,B);
+      else
+	stock_irf_dsgevar = zeros(nirfs,nvobs,exo_nbr,MAX_nirfs_dsgevar);
+      end
+      [mYY,mXY,mYX,mXX,Ydata,Xdata] = ...
+	  VarSampleMoments(options_.first_obs,options_.first_obs+options_.nobs-1,options_.varlag,-1);
+      NumberOfLags = options_.varlag;
+      NumberOfLagsTimesNvobs = NumberOfLags*nvobs;
+      COMP_draw = diag(ones(nvobs*(NumberOfLags-1),1),-nvobs);
+    end
+    h = waitbar(0,'Bayesian IRFs...');
+    if nfile-ffil+1>1
+      sfil_irf_dsge = 0;
+      irun_irf_dsge = 0;
+      sfil_irf_dsgevar = 0;
+      irun_irf_dsgevar = 0;
+      for b = 1:B;
+	irun_irf_dsge = irun_irf_dsge+1;
+	tmp_dsge = zeros(nirfs,size(lgy_,1),exo_nbr);
+	if ~isempty(dsge_prior_weight)
+	  irun_irf_dsgevar = irun_irf_dsgevar+1;
+	  tmp_dsgevar = zeros(nirfs,nvobs*exo_nbr);
+	end
+	choose_an_mh_file = rand;
+	mh_file_number = FLN(find(choose_an_mh_file>=FLN(:,3)),1);
+	if isempty(mh_file_number)
+	  mh_file_number = ffil;
+	else    
+	  mh_file_number = mh_file_number(1);
+	end
+	eval(['load ' instr1 int2str(mh_file_number) instr2]);
+	clear post2 logpo2;
+	DEEP  = x2(floor(rand*FLN(find(mh_file_number == FLN(:,1)),2))+1,:);
+	deep(subindx) = DEEP(subindx);
+	% dsge
+	set_parameters(deep);
+	dr_ = resol(ys_,0);
+	SS(lgx_orig_ord_,lgx_orig_ord_)=Sigma_e_+1e-14* ...
+	    eye(exo_nbr);
+	cs = transpose(chol(SS));
+	tit(lgx_orig_ord_,:) = lgx_;
+	for i = 1:exo_nbr
+	  if SS(i,i) > 1e-13
+	    y=irf(dr_,cs(lgx_orig_ord_,i),nirfs,options_.drop, ...
+		  options_.replic, options_.order);
+	    if options_.relative_irf
+	      y = 100*y/cs(i,i); 
+	    end
+	    for j = 1:size(lgy_,1)
+	      if max(y(j,:)) - min(y(j,:)) > 1e-10 
+		tmp_dsge(:,j,i) = transpose(y(j,:));
+	      end
+	    end
+	  end
+	end
+	if irun_irf_dsge < MAX_nirfs_dsge
+	  stock_irf_dsge(:,:,:,irun_irf_dsge) = tmp_dsge;
+	else
+	  stock_irf_dsge(:,:,:,irun_irf_dsge) = tmp_dsge;
+	  sfil_irf_dsge = sfil_irf_dsge + 1;
+	  instr = [fname_ '_irf_dsge' int2str(sfil_irf_dsge) ' stock_irf_dsge;'];
+	  eval(['save ' instr]);
+	  irun_irf_dsge = 0;
+	  stock_irf_dsge = zeros(nirfs,size(lgy_,1),exo_nbr,MAX_nirfs_dsge);
+	end
+	% bvar-dsge 
+	if ~isempty(dsge_prior_weight)
+	  [fval,cost_flag,ys,trend_coeff,info,PHI,SIGMAu,iXX] = DsgeVarLikelihood(deep',gend);
+	  DSGE_PRIOR_WEIGHT = floor(gend*(1+dsge_prior_weight));
+	  tmp1 = SIGMAu*gend*(dsge_prior_weight+1);
+          val  = 1;
+          tmp1 = chol(inv(tmp1))'; 
+	  while val;
+	    % draw from the marginal posterior of sig
+	    tmp2 = tmp1*randn(nvobs,DSGE_PRIOR_WEIGHT-NumberOfLagsTimesNvobs);
+	    SIGMAu_draw = inv(tmp2*tmp2');
+            % draw from the conditional posterior of PHI
+	    VARvecPHI = kron(SIGMAu_draw,iXX);
+	    PHI_draw  = PHI(:) + chol(VARvecPHI)'*randn(nvobs*NumberOfLagsTimesNvobs,1);
+	    COMP_draw(1:nvobs,:) = reshape(PHI_draw,NumberOfLagsTimesNvobs,nvobs)';
+	    % Check for stationarity
+	    tests = find(abs(eig(COMP_draw))>0.9999999999);
+	    if isempty(tests)
+	      val=0;
+	    end
+	  end
+	  % Get rotation
+	  if dsge_prior_weight > 0
+	    Atheta(dr_.order_var,:) = dr_.ghu*sqrt(Sigma_e_);
+	    A0 = Atheta(bayestopt_.mfys,:);
+	    [OMEGAstar,SIGMAtr] = qr2(A0');
+	  end
+          % SIGMAu_draw = A0*A0';
+	  SIGMAu_chol = chol(SIGMAu_draw)';
+	  SIGMAtrOMEGA = SIGMAu_chol*OMEGAstar';
+	  PHIpower = eye(NumberOfLagsTimesNvobs);
+	  irfs = zeros (nirfs,nvobs*exo_nbr);
+	  tmp3 = PHIpower(1:nvobs,1:nvobs)*SIGMAtrOMEGA;
+	  irfs(1,:) = tmp3(:)';
+	  for t = 2:nirfs
+	    PHIpower = COMP_draw*PHIpower;
+	    tmp3 = PHIpower(1:nvobs,1:nvobs)*SIGMAtrOMEGA;
+	    irfs(t,:)  = tmp3(:)';
+	  end            
+	  for j = 1:(nvobs*exo_nbr)
+	    if max(irfs(:,j)) - min(irfs(:,j)) > 1e-10 
+	      tmp_dsgevar(:,j) = (irfs(:,j));
+	    end
+	  end
+	  if irun_irf_dsgevar < MAX_nirfs_dsgevar
+	    stock_irf_dsgevar(:,:,:,irun_irf_dsgevar) = reshape(tmp_dsgevar,nirfs,nvobs,exo_nbr);
+	  else
+	    stock_irf_dsgevar(:,:,:,irun_irf_dsgevar) = reshape(tmp_dsgevar,nirfs,nvobs,exo_nbr);
+	    sfil_irf_dsgevar = sfil_irf_dsgevar + 1;
+	    instr = [fname_ '_irf_dsgevar' int2str(sfil_irf_dsgevar) ' stock_irf_dsgevar;'];,
+	    eval(['save ' instr]);
+	    irun_irf_dsgevar  = 0;
+	    stock_irf_dsgevar = zeros(nirfs,nvobs,exo_nbr,MAX_nirfs_dsgevar);
+	  end
+	end
+	waitbar(b/B,h);    
+      end
+      clear tmp;
+      if irun_irf_dsge
+	stock_irf_dsge = stock_irf_dsge(:,:,:,1:irun_irf_dsge);
+	sfil_irf_dsge = sfil_irf_dsge + 1;
+	instr = [fname_ '_irf_dsge' int2str(sfil_irf_dsge) ' stock_irf_dsge;'];
+	eval(['save ' instr]);
+      end
+      clear stock_irf_dsge;
+      if ~isempty(dsge_prior_weight)
+	if irun_irf_dsgevar
+	  stock_irf_dsgevar = stock_irf_dsgevar(:,:,:,1:irun_irf_dsgevar);
+	  sfil_irf_dsgevar = sfil_irf_dsgevar + 1;
+	  instr = [fname_ '_irf_dsgevar' int2str(sfil_irf_dsgevar) ' stock_irf_dsgevar;'];
+	  eval(['save ' instr]);
+	end
+	clear stock_irf_dsgevar;
+      end
+    else
+      sfil_irf_dsge = 0;
+      irun_irf_dsge = 0;
+      if ~isempty(dsge_prior_weight)
+	sfil_irf_dsgevar = 0;
+	irun_irf_dsgevar = 0;
+      end
+      eval(['load ' instr1 int2str(ffil) instr2]);
+      NumberOfSimulations = length(logpo2);
+      clear post2 logpo2;
+      for b = 1:B;
+	irun_irf_dsge = irun_irf_dsge+1;
+	tmp_dsge = zeros(nirfs,size(lgy_,1),exo_nbr);
+	if ~isempty(dsge_prior_weight)
+	  irun_irf_dsgevar = irun_irf_dsgevar+1;
+	  tmp_dsgevar = zeros(nirfs,nvobs*exo_nbr);	  
+	end
+	DEEP = x2(floor(rand*NumberOfSimulations)+1,:);
+	deep(subindx) = DEEP(subindx);
+	% dsge
+	set_parameters(deep);
+	dr_ = resol(ys_,0);
+	SS(lgx_orig_ord_,lgx_orig_ord_) = Sigma_e_+1e-14*eye(exo_nbr);
+	SS = transpose(chol(SS));
+	tit(lgx_orig_ord_,:) = lgx_;
+	for i = 1:exo_nbr
+	  if SS(i,i) > 1e-13
+	    y=irf(dr_,SS(lgx_orig_ord_,i), options_.irf, options_.drop, ...
+		  options_.replic, options_.order);
+	    if options_.relative_irf
+	      y = 100*y/cs(i,i); 
+	    end
+	    for j = 1:size(lgy_,1)
+	      if max(y(j,:)) - min(y(j,:)) > 1e-10 
+		tmp_dsge(:,j,i) = transpose(y(j,:));
+	      end
+	    end
+	  end
+	end
+	if irun_irf_dsge < MAX_nirfs_dsge
+	  stock_irf_dsge(:,:,:,irun_irf_dsge) = tmp_dsge;
+	else
+	  stock_irf_dsge(:,:,:,irun_irf_dsge) = tmp_dsge;
+	  sfil_irf_dsge = sfil_irf_dsge + 1;
+	  instr = [fname_ '_irf_dsge' int2str(sfil_irf_dsge) ' stock_irf_dsge;'];
+	  eval(['save ' instr]);
+	  irun_irf_dsge = 0;
+	  stock_irf_dsge = zeros(nirfs,size(lgy_,1),exo_nbr,MAX_nirfs_dsge);
+	end
+	% bvar-dsge
+	if ~isempty(dsge_prior_weight)
+	  [fval,cost_flag,ys,trend_coeff,info,PHI,SIGMAu,iXX] = DsgeVarLikelihood(deep',gend);
+	  DSGE_PRIOR_WEIGHT = floor(gend*(1+dsge_prior_weight));
+          tmp1 = SIGMAu*gend*(1+dsge_prior_weight);
+	  tmp1 = chol(inv(tmp1))';
+          val = 1;
+	  while val;
+	    % draw from the marginal posterior of sig
+	    tmp2 = tmp1*randn(nvobs,DSGE_PRIOR_WEIGHT-NumberOfLagsTimesNvobs);
+	    SIGMAu_draw = inv(tmp2*tmp2');
+	    % draw from the conditional posterior of PHI
+	    VARvecPHI = kron(SIGMAu_draw,iXX);
+	    PHI_draw  = PHI(:) + chol(VARvecPHI)'*randn(nvobs*NumberOfLagsTimesNvobs,1);
+	    COMP_draw(1:nvobs,:) = reshape(PHI_draw,NumberOfLagsTimesNvobs,nvobs)';
+	    % Check for stationarity
+	    tests = find(abs(eig(COMP_draw))>0.9999999999);
+	    if isempty(tests)
+	      val=0;
+	    end
+	  end
+	  % Get rotation
+	  if dsge_prior_weight > 0
+	    Atheta(dr_.order_var,:) = dr_.ghu*sqrt(Sigma_e_);
+	    A0 = Atheta(bayestopt_.mfys,:);
+	    [OMEGAstar,SIGMAtr] = qr2(A0');
+	  end
+	  SIGMAu_chol = chol(SIGMAu_draw)';
+	  SIGMAtrOMEGA = SIGMAu_chol*OMEGAstar';
+	  PHIpower = eye(NumberOfLagsTimesNvobs);
+	  irfs = zeros (nirfs,nvobs*exo_nbr);
+	  tmp3 = PHIpower(1:nvobs,1:nvobs)*SIGMAtrOMEGA;
+	  irfs(1,:) = tmp3(:)';
+	  for t = 2:nirfs
+	    PHIpower = COMP_draw*PHIpower;
+	    tmp3 = PHIpower(1:nvobs,1:nvobs)*SIGMAtrOMEGA;
+	    irfs(t,:)  = tmp3(:)';
+	  end
+	  for j = 1:(nvobs*exo_nbr)
+	    if max(irfs(:,j)) - min(irfs(:,j)) > 1e-10 
+	      tmp_dsgevar(:,j) = (irfs(:,j));
+	    end	
+	  end	
+	  if irun_irf_dsgevar < MAX_nirfs_dsgevar
+	    stock_irf_dsgevar(:,:,:,irun_irf_dsgevar) = reshape(tmp_dsgevar,nirfs,nvobs,exo_nbr);
+	  else
+	    stock_irf_dsgevar(:,:,:,irun_irf_dsgevar) = reshape(tmp_dsgevar,nirfs,nvobs,exo_nbr);
+	    sfil_irf_dsgevar = sfil_irf_dsgevar + 1;
+	    instr = [fname_ '_irf_dsgevar' int2str(sfil_irf_dsgevar) ' stock_irf_dsgevar;'];,
+	    eval(['save ' instr]);
+	    irun_irf_dsgevar = 0;
+	    stock_irf_dsgevar = zeros(nirfs,nvobs,exo_nbr,MAX_nirfs_dsgevar);
+	  end
+	end
+	waitbar(b/B,h);
+      end
+      if irun_irf_dsge
+	stock_irf_dsge = stock_irf_dsge(:,:,:,1:irun_irf_dsge);
+	sfil_irf_dsge = sfil_irf_dsge + 1;
+	instr = [fname_ '_irf_dsge' int2str(sfil_irf_dsge) ' stock_irf_dsge;'];
+	eval(['save ' instr]);
+      end
+      clear stock_irf_dsge;
+      if ~isempty(dsge_prior_weight)
+	if irun_irf_dsgevar
+	  stock_irf_dsgevar = stock_irf_dsgevar(:,:,:,1:irun_irf_dsgevar);
+	  sfil_irf_dsgevar = sfil_irf_dsgevar + 1;
+	  instr = [fname_ '_irf_dsgevar' int2str(sfil_irf_dsgevar) ' stock_irf_dsgevar;'];
+	  eval(['save ' instr]);
+	end
+	clear stock_irf_dsgevar;    
+      end
+    end
+    close(h)
+    %%
+    %%  Now i compute some statistics (mean, median, std, deciles, HPD intervals)
+    %%
+    %%  DSGE:
+    tmp = zeros(B,1);
+    MeanIRF_dsge = zeros(nirfs,nvar,exo_nbr);
+    MedianIRF_dsge = zeros(nirfs,nvar,exo_nbr);
+    StdIRF_dsge = zeros(nirfs,nvar,exo_nbr);
+    DistribIRF_dsge = zeros(nirfs,nvar,exo_nbr,9);
+    HPDIRF_dsge = zeros(nirfs,nvar,exo_nbr,2);
+    if ~isempty(dsge_prior_weight)
+      SelecVariables = bayestopt_.mfys;
+      nvar = length(SelecVariables);
+    end
+    fprintf('MH: Posterior IRFs (dsge)...\n')
+    for i = 1:exo_nbr
+      for j = 1:nvar
+	for k = 1:nirfs
+	  StartLine = 0;
+	  for file = 1:sfil_irf_dsge;
+	    instr = [fname_ '_irf_dsge' int2str(file)];
+	    eval(['load ' instr]);
+	    MeanIRF_dsge(k,j,i) = MeanIRF_dsge(k,j,i)+sum(stock_irf_dsge(k,SelecVariables(j),i,:),4);
+	    DeProfundis = size(stock_irf_dsge,4); 
+	    tmp(StartLine+1:StartLine+DeProfundis) = squeeze(stock_irf_dsge(k,SelecVariables(j),i,:)); 
+	    StartLine = StartLine+DeProfundis;
+	  end
+	  tmp = sort(tmp);
+	  MedianIRF_dsge(k,j,i) = tmp(round(B*0.5));
+	  StdIRF_dsge(k,j,i) = std(tmp);
+	  DistribIRF_dsge(k,j,i,:) = reshape(tmp(deciles),1,1,1,9);
+	  tt = floor(options_.mh_conf_sig*B);
+	  a = 1; 
+	  b = tt;
+	  tmp2 = [1;tt;tmp(tt)-tmp(1)];
+	  while b <= B
+	    tmp1 = [a;b;tmp(b)-tmp(a)];
+	    a = a + 1;
+	    b = b + 1;
+	    if tmp1(3,1) < tmp2(3,1)
+	      tmp2 = tmp1;     
+	    end
+	  end
+	  HPDIRF_dsge(k,j,i,1) = tmp(tmp2(1,1));
+	  HPDIRF_dsge(k,j,i,2) = tmp(tmp2(2,1));
+	end
+	disp(['    Variable: ' deblank(lgy_(SelecVariables(j),:)) ', orthogonalized shock to ' deblank(tit(i,:))])  
+      end
+    end
+    clear stock_irf_dsge;
+    MeanIRF_dsge = MeanIRF_dsge/B;
+    for i = 1:exo_nbr
+      for j = 1:nvar
+	eval(['oo_.PosteriorIRF.Dsge.Mean.' ...
+	      deblank(lgy_(SelecVariables(j),:)) '_' deblank(tit(i,:)) ' = MeanIRF_dsge(:,j,i);']);
+	eval(['oo_.PosteriorIRF.Dsge.Median.' ...
+	      deblank(lgy_(SelecVariables(j),:)) '_' deblank(tit(i,:)) ' = MedianIRF_dsge(:,j,i);']);
+	eval(['oo_.PosteriorIRF.Dsge.Std.' ...
+	      deblank(lgy_(SelecVariables(j),:)) '_' deblank(tit(i,:)) ' = StdIRF_dsge(:,j,i);']);
+	eval(['oo_.PosteriorIRF.Dsge.Distribution.' ...
+	      deblank(lgy_(SelecVariables(j),:)) '_' deblank(tit(i,:)) ' = squeeze(DistribIRF_dsge(:,j,i,:));']);
+	eval(['oo_.PosteriorIRF.Dsge.HPDinf.' ...
+	      deblank(lgy_(SelecVariables(j),:)) '_' deblank(tit(i,:)) ' = squeeze(HPDIRF_dsge(:,j,i,1));']);
+	eval(['oo_.PosteriorIRF.Dsge.HPDsup.' ...
+	      deblank(lgy_(SelecVariables(j),:)) '_' deblank(tit(i,:)) ' = squeeze(HPDIRF_dsge(:,j,i,2));']);
+      end
+    end
+    if ~isempty(dsge_prior_weight)% BVAR-DSGE:
+      tmp = zeros(B,1);
+      MeanIRF_dsgevar = zeros(nirfs,nvar,exo_nbr);
+      MedianIRF_dsgevar = zeros(nirfs,nvar,exo_nbr);
+      StdIRF_dsgevar = zeros(nirfs,nvar,exo_nbr);
+      DistribIRF_dsgevar = zeros(nirfs,nvar,exo_nbr,9);
+      HPDIRF_dsgevar = zeros(nirfs,nvar,exo_nbr,2);
+      disp('')
+      fprintf('MH: Posterior IRFs (bvar-dsge)...\n')
+      for i = 1:exo_nbr
+	for j = 1:nvobs
+	  for k = 1:nirfs
+	    StartLine = 0;
+	    for file = 1:sfil_irf_dsgevar
+	      instr = [fname_ '_irf_dsgevar' int2str(file)];
+	      eval(['load ' instr]);
+	      MeanIRF_dsgevar(k,j,i) = MeanIRF_dsgevar(k,j,i)+sum(stock_irf_dsgevar(k,j,i,:),4);
+	      DeProfundis = size(stock_irf_dsgevar,4); 
+	      tmp(StartLine+1:StartLine+DeProfundis) = squeeze(stock_irf_dsgevar(k,j,i,:)); 
+	      StartLine = StartLine+DeProfundis;
+	    end
+	    tmp = sort(tmp);
+	    MedianIRF_dsgevar(k,j,i) = tmp(round(B*0.5));
+	    StdIRF_dsgevar(k,j,i) = std(tmp);
+	    DistribIRF_dsgevar(k,j,i,:) = reshape(tmp(deciles),1,1,1,9);
+	    tt = floor(options_.mh_conf_sig*B);
+	    a = 1; 
+	    b = tt;
+	    tmp2 = [1;tt;tmp(tt)-tmp(1)];
+	    while b <= B
+	      tmp1 = [a;b;tmp(b)-tmp(a)];
+	      a = a + 1;
+	      b = b + 1;
+	      if tmp1(3,1) < tmp2(3,1)
+		tmp2 = tmp1;     
+	      end    
+	    end
+	    HPDIRF_dsgevar(k,j,i,1) = tmp(tmp2(1,1));
+	    HPDIRF_dsgevar(k,j,i,2) = tmp(tmp2(2,1));
+	  end
+	  disp(['    Variable: ' deblank(options_.varobs(j,:)) ', orthogonalized shock to ' deblank(tit(i,:))])  
+	end   
+      end
+      clear stock_irf_dsgevar;
+      MeanIRF_dsgevar = MeanIRF_dsgevar/B;
+      for i = 1:exo_nbr
+	for j = 1:nvobs
+	  eval(['oo_.PosteriorIRF.BvarDsge.Mean.' ...
+		deblank(options_.varobs(j,:)) '_' deblank(tit(i,:)) ' = MeanIRF_dsgevar(:,j,i);']);
+	  eval(['oo_.PosteriorIRF.BvarDsge.Median.' ...
+		deblank(options_.varobs(j,:)) '_' deblank(tit(i,:)) ' = MedianIRF_dsgevar(:,j,i);']);
+	  eval(['oo_.PosteriorIRF.BvarDsge.Std.' ...
+		deblank(options_.varobs(j,:)) '_' deblank(tit(i,:)) ' = StdIRF_dsgevar(:,j,i);']);
+	  eval(['oo_.PosteriorIRF.BvarDsge.Distribution.' ...
+		deblank(options_.varobs(j,:)) '_' deblank(tit(i,:)) ' = squeeze(DistribIRF_dsgevar(:,j,i,:));']);
+	  eval(['oo_.PosteriorIRF.BvarDsge.HPDinf.' ...
+		deblank(options_.varobs(j,:)) '_' deblank(tit(i,:)) ' = squeeze(HPDIRF_dsgevar(:,j,i,1));']);
+	  eval(['oo_.PosteriorIRF.BvarDsge.HPDsup.' ...
+		deblank(options_.varobs(j,:)) '_' deblank(tit(i,:)) ' = squeeze(HPDIRF_dsgevar(:,j,i,2));']);
+	end
+      end
+    end
+    %%
+    %%  Finally I build the plots.
+    %%
+    if TeX
+      fidTeX = fopen([fname_ '_BayesianIRF.TeX'],'w');
+      fprintf(fidTeX,'%% TeX eps-loader file generated by metropolis.m (Dynare).\n');
+      fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
+      fprintf(fidTeX,' \n');
+    end
+    tit(lgx_orig_ord_,:) = lgx_;
+    if TeX; titTeX(lgx_orig_ord_,:) = lgx_TeX_; end;
+    for i=1:exo_nbr
+      number_of_plots_to_draw = 0;
+      index = [];
+      if ~~isempty(dsge_prior_weight) 
+	for j=1:nvar
+	  if MeanIRF_dsge(1,j,i)
+	    number_of_plots_to_draw = number_of_plots_to_draw + 1;
+	    index = cat(1,index,j);
+	  end
+	end
+      else% BVAR-DSGE
+	number_of_plots_to_draw = nvar;
+	index = (1:nvar)';
+      end
+      [nbplt,nr,nc,lr,lc,nstar] = pltorg(number_of_plots_to_draw);  
+      if nbplt == 1
+	if options_.relative_irf
+	  hh = figure('Name',['Relative response to orthogonalized shock to ' tit(i,:)]);
+	else
+	  hh = figure('Name',['Orthogonalized shock to ' tit(i,:)]);
+	end
+	NAMES = [];
+	if TeX; TEXNAMES = []; end;
+	for j=1:number_of_plots_to_draw
+	  set(0,'CurrentFigure',hh)
+	  subplot(nr,nc,j);
+	  plot([1 nirfs],[0 0],'-r','linewidth',0.5);% zero line.
+	  hold on
+	  for k = 1:9
+	    plot(1:nirfs,DistribIRF_dsge(:,index(j),i,k),'-k','linewidth',0.5,'Color',[0 0 0])
+	    if ~isempty(dsge_prior_weight)
+	      plot(1:nirfs,DistribIRF_dsgevar(:,j,i,k),'-k','linewidth',0.5,'Color',[0.80 0.80 0.80])
+	    end
+	  end
+	  plot(1:nirfs,MeanIRF_dsge(:,index(j),i),'-k','linewidth',3,'Color',[0 ...
+		    0 0])
+	  if ~isempty(dsge_prior_weight)
+	    plot(1:nirfs,MeanIRF_dsgevar(:,j,i),'-k','linewidth',3,'Color',[0.80 ...
+		    0.80 0.80])
+	  end
+	  xlim([1 nirfs]);
+	  hold off
+	  name = deblank(lgy_(SelecVariables(index(j)),:));
+	  NAMES = strvcat(NAMES,name);
+	  if TeX
+	    texname = deblank(lgy_TeX_(SelecVariables(index(j)),:));
+	    TEXNAMES = strvcat(TEXNAMES,['$' texname '$']);
+	  end
+	  title(name,'Interpreter','none')
+	end
+	if isempty(dsge_prior_weight)
+	  eval(['print -depsc2 ' fname_ '_Bayesian_IRFdsge_' deblank(tit(i,:))]);
+	  eval(['print -dpdf ' fname_  '_Bayesian_IRFdsge_' deblank(tit(i,:))]);
+	  saveas(hh,[fname_  '_Bayesian_IRFdsge_' deblank(tit(i,:)) '.fig']);
+	else
+	  eval(['print -depsc2 ' fname_ '_Bayesian_IRFbvardsge_' deblank(tit(i,:))]);
+	  eval(['print -dpdf ' fname_  '_Bayesian_IRFbvardsge_' deblank(tit(i,:))]);
+	  saveas(hh,[fname_  '_Bayesian_IRFbvardsge_' deblank(tit(i,:)) '.fig']);	  
+	end
+	if options_.nograph, close(hh), end
+	if TeX
+	  fprintf(fidTeX,'\\begin{figure}[H]\n');
+	  for jj = 1:number_of_plots_to_draw
+	    fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{%s}\n'],deblank(NAMES(jj,:)),deblank(TEXNAMES(jj,:)));
+	  end    
+	  fprintf(fidTeX,'\\centering \n');
+	  if ~~isempty(dsge_prior_weight)
+	    fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_Bayesian_IRFdsge_%s}\n',fname_,deblank(tit(i,:)));
+	  else
+	    fprintf(fidTeX,['\\includegraphics[scale=0.5]{%s_Bayesian_IRFbvardsge_%s}\n',fname_,deblank(tit(i,:))]);
+	  end  
+	  if options_.relative_irf
+	    fprintf(fidTeX,['\\caption{Bayesian relative IRF.}']);
+	  else
+	    if ~~isempty(dsge_prior_weight)
+	      fprintf(fidTeX,'\\caption{Bayesian IRF (DSGE model).}');
+	    else
+	      fprintf(fidTeX,'\\caption{Bayesian IRF (BVAR-DSGE model).}');
+	    end
+	  end
+	  if ~~isempty(dsge_prior_weight)
+	    fprintf(fidTeX,'\\label{Fig:BayesianIRFdsge:%s}\n',deblank(tit(i,:)));
+	  else
+	    fprintf(fidTeX,'\\label{Fig:BayesianIRFbvardsge:%s}\n',deblank(tit(i,:)));
+	  end  
+	  fprintf(fidTeX,'\\end{figure}\n');
+	  fprintf(fidTeX,' \n');
+	end    
+      elseif nbplt > 1
+	for fig = 1:nbplt-1
+	  if options_.relative_irf
+	    hh = figure('Name',['Relative response to orthogonalized' ...
+				' shock to ' tit(i,:) ' figure ' int2str(fig) '.']);
+	  else
+	    hh = figure('Name',['Orthogonalized shock to ' tit(i,:) ...
+				' figure ' int2str(fig) '.']);
+	  end
+	  NAMES = [];
+	  if TeX; TEXNAMES = []; end;
+	  for j=1:nstar
+	    jj = (fig-1)*nstar + j;
+	    subplot(nr,nc,j);
+	    plot([1 nirfs],[0 0],'-r','linewidth',0.5)
+	    hold on
+	    for k = 1:9
+	      plot(1:options_.irf,DistribIRF_dsge(:,index(jj),i,k),'-k','linewidth',0.5,'Color',[0 0 0])
+	      if ~isempty(dsge_prior_weight)
+		plot(1:nirfs,DistribIRF_dsgevar(:,jj,i,k),'-k','linewidth',0.5,'Color',[0.80 0.80 0.80])
+	      end
+	    end
+	    plot(1:nirfs,MeanIRF_dsge(:,index(jj),i),'-k','linewidth',3,'Color',[0 0 0])
+	    if ~isempty(dsge_prior_weight)
+	      plot(1:nirfs,MeanIRF_dsgevar(:,jj,i),'-k','linewidth',3,'Color',[0.80 0.80 0.80])
+	    end
+	    xlim([1 nirfs]);
+	    hold off
+	    name = deblank(lgy_(SelecVariables(index(jj)),:));
+	    NAMES = strvcat(NAMES,name);
+	    if TeX
+	      texname = deblank(lgy_TeX_(SelecVariables(index(jj)),:));
+	      TEXNAMES   = strvcat(TEXNAMES,['$' texname '$']);
+	    end
+	    title(name,'Interpreter','none')
+	  end
+	  if ~~isempty(dsge_prior_weight)
+	    eval(['print -depsc2 ' fname_ '_Bayesian_IRFdsge_' deblank(tit(i,:)) int2str(fig)]);
+	    eval(['print -dpdf ' fname_  '_Bayesian_IRFdsge_' deblank(tit(i,:)) int2str(fig)]);
+	    saveas(hh,[fname_  '_Bayesian_IRFdsge_' deblank(tit(i,:)) int2str(fig) '.fig']);
+	  else
+	    eval(['print -depsc2 ' fname_ '_Bayesian_IRFbvardsge_' deblank(tit(i,:)) int2str(fig)]);
+	    eval(['print -dpdf ' fname_  '_Bayesian_IRFbvardsge_' deblank(tit(i,:)) int2str(fig)]);
+	    saveas(hh,[fname_  '_Bayesian_IRFbvardsge_' deblank(tit(i,:)) int2str(fig) '.fig']);
+	  end
+	  if options_.nograph, close(hh), end
+	  if TeX
+	    fprintf(fidTeX,'\\begin{figure}[H]\n');
+	    for jj = 1:nstar
+	      fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{%s}\n'],deblank(NAMES(jj,:)),deblank(TEXNAMES(jj,:)));
+	    end    
+	    fprintf(fidTeX,'\\centering \n');
+	    if ~~isempty(dsge_prior_weight)
+	      fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_Bayesian_IRFdsge_%s%s}\n',fname_,deblank(tit(i,:)),int2str(fig));
+	    else
+	      fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_Bayesian_IRFbvardsge_%s%s}\n',fname_,deblank(tit(i,:)),int2str(fig));
+	    end
+	    if options_.relative_irf == 1
+	      fprintf(fidTeX,['\\caption{Bayesian relative IRF.}']);
+	    else
+	      if ~~isempty(dsge_prior_weight)
+		fprintf(fidTeX,'\\caption{Bayesian IRF (DSGE model).}');
+	      else
+		fprintf(fidTeX,['\\caption{Bayesian IRF (BVAR-DSGE model).}']);
+	      end
+	    end
+	    if ~~isempty(dsge_prior_weight)
+	      fprintf(fidTeX,'\\label{Fig:BayesianIRFdsge:%s:%s}\n',deblank(tit(i,:)), int2str(fig));
+	    else
+	      fprintf(fidTeX,'\\label{Fig:BayesianIRFbvardsge:%s:%s}\n',deblank(tit(i,:)), int2str(fig));
+	    end
+	    fprintf(fidTeX,'\\end{figure}\n');
+	    fprintf(fidTeX,' \n');
+	  end    
+	end
+	hh = figure('Name',['Orthogonalized shock to ' tit(i,:) ' figure ' int2str(nbplt) '.']);
+	NAMES = [];
+	if TeX; TEXNAMES = []; end;
+	for j=1:number_of_plots_to_draw -(nbplt-1)*nstar
+	  jj = (nbplt-1)*nstar + j;
+	  subplot(nr,nc,j);
+	  plot([1 nirfs],[0 0],'-r','linewidth',0.5);
+	  hold on
+	  for k = 1:9
+	    plot(1:options_.irf,DistribIRF_dsge(:,index(jj),i,k),'-k','linewidth',0.5,'Color',[0 0 0])
+	    if ~isempty(dsge_prior_weight)
+	      plot(1:nirfs,DistribIRF_dsgevar(:,jj,i,k),'-k','linewidth',0.5,'Color',[0.80 0.80 0.80])
+	    end
+	  end
+	  plot(1:nirfs,MeanIRF_dsge(:,index(jj),i),'-k','linewidth',3,'Color',[0 0 0])
+	  if ~isempty(dsge_prior_weight)
+	    plot(1:nirfs,MeanIRF_dsgevar(:,jj,i),'-k','linewidth',3,'Color',[0.80 0.80 0.80])
+	  end  
+	  xlim([1 nirfs]);
+	  hold off
+	  name = deblank(lgy_(SelecVariables(index(jj)),:));
+	  NAMES = strvcat(NAMES,name);
+	  if TeX
+	    texname = deblank(lgy_TeX_(SelecVariables(index(jj)),:));
+	    TEXNAMES   = strvcat(TEXNAMES,['$' texname '$']);
+	  end
+	  title(name,'Interpreter','none')
+	end
+	if ~~isempty(dsge_prior_weight)
+	  eval(['print -depsc2 ' fname_ '_Bayesian_IRFdsge_' deblank(tit(i,:)) int2str(nbplt)]);
+	  eval(['print -dpdf ' fname_  '_Bayesian_IRFdsge_' deblank(tit(i,:)) int2str(nbplt)]);
+	  saveas(hh,[fname_  '_Bayesian_IRFdsge_' deblank(tit(i,:)) int2str(nbplt) '.fig']);
+	else
+	  eval(['print -depsc2 ' fname_ '_Bayesian_IRFbvardsge_' deblank(tit(i,:)) int2str(nbplt)]);
+	  eval(['print -dpdf ' fname_  '_Bayesian_IRFbvardsge_' deblank(tit(i,:)) int2str(nbplt)]);
+	  saveas(hh,[fname_  '_Bayesian_IRFbvardsge_' deblank(tit(i,:)) int2str(nbplt) '.fig']);	  
+	end  
+	  if options_.nograph, close(hh), end
+	if TeX
+	  fprintf(fidTeX,'\\begin{figure}[H]\n');
+	  for jj = 1:nstar
+	    fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{%s}\n'],deblank(NAMES(jj,:)),deblank(TEXNAMES(jj,:)));
+	  end    
+	  fprintf(fidTeX,'\\centering \n');
+	  if ~~isempty(dsge_prior_weight)
+	    fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_Bayesian_IRFdsge_%s%s}\n',fname_,deblank(tit(i,:)),int2str(nbplt));
+	    fprintf(fidTeX,'\\caption{Bayesian IRF (DSGE model).}');
+	    fprintf(fidTeX,'\\label{Fig:BayesianIRFdsge:%s:%s}\n',deblank(tit(i,:)), int2str(nbplt));
+	  else
+	    fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_Bayesian_IRFbvardsge_%s%s}\n',fname_,deblank(tit(i,:)),int2str(nbplt));
+	    fprintf(fidTeX,'\\caption{Bayesian IRF (BVAR-DSGE model).}');
+	    fprintf(fidTeX,'\\label{Fig:BayesianIRF:%s:%s}\n',deblank(tit(i,:)), int2str(nbplt));
+	  end
+	  fprintf(fidTeX,'\\end{figure}\n');
+	  fprintf(fidTeX,' \n');
+	end    
+      else % nbplt = 0
+	disp('There''s nothing to plot here!')
+      end
+    end
+    if TeX
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end
+    fprintf('MH: Posterior IRFs, done!\n');
+  end
+  %%
+  %%    Posterior theoretical moments. Instead of displaying the posterior moments 
+  %%  associated to the posterior mean of the structural parameters (by calling 
+  %%  stoch_simul after estimation), metropolis.m will display the posterior mean 
+  %%  of the theoretical moments and the posterior HPD intervals of theoretical
+  %%  moments. All the results are saved in the global structure oo_ (posterior 
+  %%  medians, posterior standard deviations and posterior deciles are also
+  %%    computed and saved).
+  %%
+  if ~isempty(options_.unit_root_vars)
+    vartan = []; 
+    for i=1:nvar
+      if isempty(strmatch(deblank(varlist(i,:)),options_.unit_root_vars,'exact'))       
+	vartan = strvcat(vartan,varlist(i,:));
+      end
+    end
+  else
+    vartan = varlist;
+  end
+  if options_.moments_varendo & ~isempty(vartan)
+    deep = MU;
+    subindx = subset();
+    nvar    = size(vartan,1);
+    ivar = zeros(nvar,1);
+    for i = 1:nvar
+      ivar(i) = strmatch(vartan(i,:),lgy_,'exact');
+    end
+    nar = options_.ar;
+    if B <= MAX_nthm1
+      stock_thm1 = zeros(nvar,B);
+    elseif B > MAX_nthm1
+      stock_thm1 = zeros(nvar,MAX_nthm1);
+    end
+    if B <= MAX_nthm2
+      stock_thm2 = zeros(nvar,nvar,B);
+    elseif B > MAX_nthm2
+      stock_thm2 = zeros(nvar,nvar,MAX_nthm2);
+    end
+    if B <= MAX_nthm3
+      stock_thm3 = zeros(nvar,exo_nbr,B);
+    elseif B > MAX_nthm3
+      stock_thm3 = zeros(nvar,exo_nbr,MAX_nthm3);
+    end
+    if B <= MAX_nthm4
+      stock_thm4 = zeros(nvar,nar,B);
+    elseif B > MAX_nthm4
+      stock_thm4 = zeros(nvar,nar,MAX_nthm4);
+    end
+    h = waitbar(0,'Posterior theoretical moments...');
+    if nfile-ffil+1>1
+      sfil_thm1 = 0;
+      irun_thm1 = 0;
+      sfil_thm2 = 0;
+      irun_thm2 = 0;
+      sfil_thm3 = 0;
+      irun_thm3 = 0;
+      sfil_thm4 = 0;
+      irun_thm4 = 0;
+      for b = 1:B;
+	irun_thm1 = irun_thm1+1;
+	irun_thm2 = irun_thm2+1;
+	irun_thm3 = irun_thm3+1;
+	irun_thm4 = irun_thm4+1;
+	choose_an_mh_file = rand;
+	mh_file_number = ...
+	    FLN(find(choose_an_mh_file>=FLN(:,3)),1);
+	if isempty(mh_file_number)
+	  mh_file_number = ffil;
+	else    
+	  mh_file_number = mh_file_number(1);
+	end    
+	eval(['load ' instr1 int2str(mh_file_number) instr2]);
+	clear post2 logpo2;
+	DEEP  = x2(floor(rand*FLN(find(mh_file_number == FLN(:,1)),2))+1,:);
+	deep(subindx) = DEEP(subindx);
+	set_parameters(deep);
+	dr_ = resol(ys_,0);
+	Gamma_y = th_autocovariances(dr_,ivar);
+	if options_.order == 2
+	  m_mean = dr_.ys(ivar) + Gamma_y{options_.ar+3};
+	else
+	  m_mean = dr_.ys(ivar);
+	end
+	variance =  Gamma_y{1};
+	if irun_thm1 < MAX_nthm1
+	  stock_thm1(:,irun_thm1) = m_mean;
+	else
+	  stock_thm1(:,irun_thm1) = m_mean;
+	  sfil_thm1 = sfil_thm1 + 1;
+	  instr = [fname_ '_thm1' int2str(sfil_thm1) ' stock_thm1;'];
+	  eval(['save ' instr]);
+	  irun_thm1 = 0;
+	  stock_thm1 = zeros(nvar,MAX_nthm1);
+	end
+	if irun_thm2 < MAX_nthm2
+	  stock_thm2(:,:,irun_thm2) = variance;
+	else
+	  stock_thm2(:,:,irun_thm2) = variance;
+	  sfil_thm2 = sfil_thm2 + 1;
+	  instr = [fname_ '_thm2' int2str(sfil_thm2) ' stock_thm2;'];
+	  eval(['save ' instr]);
+	  irun_thm2 = 0;
+	  stock_thm2 = zeros(nvar,nvar,MAX_nthm2);
+	end
+	if irun_thm3 < MAX_nthm3
+	  stock_thm3(:,:,irun_thm3) = Gamma_y{nar+2};
+	else
+	  stock_thm3(:,:,irun_thm3) = Gamma_y{nar+2};
+	  sfil_thm3 = sfil_thm3 + 1;
+	  instr = [fname_ '_thm3' int2str(sfil_thm3) ' stock_thm3;'];
+	  eval(['save ' instr]);
+	  irun_thm3 = 0;
+	  stock_thm3 = zeros(nvar,exo_nbr,MAX_nthm3);
+	end
+	if irun_thm4 < MAX_nthm4
+	  for lag = 1:nar
+	    stock_thm4(:,lag,irun_thm4) = diag(Gamma_y{1+lag});
+	  end	
+	else
+	  for lag = 1:nar
+	    stock_thm4(:,lag,irun_thm4) = diag(Gamma_y{1+lag});
+	  end	
+	  sfil_thm4 = sfil_thm4 + 1;
+	  instr = [fname_ '_thm4' int2str(sfil_thm4) ' stock_thm4;'];
+	  eval(['save ' instr]);
+	  irun_thm4 = 0;
+	  stock_thm4 = zeros(nvar,nar,MAX_nthm4);
+	end
+	waitbar(b/B,h);    
+      end
+      clear m_mean variance Gamma_y;
+      if irun_thm1
+	stock_thm1 = stock_thm1(:,1:irun_thm1);
+	sfil_thm1 = sfil_thm1 + 1;
+	instr = [fname_ '_thm1' int2str(sfil_thm1) ' stock_thm1;'];
+	eval(['save ' instr]);
+      end
+      clear stock_thm1;
+      if irun_thm2
+	stock_thm2 = stock_thm2(:,:,1:irun_thm2);
+	sfil_thm2 = sfil_thm2 + 1;
+	instr = [fname_ '_thm2' int2str(sfil_thm2) ' stock_thm2;'];
+	eval(['save ' instr]);
+      end
+      clear stock_thm2;
+      if irun_thm3
+	stock_thm3 = stock_thm3(:,:,1:irun_thm3);
+	sfil_thm3 = sfil_thm3 + 1;
+	instr = [fname_ '_thm3' int2str(sfil_thm3) ' stock_thm3;'];
+	eval(['save ' instr]);
+      end
+      clear stock_thm3;
+      if irun_thm4
+	stock_thm4 = stock_thm4(:,:,1:irun_thm4);
+	sfil_thm4 = sfil_thm4 + 1;
+	instr = [fname_ '_thm4' int2str(sfil_thm4) ' stock_thm4;'];
+	eval(['save ' instr]);
+      end
+      clear stock_thm4;
+    else        
+      sfil_thm1 = 0;
+      irun_thm1 = 0;
+      sfil_thm2 = 0;
+      irun_thm2 = 0;
+      sfil_thm3 = 0;
+      irun_thm3 = 0;
+      sfil_thm4 = 0;
+      irun_thm4 = 0;
+      eval(['load ' instr1 int2str(ffil) instr2]);
+      NumberOfSimulations = length(logpo2);
+      clear post2 logpo2;
+      ivar1 = find(ismember(ivar,bayestopt_.i_var_stable));
+      ivar1 = ivar(ivar1);
+      for b = 1:B;
+	irun_thm1 = irun_thm1+1;
+	irun_thm2 = irun_thm2+1;
+	irun_thm3 = irun_thm3+1;
+	irun_thm4 = irun_thm4+1;
+	DEEP  = x2(floor(rand*NumberOfSimulations)+1,:);
+	deep(subindx) = DEEP(subindx);
+	set_parameters(deep);
+	dr_ = resol(ys_,0);
+	Gamma_y = th_autocovariances(dr_,ivar1);
+	if options_.order == 2
+	  m_mean = dr_.ys(ivar) + Gamma_y{options_.ar+3};
+	else
+	  m_mean = dr_.ys(ivar);
+	end
+	variance = Gamma_y{1};
+	if irun_thm1 < MAX_nthm1
+	  stock_thm1(:,irun_thm1) = m_mean;
+	else
+	  stock_thm1(:,irun_thm1) = m_mean;
+	  sfil_thm1 = sfil_thm1 + 1;
+	  instr = [fname_ '_thm1' int2str(sfil_thm1) ' stock_thm1;'];
+	  eval(['save ' instr]);
+	  irun_thm1 = 0;
+	  stock_thm1 = zeros(nvar,MAX_nthm1);
+	end
+	if irun_thm2 < MAX_nthm2
+	  stock_thm2(:,:,irun_thm2) = variance;
+	else
+	  stock_thm2(:,:,irun_thm2) = variance;
+	  sfil_thm2 = sfil_thm2 + 1;
+	  instr = [fname_ '_thm2' int2str(sfil_thm2) ' stock_thm2;'];
+	  eval(['save ' instr]);
+	  irun_thm2 = 0;
+	  stock_thm2 = zeros(nvar,nvar,MAX_nthm2);
+	end
+	if irun_thm3 < MAX_nthm3
+	  stock_thm3(:,:,irun_thm3) = Gamma_y{nar+2};
+	else
+	  stock_thm3(:,:,irun_thm3) = Gamma_y{nar+2};
+	  sfil_thm3 = sfil_thm3 + 1;
+	  instr = [fname_ '_thm3' int2str(sfil_thm3) ' stock_thm3;'];
+	  eval(['save ' instr]);
+	  irun_thm3 = 0;
+	  stock_thm3 = zeros(nvar,exo_nbr,MAX_nthm3);
+	end
+	if irun_thm4 < MAX_nthm4
+	  for lag = 1:nar
+	    stock_thm4(:,lag,irun_thm4) = diag(Gamma_y{1+lag});
+	  end	
+	else
+	  for lag = 1:nar
+	    stock_thm4(:,lag,irun_thm4) = diag(Gamma_y{1+lag});
+	  end	
+	  sfil_thm4 = sfil_thm4 + 1;
+	  instr = [fname_ '_thm4' int2str(sfil_thm4) ' stock_thm4;'];
+	  eval(['save ' instr]);
+	  irun_thm4 = 0;
+	  stock_thm4 = zeros(nvar,nar,MAX_nthm4);
+	end
+	waitbar(b/B,h);    
+      end
+      clear m_mean variance Gamma_y;
+      if irun_thm1
+	stock_thm1 = stock_thm1(:,1:irun_thm1);
+	sfil_thm1 = sfil_thm1 + 1;
+	instr = [fname_ '_thm1' int2str(sfil_thm1) ' stock_thm1;'];
+	eval(['save ' instr]);
+      end
+      clear stock_thm1;
+      if irun_thm2
+	stock_thm2 = stock_thm2(:,:,1:irun_thm2);
+	sfil_thm2 = sfil_thm2 + 1;
+	instr = [fname_ '_thm2' int2str(sfil_thm2) ' stock_thm2;'];
+	eval(['save ' instr]);
+      end
+      clear stock_thm2;
+      if irun_thm3
+	stock_thm3 = stock_thm3(:,:,1:irun_thm3);
+	sfil_thm3 = sfil_thm3 + 1;
+	instr = [fname_ '_thm3' int2str(sfil_thm3) ' stock_thm3;'];
+	eval(['save ' instr]);
+      end
+      clear stock_thm3;
+      if irun_thm4
+	stock_thm4 = stock_thm4(:,:,1:irun_thm4);
+	sfil_thm4 = sfil_thm4 + 1;
+	instr = [fname_ '_thm4' int2str(sfil_thm4) ' stock_thm4;'];
+	eval(['save ' instr]);
+      end
+      clear stock_thm4;
+    end     
+    close(h)
+    %%
+    %%  Now i compute some statistics (mean, median, std, deciles, HPD intervals)
+    %%
+    MeanMean = zeros(nvar,1);
+    MedianMean = zeros(nvar,1);
+    StdMean = zeros(nvar,1);
+    DistribMean = zeros(nvar,9);
+    HPDMean = zeros(nvar,2);
+    tmp = zeros(B,1);
+    for i = 1:nvar
+      StartLine = 0;
+      for file = 1:sfil_thm1 
+	instr = [fname_ '_thm1' int2str(file)];
+	eval(['load ' instr]);
+	DeProfundis = size(stock_thm1,2);
+	tmp(StartLine+1:StartLine+DeProfundis) = squeeze(stock_thm1(i,:));
+	StartLine = StartLine+DeProfundis;
+      end
+      tmp = sort(tmp);
+      MeanMean(i) = mean(tmp);
+      MedianMean(i) = tmp(round(B*0.5));
+      StdMean(i) = std(tmp);
+      DistribMean(i,:) = reshape(tmp(deciles),1,9);
+      tt = floor(options_.mh_conf_sig*B);
+      a = 1; 
+      b = tt;
+      tmp2 = [1;tt;tmp(tt)-tmp(1)];
+      while b <= B
+	tmp1 = [a;b;tmp(b)-tmp(a)];
+	a = a + 1;
+	b = b + 1;
+	if tmp1(3,1) < tmp2(3,1)
+	  tmp2 = tmp1;     
+	end    
+      end
+      HPDMean(i,1) = tmp(tmp2(1,1));
+      HPDMean(i,2) = tmp(tmp2(2,1));
+    end
+    disp(' ')
+    disp(' ')
+    disp('POSTERIOR THEORETICAL EXPECTATION')
+    disp(' ')
+    titre = sprintf('%15s \t %6s \t %6s \t %6s \t %6s \t %6s\n',...
+            'Variables',...
+            'mean  ',...
+            'median',...
+            'std   ',...
+            'HPDinf',...
+            'HPDsup');
+    disp(titre)
+    for i=1:nvar
+      disp(sprintf('%15s \t %6.3f \t %6.3f \t %6.3f \t %6.3f \t %6.3f',...
+           deblank(lgy_(ivar(i),:)), ...
+           MeanMean(i),...
+           MedianMean(i),...
+           StdMean(i),...
+           HPDMean(i,1),...
+           HPDMean(i,2)));
+      eval(['oo_.PosteriorTheoreticalMoment.Expectation.Mean.' deblank(lgy_(ivar(i),:)) ' = MeanMean(i);']);
+      eval(['oo_.PosteriorTheoreticalMoment.Expectation.Median.' deblank(lgy_(ivar(i),:)) ' = MedianMean(i);']);
+      eval(['oo_.PosteriorTheoreticalMoment.Expectation.Std.' deblank(lgy_(ivar(i),:)) ' = StdMean(i);']);
+      eval(['oo_.PosteriorTheoreticalMoment.Expectation.HPDinf.' deblank(lgy_(ivar(i),:)) ' = HPDMean(i,1);']);
+      eval(['oo_.PosteriorTheoreticalMoment.Expectation.HPDsup.' deblank(lgy_(ivar(i),:)) ' = HPDMean(i,2);']);
+    end
+    if TeX
+      fidTeX = fopen([fname_ '_PosteriorTheoreticalExpectation.TeX'],'w');
+      fprintf(fidTeX,'%% TeX-table generated by metropolis.m (Dynare).\n');
+      fprintf(fidTeX,['%% ' datestr(now,0)]);
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,'{\\tiny \n');
+      fprintf(fidTeX,'\\begin{table}\n');
+      fprintf(fidTeX,'\\centering\n');
+      fprintf(fidTeX,'\\begin{tabular}{l|ccccc} \n');
+      fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+      fprintf(fidTeX,' Variables & mean & median  & std & HPD inf & HPD sup  \\\\ \n');
+      fprintf(fidTeX,'\\hline \\\\ \n');
+      for i=1:nvar
+	fprintf(fidTeX,' $%s$ & %6.3f & %6.3f & %6.3f & %6.3f & %6.3f \\\\ \n',...
+		deblank(lgy_TeX_(ivar(i),:)), ...
+		MeanMean(i),...
+		MedianMean(i),...
+		StdMean(i),...
+		HPDMean(i,1),...
+		HPDMean(i,2));
+      end   
+      fprintf(fidTeX,'\\hline\\hline \n');
+      fprintf(fidTeX,'\\end{tabular}\n ');    
+      fprintf(fidTeX,'\\caption{Posterior theoretical expectation.}\n ');
+      fprintf(fidTeX,'\\label{Table:PosteriorTheoreticalExpectation}\n');
+      fprintf(fidTeX,'\\end{table}\n');
+      fprintf(fidTeX,'} \n');
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end 
+    MeanVariance = zeros(nvar,nvar,1);
+    MedianVariance = zeros(nvar,nvar,1);
+    StdVariance = zeros(nvar,nvar,1);
+    DistribVariance = zeros(nvar,nvar,9);
+    HPDVariance = zeros(nvar,nvar,2);
+    for i = 1:nvar
+      for j=1:nvar
+	StartLine = 0;
+	tmp = zeros(B,1);
+	for file = 1:sfil_thm2 
+	  instr = [fname_ '_thm2' int2str(file)];
+	  eval(['load ' instr]);
+	  DeProfundis = size(stock_thm2,3);
+	  tmp(StartLine+1:StartLine+DeProfundis) = squeeze(stock_thm2(i,j,:));
+	  StartLine = StartLine+DeProfundis;
+	end 
+	tmp = sort(tmp);
+	MeanVariance(i,j) = mean(tmp);
+	MedianVariance(i,j) = tmp(round(B*0.5));
+	StdVariance(i,j) = std(tmp);
+	DistribVariance(i,j,:) = reshape(tmp(deciles),1,1,9);
+	tt = floor(options_.mh_conf_sig*B);
+	a = 1; 
+	b = tt;
+	tmp2 = [1;tt;tmp(tt)-tmp(1)];
+	while b <= B
+	  tmp1 = [a;b;tmp(b)-tmp(a)];
+	  a = a + 1;
+	  b = b + 1;
+	  if tmp1(3,1) < tmp2(3,1)
+	    tmp2 = tmp1;     
+	  end    
+	end
+	HPDVariance(i,j,1) = tmp(tmp2(1,1));
+	HPDVariance(i,j,2) = tmp(tmp2(2,1));
+      end   
+    end
+    disp(' ')
+    disp(' ')
+    disp('POSTERIOR THEORETICAL VARIANCES AND COVARIANCES')
+    disp(' ')
+    titre = sprintf('%15s \t %15s \t %9s \t %9s \t %9s \t %9s \t %9s\n',...
+            'Variables',...
+            'Variables',...
+            'mean  ',...
+            'median',...
+            'std   ',...
+            'HPDinf',...
+            'HDPsup');
+    disp(titre)
+    for i=1:nvar
+      for j=i:nvar
+	disp(sprintf('%15s \t %15s \t %9.3g \t %9.3g \t %9.3g \t %9.3g \t %9.3g',...
+		     deblank(lgy_(ivar(i),:)), ...
+		     deblank(lgy_(ivar(j),:)), ...
+		     MeanVariance(i,j),...
+		     MedianVariance(i,j),...
+		     StdVariance(i,j),...
+		     HPDVariance(i,j,1),...
+		     HPDVariance(i,j,2)));
+	eval(['oo_.PosteriorTheoreticalMoment.Variance.Mean.' deblank(lgy_(ivar(i),:)) '_' deblank(lgy_(ivar(j),:)) ' = MeanVariance(i,j);']);
+	eval(['oo_.PosteriorTheoreticalMoment.Variance.Median.' deblank(lgy_(ivar(i),:)) '_' deblank(lgy_(ivar(j),:)) ' = MedianVariance(i,j);']);
+	eval(['oo_.PosteriorTheoreticalMoment.Variance.Std.' deblank(lgy_(ivar(i),:)) '_' deblank(lgy_(ivar(j),:)) ' = StdVariance(i,j);']);
+	eval(['oo_.PosteriorTheoreticalMoment.Variance.HPDinf.' deblank(lgy_(ivar(i),:)) '_' deblank(lgy_(ivar(j),:)) ' = HPDVariance(i,j,1);']);
+	eval(['oo_.PosteriorTheoreticalMoment.Variance.HPDsup.' deblank(lgy_(ivar(i),:)) '_' deblank(lgy_(ivar(j),:)) ' = HPDVariance(i,j,2);']);
+      end       
+    end
+    if TeX
+      fidTeX = fopen([fname_ '_PosteriorTheoreticalVariance.TeX'],'w');
+      fprintf(fidTeX,'%% TeX-table generated by metropolis.m (Dynare).\n');
+      fprintf(fidTeX,['%% ' datestr(now,0)]);
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,'{\\tiny \n');
+      fprintf(fidTeX,'\\begin{table}\n');
+      fprintf(fidTeX,'\\centering\n');
+      fprintf(fidTeX,'\\begin{tabular}{ll|ccccc} \n');
+      fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+      fprintf(fidTeX,' Variables & Variables & mean & median  & std & HPD inf & HPD sup  \\\\ \n');
+      fprintf(fidTeX,'\\hline \\\\ \n');
+      for i=1:nvar
+	for j=i:nvar
+	  fprintf(fidTeX,' $%s$ & $%s$ & %6.3f & %6.3f & %6.3f & %6.3f & %6.3f \\\\ \n',...
+		  deblank(lgy_TeX_(ivar(i),:)), ...
+		  deblank(lgy_TeX_(ivar(j),:)), ...
+		  MeanVariance(i,j),...
+		  MedianVariance(i,j),...
+		  StdVariance(i,j),...
+		  HPDVariance(i,j,1),...
+		  HPDVariance(i,j,2));
+	end     
+      end   
+      fprintf(fidTeX,'\\hline\\hline \n');
+      fprintf(fidTeX,'\\end{tabular}\n ');    
+      fprintf(fidTeX,'\\caption{Posterior theoretical variances and covariances.}\n ');
+      fprintf(fidTeX,'\\label{Table:PosteriorTheoreticalVariances}\n');
+      fprintf(fidTeX,'\\end{table}\n');
+      fprintf(fidTeX,'} \n');
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end 
+    MeanCorrelation = zeros(nvar,nvar,1);
+    MedianCorrelation = zeros(nvar,nvar,1);
+    StdCorrelation = zeros(nvar,nvar,1);
+    DistribCorrelation = zeros(nvar,nvar,9);
+    HPDCorrelation = zeros(nvar,nvar,2);
+    tmpp    = zeros(B,1);
+    tmppp   = zeros(B,1);
+    for i = 1:nvar
+      for j=1:nvar
+	StartLine = 0;
+	tmp = zeros(B,1);
+	for file = 1:sfil_thm2 
+	  instr = [fname_ '_thm2' int2str(file)];
+	  eval(['load ' instr]);
+	  DeProfundis = size(stock_thm2,3);
+	  tmp(StartLine+1:StartLine+DeProfundis) = squeeze(stock_thm2(i,j,:));
+	  tmpp(StartLine+1:StartLine+DeProfundis) = squeeze(stock_thm2(i,i,:));
+	  tmppp(StartLine+1:StartLine+DeProfundis) = squeeze(stock_thm2(j,j,:));
+	  StartLine = StartLine+DeProfundis;
+	end
+	tmp = sort(tmp./sqrt(tmpp.*tmppp));
+	MeanCorrelation(i,j) = mean(tmp);
+	MedianCorrelation(i,j) = tmp(round(B*0.5));
+	StdCorrelation(i,j) = std(tmp);
+	DistribCorrelation(i,j,:) = reshape(tmp(deciles),1,1,9);
+	tt = floor(options_.mh_conf_sig*B);
+	a = 1; 
+	b = tt;
+	tmp2 = [1;tt;tmp(tt)-tmp(1)];
+	while b <= B
+	  tmp1 = [a;b;tmp(b)-tmp(a)];
+	  a = a + 1;
+	  b = b + 1;
+	  if tmp1(3,1) < tmp2(3,1)
+	    tmp2 = tmp1;     
+	  end    
+	end
+	HPDCorrelation(i,j,1) = tmp(tmp2(1,1));
+	HPDCorrelation(i,j,2) = tmp(tmp2(2,1));
+      end   
+    end
+    clear tmpp tmppp;
+    disp(' ')
+    disp(' ')
+    disp('POSTERIOR THEORETICAL CORRELATIONS')
+    disp(' ')
+    titre = sprintf('%15s \t %15s \t %6s \t %6s \t %6s \t %6s \t %6s\n',...
+            'Variables',...
+            'Variables',...
+            'mean  ',...
+            'median',...
+            'std   ',...
+            'HPDinf',...
+            'HPDsup');
+    disp(titre)
+    for i=1:nvar-1
+      for j=i+1:nvar
+	disp(sprintf('%15s \t %15s \t %6.3f \t %6.3f \t %6.3f \t %6.3f \t %6.3f',...
+		     deblank(lgy_(ivar(i),:)), ...
+		     deblank(lgy_(ivar(j),:)), ...
+		     MeanCorrelation(i,j),...
+		     MedianCorrelation(i,j),...
+		     StdCorrelation(i,j),...
+		     HPDCorrelation(i,j,1),...
+		     HPDCorrelation(i,j,2)));
+	eval(['oo_.PosteriorTheoreticalMoment.Correlation.Mean.' deblank(lgy_(ivar(i),:)) '_' deblank(lgy_(ivar(j),:)) ' = MeanCorrelation(i,j);']);
+	eval(['oo_.PosteriorTheoreticalMoment.Correlation.Median.' deblank(lgy_(ivar(i),:)) '_' deblank(lgy_(ivar(j),:)) ' = MedianCorrelation(i,j);']);
+	eval(['oo_.PosteriorTheoreticalMoment.Correlation.Std.' deblank(lgy_(ivar(i),:)) '_' deblank(lgy_(ivar(j),:)) ' = StdCorrelation(i,j);']);
+	eval(['oo_.PosteriorTheoreticalMoment.Correlation.HPDinf.' deblank(lgy_(ivar(i),:)) '_' deblank(lgy_(ivar(j),:)) ' = HPDCorrelation(i,j,1);']);
+	eval(['oo_.PosteriorTheoreticalMoment.Correlation.HPDsup.' deblank(lgy_(ivar(i),:)) '_' deblank(lgy_(ivar(j),:)) ' = HPDCorrelation(i,j,2);']);
+      end       
+    end
+    if TeX
+      fidTeX = fopen([fname_ '_PosteriorTheoreticalCorrelation.TeX'],'w');
+      fprintf(fidTeX,'%% TeX-table generated by metropolis.m (Dynare).\n');
+      fprintf(fidTeX,['%% ' datestr(now,0)]);
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,'{\\tiny \n');
+      fprintf(fidTeX,'\\begin{table}\n');
+      fprintf(fidTeX,'\\centering\n');
+      fprintf(fidTeX,'\\begin{tabular}{ll|ccccc} \n');
+      fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+      fprintf(fidTeX,' Variables & Variables & mean & median  & std & HPD inf & HPD sup  \\\\ \n');
+      fprintf(fidTeX,'\\hline \\\\ \n');
+      for i=1:nvar-1
+	for j=i+1:nvar
+	  fprintf(fidTeX,' $%s$ & $%s$ & %6.3f & %6.3f & %6.3f & %6.3f & %6.3f \\\\ \n',...
+		  deblank(lgy_TeX_(ivar(i),:)), ...
+		  deblank(lgy_TeX_(ivar(j),:)), ...
+		  MeanCorrelation(i,j),...
+		  MedianCorrelation(i,j),...
+		  StdCorrelation(i,j),...
+		  HPDCorrelation(i,j,1),...
+		  HPDCorrelation(i,j,2));
+	end
+      end   
+      fprintf(fidTeX,'\\hline\\hline \n');
+      fprintf(fidTeX,'\\end{tabular}\n ');    
+      fprintf(fidTeX,'\\caption{Posterior theoretical correlations.}\n ');
+      fprintf(fidTeX,'\\label{Table:PosteriorTheoreticalCorrelations}\n');
+      fprintf(fidTeX,'\\end{table}\n');
+      fprintf(fidTeX,'} \n');
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end 
+    MeanDecomp = zeros(nvar,exo_nbr,1);
+    MedianDecomp = zeros(nvar,exo_nbr,1);
+    StdDecomp = zeros(nvar,exo_nbr,1);
+    DistribDecomp = zeros(nvar,exo_nbr,9);
+    HPDDecomp = zeros(nvar,exo_nbr,2);
+    for i = 1:nvar
+      for j=1:exo_nbr
+	StartLine = 0;
+	for file = 1:sfil_thm3 
+	  instr = [fname_ '_thm3' int2str(file)];
+	  eval(['load ' instr]);
+	  DeProfundis = size(stock_thm3,3);
+	  tmp(StartLine+1:StartLine+DeProfundis) = squeeze(stock_thm3(i,j,:));
+	  StartLine = StartLine+DeProfundis;
+	end
+	tmp = sort(tmp);
+	MeanDecomp(i,j) = mean(tmp);
+	MedianDecomp(i,j) = tmp(round(B*0.5));
+	StdDecomp(i,j) = std(tmp);
+	DistribDecomp(i,j,:) = reshape(tmp(deciles),1,1,9);
+	tt = floor(options_.mh_conf_sig*B);
+	a = 1; 
+	b = tt;
+	tmp2 = [1;tt;tmp(tt)-tmp(1)];
+	while b <= B
+	  tmp1 = [a;b;tmp(b)-tmp(a)];
+	  a = a + 1;
+	  b = b + 1;
+	  if tmp1(3,1) < tmp2(3,1)
+	    tmp2 = tmp1;     
+	  end    
+	end
+	HPDDecomp(i,j,1) = tmp(tmp2(1,1));
+	HPDDecomp(i,j,2) = tmp(tmp2(2,1));
+      end   
+    end
+    disp(' ')
+    disp(' ')
+    disp('POSTERIOR THEORETICAL VARIANCE DECOMPOSITION')
+    disp(' ')
+    titre = sprintf('%15s \t %15s \t %6s \t %6s \t %6s \t %6s \t %6s\n',...
+            'Variables',...
+            'Sources',...
+            'mean  ',...
+            'median',...
+            'std   ',...
+            'HPDinf',...
+            'HDPsup');
+    disp(titre)
+    lgx1(lgx_orig_ord_,:) = lgx_;
+    for i=1:nvar
+      for j=1:exo_nbr
+	disp(sprintf('%15s \t %15s \t %6.3f \t %6.3f \t %6.3f \t %6.3f \t %6.3f',...
+		     deblank(lgy_(ivar(i),:)), ...
+		     deblank(lgx1(j,:)), ...
+		     MeanDecomp(i,j),...
+		     MedianDecomp(i,j),...
+		     StdDecomp(i,j),...
+		     HPDDecomp(i,j,1),...
+		     HPDDecomp(i,j,2)));
+	eval(['oo_.PosteriorTheoreticalMoment.Decomp.Mean.' deblank(lgy_(ivar(i),:)) '_' deblank(lgx1(j,:)) ' = MeanDecomp(i,j);']);
+	eval(['oo_.PosteriorTheoreticalMoment.Decomp.Median.' deblank(lgy_(ivar(i),:)) '_' deblank(lgx1(j,:)) ' = MedianDecomp(i,j);']);
+	eval(['oo_.PosteriorTheoreticalMoment.Decomp.Std.' deblank(lgy_(ivar(i),:)) '_' deblank(lgx1(j,:)) ' = StdDecomp(i,j);']);
+	eval(['oo_.PosteriorTheoreticalMoment.Decomp.HPDinf.' deblank(lgy_(ivar(i),:)) '_' deblank(lgx1(j,:)) ' = HPDDecomp(i,j,1);']);
+	eval(['oo_.PosteriorTheoreticalMoment.Decomp.HPDsup.' deblank(lgy_(ivar(i),:)) '_' deblank(lgx1(j,:)) ' = HPDDecomp(i,j,2);']);
+      end       
+    end
+    if TeX
+      fidTeX = fopen([fname_ '_PosteriorTheoreticalVarianceDecomposition.TeX'],'w');
+      fprintf(fidTeX,'%% TeX-table generated by metropolis.m (Dynare).\n');
+      fprintf(fidTeX,['%% ' datestr(now,0)]);
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,'{\\tiny \n');
+      fprintf(fidTeX,'\\begin{table}\n');
+      fprintf(fidTeX,'\\centering\n');
+      fprintf(fidTeX,'\\begin{tabular}{ll|ccccc} \n');
+      fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+      fprintf(fidTeX,' Variables & Sources & mean & median  & std & HPD inf & HPD sup  \\\\ \n');
+      fprintf(fidTeX,'\\hline \\\\ \n');
+      lgx_TeX1(lgx_orig_ord_) = lgx_Tex_;
+      for i=1:nvar
+	for j=1:exo_nbr
+	  fprintf(fidTeX,' $%s$ & $%s$ & %6.3f & %6.3f & %6.3f & %6.3f & %6.3f \\\\ \n',...
+		  deblank(lgy_TeX_(ivar(i),:)), ...
+		  deblank(lgx_TeX1(j,:)), ...
+		  MeanDecomp(i,j),...
+		  MedianDecomp(i,j),...
+		  StdDecomp(i,j),...
+		  HPDDecomp(i,j,1),...
+		  HPDDecomp(i,j,2));
+	end     
+      end   
+      fprintf(fidTeX,'\\hline\\hline \n');
+      fprintf(fidTeX,'\\end{tabular}\n ');    
+      fprintf(fidTeX,'\\caption{Posterior theoretical variance decomposition.}\n ');
+      fprintf(fidTeX,'\\label{Table:PosteriorTheoreticalVarianceDecomposition}\n');
+      fprintf(fidTeX,'\\end{table}\n');
+      fprintf(fidTeX,'} \n');
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end 
+    MeanAutoCorr = zeros(nvar,nar,1);
+    MedianAutoCorr = zeros(nvar,nar,1);
+    StdAutoCorr = zeros(nvar,nar,1);
+    DistribAutoCorr = zeros(nvar,nar,9);
+    HPDAutoCorr = zeros(nvar,nar,2);
+    for i = 1:nvar
+      for j=1:nar
+	StartLine = 0;
+	for file = 1:sfil_thm4 
+	  instr = [fname_ '_thm4' int2str(file)];
+	  eval(['load ' instr]);
+	  DeProfundis = size(stock_thm4,3);
+	  tmp(StartLine+1:StartLine+DeProfundis) = squeeze(stock_thm4(i,j,:));
+	  StartLine = StartLine+DeProfundis;
+	end
+	tmp = sort(tmp);
+	MeanAutoCorr(i,j) = mean(tmp);
+	MedianAutoCorr(i,j) = tmp(round(B*0.5));
+	StdAutoCorr(i,j) = std(tmp);
+	DistribAutoCorr(i,j,:) = reshape(tmp(deciles),1,1,9);
+	tt = floor(options_.mh_conf_sig*B);
+	a = 1; 
+	b = tt;
+	tmp2 = [1;tt;tmp(tt)-tmp(1)];
+	while b <= B
+	  tmp1 = [a;b;tmp(b)-tmp(a)];
+	  a = a + 1;
+	  b = b + 1;
+	  if tmp1(3,1) < tmp2(3,1)
+	    tmp2 = tmp1;     
+	  end    
+	end
+	HPDAutoCorr(i,j,1) = tmp(tmp2(1,1));
+	HPDAutoCorr(i,j,2) = tmp(tmp2(2,1));
+      end   
+    end
+    disp(' ')
+    disp(' ')
+    disp('POSTERIOR THEORETICAL AUTOCORRELATION')
+    disp(' ')
+    titre = sprintf('%15s \t %3s \t %6s \t %6s \t %6s \t %6s \t %6s\n',...
+            'Variables',...
+            'Lag',...
+            'mean  ',...
+            'median',...
+            'std   ',...
+            'HPDinf',...
+            'HDPsup');
+    disp(titre)
+    for i=1:nvar
+      for j=1:nar
+	disp(sprintf('%15s \t %3s \t %6.3f \t %6.3f \t %6.3f \t %6.3f \t %6.3f',...
+		     deblank(lgy_(ivar(i),:)), ...
+		     [int2str(j) ' '], ...
+		     MeanAutoCorr(i,j),...
+		     MedianAutoCorr(i,j),...
+		     StdAutoCorr(i,j),...
+		     HPDAutoCorr(i,j,1),...
+		     HPDAutoCorr(i,j,2)));
+	eval(['oo_.PosteriorTheoreticalMoment.AutoCorrelation.Mean.' deblank(lgy_(ivar(i),:)) '_lag' int2str(j) ' = MeanAutoCorr(i,j);']);
+	eval(['oo_.PosteriorTheoreticalMoment.AutoCorrelation.Median.' deblank(lgy_(ivar(i),:)) '_lag' int2str(j) ' = MedianAutoCorr(i,j);']);
+	eval(['oo_.PosteriorTheoreticalMoment.AutoCorrelation.Std.' deblank(lgy_(ivar(i),:)) '_lag' int2str(j) ' = StdAutoCorr(i,j);']);
+	eval(['oo_.PosteriorTheoreticalMoment.AutoCorrelation.HPDinf.' deblank(lgy_(ivar(i),:)) '_lag' int2str(j) ' = HPDAutoCorr(i,j,1);']);
+	eval(['oo_.PosteriorTheoreticalMoment.AutoCorrelation.HPDsup.' deblank(lgy_(ivar(i),:)) '_lag' int2str(j) ' = HPDAutoCorr(i,j,2);']);
+      end       
+    end
+    if TeX
+      fidTeX = fopen([fname_ '_PosteriorTheoreticalAutocorrelation.TeX'],'w');
+      fprintf(fidTeX,'%% TeX-table generated by metropolis.m (Dynare).\n');
+      fprintf(fidTeX,['%% ' datestr(now,0)]);
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,'{\\tiny \n');
+      fprintf(fidTeX,'\\begin{table}\n');
+      fprintf(fidTeX,'\\centering\n');
+      fprintf(fidTeX,'\\begin{tabular}{ll|ccccc} \n');
+      fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+      fprintf(fidTeX,' Variables & Lag & mean & median  & std & HPD inf & HPD sup  \\\\ \n');
+      fprintf(fidTeX,'\\hline \\\\ \n');
+      for i=1:nvar
+	for j=1:nar
+	  fprintf(fidTeX,' $%s$ & $%s$ & %6.3f & %6.3f & %6.3f & %6.3f & %6.3f \\\\ \n',...
+		  deblank(lgy_TeX_(ivar(i),:)), ...
+		  int2str(j), ...
+		  MeanAutoCorr(i,j),...
+		  MedianAutoCorr(i,j),...
+		  StdAutoCorr(i,j),...
+		  HPDAutoCorr(i,j,1),...
+		  HPDAutoCorr(i,j,2));
+	end     
+      end   
+      fprintf(fidTeX,'\\hline\\hline \n');
+      fprintf(fidTeX,'\\end{tabular}\n ');    
+      fprintf(fidTeX,'\\caption{Posterior theoretical auto-correlation.}\n ');
+      fprintf(fidTeX,'\\label{Table:PosteriorTheoreticalAutoCorrelation}\n');
+      fprintf(fidTeX,'\\end{table}\n');
+      fprintf(fidTeX,'} \n');
+      fprintf(fidTeX,'%% End of TeX file.\n');
+      fclose(fidTeX);
+    end 
+  end % options_.moments_varendo
+  
+  %% Un dernier petit coup de DsgeLikelihood juste pour remettre les parametres
+  %% structurels et la matrice de variance-covariance aux valeurs qui
+  %% correspondent a la moyenne posterieure (en vue d'une utilisation �ventuelle
+  %% de stoch_simul apr�s le Metropolis-Hastings).
+  [lnprior,cost_flag,ys,trend_coeff] = DsgeLikelihood(post_mean,gend,data);
+  %% Now I save the seeds (If the user wants to start another MH, he can start from the
+  %% previous state of the random number generator by using the command "LoadPreviousSeed"
+  %% before the estimation command)
+  Seed.NormalDeviates  = randn('state');
+  Seed.UniformDeviates = rand('state');
+  save LastSeed Seed;
+  %% That's All!
+
+
+  % SA 08-18-2004       * Corrected a bug in forecasts (HPD intervals).
+  %                 * metropolis.m now displays "true bayesian" smooth shocks. The mean
+  %                 - across the metropolis draws - of the smooth shocks instead of the 
+  %                 smooth shocks obtained from the posterior mean are displayed.
+  %                 * Added "true bayesian" smooth measurement error.
+  %                 * Added "true bayesian" smooth variables (all the variables in the 
+  %                 state vector).
+  %                 * Added deciles for the posterior distribution of the smooth shocks,
+  %                 variables and measurement errors (green curves).
+  % SA 08-19-2004       * Added posterior IRFs.
+  % SA 08-21-2004       * Added posterior theoretical moments.
+  % SA 08-23-2004     * Added correction to the modified harmonic mean estimator of the
+  %                   log-marginal density. The variance of the weighting distribution
+  %                   automatically increases if needed (to be revised).)
+  % SA 12-02-2004       * Changed architecture for the global structure oo_ 
diff --git a/tags/v_3.062/matlab/metropolis99.m b/tags/v_3.062/matlab/metropolis99.m
new file mode 100644
index 0000000000000000000000000000000000000000..5d8edbbc0a696520599d6d2140a3ce32b89e43f5
--- /dev/null
+++ b/tags/v_3.062/matlab/metropolis99.m
@@ -0,0 +1,262 @@
+function [PostMod,PostVar,Scale,PostMean] = ...
+    samaxwell(xparam1,gend,data,mh_bounds,NumberOfIterationsForInitialization,init_scale,info,MeanPar,VarCov)
+% stephane.adjemian@cepremap.cnrs.fr [11-22-2005]
+global bayestopt_ exo_nbr dr_ estim_params_ Sigma_e_ options_ xparam_test
+global lgy_ lgx_ fname_ ys_ xkmin_ xkmax_ ykmin_ ykmax_ endo_nbr mean_varobs
+global oo_ lgx_orig_ord_ lgy_TeX_ lgx_TeX_ dsge_prior_weight
+nvx   	= estim_params_.nvx;
+nvn   	= estim_params_.nvn;
+ncx   	= estim_params_.ncx;
+ncn   	= estim_params_.ncn;
+np    	= estim_params_.np ;
+ns      = nvx+nvn+ncx+ncn; 
+nx    	= nvx+nvn+ncx+ncn+np;
+npar  	= length(xparam1);
+nvobs 	= size(options_.varobs,1);
+options_.lik_algo = 1;
+MaxNumberOfTuningSimulations = 100000;
+MaxNumberOfClimbingSimulations = 20000;
+AcceptanceTarget = 0.33;
+
+%% [1] I build a covariance matrix for the jumping distribution.
+stdev = bayestopt_.pstdev;
+indx = find(isinf(stdev));
+stdev(indx) = 10*ones(length(indx),1);
+CovJump = diag(stdev).^2;
+if nargin == 9
+  CovJump = VarCov;
+end
+ModePar = xparam1;
+%% [2] For this covariance matrix I tune the scale parameter.
+hh = waitbar(0,'Tuning of the scale parameter...');
+set(hh,'Name','Tuning of the scale parameter (1)')
+j = 1; jj  = 1;
+isux = 0;
+jsux = 0;
+test = 0;
+% TEST = 0;
+ix2 = ModePar;% initial condition! 
+if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+  ilogpo2 = -DsgeLikelihood(ix2,gend,data);% initial posterior density
+else
+  ilogpo2 = -DsgeVarLikelihood(ix2,gend);% initial posterior density
+end
+mlogpo2 = ilogpo2;
+dd = transpose(chol(CovJump));
+while j<=MaxNumberOfTuningSimulations
+  proposal = init_scale*dd*randn(npar,1) + ix2;
+  if all(proposal > mh_bounds(:,1)) & all(proposal < mh_bounds(:,2))
+    if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+      logpo2 = -DsgeLikelihood(proposal,gend,data);
+    else
+      logpo2 = -DsgeVarLikelihood(proposal,gend);
+    end
+  else
+    logpo2 = -inf;
+  end
+  % I move if the proposal is enough likely...
+  if logpo2 > -inf & log(rand) < logpo2 - ilogpo2
+    ix2 = proposal; 
+    if logpo2 > mlogpo2
+      ModePar = proposal;
+      mlogpo2 = logpo2;
+    end
+    ilogpo2 = logpo2;
+    isux = isux + 1;
+    jsux = jsux + 1;
+  else
+    % ... otherwise I don't move.
+  end	
+  prtfrc = j/MaxNumberOfTuningSimulations;
+  waitbar(prtfrc,hh,sprintf('%f done, acceptation rate %f',prtfrc,isux/j));
+  if  j/500 == round(j/500)
+    test1 = jsux/jj;
+    test2 = isux/j;
+    cfactor = (test1/AcceptanceTarget)^1.0*(test2/AcceptanceTarget)^0.0;
+    if cfactor>0
+      init_scale = init_scale*cfactor;
+    end
+    jsux = 0; jj = 0;
+    if test1>AcceptanceTarget*0.90 & test1<AcceptanceTarget*1.10
+      test = test+1;
+    end
+    if test>6
+      break
+    end
+  end
+  j = j+1;
+  jj = jj + 1;
+end
+close(hh);
+%% [3] One block metropolis, I update the covariance matrix of the jumping distribution
+hh = waitbar(0,'Metropolis-Hastings...');
+set(hh,'Name','Looking for the posterior covariance...')
+j = 1;
+isux = 0;
+% ix2 = xparam1;% initial condition! 
+if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & Isempty(dsge_prior_weight)
+  ilogpo2 = -DsgeLikelihood(ix2,gend,data);
+else
+  ilogpo2 = -DsgeVarLikelihood(ix2,gend);
+end
+dd = transpose(chol(CovJump));
+while j<=NumberOfIterationsForInitialization
+  proposal = init_scale*dd*randn(npar,1) + ix2;
+  if all(proposal > mh_bounds(:,1)) & all(proposal < mh_bounds(:,2))
+    if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+      logpo2 = -DsgeLikelihood(proposal,gend,data);
+    else
+      logpo2 = -DsgeVarLikelihood(proposal,gend);
+    end
+  else
+    logpo2 = -inf;
+  end
+  % I move if the proposal is enough likely...
+  if logpo2 > -inf & log(rand) < logpo2 - ilogpo2
+    ix2 = proposal; 
+    if logpo2 > mlogpo2
+      ModePar = proposal;
+      mlogpo2 = logpo2;
+    end
+    ilogpo2 = logpo2;
+    isux = isux + 1;
+    jsux = jsux + 1;
+  else
+    % ... otherwise I don't move.
+  end	
+  prtfrc = j/NumberOfIterationsForInitialization;
+  waitbar(prtfrc,hh,sprintf('%f done, acceptation rate %f',prtfrc,isux/j));
+  % I update the covariance matrix and the mean:
+  oldMeanPar = MeanPar;
+  MeanPar = oldMeanPar + (1/j)*(ix2-oldMeanPar);
+  CovJump = CovJump + oldMeanPar*oldMeanPar' - MeanPar*MeanPar' + ...
+                 (1/j)*(ix2*ix2' - CovJump - oldMeanPar*oldMeanPar');
+  j = j+1;
+end
+close(hh);
+%% [4 & 5] I tune the scale parameter (with the new covariance matrix) if
+%% this is the last call to the routine, and I climb the hill (without
+%% updating the covariance matrix)...
+if strcmpi(info,'LastCall')
+  % MeanPar = xparam1;  
+  % ModePar = xparam1; I'm stupid!
+  hh = waitbar(0,'Tuning of the scale parameter...');
+  set(hh,'Name','Tuning of the scale parameter (2)')
+  j = 1; jj  = 1;
+  isux = 0;
+  jsux = 0;
+  test = 0;
+  % ix2 = ModePar;% initial condition! Again stupid 
+  if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+    ilogpo2 = -DsgeLikelihood(ix2,gend,data);% initial posterior density
+  else
+    ilogpo2 = -DsgeVarLikelihood(ix2,gend);% initial posterior density
+  end
+  dd = transpose(chol(CovJump));
+  while j<=MaxNumberOfTuningSimulations
+    proposal = init_scale*dd*randn(npar,1) + ix2;
+    if all(proposal > mh_bounds(:,1)) & all(proposal < mh_bounds(:,2))
+      if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+	logpo2 = -DsgeLikelihood(proposal,gend,data);
+      else
+	logpo2 = -DsgeVarLikelihood(proposal,gend);
+      end
+    else
+      logpo2 = -inf;
+    end
+    % I move if the proposal is enough likely...
+    if logpo2 > -inf & log(rand) < logpo2 - ilogpo2
+      ix2 = proposal;
+      if logpo2 > mlogpo2
+	ModePar = proposal;
+	mlogpo2 = logpo2;
+      end
+      ilogpo2 = logpo2;
+      isux = isux + 1;
+      jsux = jsux + 1;
+    else
+      % ... otherwise I don't move.
+    end
+    prtfrc = j/MaxNumberOfTuningSimulations;
+    waitbar(prtfrc,hh,sprintf('%f done, acceptation rate %f',prtfrc,isux/j));  
+    if  j/500 == round(j/500) 
+      test1 = jsux/jj;
+      test2 = isux/j;  
+      cfactor = (test1/AcceptanceTarget)^1.0*(test2/AcceptanceTarget)^0.0;
+      init_scale = init_scale*cfactor;
+      jsux = 0; jj = 0;
+      if test1>AcceptanceTarget*0.90 & test1<AcceptanceTarget*1.10
+	test = test+1;
+      end
+      if test>6
+	break
+      end
+    end
+    j = j+1;
+    jj = jj + 1;
+  end
+  close(hh);
+  PostVar = CovJump;
+  PostMean = MeanPar;
+  Scale = init_scale;
+  %%
+  %% Now I climb the hill
+  %%
+  hh = waitbar(0,' ');
+  set(hh,'Name','Now I am climbing the hill...')
+  j = 1; jj  = 1;
+  jsux = 0;
+  test = 0;
+  dd = transpose(chol(CovJump));
+  init_scale = eye(length(dd))*init_scale;
+  indx = strmatch('dsge_prior_weight',estim_params_.param_names,'exact');
+  while j<=MaxNumberOfClimbingSimulations
+    proposal = init_scale*dd*randn(npar,1) + ModePar;
+    if all(proposal > mh_bounds(:,1)) & all(proposal < mh_bounds(:,2))
+      if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+	logpo2 = -DsgeLikelihood(proposal,gend,data);
+      else
+	logpo2 = -DsgeVarLikelihood(proposal,gend);
+      end
+    else
+      logpo2 = -inf;
+    end
+    if logpo2 > mlogpo2% I move if the proposal is higher...
+      ModePar = proposal;
+      mlogpo2 = logpo2;
+      jsux = jsux + 1;
+    else
+      % otherwise I don't move...
+    end
+    prtfrc = j/MaxNumberOfClimbingSimulations;
+    waitbar(prtfrc,hh,sprintf('%f done, acceptation rate %f',prtfrc,jsux/jj));  
+    if  j/200 == round(j/200) 
+      test1 = jsux/jj;
+      %cfactor = (test1/AcceptanceTarget)^1.0*(test2/AcceptanceTarget)^0.0;
+      %init_scale = init_scale*cfactor;
+      jsux = 0; 
+      jj = 0;
+      if test1<0.001
+	test = test+1;
+      end
+      if test>4% If I do not progress enough I reduce the scale parameter
+               % of the jumping distribution (cooling down the system).
+	if isempty(indx)
+          init_scale = init_scale/1.10;
+        else
+          init_scale = init_scale/1.10;
+          % USEFUL IF THE MODEL IS TRUE:
+          % init_scale(indx+ns,indx+ns) = init_scale(indx+ns,indx+ns)*1.10/1.001; 
+        end
+      end
+    end
+    j = j+1;
+    jj = jj + 1;
+  end
+  close(hh);
+else
+  PostVar = CovJump;
+  PostMean = MeanPar;
+  Scale = init_scale;
+end
+PostMod = ModePar;
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/mgnldnsty.m b/tags/v_3.062/matlab/mgnldnsty.m
new file mode 100644
index 0000000000000000000000000000000000000000..9a0cbc7f891caf30e10f243c8a5661fdf68631d1
--- /dev/null
+++ b/tags/v_3.062/matlab/mgnldnsty.m
@@ -0,0 +1,50 @@
+function w=mgnldnsty(ydata,lags,xdata,breaks,lambda,mu,mnprior,vprior,train,flat)
+%function w=mgnldnsty(ydata,lags,xdata,breaks,lambda,mu,mnprior,vprior,train,flat)
+% ydata:        endogenous variable data matrix, including initial condition dates.
+% xdata:        exogenous variable data matrix, including initial condition dates.
+% breaks:       breaks in the data.  The first lags data points after a break are used
+%               as new initial conditions, not data points for the fit.
+% lambda:       weight on the co-persistence prior dummy observation.  (5 is reasonable)
+%               lambda>0 => x variables included; lambda<0 => x variables excluded;
+% mu:           weight on variable-by-variable sum of coeffs dummy obs. (1 is reasonable)
+% mnprior.tight:weight on the Minnesota prior dummies.  Prior std dev on first lag is
+%               1/mnprior.tight
+% mnprior.decay:prior std dev on lag j is 1/j^decay
+% vprior.sig:   vector of nv prior std dev's of equation shocks
+% vprior.w:     weight on vcv dummies.  (1 is reasonable; higher values tighten up.)
+% train:        If present and non-zero, this is the point in the sample at which the
+%               "training sample" ends.  Prior x likelihood to this point is weighted to
+%               integrate to 1, and therefore is treated as if it were itself the prior.
+%               To do a pure training sample prior, set lambda=mu=0, mnprior=vprior=[],
+%               train>lags.  
+%
+%flat:          Even with lambda=mu=0, vprior=mnprior=[], det(Sigma)^(-(nv+1)/2) is used
+%               as a "prior", unless flat=1.  flat, if present, must be 1 or 0.
+%               flat=1 is likely not to work unless train is reasonably large.
+if nargin<10,flat=0;end
+[T,nv]=size(ydata);
+[Tx,nx]=size(xdata);
+if Tx ~= T, error('ydata and xdata length mismatch'),end
+[ydum,xdum,pbreaks]=varprior(nv,nx,lags,mnprior,vprior);
+var=rfvar3([ydata;ydum],lags,[xdata;xdum],[breaks;T;T+pbreaks],lambda,mu);
+Tu=size(var.u,1);
+w=matrictint(var.u'*var.u,var.xxi,Tu-flat*(nv+1))-flat*.5*nv*(nv+1)*log(2*pi);
+if nargin>8
+    if ~isempty(train) & train>0
+        if train <= lags
+            error('end of training sample <= # of lags')
+        end
+        Tp=train;
+        tbreaks=breaks(find(breaks<train));
+    else
+        Tp=lags;
+        tbreaks=[];
+    end
+else
+    Tp=lags;
+    tbreaks=[];
+end
+varp=rfvar3([ydata(1:Tp,:);ydum],lags,[xdata(1:Tp);xdum],[tbreaks;Tp;Tp+pbreaks],lambda,mu);
+Tup=size(varp.u,1);
+wp=matrictint(varp.u'*varp.u,varp.xxi,Tup-flat*(nv+1)/2)-flat*.5*nv*(nv+1)*log(2*pi);
+w=w-wp;
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/mh_optimal_bandwidth.m b/tags/v_3.062/matlab/mh_optimal_bandwidth.m
new file mode 100644
index 0000000000000000000000000000000000000000..f7350bea8cbb5b437cdc6c0cad884c3bf5e5dff5
--- /dev/null
+++ b/tags/v_3.062/matlab/mh_optimal_bandwidth.m
@@ -0,0 +1,150 @@
+function optimal_bandwidth = mh_optimal_bandwidth(data,n,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.  
+%% 
+%%  * M. Skold and G.O. Roberts [2003], "Density estimation for the Metropolis-Hastings algorithm". 
+%%  * Silverman [1986], "Density estimation for statistics and data analysis". 
+%%
+%%  data            :: a vector with n elements.
+%%  bandwidth       :: a scalar equal to 0,-1 or -2. For a value different from 0,-1 or -2 the
+%%                     function will return optimal_bandwidth = bandwidth.
+%%  kernel_function :: 'gaussian','uniform','triangle','epanechnikov',
+%%                     'quartic','triweight','cosinus'.
+%%
+%%  stephane.adjemian@cepremap.cnrs.fr [07-15-2004] <-- [01/16/2004] 
+
+
+%% KERNEL SPECIFICATION...
+if strcmpi(kernel_function,'gaussian') 
+    k    = inline('inv(sqrt(2*pi))*exp(-0.5*x.^2)'); 
+    k2   = inline('inv(sqrt(2*pi))*(-exp(-0.5*x.^2)+(x.^2).*exp(-0.5*x.^2))'); % second derivate of the gaussian kernel 
+    k4   = inline('inv(sqrt(2*pi))*(3*exp(-0.5*x.^2)-6*(x.^2).*exp(-0.5*x.^2)+(x.^4).*exp(-0.5*x.^2))'); % fourth derivate... 
+    k6   = inline('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))'); % sixth derivate... 
+    mu02 = inv(2*sqrt(pi)); 
+    mu21 = 1; 
+elseif strcmpi(kernel_function,'uniform') 
+    k    = inline('0.5*(abs(x) <= 1)'); 
+    mu02 = 0.5; 
+    mu21 = 1/3; 
+elseif strcmpi(kernel_function,'triangle') 
+    k    = inline('(1-abs(x)).*(abs(x) <= 1)'); 
+    mu02 = 2/3; 
+    mu21 = 1/6; 
+elseif strcmpi(kernel_function,'epanechnikov') 
+    k    = inline('0.75*(1-x.^2).*(abs(x) <= 1)'); 
+    mu02 = 3/5; 
+    mu21 = 1/5;     
+elseif strcmpi(kernel_function,'quartic') 
+    k    = inline('0.9375*((1-x.^2).^2).*(abs(x) <= 1)'); 
+    mu02 = 15/21; 
+    mu21 = 1/7; 
+elseif strcmpi(kernel_function,'triweight') 
+    k    = inline('1.09375*((1-x.^2).^3).*(abs(x) <= 1)'); 
+    k2   = inline('(105/4*(1-x.^2).*x.^2-105/16*(1-x.^2).^2).*(abs(x) <= 1)'); 
+    k4   = inline('(-1575/4*x.^2+315/4).*(abs(x) <= 1)'); 
+    k6   = inline('(-1575/2).*(abs(x) <= 1)'); 
+    mu02 = 350/429; 
+    mu21 = 1/9;     
+elseif strcmpi(kernel_function,'cosinus') 
+    k    = inline('(pi/4)*cos((pi/2)*x).*(abs(x) <= 1)'); 
+    k2   = inline('(-1/16*cos(pi*x/2)*pi^3).*(abs(x) <= 1)'); 
+    k4   = inline('(1/64*cos(pi*x/2)*pi^5).*(abs(x) <= 1)'); 
+    k6   = inline('(-1/256*cos(pi*x/2)*pi^7).*(abs(x) <= 1)'); 
+    mu02 = (pi^2)/16; 
+    mu21 = (pi^2-8)/pi^2;     
+else
+    disp('mh_optimal_bandwidth :: ');
+    error('This kernel function is not yet implemented in Dynare!');        
+end     
+
+
+%% OPTIMAL BANDWIDTH PARAMETER....
+if bandwidth == 0;  %  Rule of thumb bandwidth parameter (Silverman [1986] corrected by 
+                    %  Skold and Roberts [2003] for Metropolis-Hastings). 
+    sigma = std(data); 
+    h = 2*sigma*(sqrt(pi)*mu02/(12*(mu21^2)*n))^(1/5); % Silverman's optimal bandwidth parameter. 
+    A = 0; 
+    for i=1:n; 
+        j = i; 
+        while j<= n & data(j,1)==data(i,1); 
+            j = j+1; 
+        end;     
+        A = A + 2*(j-i) - 1; 
+    end; 
+    A = A/n; 
+    h = h*A^(1/5); % correction 
+elseif bandwidth == -1;     % Adaptation of the Sheather and Jones [1991] plug-in estimation of the optimal bandwidth 
+                            % parameter for metropolis hastings algorithm. 
+    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;         
+    sigma = std(data); 
+    A = 0; 
+    for i=1:n; 
+        j = i; 
+        while j<= n & data(j,1)==data(i,1); 
+            j = j+1; 
+        end;     
+        A = A + 2*(j-i) - 1; 
+    end; 
+    A = A/n; 
+    Itilda4 = 8*7*6*5/(((2*sigma)^9)*sqrt(pi)); 
+    g3      = abs(2*A*k6(0)/(mu21*Itilda4*n))^(1/9); 
+    Ihat3 = 0; 
+    for i=1:n; 
+        Ihat3 = Ihat3 + sum(k6((data(i,1)-data)/g3)); 
+    end;     
+    Ihat3 = -Ihat3/((n^2)*g3^7); 
+    g2      = abs(2*A*k4(0)/(mu21*Ihat3*n))^(1/7); 
+    Ihat2 = 0; 
+    for i=1:n; 
+        Ihat2 = Ihat2 + sum(k4((data(i)-data)/g2)); 
+    end;     
+    Ihat2 = Ihat2/((n^2)*g2^5); 
+    h       = (A*mu02/(n*Ihat2*mu21^2))^(1/5);    % equation (22) in Skold and Roberts [2003] --> h_{MH} 
+elseif bandwidth == -2;     % Bump killing... We construct 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;         
+    sigma = std(data); 
+    A = 0; 
+    T = zeros(n,1); 
+    for i=1:n; 
+        j = i; 
+        while j<= n & data(j,1)==data(i,1); 
+            j = j+1; 
+        end;     
+        T(i) = (j-i); 
+        A = A + 2*T(i) - 1; 
+    end; 
+    A = A/n; 
+    Itilda4 = 8*7*6*5/(((2*sigma)^9)*sqrt(pi)); 
+    g3      = abs(2*A*k6(0)/(mu21*Itilda4*n))^(1/9); 
+    Ihat3 = 0; 
+    for i=1:n; 
+        Ihat3 = Ihat3 + sum(k6((data(i,1)-data)/g3)); 
+    end;     
+    Ihat3 = -Ihat3/((n^2)*g3^7); 
+    g2      = abs(2*A*k4(0)/(mu21*Ihat3*n))^(1/7); 
+    Ihat2 = 0; 
+    for i=1:n; 
+        Ihat2 = Ihat2 + sum(k4((data(i)-data)/g2)); 
+    end;     
+    Ihat2 = Ihat2/((n^2)*g2^5); 
+    h = ((2*T-1)*mu02/(n*Ihat2*mu21^2)).^(1/5); % Note that h is a column vector (local banwidth parameters). 
+elseif bandwidth > 0 
+    h = bandwidth; 
+else
+    disp('mh_optimal_bandwidth :: ');
+    error('Parameter bandwidth must be a real parameter value or equal to 0,-1 or -2.'); 
+end
+
+optimal_bandwidth = h;
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/mj_optmumlik.m b/tags/v_3.062/matlab/mj_optmumlik.m
new file mode 100644
index 0000000000000000000000000000000000000000..c41c97aa203e7fdb886121b1a40037daa68af3a6
--- /dev/null
+++ b/tags/v_3.062/matlab/mj_optmumlik.m
@@ -0,0 +1,223 @@
+% Program calculating the posterior density 
+% 1. define xparam
+% 2. call model setup & reduction program
+% 3. prepare state space variables and kalman-filter setup
+% 4. evaluate likelihood with kalman filter
+% 5. evaluate prior
+%------------------------------------------------------------------------------
+%------------------------------------------------------------------------------
+function [fval,cost_flag,atT,innov,ys,trend_coeff] = ...
+      mj_optmumlik(xparam1,gend,rawdata,algo);
+
+% algo = 1: computes filter + likelihood
+% alog = 2: computes filter + likelihood + smoother
+
+global bayestopt_ exo_nbr dr_ estim_params_ Sigma_e_ options_ xparam_test ...
+    dr1_test_ trend_coeff_
+
+xparam_test = xparam1;
+cost_flag = 1;
+if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb)
+  k = find(xparam1 < bayestopt_.lb);
+  fval = bayestopt_.penalty+sum(bayestopt_.lb(k)-xparam1(k));
+  cost_flag = 0;
+  return;
+end
+if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub)
+  k = find(xparam1 > bayestopt_.ub);
+  fval = bayestopt_.penalty+sum(xparam1(k)-bayestopt_.ub(k));
+  cost_flag = 0;
+  return;
+end
+
+nobs = size(options_.varobs,1);
+
+q = Sigma_e_;
+for i=1:estim_params_.nvx
+  k =estim_params_.var_exo(i,1);
+  q(k,k) = xparam1(i)*xparam1(i);
+end
+
+offset = estim_params_.nvx;
+h = zeros(nobs,nobs);
+for i=1:estim_params_.nvn
+  k =estim_params_.var_endo(i,1);
+  h(k,k) = xparam1(i+offset)*xparam1(i+offset);
+end
+
+offset = offset+estim_params_.nvn;
+for i=1:estim_params_.ncx
+  k1 =estim_params_.corrx(i,1);
+  k2 =estim_params_.corrx(i,2);
+  q(k1,k2) = xparam1(i+offset)*sqrt(q(k1,k1)*q(k2,k2));
+  q(k2,k1) = q(k1,k2);
+end
+
+offset = offset+estim_params_.ncx;
+for i=1:estim_params_.ncn
+  k1 =estim_params_.corrn(i,1);
+  k2 =estim_params_.corrn(i,2);
+  h(k1,k2) = xparam1(i+offset)*sqrt(h(k1,k1)*h(k2,k2));
+  h(k2,k1) = h(k1,k2);
+end
+
+offset = offset+estim_params_.ncn;
+for i=1:estim_params_.np
+   assignin('base',deblank(estim_params_.param_names(i,:)),xparam1(i+offset));
+end
+
+%------------------------------------------------------------------------------
+% 2. call model setup & reduction program
+%------------------------------------------------------------------------------
+
+[A,B,ys] = dynare_resolve;
+
+if dr1_test_(1) == 1
+    fval = bayestopt_.penalty*exp(dr1_test_(2));
+    cost_flag = 0;
+    return;
+elseif dr1_test_(1) == 2;
+    fval = bayestopt_.penalty*exp(dr1_test_(2));
+    cost_flag = 0;
+    return;
+elseif dr1_test_(1) == 3;
+    fval = bayestopt_.penalty*exp(dr1_test_(2));
+    cost_flag = 0;
+    return;    
+end
+
+if options_.loglinear == 1
+  ys1 = log(ys(bayestopt_.mfys));
+else
+  ys1 = ys(bayestopt_.mfys);
+end
+
+aa = A;
+
+np = size(A,1);
+mf = eye(np);
+mf = bayestopt_.mf;
+
+% Set initial values                                             @
+
+
+at = zeros(np,gend+1);            
+gconst = log(2*pi);
+lik = zeros(gend,1);
+
+if options_.lik_init == 1
+  p0 = lyapunov_symm(aa,B*q*B');
+elseif options_.lik_init == 2
+  p0=eye(np)*10.0; 
+end
+pt = p0;        
+BqB = B*q*B';
+
+trend_coeff = zeros(nobs,1);
+if bayestopt_.with_trend == 1
+  nx1 = estim_params_.nvx+estim_params_.nvn+estim_params_.ncx+ ...
+	estim_params_.ncn;
+  for i=1:nobs
+    trend_coeff(i) = eval(bayestopt_.trend_coeff{i});
+  end
+end
+
+not_steady = 1;
+ldetf_old = NaN;
+warning_state = warning;
+warning off;
+if algo == 1
+  for t = 1:gend
+    if not_steady
+      ptt1 = aa*pt*aa'+BqB;               
+      f = ptt1(mf,mf)+h;    
+      ldetf = log(det(f));
+      finv = inv(f);                    
+      if any(isinf(finv)) | ~isreal(ldetf)
+	disp('singularity in Kalman filter');
+        fval = bayestopt_.penalty;
+	warning(warning_state);
+	cost_flag = 0;
+	dr1_test_(1) = 4;
+	return
+      end
+      pt = ptt1-ptt1(:,mf)*finv*ptt1(mf,:);
+      if abs(ldetf-ldetf_old) < 1e-12
+	not_steady = 0;
+      end
+      ldetf_old = ldetf;
+    end
+    att1 = aa*at(:,t);                
+    v  = rawdata(t,:)'-att1(mf,:)-ys1;
+    if bayestopt_.with_trend == 1
+      v = v - trend_coeff*t;
+    end
+    at(:,t+1) = att1+ptt1(:,mf)*finv*v;   
+    if t > options_.presample
+      lik(t,1) = ldetf+v'*finv*v;
+    end
+  end 
+elseif algo == 2
+  PPt = zeros(np^2,gend);
+  for t = 1:gend
+    if not_steady
+      ptt1 = aa*pt*aa'+BqB;               
+      f = ptt1(mf,mf)+h;    
+      ldetf = log(det(f));
+      finv = inv(f);                    
+      if any(isinf(finv)) | ~isreal(ldetf)
+%        disp('singularity in Kalman filter');
+        fval = bayestopt_.penalty;
+	warning(warning_state);
+	cost_flag = 0;
+	dr1_test_(1) = 4;
+	return
+      end
+      pt = ptt1-ptt1(:,mf)*finv*ptt1(mf,:);
+      if abs(ldetf-ldetf_old) < 1e-12
+	not_steady = 0;
+      end
+      ldetf_old = ldetf;
+    end
+    att1 = aa*at(:,t);                
+    v  = rawdata(t,:)' - att1(mf,:) - ys1;
+    if bayestopt_.with_trend == 1
+      v = v - trend_coeff*t;
+    end
+    at(:,t+1) = att1+ptt1(:,mf)*finv*v;   
+    PPt(:,t) = pt(:);
+    if t > options_.presample
+      lik(t,1) = ldetf+v'*finv*v;
+    end
+  end 
+  atT =zeros(np,gend+1);
+  atT(:,gend+1) = at(:,gend+1);
+  innov = zeros(exo_nbr,gend);
+  for t = gend:-1:1
+    pt = reshape(PPt(:,t),np,np);
+    ptt1 = aa*pt*aa'+BqB;
+    Pstar = pt*aa'*pinv(ptt1);
+    atT(:,t) = at(:,t)+Pstar*(atT(:,t+1)-aa*at(:,t));
+    shocks1 = atT(:,t+1)-aa*atT(:,t);
+    innov(:,t) = B\shocks1;
+  end
+end
+
+warning(warning_state);
+
+likelihood = 0.5*sum(nobs*gconst+lik(options_.presample+1:end));
+
+if imag(likelihood) ~= 0
+  
+   likelihood = 10000000;
+end
+
+% ------------------------------------------------------------------------------
+% PRIOR SPECIFICATION
+% ------------------------------------------------------------------------------
+
+lnprior = priordens(xparam1, bayestopt_.pshape, bayestopt_.p1, bayestopt_.p2, bayestopt_.p3, bayestopt_.p4 );
+
+fval = (likelihood-lnprior);
+
+% 11/18/03 MJ changed input parameters for priordens()
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/mj_qgamma.m b/tags/v_3.062/matlab/mj_qgamma.m
new file mode 100644
index 0000000000000000000000000000000000000000..cf927c253e0a3faf2e257310b14000d1a9a2df4c
--- /dev/null
+++ b/tags/v_3.062/matlab/mj_qgamma.m
@@ -0,0 +1,30 @@
+function x = mj_qgamma(p,a)
+%MJ_QGAMMA   The gamma inverse distribution function
+%
+%         x = mj_qgamma(p,a)
+
+%        Anders Holtsberg, 18-11-93
+%        Copyright (c) Anders Holtsberg
+% MJ 02/20/04 uses lpdfgam() to avoid overflow in dgamma
+%
+  
+if any(any(abs(2*p-1)>1))
+   error('A probability should be 0<=p<=1, please!')
+end
+if any(any(a<=0))
+   error('Parameter a is wrong')
+end
+
+x = max(a-1,0.1);
+dx = 1;
+while any(any(abs(dx)>256*eps*max(x,1)))
+%   dx = (pgamma(x,a) - p) ./ dgamma(x,a,1);
+   dx = (pgamma(x,a) - p) ./ exp(lpdfgam(x,a,1));
+   x = x - dx;
+   x = x + (dx - x) / 2 .* (x<0);
+end
+
+I0 = find(p==0);
+x(I0) = zeros(size(I0));
+I1 = find(p==1);
+x(I1) = zeros(size(I1)) + Inf;
diff --git a/tags/v_3.062/matlab/mjdgges.dll b/tags/v_3.062/matlab/mjdgges.dll
new file mode 100755
index 0000000000000000000000000000000000000000..346c607564c7cfa770bb8d4c7a7a407e4def88fc
Binary files /dev/null and b/tags/v_3.062/matlab/mjdgges.dll differ
diff --git a/tags/v_3.062/matlab/mode_check.m b/tags/v_3.062/matlab/mode_check.m
new file mode 100644
index 0000000000000000000000000000000000000000..342bced812c394cd663966f1ee72a88d90992147
--- /dev/null
+++ b/tags/v_3.062/matlab/mode_check.m
@@ -0,0 +1,193 @@
+function mode_check(x,fval,hessian,gend,data,lb,ub)
+global bayestopt_ estim_params_ fname_ options_ dsge_prior_weight
+
+TeX = options_.TeX;
+[s_min,k] = min(diag(hessian))
+  
+disp('\nMODE CHECK\n')
+disp(sprintf('Fval obtained by fmincon: %f', fval))
+disp(bayestopt_.name)
+cname = bayestopt_.name{k};
+disp(sprintf('Most negative variance %f for parameter %d (%s = %f)',s_min,k,cname,x(k)))
+
+[nbplt,nr,nc,lr,lc,nstar] = pltorg(length(x));
+
+if TeX
+  fidTeX = fopen([fname_ '_CheckPlots.TeX'],'w');
+  fprintf(fidTeX,'%% TeX eps-loader file generated by mode_check.m (Dynare).\n');
+  fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
+  fprintf(fidTeX,' \n');
+end
+
+
+if nbplt == 1
+  if TeX
+    NAMES = [];
+    TeXNAMES = [];
+  end    
+  hh = figure('Name','Check plots');
+  for k=1:length(x)
+    subplot(nr,nc,k)
+    [name,texname] = get_the_name(k,TeX);
+    if TeX
+      NAMES = strvcat(NAMES,name);
+      TeXNAMES = strvcat(TeXNAMES,texname);
+    end    
+    xx = x;
+    l1 = max(lb(k),0.8*x(k)); % kk -> k
+    l2 = min(ub(k),1.2*x(k)); % kk -> k
+    z = [l1:(l2-l1)/20:l2];
+    y = zeros(length(z),1);
+    for i=1:length(z)
+      xx(k) = z(i); % kk -> k
+      if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+	y(i) = DsgeLikelihood(xx,gend,data);
+      else
+	y(i) = DsgeVarLikelihood(xx,gend);
+      end    
+    end
+    plot(z,y)
+    hold on
+    yl=get(gca,'ylim');
+    plot([x(k) x(k)],yl,'c','LineWidth', 1);% kk -> k
+    title(name,'interpreter','none');
+    hold off
+    drawnow
+  end
+  eval(['print -depsc2 ' fname_ '_CheckPlots' int2str(1)]);
+  eval(['print -dpdf ' fname_ '_CheckPlots' int2str(1)]);
+  saveas(hh,[fname_ '_CheckPlots' int2str(1) '.fig']);
+  if options_.nograph, close(hh), end  
+  % TeX eps loader file
+  if TeX
+    fprintf(fidTeX,'\\begin{figure}[H]\n');
+    for jj = 1:length(x)
+      fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:)));
+    end    
+    fprintf(fidTeX,'\\centering \n');
+    fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_CheckPlots%s}\n',fname_,int2str(1));
+    fprintf(fidTeX,'\\caption{Priors.}');
+    fprintf(fidTeX,'\\label{Fig:CheckPlots:%s}\n',int2str(1));
+    fprintf(fidTeX,'\\end{figure}\n');
+    fprintf(fidTeX,'\n');
+    fprintf(fidTeX,'%% End of TeX file.\n');
+    fclose(fidTeX);
+  end    
+else
+  for plt = 1:nbplt-1
+    if TeX
+      NAMES = [];
+      TeXNAMES = [];
+    end    
+    hh = figure('Name','Check plots');
+    for k=1:nstar
+      subplot(nr,nc,k)
+      kk = (plt-1)*nstar+k;
+      [name,texname] = get_the_name(kk,TeX);
+      if TeX
+	NAMES = strvcat(NAMES,name);
+	TeXNAMES = strvcat(TeXNAMES,texname);
+      end    
+      xx = x;
+      l1 = max(lb(kk),0.8*x(kk));
+      l2 = min(ub(kk),1.2*x(kk));
+      z = [l1:(l2-l1)/20:l2];
+      y = zeros(length(z),1);
+      for i=1:length(z)
+	xx(kk) = z(i);
+	if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+	  y(i) = DsgeLikelihood(xx,gend,data);
+	else
+	  y(i) = DsgeVarLikelihood(xx,gend);
+	end
+      end
+      plot(z,y);
+      hold on
+      yl=get(gca,'ylim');
+      plot( [x(kk) x(kk)], yl, 'c', 'LineWidth', 1)
+      title(name,'interpreter','none')
+      hold off
+      drawnow
+    end    
+    eval(['print -depsc2 ' fname_ '_CheckPlots' int2str(plt)]);
+    eval(['print -dpdf ' fname_ '_CheckPlots' int2str(plt)]);
+    saveas(hh,[fname_ '_CheckPlots' int2str(plt) '.fig']);
+    if options_.nograph, close(hh), end
+    if TeX
+      % TeX eps loader file    
+      fprintf(fidTeX,'\\begin{figure}[H]\n');
+      for jj = 1:nstar
+	fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:)));
+      end    
+      fprintf(fidTeX,'\\centering \n');
+      fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_CheckPlots%s}\n',fname_,int2str(plt));
+      fprintf(fidTeX,'\\caption{Check plots.}');
+      fprintf(fidTeX,'\\label{Fig:CheckPlots:%s}\n',int2str(plt));
+      fprintf(fidTeX,'\\end{figure}\n');
+      fprintf(fidTeX,' \n');
+    end
+  end
+  hh = figure('Name','Check plots');
+  k = 1;
+  if TeX
+    NAMES = [];
+    TeXNAMES = [];
+  end
+  while (nbplt-1)*nstar+k <= length(x)
+    kk = (nbplt-1)*nstar+k;
+    [name,texname] = get_the_name(kk,TeX);
+    if TeX
+      NAMES = strvcat(NAMES,name);
+      TeXNAMES = strvcat(TeXNAMES,texname);
+    end    
+    if lr ~= 0
+      subplot(lr,lc,k)
+    else
+      subplot(nr,nc,k)
+    end    
+    xx = x;
+    l1 = max(lb(kk),0.8*x(kk));
+    l2 = min(ub(kk),1.2*x(kk));
+    z = [l1:(l2-l1)/20:l2];
+    y = zeros(length(z),1);
+    for i=1:length(z)
+      xx(kk) = z(i);
+      if isempty(strmatch('dsge_prior_weight',estim_params_.param_names)) & isempty(dsge_prior_weight)
+	y(i) = DsgeLikelihood(xx,gend,data);
+      else
+	y(i) = DsgeVarLikelihood(xx,gend);
+      end
+    end
+    plot(z,y)
+    hold on
+    yl=get(gca,'ylim');
+    plot( [x(kk) x(kk)], yl, 'c', 'LineWidth', 1)
+    title(name,'interpreter','none')
+    hold off
+    k = k + 1;
+    drawnow
+  end
+  eval(['print -depsc2 ' fname_ '_CheckPlots' int2str(nbplt)]);
+  eval(['print -dpdf ' fname_ '_CheckPlots' int2str(nbplt)]);
+  saveas(hh,[fname_ '_CheckPlots' int2str(nbplt) '.fig']);
+  if options_.nograph, close(hh), end
+  if TeX
+    fprintf(fidTeX,'\\begin{figure}[H]\n');
+    for jj = 1:lr*lc
+      fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:)));
+    end    
+    fprintf(fidTeX,'\\centering \n');
+    fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_CheckPlots%s}\n',fname_,int2str(nbplt));
+    fprintf(fidTeX,'\\caption{Check plots.}');
+    fprintf(fidTeX,'\\label{Fig:CheckPlots:%s}\n',int2str(nbplt));
+    fprintf(fidTeX,'\\end{figure}\n');
+    fprintf(fidTeX,' \n');
+    fprintf(fidTeX,'%% End of TeX file.\n');
+    fclose(fidTeX);
+  end
+end
+
+% SA 07-31-2004     * New default : no more than nine plots per figure.
+%                   * Figures are automatically saved in eps, pdf and fig formats.
+%                   * Figures are automatically closed (this should be an option).
+%                   * Creation of a TeX-loader file for the postcript file. 
diff --git a/tags/v_3.062/matlab/model_comparison.m b/tags/v_3.062/matlab/model_comparison.m
new file mode 100644
index 0000000000000000000000000000000000000000..7319cea376924a05c91eefdd6f29fbded3934ffe
--- /dev/null
+++ b/tags/v_3.062/matlab/model_comparison.m
@@ -0,0 +1,92 @@
+function PosteriorOddsTable = model_comparison(ModelNames,ModelPriors)
+% 05-30-2005
+%
+% type is a string  = Laplace
+%                   = ModifiedHarmonicMean
+% ModelPriors is a m*1 column vector
+% ModelNames is m*1 cell array
+
+global oo_ options_ fname_
+
+tmp_oo = oo_;
+if isfield(options_,'model_comparison_approximation')
+  type = options_.model_comparison_approximation;
+else
+  type = '';
+end
+
+if strcmp(type,'Laplace')
+  type = 'LaplaceApproximation';
+end
+
+NumberOfModels = size(ModelNames,1);
+MarginalLogDensity = zeros(NumberOfModels,1);
+if isempty(ModelPriors)
+  ModelPriors = ones(NumberOfModels,1);
+end
+
+% Get the estimates of the (logged) marginal densities
+
+init_loop = 1;
+if isempty(type)
+  if strcmp(ModelNames{1},fname_)
+    oo_ = tmp_oo;
+  else
+    load([ModelNames{1} '_results.mat' ],'oo_');
+  end
+  try
+    type = 'LaplaceApproximation';
+    eval(['MarginalLogDensity(1) =' ...
+	  ' oo_.MarginalDensity.LaplaceApproximation;']);
+  catch
+    try
+      type = 'ModifiedHarmonicMean';
+      eval(['MarginalLogDensity(1) = oo_.MarginalDensity.ModifiedHarmonicMean;']); 
+    catch
+      disp(['CompareModels :: I cant''t find any marginal density approximation associated to model ' ModelNames{1}])
+      return
+    end
+  end
+  init_loop = 2;
+end
+for i = init_loop:NumberOfModels
+  if strcmp(ModelNames{i},fname_)
+    oo_ = tmp_oo;
+  else
+    load([ModelNames{i} '_results.mat' ],'oo_');
+  end
+  try
+    eval(['MarginalLogDensity(i) = oo_.MarginalDensity.' type ';']) 
+  catch
+    if strcmpi(type,'LaplaceApproximation')
+      disp(['CompareModels :: I cant''t find the Laplace approximation associated to model ' ModelNames{i}])
+      return
+    elseif strcmpi(type,'ModifiedHarmonicMean')
+      disp(['CompareModels :: I cant''t find the modified harmonic mean estimate associated to model ' ModelNames{i}])
+      return
+    end
+  end
+end
+
+%MarginalDensity = exp(MarginalLogDensity);
+LogConstantOfIntegration  = sum(log(ModelPriors)+MarginalLogDensity);
+PosteriorProbabilities = log(ModelPriors) + MarginalLogDensity - ...
+    LogConstantOfIntegration;
+
+PosteriorOddsTable = exp(repmat(PosteriorProbabilities,1,NumberOfModels)- ...
+			 repmat(PosteriorProbabilities',NumberOfModels,1));
+
+% Now I display the posterior probabilities:
+if NumberOfModels == 2
+    disp(' ')
+    disp(['Posterior odd (' ModelNames{1} '/' ModelNames{2} ') =  ' num2str(PosteriorOddsTable(1,2))])
+    disp(' ')
+else
+    disp(' ')
+    disp(' Posterior probabilities:')
+    for i=1:NumberOfModels
+            disp([ 'Model ' int2str(i) ' (' ModelNames{i} ') = ' num2str(PosteriorProbabilities(i))])
+    end
+    disp(' ')
+end
+oo_ = tmp_oo;
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/mr_hessian.m b/tags/v_3.062/matlab/mr_hessian.m
new file mode 100644
index 0000000000000000000000000000000000000000..5925d3446d7485108026abb63a5ffbf338a4b2ea
--- /dev/null
+++ b/tags/v_3.062/matlab/mr_hessian.m
@@ -0,0 +1,131 @@
+% Copyright (C) 2001 Michel Juillard
+%
+% computes second order partial derivatives
+% uses Abramowitz and Stegun (1965) formulas 25.3.24 and 25.3.27 p. 884
+%
+% Adapted by M. Ratto from original M. Juillard routine
+%
+function [hessian_mat, gg] = mr_hessian(func,x,hflag,varargin)
+global gstep_
+persistent h1
+
+func = str2func(func);
+f0=feval(func,x,varargin{:});
+n=size(x,1);
+%h1=max(abs(x),gstep_*ones(n,1))*eps^(1/3);
+%h1=max(abs(x),sqrt(gstep_)*ones(n,1))*eps^(1/6);
+if isempty(h1),
+    h1=max(abs(x),sqrt(gstep_)*ones(n,1))*eps^(1/4);
+end
+htol = 1.e-4;
+xh1=x;
+f1=zeros(size(f0,1),n);
+f_1=f1;
+
+for i=1:n,
+    xh1(i)=x(i)+h1(i);
+    fx=feval(func,xh1,varargin{:});
+    if abs(fx-f0)<htol | abs(fx-f0)>(5*htol),
+        c=mr_nlincon(xh1,varargin{:});
+        ic=0;
+        while c
+            h1(i)=h1(i)*0.9;
+            xh1(i)=x(i)+h1(i);
+            c=mr_nlincon(xh1,varargin{:});        
+            ic=1;
+        end   
+        if ic,
+            fx=feval(func,xh1,varargin{:});
+        end
+
+        icount = 0;
+        while abs(fx-f0)<htol & icount< 10,
+            icount=icount+1;
+            h1(i)=min(0.3*abs(x(i)), 1.e-3/(abs(fx-f0)/h1(i)));
+            xh1(i)=x(i)+h1(i);
+            c=mr_nlincon(xh1,varargin{:});
+            while c
+                h1(i)=h1(i)*0.9;
+                xh1(i)=x(i)+h1(i);
+                c=mr_nlincon(xh1,varargin{:});        
+            end        
+            fx=feval(func,xh1,varargin{:});
+        end
+        while abs(fx-f0)>(5*htol),
+            h1(i)=h1(i)*0.5;    
+            xh1(i)=x(i)+h1(i);
+            fx=feval(func,xh1,varargin{:});
+        end
+    end
+    f1(:,i)=fx;
+    xh1(i)=x(i)-h1(i);
+    c=mr_nlincon(xh1,varargin{:});
+    ic=0;
+    while c
+        h1(i)=h1(i)*0.9;
+        xh1(i)=x(i)-h1(i);
+        c=mr_nlincon(xh1,varargin{:});  
+        ic = 1;
+    end    
+    fx=feval(func,xh1,varargin{:});
+    f_1(:,i)=fx;
+    if ic,
+        xh1(i)=x(i)+h1(i);
+        f1(:,i)=feval(func,xh1,varargin{:});
+    end
+    xh1(i)=x(i);
+end
+
+h_1=h1;
+xh1=x;
+xh_1=xh1;
+gg=(f1'-f_1')./(2.*h1);
+
+if hflag,
+    hessian_mat = zeros(size(f0,1),n*n);
+    for i=1:n
+        if i > 1
+            k=[i:n:n*(i-1)];
+            hessian_mat(:,(i-1)*n+1:(i-1)*n+i-1)=hessian_mat(:,k);
+        end 
+        hessian_mat(:,(i-1)*n+i)=(f1(:,i)+f_1(:,i)-2*f0)./(h1(i)*h_1(i));
+        temp=f1+f_1-f0*ones(1,n);
+        for j=i+1:n
+            xh1(i)=x(i)+h1(i);
+            xh1(j)=x(j)+h_1(j);
+            xh_1(i)=x(i)-h1(i);
+            xh_1(j)=x(j)-h_1(j);
+            %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));
+            temp1 = feval(func,xh1,varargin{:});
+            %c=mr_nlincon(xh1,varargin{:});
+            %if c, disp( ['hessian warning cross ', num2str(c) ]), end
+            
+            temp2 = feval(func,xh_1,varargin{:});
+            %c=mr_nlincon(xh_1,varargin{:});
+            %if c, disp( ['hessian warning cross ', num2str(c) ]), end
+            hessian_mat(:,(i-1)*n+j)=-(-temp1 -temp2+temp(:,i)+temp(:,j))./(2*h1(i)*h_1(j));
+            xh1(i)=x(i);
+            xh1(j)=x(j);
+            xh_1(i)=x(i);
+            xh_1(j)=x(j);
+            j=j+1;
+        end
+        i=i+1;
+    end
+    
+else
+    hessian_mat = zeros(size(f0,1),n*n);
+    for i=1:n,
+        dum = (f1(:,i)+f_1(:,i)-2*f0)./(h1(i)*h_1(i));
+        if dum>0,
+            hessian_mat(:,(i-1)*n+i)=dum;
+        else
+            hessian_mat(:,(i-1)*n+i)=gg(i)^2;
+        end                        
+    end
+end
+hh1=h1;
+save hess
+% 11/25/03 SA Created from Hessian_sparse (removed sparse)
+
+
diff --git a/tags/v_3.062/matlab/mr_nlincon.m b/tags/v_3.062/matlab/mr_nlincon.m
new file mode 100644
index 0000000000000000000000000000000000000000..2938ab986ecd313b275d922ea5163a7539486a82
--- /dev/null
+++ b/tags/v_3.062/matlab/mr_nlincon.m
@@ -0,0 +1,123 @@
+% Program calculating the non-l;inear constraint for posterior mximisation
+% M. Ratto
+% adapted from mj_optmumlik.m
+%------------------------------------------------------------------------------
+%------------------------------------------------------------------------------
+function [c, ceq] = mr_nlincon(xparam1,gend,rawdata,algo);
+
+
+global bayestopt_ exo_nbr dr_ estim_params_ Sigma_e_ options_ xparam_test ...
+    trend_coeff_ 
+
+
+c=0;
+ceq=0;
+
+xparam_test = xparam1;
+cost_flag = 1;
+if options_.mode_compute ~= 1 && any(xparam1 < bayestopt_.lb)
+  k = find(xparam1 < bayestopt_.lb);
+  c = sum(bayestopt_.lb(k)-xparam1(k));
+  cost_flag = 0;
+  return;
+end
+if options_.mode_compute ~= 1 && any(xparam1 > bayestopt_.ub)
+  k = find(xparam1 > bayestopt_.ub);
+  c = sum(xparam1(k)-bayestopt_.ub(k));
+  cost_flag = 0;
+  return;
+end
+
+nobs = size(options_.varobs,1);
+
+Q = Sigma_e_;
+for i=1:estim_params_.nvx
+	k =estim_params_.var_exo(i,1);
+	Q(k,k) = xparam1(i)*xparam1(i);
+end
+offset = estim_params_.nvx;
+if estim_params_.nvn
+	H = zeros(nobs,nobs);
+	for i=1:estim_params_.nvn
+		k = estim_params_.var_endo(i,1);
+		H(k,k) = xparam1(i+offset)*xparam1(i+offset);
+	end
+	offset = offset+estim_params_.nvn;
+end	
+if estim_params_.ncx
+	for i=1:estim_params_.ncx
+		k1 =estim_params_.corrx(i,1);
+		k2 =estim_params_.corrx(i,2);
+		Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2));
+		Q(k2,k1) = Q(k1,k2);
+	end
+	[CholQ,testQ] = chol(Q);
+	if testQ 	%% The variance-covariance matrix of the structural innovations is not definite positive.
+    			%% We have to compute the eigenvalues of this matrix in order to build the penalty.
+    	a = diag(eig(Q));
+		%fval = bayestopt_.penalty*min(1e3,exp(sum(-a(a<=0))));
+    	c =  sum(-a(a<=0));
+    	cost_flag = 0;
+		return
+	end
+	offset = offset+estim_params_.ncx;
+end
+if estim_params_.nvn & estim_params_.ncn 
+	for i=1:estim_params_.ncn
+		k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1));
+		k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2));
+		H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2));
+		H(k2,k1) = H(k1,k2);
+	end
+	[CholH,testH] = chol(H);
+	if testH
+		a = diag(eig(H));
+		if nobs == estim_params_.nvn
+			% fval = bayestopt_.penalty*min(1e3,exp(sum(-a(a<=0))));
+   			c = sum(-a(a<=0));
+   			cost_flag = 0;
+			return
+		else
+			if sum(abs(a)<crit) == nobs-estim_params_.nvn
+				if any(a<0)
+					% fval = bayestopt_.penalty*min(1e3,exp(sum(-a(a<0))));
+   					c = sum(-a(a<0));
+   					cost_flag = 0;
+					return					
+				else
+					% All is fine, there's nothing to do here...
+				end 					
+			else
+				fval = bayestopt_.penalty*min(1e3,exp(sum(-a(a<=0))));
+   				c = sum(-a(a<=0));
+   				cost_flag = 0;
+				return			
+			end 
+		end
+	end
+	offset = offset+estim_params_.ncn;
+end
+for i=1:estim_params_.np
+	assignin('base',deblank(estim_params_.param_names(i,:)),xparam1(i+offset));
+end
+Sigma_e_ = Q;
+
+
+%------------------------------------------------------------------------------
+% 2. call model setup & reduction program
+%------------------------------------------------------------------------------
+
+[A,B,ys,info] = dynare_resolve;
+if info(1) == 1 | info(1) == 2 | info(1) == 5
+  fval = bayestopt_.penalty;
+  cost_flag = 0;
+  return
+elseif info(1) == 3 | info(1) == 4 | info(1) == 20
+  fval = bayestopt_.penalty*min(1e3,exp(info(2)));
+  cost_flag = 0;
+  return
+end
+
+
+
+% 11/18/03 MJ changed input parameters for priordens()
diff --git a/tags/v_3.062/matlab/my_subplot.m b/tags/v_3.062/matlab/my_subplot.m
new file mode 100644
index 0000000000000000000000000000000000000000..f264c3dcde5548a5ccb828b79018da1a36cf1f6d
--- /dev/null
+++ b/tags/v_3.062/matlab/my_subplot.m
@@ -0,0 +1,30 @@
+function my_subplot(i,imax,irow,icol,fig_title)
+% spreads subplots on several figures according to a maximum number of
+% subplots per figure
+%
+% INPUTS
+% i: subplot number
+% imax: total number of subplots
+% irow: maximum number of rows in a figure
+% icol: maximum number of columns in a figure
+% fig_title: title to be repeated on each figure
+  nfig_max = irow*icol;
+  if imax < nfig_max
+    icol = ceil(sqrt(imax));
+    irow=icol;
+    if (icol-1)*(icol-2) >= imax
+      irow = icol-2;
+      icol = icol-1;
+    elseif (icol)*(icol-2) >= imax
+      irow = icol-2;
+    elseif icol*(icol-1) >= imax
+      irow = icol-1;
+    end
+  end
+
+  i1 = mod(i-1,nfig_max);
+  if i1 == 0
+    figure('Name',fig_title);
+  end
+  
+  subplot(irow,icol,i1+1);
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/newrat.m b/tags/v_3.062/matlab/newrat.m
new file mode 100644
index 0000000000000000000000000000000000000000..8f241a617420163ee0450de31994a1e06ea76198
--- /dev/null
+++ b/tags/v_3.062/matlab/newrat.m
@@ -0,0 +1,159 @@
+function [xparam1, hh, gg, fval] = newrat(func0,x,hh,gg,flag,varargin)
+%
+%  [xparam1, hh, gg, fval] = newrat(func0,x,hh,gg,flag,varargin)
+%
+%  Standard Newton search
+%
+%  flag = 0, to begin with a pure gradient search (the program shifts to
+%  pure Newton when improvement of pure gradient is below ftol)
+%
+%  flag = 1, to start with the compelte Newton search
+
+  global bayestopt_
+icount=0;
+nx=length(x);
+xparam1=x;
+lamtol=1.e-7;
+ftol=1.e-5;
+options=optimset('fminunc');
+options.MaxFunEvals=200;
+options.TolFun= 1.0000e-005;
+options.MaxIter=1;
+options.LargeScale='off';
+
+optim_options=optimset('fminsearch');
+optim_options.display='iter';
+optim_options.MaxFunEvals=1000;
+optim_options.TolFun= 1.0000e-003;
+optim_options.TolX= 1.0000e-006;
+
+
+func = str2func(func0);
+fval0=feval(func,x,varargin{:});
+if isempty(hh)
+    [dum, gg]=mr_hessian(func0,x,flag,varargin{:});
+    hh = reshape(dum,nx,nx);
+end
+disp(['Gradient norm ',num2str(norm(gg))])
+disp(['Minimum Hessian eigenvalue ',num2str(min(eig(hh)))])
+disp(['Maximum Hessian eigenvalue ',num2str(max(eig(hh)))])
+g=gg;
+h{1}=hh;
+check=0;
+if max(eig(hh))<0, disp('Negative definite Hessian! Local maximum!'), pause, end,
+while norm(gg)>1.e-3 & check==0,
+    icount=icount+1;
+    bayestopt_.penalty = fval0(icount);
+    disp([' '])
+    disp(['Iteration ',num2str(icount)])
+    x0=xparam1-inv(hh)*gg;
+    c=mr_nlincon(x0,varargin{:},1);
+    lam=1;
+    while c
+        lam=lam*0.9;
+        x0=xparam1-inv(hh)*gg.*lam;
+        c=mr_nlincon(x0,varargin{:},1);
+    end        
+    fval=feval(func,x0,varargin{:});
+%     if (fval0(icount)-fval)<ftol & flag==0,
+%         fvala=fval;
+%         x0a=x0;
+%         disp('Try to modify Hessian')
+%         x0=xparam1-inv(gg*gg')*gg;
+%         c=mr_nlincon(x0,varargin{:},1);
+%         lam=1;
+%         while c
+%             lam=lam*0.9;
+%             x0=xparam1-inv(gg*gg')*gg.*lam;
+%             c=mr_nlincon(x0,varargin{:},1);
+%         end        
+%         fval=feval(func,x0,varargin{:});
+%         if fvala<=fval, 
+%             x0=x0a;
+%             fval=fvala;
+%         end            
+%     end            
+    if (fval0(icount)-fval)<ftol,
+        disp('Try line search')
+        [lam,fval,EXITFLAG,OUTPUT,GRAD,HESSIAN]=fminunc(@lsearch, 0, options, func, xparam1, inv(hh)*gg , varargin{:});
+        x0=xparam1-inv(hh)*gg.*lam;
+    end
+    if (fval0(icount)-fval)<ftol & flag==1,
+        fvala=fval;
+        x0a=x0;
+        disp('Try gradient direction')
+        [lam,fval,EXITFLAG,OUTPUT,GRAD,HESSIAN]=fminunc(@lsearch, 0, options, func, xparam1, gg , varargin{:});
+        if fvala<=fval, 
+            x0=x0a;
+            fval=fvala;
+        else
+            x0=xparam1-gg*lam;
+            if (fval0(icount)-fval)>ftol,
+                flag=0;
+            end
+        end
+    end
+    if (fval0(icount)-fval)<ftol,
+        fvala=fval;
+        x0a=x0;
+        disp('Try some simplex iterations')
+        [x0,fval,EXITFLAG,OUTPUT] = fminsearch(func, xparam1, optim_options, varargin{:});
+        if fvala<fval, 
+            x0=x0a;
+            fval=fvala;
+        else
+            lam = NaN;
+        end
+    end
+    if (fval0(icount)-fval)<ftol*ftol & flag==1;,
+        %         if fvala<fval,
+        %             fval=fvala;
+        %             x0=x0a;
+        %         end
+        disp('No further improvement is possible!')
+        check=1;
+    else
+        
+        if (fval0(icount)-fval)<ftol & flag==0,
+            flag=1;
+        end
+        
+        xparam1=x0;
+        x(:,icount+1)=xparam1;
+        fval0(icount+1)=fval;
+        disp(['LAMBDA        ',num2str(lam)])
+        %disp(['DX norm       ',num2str(norm(inv(hh)*gg.*lam))])
+        disp(['DX norm       ',num2str(norm(x(:,end)-x(:,end-1)))])
+        disp(['FVAL          ',num2str(fval)])
+        disp(['Improvement   ',num2str(fval0(icount)-fval)])
+        
+        if norm(x(:,icount)-xparam1)>1.e-12,
+            %[dum, gg]=hessian('mj_optmumlik',xparam1,gend,data,1);
+            [dum, gg]=mr_hessian(func0,xparam1,flag,varargin{:});
+            hh = reshape(dum,nx,nx);
+        end
+        disp(['Gradient norm  ',num2str(norm(gg))])
+        disp(['Minimum Hessian eigenvalue ',num2str(min(eig(hh)))])
+        disp(['Maximum Hessian eigenvalue ',num2str(max(eig(hh)))])
+        if max(eig(hh))<0, disp('Negative definite Hessian! Local maximum!'), pause, end,
+        
+        h{icount+1}=hh;
+        g(:,icount+1)=gg;
+        save m1 x h g fval0
+    end
+end
+
+return
+
+%  
+function f00 = lsearch(lam,func,x,dx,varargin)
+
+
+x0=x-dx*lam;
+f00=feval(func,x0,varargin{:});
+
+
+
+
+
+
diff --git a/tags/v_3.062/matlab/numgrad.m b/tags/v_3.062/matlab/numgrad.m
new file mode 100644
index 0000000000000000000000000000000000000000..03457df2fe6c7fae75ea4ba2e230d9fd59beb7da
--- /dev/null
+++ b/tags/v_3.062/matlab/numgrad.m
@@ -0,0 +1,98 @@
+function [g, badg] = numgrad(fcn,x,varargin)
+% function [g badg] = numgrad(fcn,xvarargin)
+%
+delta = 1e-6;
+%delta=1e-2;
+n=length(x);
+tvec=delta*eye(n);
+g=zeros(n,1);
+%--------------------old way to deal with variable # of P's--------------
+%tailstr = ')';
+%stailstr = [];
+%for i=nargin-2:-1:1
+%   tailstr=[ ',P' num2str(i)  tailstr];
+%   stailstr=[' P' num2str(i) stailstr];
+%end
+%f0 = eval([fcn '(x' tailstr]); % Is there a way not to do this?
+%---------------------------------------------------------------^yes
+f0 = eval([fcn '(x,varargin{:})']);
+% disp(' first fcn in numgrad.m ------------------')
+%home
+% disp('numgrad.m is working. ----') % Jiinil on 9/5/95
+% sizex=size(x),sizetvec=size(tvec),x,    % Jinill on 9/6/95
+badg=0;
+for i=1:n
+   scale=1; % originally 1
+   % i,tveci=tvec(:,i)% ,plus=x+scale*tvec(:,i) % Jinill Kim on 9/6/95
+   if size(x,1)>size(x,2)
+      tvecv=tvec(i,:);
+   else
+      tvecv=tvec(:,i);
+   end
+   g0 = (eval([fcn '(x+scale*tvecv'', varargin{:})']) - f0) ...
+         /(scale*delta);
+   % disp(' fcn in the i=1:n loop of numgrad.m ------------------')% Jinill 9/6/95
+   % disp('          and i is')               % Jinill
+   % i                         % Jinill
+   % fprintf('Gradient w.r.t. %3d: %10g\n',i,g0) %see below Jinill 9/6/95
+% -------------------------- special code to essentially quit here
+   % absg0=abs(g0) % Jinill on 9/6/95
+   if abs(g0)< 1e15
+      g(i)=g0;
+      % disp('good gradient') % Jinill Kim
+   else
+      disp('bad gradient ------------------------') % Jinill Kim
+      % fprintf('Gradient w.r.t. %3d: %10g\n',i,g0) %see above
+      g(i)=0;
+      badg=1;
+      % return
+      % can return here to save time if the gradient will never be
+      % used when badg returns as true.
+   end
+end
+%-------------------------------------------------------------
+%     if g0 > 0
+%        sided=2;
+%        g1 = -(eval([fcn '(x-scale*tvec(:,i)''' tailstr]) - f0) ...
+%           /(scale*delta);
+%        if g1<0
+%           scale = scale/10;
+%        else
+%           break
+%        end
+%     else
+%        sided=1;
+%        break
+%     end
+%  end
+%  if sided==1
+%     g(i)=g0;
+%  else
+%     if (g0<1e20)
+%        if (g1>-1e20)
+%           g(i)=(g0+g1)/2;
+%        else
+%           g(i)=0;
+%           badg=1;
+%           disp( ['Banging against wall, parameter ' int2str(i)] );
+%        end
+%     else
+%        if g1>-1e20
+%           if g1<0
+%              g(i)=0;
+%              badg=1;
+%              disp( ['Banging against wall, parameter ' int2str(i)] );
+%           else
+%              g(i)=g1;
+%           end
+%        else
+%           g(i)=0;
+%           badg=1;
+%           disp(['Valley around parameter ' int2str(i)])
+%        end
+%     end
+%  end
+%end
+%save g.dat g x f0
+%eval(['save g g x f0 ' stailstr]);
+
diff --git a/tags/v_3.062/matlab/osr.m b/tags/v_3.062/matlab/osr.m
new file mode 100644
index 0000000000000000000000000000000000000000..df6c72a172685b5e2cd74b6318e74a55a7fa4563
--- /dev/null
+++ b/tags/v_3.062/matlab/osr.m
@@ -0,0 +1,162 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function osr(var_list,params,W)
+  global iter_ ys_ dr_ y_ dr_ exo_nbr lgy_ lgx_ Sigma_e_ ykmin_ ykmax_ ...
+      endo_nbr options_ lgx_orig_ord_
+  
+  options_old = options_;
+  options_.order = 1;
+  options_.linear = 1;
+  options_ = set_default_option(options_,'ar',5);
+  options_ = set_default_option(options_,'irf',40);
+  options_ = set_default_option(options_,'dr_algo',0);
+  options_ = set_default_option(options_,'simul_algo',0);
+  options_ = set_default_option(options_,'drop',100);
+  options_ = set_default_option(options_,'replic',1);
+  options_ = set_default_option(options_,'nomoments',0);
+  options_ = set_default_option(options_,'nocorr',0);
+  options_ = set_default_option(options_,'simul_seed',[]);
+  options_ = set_default_option(options_,'hp_filter',0);
+  options_ = set_default_option(options_,'hp_ngrid',512);
+  options_ = set_default_option(options_,'simul',0);
+  options_ = set_default_option(options_,'periods',1);
+  options_ = set_default_option(options_,'TeX',0);
+  options_ = set_default_option(options_,'noprint',0);
+  if options_.simul & ~isempty(iter_) & options_.periods == 0
+    options_.periods = iter_;
+  end
+
+  iter_ = max(options_.periods,1);
+  options_.periods = iter_;
+  
+  make_ex_;
+
+  disp(' ')
+  disp('OPTIMAL SIMPLE RULE')
+  disp(' ')
+  [dr_,info] = osr1(params,W);
+  if info > 0
+    options_ = options_old;
+    return
+  elseif options_.noprint ~= 1
+      disp('MODEL SUMMARY')
+      disp(' ')
+      disp(['  Number of variables:         ' int2str(endo_nbr)])
+      disp(['  Number of stochastic shocks: ' int2str(exo_nbr)])
+      disp(['  Number of state variables:   ' ...
+	    int2str(length(find(dr_.kstate(:,2) <= ykmin_+1)))])
+      disp(['  Number of jumpers:           ' ...
+	    int2str(length(find(dr_.kstate(:,2) == ykmin_+2)))])
+      disp(['  Number of static variables:  ' int2str(dr_.nstatic)])
+      my_title='MATRIX OF COVARIANCE OF EXOGENOUS SHOCKS';
+      labels = deblank(lgx_);
+      headers = strvcat('Variables',labels);
+      lh = size(labels,2)+2;
+      table(my_title,headers,labels,Sigma_e_,lh,10,6);
+      disp(' ')
+      disp_dr(dr_,options_.order,var_list);
+      if options_.order == 1 & options_.simul == 0 & options_.nomoments == 0
+	disp_th_moments(dr_,var_list);
+      elseif options_.simul == 1 | options_.nomoments == 0
+	if options_.periods == 0
+	  error('OSR error: number of periods for the simulation isn''t specified')
+	end
+	if options_.periods < options_.drop
+	  disp(['OSR error: The horizon of simulation is shorter' ...
+		' than the number of observations to be DROPed'])
+	  return
+	end
+	
+	y_ = simult(repmat(dr_.ys,1,ykmin_),dr_);
+	dyn2vec;
+	if options_.nomoments == 0
+	  disp_moments(y_,var_list);
+	end
+      end
+      
+      n = size(var_list,1);
+      if n == 0
+	n = length(dr_.order_var);
+	ivar = [1:n]';
+	var_list = lgy_;
+      else
+	ivar=zeros(n,1);
+	for i=1:n
+	  i_tmp = strmatch(var_list(i,:),lgy_,'exact');
+	  if isempty(i_tmp)
+	    error (['One of the specified variables does not exist']) ;
+	  else
+	    ivar(i) = i_tmp;
+	  end
+	end
+      end
+
+      if n < 13 & options_.irf > 0
+	if n == 1
+	  nr = 1;
+	  nc = 1;
+	elseif n == 2
+	  nr = 1;
+	  nc = 2;
+	elseif n <= 4
+	  nr = 2;
+	  nc = 2;
+	elseif n <= 6
+	  nr = 2;
+	  nc = 3;
+	elseif n <= 9
+	  nr = 3;
+	  nc = 3;
+	elseif n <= 12
+	  nr = 3;
+	  nc = 4;
+	end
+	olditer = iter_;
+	if options_.order == 1
+	  options_.replic = 1;
+	else
+	  if options_.replic == 0
+	    options_.replic = 50;
+	  end
+	end
+	SS(lgx_orig_ord_,lgx_orig_ord_)=Sigma_e_+1e-14*eye(exo_nbr);
+	cs = transpose(chol(SS));
+
+	for i = 1:exo_nbr
+	  if SS(i,i) > 1e-13
+	    figure('Name',['Shock to ' lgx_(i,:)]);
+	    y=irf(dr_,cs(lgx_orig_ord_,i), options_.irf, options_.drop, options_.replic, options_.order);
+	    for j = 1:n
+	      subplot(nr,nc,j);
+	      plot([y(ivar(j),:)']);
+	      title(var_list(j,:),'Interpreter','none');
+	      assignin('base',[deblank(var_list(j,:)) '_' deblank(lgx_(i,:))],y(ivar(j),:)');
+	    end
+	  end
+	  
+	end
+	iter_ = olditer;
+      end
+  end
+  options_ = options_old;
+  
+% 01/10/01 FC dr_ and y_ made global
+% 02/20/01 MJ ys_ removed from calling sequence for simult (all in dr_)
+% 02/23/01 MJ added dyn2vec()
+% 06/24/01 MJ steady -> steady_
+% 09/24/01 MJ dr_ made global
+% 08/28/02 MJ added var_list
+% 10/09/02 MJ no simulation and theoretical moments for order 1 
+% 10/14/02 MJ added plot of IRFs
+% 10/30/02 MJ options_ are now a structure
+% 01/01/03 MJ added dr_algo
+% 01/09/03 MJ set default values for options_ (correct absence of autocorr
+%             when order == 1)
+% 01/12/03 MJ removed call to steady_ as already checked in resol()
+% 01/31/03 MJ make IRF global with varname_shockname
+% 02/09/03 MJ ys_ reset with value declared in initval after computations
+% 02/18/03 MJ removed above change. ys_ shouldn't be affected by
+%             computations in this function
+%             new option SIMUL computes a stochastic simulation and save
+%             results in y_ and via dyn2vec
+% 04/03/03 MJ corrected bug for simulation with ykmin_ > 1
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/osr1.m b/tags/v_3.062/matlab/osr1.m
new file mode 100644
index 0000000000000000000000000000000000000000..bfc17203cfcc1f6b94628ed459fb2c529f0fcfd4
--- /dev/null
+++ b/tags/v_3.062/matlab/osr1.m
@@ -0,0 +1,45 @@
+function [dr_,info]=osr1(params,weights)
+  global xkmax_ xkmin_ ykmin_ ykmax_ ys_ iy_ exo_nbr endo_nbr fname_ ...
+      dynatol_ options_ it_ dr_
+
+  it_ = ykmin_ + 1 ;
+
+  set_default_option(options_,'dr_algo',0);
+  
+  if exo_nbr == 0
+    exe_ = [] ;
+  end
+
+  check_model;
+  
+  np = size(params,1);
+  t0 = zeros(np,1);
+  for i=1:np
+    t0(i)=evalin('base',[params(i,:) ';']);
+  end
+  
+  [f,info] = osr_obj(t0,params,weights);
+  if info > 0
+    disp('OSR: bad initial value for the parameters');
+    return
+  end
+  [p,f]=fminsearch(@osr_obj,t0,[],params,weights);
+
+  [f,info] = osr_obj(p,params,weights);
+  if info > 0
+    disp(['OSR ends on a pathological case, try different initial values' ...
+	  ' for the parameters']);
+    return
+  else
+    disp('')
+    disp('OPTIMAL VALUE OF THE PARAMETERS:')
+    disp('')
+    for i=1:np
+      disp(sprintf('%16s %16.6g\n',params(i,:),p(i)))
+    end
+    disp(sprintf('Objective function : %16.6g\n',f));
+    disp(' ')
+    dr_=resol(ys_,0);
+  end
+
+  % 05/10/03 MJ modified to work with osr.m and give full report
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/osr_obj.m b/tags/v_3.062/matlab/osr_obj.m
new file mode 100644
index 0000000000000000000000000000000000000000..7302daace457e2429e8d0937d50e8672a009f467
--- /dev/null
+++ b/tags/v_3.062/matlab/osr_obj.m
@@ -0,0 +1,61 @@
+% the beginning and the end of this function may be adapted by the userx
+function [loss,vx]=osr_obj(x,params,weights);
+  global ys_ Sigma_e_ endo_nbr exo_nbr optimal_Q_ it_ ykmin_ options_
+  
+  vx = [];
+  % set parameters of the policiy rule
+  np = size(params,1);
+  for i=1:np
+    assignin('base',deblank(params(i,:)),x(i))
+  end
+  
+  % don't change below until the part where the loss function is computed
+  it_ = ykmin_+1;
+  [dr_,info] = resol(ys_,0);
+  
+  switch info(1)
+   case 1
+    loss = 1e8;
+    return
+   case 2
+    loss = 1e8*min(1e3,info(2));
+    return
+   case 3
+    loss = 1e8*min(1e3,info(2));
+    return
+   case 4
+    loss = 1e8*min(1e3,info(2));
+    return
+   case 5
+    loss = 1e8;
+    return
+   case 20
+    loss = 1e8*min(1e3,info(2));
+    return
+   otherwise
+  end
+  
+  [A,B] = kalman_transition_matrix(dr_);
+  [vx, info] = lyapunov_symm(A,B*Sigma_e_*B');
+  if info > 0
+    loss = 1e8;
+    return
+  end
+  weights = weights(dr_.order_var,dr_.order_var);
+  vx = vx(1:endo_nbr,1:endo_nbr);
+  loss = weights(:)'*vx(:);
+  
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tags/v_3.062/matlab/p2toperc.m b/tags/v_3.062/matlab/p2toperc.m
new file mode 100644
index 0000000000000000000000000000000000000000..4ac9d2b76c44fbed6dd5a1b9f6f8874c13b01334
--- /dev/null
+++ b/tags/v_3.062/matlab/p2toperc.m
@@ -0,0 +1,29 @@
+function y=p2toperc(x)
+  
+  n = size(x,1);
+  y = zeros(n,1);
+  
+  for i=1:n
+%    if x(i,6) == 0  have to wait until the 2nd part works
+    if 1
+      y(i) = x(i,3);
+    else
+      if x(i,3) < x(i,2)
+	p = 0.05;
+      else
+	p = 0.95;
+      end
+    
+      if x(i,1) == 1
+	y(i) = fsolve(@fbeta,1,p,x(i,2),x(i,3));
+      elseif x(i,1) == 2
+	y(i) = fsolve(@fgamma,1,p,x(i,2),x(i,3));
+      elseif x(i,1) == 3
+	y(i) = (x(i,3)-x(i,2))/qnorm(p,0,1);
+      elseif x(i,1) == 4
+	y(i) = fsolve(@figamm,1,p,x(i,2),x(i,3));
+      elseif x(i,1) == 5
+%	y(i) = fsolve(@fgamma,1,p,x(i,2));
+      end
+    end
+  end
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/pdfig.m b/tags/v_3.062/matlab/pdfig.m
new file mode 100644
index 0000000000000000000000000000000000000000..6f27e7ea898b826d1a0912b4d16972d63f579f90
--- /dev/null
+++ b/tags/v_3.062/matlab/pdfig.m
@@ -0,0 +1,2 @@
+function y=pdfig(x,a,b)
+  y=exp(lpdfig(x,a,b));
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/pgamma.m b/tags/v_3.062/matlab/pgamma.m
new file mode 100644
index 0000000000000000000000000000000000000000..1398967705ef3e18d18d1d9e1d026936008a287a
--- /dev/null
+++ b/tags/v_3.062/matlab/pgamma.m
@@ -0,0 +1,15 @@
+function F = pgamma(x,a)
+%PGAMMA   The gamma distribution function
+%
+%         F = pgamma(x,a)
+
+%       Anders Holtsberg, 18-11-93
+%       Copyright (c) Anders Holtsberg
+
+if any(any(a<=0))
+   error('Parameter a is wrong')
+end
+
+F = gammainc(x,a);
+I0 = find(x<0);
+F(I0) = zeros(size(I0));
diff --git a/tags/v_3.062/matlab/plot_priors.m b/tags/v_3.062/matlab/plot_priors.m
new file mode 100644
index 0000000000000000000000000000000000000000..684e51195b240d31c357a7f6ca63a4b80603edd0
--- /dev/null
+++ b/tags/v_3.062/matlab/plot_priors.m
@@ -0,0 +1,137 @@
+function plot_priors
+% stephane.adjemian@cepremap.cnrs.fr [07-31-2004]
+global bayestopt_ fname_ options_
+
+TeX = options_.TeX;
+
+figurename = 'Priors';
+npar = length(bayestopt_.pmean);
+[nbplt,nr,nc,lr,lc,nstar] = pltorg(npar);
+
+if TeX
+	fidTeX = fopen([fname_ '_Priors.TeX'],'w');
+	fprintf(fidTeX,'%% TeX eps-loader file generated by plot_priors.m (Dynare).\n');
+	fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
+	fprintf(fidTeX,' \n');
+end
+if nbplt == 1
+    h1 = figure('Name',figurename);
+    if TeX
+        TeXNAMES = [];
+        NAMES    = []; 
+    end    
+    for i=1:npar
+        [x,f,abscissa,dens,binf,bsup] = draw_prior_density(i);
+        [nam,texnam] = get_the_name(i,TeX);
+        if TeX
+            TeXNAMES = strvcat(TeXNAMES,texnam);
+            NAMES = strvcat(NAMES,nam);
+        end    
+        subplot(nr,nc,i)
+        hh = plot(x,f,'-k','linewidth',2);
+        set(hh,'color',[0.7 0.7 0.7]);
+        box on
+        title(nam,'Interpreter','none')
+        drawnow
+    end
+    print('-depsc2',[fname_ '_Priors' int2str(1)]);
+    print('-dpdf',[fname_ '_Priors' int2str(1)]);
+    saveas(h1,[fname_ '_Priors' int2str(1) '.fig']);
+    if options_.nograph, close(h1), end
+    if TeX
+    	fprintf(fidTeX,'\\begin{figure}[H]\n');
+        for jj = 1:npar
+        	fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:)));
+        end    
+        fprintf(fidTeX,'\\centering\n');
+        fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_Priors%s}\n',fname_,int2str(1));
+        fprintf(fidTeX,'\\caption{Priors.}');
+        fprintf(fidTeX,'\\label{Fig:Priors:%s}\n',int2str(1));
+        fprintf(fidTeX,'\\end{figure}\n');
+        fprintf(fidTeX,' \n');
+        fprintf(fidTeX,'%% End of TeX file.\n');
+        fclose(fidTeX);
+	end
+else
+    for plt = 1:nbplt-1
+        hplt = figure('Name',figurename);
+        if TeX
+            TeXNAMES = [];
+            NAMES    = []; 
+        end    
+        for index=1:nstar
+            names = [];
+            i = (plt-1)*nstar + index;
+            [x,f,abscissa,dens,binf,bsup] = draw_prior_density(i);
+            [nam,texnam] = get_the_name(i,TeX);
+            if TeX
+                TeXNAMES = strvcat(TeXNAMES,texnam);
+                NAMES = strvcat(NAMES,nam);
+            end    
+            subplot(nr,nc,index)
+            hh = plot(x,f,'-k','linewidth',2);
+            set(hh,'color',[0.7 0.7 0.7]);
+            box on
+            title(nam,'Interpreter','none')
+            drawnow
+        end  % index=1:nstar
+        print('-depsc2',[fname_ '_Priors' int2str(plt)]);
+        print('-dpdf',[fname_ '_Priors' int2str(plt)]);
+	saveas(hplt,[fname_ '_Priors' int2str(plt) '.fig']);
+    	if options_.nograph, close(hplt), end
+		if TeX
+            fprintf(fidTeX,'\\begin{figure}[H]\n');
+            for jj = 1:nstar
+                fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:)));
+            end    
+            fprintf(fidTeX,'\\centering\n');
+            fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_Priors%s}\n',fname_,int2str(plt));
+            fprintf(fidTeX,'\\caption{Priors.}');
+            fprintf(fidTeX,'\\label{Fig:Priors:%s}\n',int2str(plt));
+            fprintf(fidTeX,'\\end{figure}\n');
+            fprintf(fidTeX,' \n');
+        end    
+    end % plt = 1:nbplt-1
+    hplt = figure('Name',figurename);
+    if TeX
+        TeXNAMES = [];
+        NAMES    = []; 
+    end    
+    for index=1:npar-(nbplt-1)*nstar
+        i = (nbplt-1)*nstar +  index;
+        [x,f,abscissa,dens,binf,bsup] = draw_prior_density(i);
+        [nam,texnam] = get_the_name(i,TeX);
+        if TeX
+            TeXNAMES = strvcat(TeXNAMES,texnam);
+            NAMES = strvcat(NAMES,nam);
+        end    
+        if lr
+            subplot(lc,lr,index);
+        else
+            subplot(nr,nc,index);
+        end    
+        hh = plot(x,f,'-k','linewidth',2);
+        set(hh,'color',[0.7 0.7 0.7]);
+        box on
+        title(nam,'Interpreter','none')
+        drawnow
+    end  % index=1:npar-(nbplt-1)*nstar
+    print('-depsc2',[ fname_ '_Priors' int2str(nbplt)]);
+    print('-dpdf',[ fname_ '_Priors' int2str(nbplt)]);
+    saveas(hplt,[fname_ '_Priors' int2str(nbplt) '.fig']);
+    if options_.nograph, close(hplt), end
+	if TeX
+        fprintf(fidTeX,'\\begin{figure}[H]\n');
+        for jj = 1:npar-(nbplt-1)*nstar
+            fprintf(fidTeX,'\\psfrag{%s}[1][][0.5][0]{%s}\n',deblank(NAMES(jj,:)),deblank(TeXNAMES(jj,:)));
+        end    
+        fprintf(fidTeX,'\\centering\n');
+        fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_Priors%s}\n',fname_,int2str(nbplt));
+        fprintf(fidTeX,'\\caption{Priors.}');
+        fprintf(fidTeX,'\\label{Fig:Priors:%s}\n',int2str(nbplt));
+        fprintf(fidTeX,'\\end{figure}\n');
+        fprintf(fidTeX,' \n');
+        fprintf(fidTeX,'%% End of TeX file.\n');
+        fclose(fidTeX);
+    end
+end
diff --git a/tags/v_3.062/matlab/pltorg.m b/tags/v_3.062/matlab/pltorg.m
new file mode 100644
index 0000000000000000000000000000000000000000..45fbc203e1c5c6308bdda77dc4d1edf06c15c406
--- /dev/null
+++ b/tags/v_3.062/matlab/pltorg.m
@@ -0,0 +1,85 @@
+function [nbplt,nr,nc,lr,lc,nstar] = pltorg(number)
+% stephane.adjemian@cepremap.cnrs.fr [06-07-2004]
+nrstar = 3;
+ncstar = 3;
+nstar  = nrstar*ncstar;
+nbplt  = 0;
+nr     = 0;
+nc     = 0;
+lr     = 0;
+lc     = 0;
+if number == 1
+    nbplt = 1;
+    nr    = 1;
+    nc    = 1;
+elseif number == 2
+    nbplt = 1;
+    nr    = 2;
+    nc    = 1;
+elseif number == 3
+    nbplt = 1;
+    nr    = 3;
+    nc    = 1;
+elseif number == 4
+    nbplt = 1;
+    nr    = 2;
+    nc    = 2;
+elseif number == 5
+    nbplt = 1;
+    nr    = 3;
+    nc    = 2;
+elseif number == 6
+    nbplt = 1;
+    nr    = 3;
+    nc    = 2;    
+elseif number == 7
+    nbplt = 1;
+    nr    = 3;
+    nc    = 3;    
+elseif number == 8
+    nbplt = 1;
+    nr    = 3;
+    nc    = 3;
+elseif number == 9
+    nbplt = 1;
+    nr    = 3;
+    nc    = 3;
+else
+    if number/nstar == round(number/nstar)
+        nbplt = number/nstar;
+        nr    = nrstar;
+        nc    = ncstar;
+        lr    = nr;
+        lc    = nc; 
+    else
+        nbplt = ceil(number/nstar);
+        nr    = nrstar;
+        nc    = ncstar;
+        reste = number-(nbplt-1)*nstar;
+        if reste == 1
+            lr    = 1;
+            lc    = 1;
+        elseif reste == 2
+            lr    = 2;
+            lc    = 1;
+        elseif reste == 3
+            lr    = 3;
+            lc    = 1;
+        elseif reste == 4
+            lr    = 2;
+            lc    = 2;
+        elseif reste == 5
+            lr    = 3;
+            lc    = 2;
+        elseif reste == 6
+            lr    = 3;
+            lc    = 2;    
+        elseif reste == 7
+            lr    = 3;
+            lc    = 3;    
+        elseif reste == 8
+            lr    = 3;
+            lc    = 3;
+        end
+    end
+end    
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/pnorm.m b/tags/v_3.062/matlab/pnorm.m
new file mode 100644
index 0000000000000000000000000000000000000000..4e06ae79bfae23ed6d5d4d60d55918d459c997b7
--- /dev/null
+++ b/tags/v_3.062/matlab/pnorm.m
@@ -0,0 +1,11 @@
+function  p = pnorm(x,m,s)
+%PNORM 	  The normal distribution function
+%
+%         p = pnorm(x,Mean,StandardDeviation)
+
+%       Anders Holtsberg, 18-11-93
+%       Copyright (c) Anders Holtsberg
+
+if nargin<3, s=1; end
+if nargin<2, m=0; end
+p = (1+erf((x-m)./(sqrt(2).*s)))/2;
diff --git a/tags/v_3.062/matlab/posterior_density_estimate.m b/tags/v_3.062/matlab/posterior_density_estimate.m
new file mode 100644
index 0000000000000000000000000000000000000000..18e6da0329c2d1dda0870dfcaa569febf159df9a
--- /dev/null
+++ b/tags/v_3.062/matlab/posterior_density_estimate.m
@@ -0,0 +1,178 @@
+function [abscissa,f,h] = posterior_density_estimate(data,number_of_grid_points,bandwidth,kernel_function) 
+%%   
+%%  This function aims at estimating posterior univariate densities from realisations of a Metropolis-Hastings 
+%%  algorithm. A kernel density estimator is used (see Silverman [1986]) and the main task of this function is 
+%%  to obtain an optimal bandwidth parameter. 
+%% 
+%%  * Silverman [1986], "Density estimation for statistics and data analysis". 
+%%  * M. Skold and G.O. Roberts [2003], "Density estimation for the Metropolis-Hastings algorithm". 
+%%
+%%  The last section is adapted from Anders Holtsberg's matlab toolbox (stixbox).
+%%
+%%  stephane.adjemian@cepremap.cnrs.fr [01/16/2004]. 
+
+if size(data,2) > 1 & size(data,1) == 1; 
+    data = data'; 
+elseif size(data,2)>1 & size(data,1)>1; 
+    error('density_estimate: data must be a one dimensional array.'); 
+end;
+test = log(number_of_grid_points)/log(2);
+if ( abs(test-round(test)) > 10^(-12));
+    error('The number of grid points must be a power of 2.');
+end;
+
+n = size(data,1); 
+
+
+%% KERNEL SPECIFICATION...
+
+if strcmp(kernel_function,'gaussian'); 
+    k    = inline('inv(sqrt(2*pi))*exp(-0.5*x.^2)'); 
+    k2   = inline('inv(sqrt(2*pi))*(-exp(-0.5*x.^2)+(x.^2).*exp(-0.5*x.^2))'); % second derivate of the gaussian kernel 
+    k4   = inline('inv(sqrt(2*pi))*(3*exp(-0.5*x.^2)-6*(x.^2).*exp(-0.5*x.^2)+(x.^4).*exp(-0.5*x.^2))'); % fourth derivate... 
+    k6   = inline('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))'); % sixth derivate... 
+    mu02 = inv(2*sqrt(pi)); 
+    mu21 = 1; 
+elseif strcmp(kernel_function,'uniform'); 
+    k    = inline('0.5*(abs(x) <= 1)'); 
+    mu02 = 0.5; 
+    mu21 = 1/3; 
+elseif strcmp(kernel_function,'triangle'); 
+    k    = inline('(1-abs(x)).*(abs(x) <= 1)'); 
+    mu02 = 2/3; 
+    mu21 = 1/6; 
+elseif strcmp(kernel_function,'epanechnikov'); 
+    k    = inline('0.75*(1-x.^2).*(abs(x) <= 1)'); 
+    mu02 = 3/5; 
+    mu21 = 1/5;     
+elseif strcmp(kernel_function,'quartic'); 
+    k    = inline('0.9375*((1-x.^2).^2).*(abs(x) <= 1)'); 
+    mu02 = 15/21; 
+    mu21 = 1/7; 
+elseif strcmp(kernel_function,'triweight'); 
+    k    = inline('1.09375*((1-x.^2).^3).*(abs(x) <= 1)'); 
+    k2   = inline('(105/4*(1-x.^2).*x.^2-105/16*(1-x.^2).^2).*(abs(x) <= 1)'); 
+    k4   = inline('(-1575/4*x.^2+315/4).*(abs(x) <= 1)'); 
+    k6   = inline('(-1575/2).*(abs(x) <= 1)'); 
+    mu02 = 350/429; 
+    mu21 = 1/9;     
+elseif strcmp(kernel_function,'cosinus'); 
+    k    = inline('(pi/4)*cos((pi/2)*x).*(abs(x) <= 1)'); 
+    k2   = inline('(-1/16*cos(pi*x/2)*pi^3).*(abs(x) <= 1)'); 
+    k4   = inline('(1/64*cos(pi*x/2)*pi^5).*(abs(x) <= 1)'); 
+    k6   = inline('(-1/256*cos(pi*x/2)*pi^7).*(abs(x) <= 1)'); 
+    mu02 = (pi^2)/16; 
+    mu21 = (pi^2-8)/pi^2;     
+end;     
+
+
+%% OPTIMAL BANDWIDTH PARAMETER....
+
+if bandwidth == 0;  %  Rule of thumb bandwidth parameter (Silverman [1986] corrected by 
+                    %  Skold and Roberts [2003] for Metropolis-Hastings). 
+    sigma = std(data); 
+    h = 2*sigma*(sqrt(pi)*mu02/(12*(mu21^2)*n))^(1/5); % Silverman's optimal bandwidth parameter. 
+    A = 0; 
+    for i=1:n; 
+        j = i; 
+        while j<= n & data(j,1)==data(i,1); 
+            j = j+1; 
+        end;     
+        A = A + 2*(j-i) - 1; 
+    end; 
+    A = A/n; 
+    h = h*A^(1/5); % correction 
+elseif bandwidth == -1;     % Adaptation of the Sheather and Jones [1991] plug-in estimation of the optimal bandwidth 
+                            % parameter for metropolis hastings algorithm. 
+    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;         
+    sigma = std(data); 
+    A = 0; 
+    for i=1:n; 
+        j = i; 
+        while j<= n & data(j,1)==data(i,1); 
+            j = j+1; 
+        end;     
+        A = A + 2*(j-i) - 1; 
+    end; 
+    A = A/n; 
+    Itilda4 = 8*7*6*5/(((2*sigma)^9)*sqrt(pi)); 
+    g3      = abs(2*A*k6(0)/(mu21*Itilda4*n))^(1/9); 
+    Ihat3 = 0; 
+    for i=1:n; 
+        Ihat3 = Ihat3 + sum(k6((data(i,1)-data)/g3)); 
+    end;     
+    Ihat3 = -Ihat3/((n^2)*g3^7); 
+    g2      = abs(2*A*k4(0)/(mu21*Ihat3*n))^(1/7); 
+    Ihat2 = 0; 
+    for i=1:n; 
+        Ihat2 = Ihat2 + sum(k4((data(i)-data)/g2)); 
+    end;     
+    Ihat2 = Ihat2/((n^2)*g2^5); 
+    h       = (A*mu02/(n*Ihat2*mu21^2))^(1/5);    % equation (22) in Skold and Roberts [2003] --> h_{MH} 
+elseif bandwidth == -2;     % Bump killing... We construct 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;         
+    sigma = std(data); 
+    A = 0; 
+    T = zeros(n,1); 
+    for i=1:n; 
+        j = i; 
+        while j<= n & data(j,1)==data(i,1); 
+            j = j+1; 
+        end;     
+        T(i) = (j-i); 
+        A = A + 2*T(i) - 1; 
+    end; 
+    A = A/n; 
+    Itilda4 = 8*7*6*5/(((2*sigma)^9)*sqrt(pi)); 
+    g3      = abs(2*A*k6(0)/(mu21*Itilda4*n))^(1/9); 
+    Ihat3 = 0; 
+    for i=1:n; 
+        Ihat3 = Ihat3 + sum(k6((data(i,1)-data)/g3)); 
+    end;     
+    Ihat3 = -Ihat3/((n^2)*g3^7); 
+    g2      = abs(2*A*k4(0)/(mu21*Ihat3*n))^(1/7); 
+    Ihat2 = 0; 
+    for i=1:n; 
+        Ihat2 = Ihat2 + sum(k4((data(i)-data)/g2)); 
+    end;     
+    Ihat2 = Ihat2/((n^2)*g2^5); 
+    h = ((2*T-1)*mu02/(n*Ihat2*mu21^2)).^(1/5); % Note that h is a column vector (local banwidth parameters). 
+elseif bandwidth > 0; 
+    h = bandwidth; 
+else; 
+    error('density_estimate: bandwidth must be positive or equal to 0,-1 or -2.'); 
+end; 
+
+%% COMPUTE DENSITY ESTIMATE, using the optimal bandwidth parameter.
+%%
+%% This section is adapted from Anders Holtsberg's matlab toolbox
+%% (stixbox --> plotdens.m).
+
+
+a  = min(data) - (max(data)-min(data))/3;
+b  = max(data) + (max(data)-min(data))/3;
+abscissa = linspace(a,b,number_of_grid_points)';
+d  = abscissa(2)-abscissa(1); 
+xi = zeros(number_of_grid_points,1);
+xa = (data-a)/(b-a)*number_of_grid_points; 
+for i = 1:n;
+    indx = floor(xa(i));
+    temp = xa(i)-indx;
+    xi(indx+[1 2]) = xi(indx+[1 2]) + [1-temp,temp]';
+end;    
+xk = [-number_of_grid_points:number_of_grid_points-1]'*d;
+kk = k(xk/h);
+kk = kk / (sum(kk)*d*n);
+f = ifft(fft(fftshift(kk)).*fft([xi ;zeros(size(xi))]));
+f = real(f(1:number_of_grid_points));
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/posterior_distribution.m b/tags/v_3.062/matlab/posterior_distribution.m
new file mode 100644
index 0000000000000000000000000000000000000000..2e8510242860c2ef80a9e0c4ec54f29f785550b9
--- /dev/null
+++ b/tags/v_3.062/matlab/posterior_distribution.m
@@ -0,0 +1,72 @@
+function [borneinf,bornesup,x1,x2,f1,f2,top,nam,texnam] = ...
+    posterior_distribution(indx,number_of_mh_files,first_mh_file,first_line,...
+					number_of_blocks,number_of_simulations,...
+					number_of_simulations_per_file,TeX);
+% stephane.adjemian@cepremap.cnrs.fr [07-15-2004]
+
+global fname_ bayestopt_ estim_params_ options_
+
+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.  
+             
+
+mcsimulations = zeros(number_of_simulations,1);
+
+if number_of_blocks == 1
+	EndOfFile = number_of_simulations_per_file(first_mh_file+1)-first_line+1;
+	instr = [fname_ '_mh' int2str(first_mh_file)];
+	eval(['load ' instr]);
+	clear post2 logpo2;
+    mcsimulations(1:EndOfFile) = x2(first_line:end,indx);
+	OldEndOfFile = EndOfFile;
+	for f = first_mh_file+1:number_of_mh_files
+		NewEndOfFile = number_of_simulations_per_file(f+1);
+       	instr = [fname_ '_mh' int2str(f)];
+		eval(['load ' instr]);
+		clear post2 logpo2;
+		mcsimulations(OldEndOfFile+1:OldEndOfFile+NewEndOfFile) = x2(:,indx);
+		OldEndOfFile = OldEndOfFile + NewEndOfFile;
+	end
+	clear x2;
+else
+	EndOfFile = number_of_simulations_per_file(first_mh_file+1)-first_line+1;
+	NewStartLine = 0;
+	inst = [fname_ '_mh' int2str(first_mh_file)];
+	for b = 1:number_of_blocks
+		instr = [inst '_blck' int2str(b)];
+		eval(['load ' instr]);
+		clear post2 logpo2;
+       	mcsimulations(NewStartLine+1:NewStartLine+EndOfFile,1) = x2(first_line:end,indx);
+		NewStartLine = NewStartLine + EndOfFile;
+	end
+	for f = first_mh_file+1:number_of_mh_files
+		EndOfFile = number_of_simulations_per_file(f+1);
+       	inst = [fname_ '_mh' int2str(f)];
+		for B = 1:number_of_blocks
+			instr = [inst '_blck' int2str(b)];
+			eval(['load ' instr]);
+			clear post2 logpo2;
+			mcsimulations(NewStartLine+1:NewStartLine+EndOfFile,1) = x2(:,indx);
+			NewStartLine = NewStartLine + EndOfFile;
+		end
+	end
+	clear x2;
+end
+
+[nam,texnam] = get_the_name(indx,TeX);
+
+%% Kernel estimator of the posterior density:
+optimal_bandwidth = mh_optimal_bandwidth(mcsimulations,number_of_simulations,bandwidth,kernel_function); 
+[x1,f1] = kernel_density_estimate(mcsimulations,number_of_grid_points,...
+    optimal_bandwidth,kernel_function);
+binf1 = x1(1);
+bsup1 = x1(length(x1));
+
+%% Prior density:
+[x2,f2,abscissa,dens,binf2,bsup2] = draw_prior_density(indx);
+clear abscissa dens;
+
+borneinf = min(binf1,binf2);
+bornesup = max(bsup1,bsup2);
+top      = max([max(f1);max(f2)]);
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/posterior_moments.m b/tags/v_3.062/matlab/posterior_moments.m
new file mode 100644
index 0000000000000000000000000000000000000000..ca76751dd0da0c6f2a2e58de8a449a1ea7f50dd0
--- /dev/null
+++ b/tags/v_3.062/matlab/posterior_moments.m
@@ -0,0 +1,25 @@
+function [post_mean, min_interval] = posterior_moments(x2)
+% computes mean and minimum interval from posterior draws generated by metropolis.m
+  global options_
+  
+  n = size(x2,1);
+  np = size(x2,2);
+  
+  post_mean = mean(x2(1:end,:))';
+  
+  n1 = round((1-options_.mh_conf_sig)*n);
+  k = zeros(n1,1);
+  for i = 1:np
+    x3 = sort(x2(1:end,i));
+  
+    j2 = n-n1;
+    for j1 = 1:n1
+      k(j1) = x3(j2)-x3(j1);
+      j2 = j2 + 1;
+    end
+    
+    [kmin,k1] = min(k);
+    
+    min_interval(i,:) = [x3(k1) x3(k1)+kmin];
+  end
+  
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/print_info.m b/tags/v_3.062/matlab/print_info.m
new file mode 100644
index 0000000000000000000000000000000000000000..4ce5d9ea3ac67e64575e6776bfe4f448fb07da6c
--- /dev/null
+++ b/tags/v_3.062/matlab/print_info.m
@@ -0,0 +1,39 @@
+% Copyright (C) 2005 Michel Juillard
+%
+function print_info(info)
+  global options_
+
+  options_ = set_default_option(options_,'noprint',0);
+  
+  if ~options_.noprint
+    if info(1) > 10 & info(1) < 20
+      disp('Failure in dr_algo=2')
+      info(1) = info(1) - 10;
+    end
+    switch info(1)
+     case 1
+      error(['The model doesn''t determine the current variables' ...
+	     ' uniquely'])
+     case 2
+      error(['MJDGGES returns the following error code' ...
+	     int2str(info(2))])
+     case 3
+      error(['Blanchard Kahn conditions are not satisfied: no stable' ...
+	     ' equilibrium'])
+     case 4
+      error(['Blanchard Kahn conditions are not satisfied:' ...
+	     ' indeterminacy'])
+     case 5
+      error(['Blanchard Kahn conditions are not satisfied:' ...
+	     ' indeterminacy due to rank failure'])
+     case 20
+      error(['Impossible to find the steady state. Either the model' ...
+	     ' doesn''t have a unique steady state of the guess values' ...
+	     ' are too far from the solution']) 
+     case 30
+      error('Variance can''t be computed')
+     otherwise
+      error('This case shouldn''t happen. Contact the authors of Dynare')
+    end
+  end
+  
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/prior_bounds.m b/tags/v_3.062/matlab/prior_bounds.m
new file mode 100644
index 0000000000000000000000000000000000000000..eaac03928c3beea741176c1432d662ba678e9ce7
--- /dev/null
+++ b/tags/v_3.062/matlab/prior_bounds.m
@@ -0,0 +1,46 @@
+function bounds = prior_bounds(bayestopt)
+  global options_
+  
+  pshape = bayestopt.pshape;
+  pmean = bayestopt.pmean;
+  p1 = bayestopt.p1;
+  p2 = bayestopt.p2;
+  p3 = bayestopt.p3;
+  p4 = bayestopt.p4;
+  
+  n = length(pmean);
+  bounds = zeros(n,2);
+  
+  for i=1:n
+    switch pshape(i)
+     case 1
+      mu = (pmean(i)-p3(i))/(p4(i)-p3(i));
+      stdd = p2(i)/(p4(i)-p3(i));
+      A = (1-mu)*mu^2/stdd^2 - mu;
+      B = A*(1/mu - 1);
+      bounds(i,1) = qbeta(options_.prior_trunc,A,B)*(p4(i)-p3(i))+p3(i);
+      bounds(i,2) = qbeta(1-options_.prior_trunc,A,B)*(p4(i)-p3(i))+p3(i);
+     case 2
+      b = p2(i)^2/(pmean(i)-p3(i));
+      a = (pmean(i)-p3(i))/b;
+      bounds(i,1) = mj_qgamma(options_.prior_trunc,a)*b+p3(i);
+      bounds(i,2) = mj_qgamma(1-options_.prior_trunc,a)*b+p3(i);
+     case 3
+      bounds(i,1) = qnorm(options_.prior_trunc,pmean(i),p2(i));
+      bounds(i,2) = qnorm(1-options_.prior_trunc,pmean(i),p2(i));
+     case 4
+      nu = p2(i);
+      mu = pmean(i);
+      beta = ( gamma( (nu-1)/2 ) / mu / gamma( nu/2 ) )^2;
+      a=2/beta;
+      bounds(i,1) = 1/sqrt(mj_qgamma(1-options_.prior_trunc,p2(i)/2)*beta);
+      bounds(i,2) = 1/sqrt(mj_qgamma(options_.prior_trunc,p2(i)/2)*beta);
+     case 5
+      bounds(i,1) = p1(i);
+      bounds(i,2) = p2(i);
+     otherwise
+      bounds(i,1) = -Inf;
+      bounds(i,2) = Inf;
+    end
+  end
+  
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/priordens.m b/tags/v_3.062/matlab/priordens.m
new file mode 100644
index 0000000000000000000000000000000000000000..77e41eff9d24192c2d27fc835db9177f533e2cc9
--- /dev/null
+++ b/tags/v_3.062/matlab/priordens.m
@@ -0,0 +1,48 @@
+function lnprior = priordens(para, pshape, p1, p2, p3, p4)
+
+% This procedure computes a prior density for
+% the structural parameters of the DSGE models
+% pshape: 0 is point mass, both para and p2 are ignored
+%         1 is BETA(mean,stdd)
+%         2 is GAMMA(mean,stdd)
+%         3 is NORMAL(mean,stdd)
+%         4 is INVGAMMA(s^2,nu)
+%         5 is UNIFORM [p3,p4]
+
+lnprior = 0;
+nprio = length(pshape);
+
+i = 1;
+while i <=  nprio;
+a = 0;
+b = 0;
+
+   if pshape(i) == 1;     % (generalized) BETA Prior 
+     mu = (p1(i)-p3(i))/(p4(i)-p3(i));
+     stdd = p2(i)/(p4(i)-p3(i));
+     a = (1-mu)*mu^2/stdd^2 - mu;
+     b = a*(1/mu - 1);
+     lnprior = lnprior + lpdfgbeta(para(i),a,b,p3(i),p4(i))   ;
+   elseif pshape(i) == 2; % GAMMA PRIOR 
+     b = p2(i)^2/(p1(i)-p3(i));
+     a = (p1(i)-p3(i))/b;
+     lnprior = lnprior + lpdfgam(para(i)-p3(i),a,b);
+   elseif pshape(i) == 3; % GAUSSIAN PRIOR 
+     lnprior = lnprior + lpdfnorm(para(i),p1(i),p2(i));
+   elseif pshape(i) == 4; % INVGAMMA1 PRIOR 
+     lnprior = lnprior + lpdfig1(para(i),p1(i),p2(i));
+   elseif pshape(i) == 5; % UNIFORM PRIOR 
+     lnprior = lnprior + log(1/(p2(i)-p1(i)));
+   elseif pshape(i) == 6; % INVGAMMA2 PRIOR 
+     lnprior = lnprior + lpdfig2(para(i),p1(i),p2(i));
+   end;
+  i = i+1;
+end;
+
+% 10/11/03 MJ adapted from an earlier version in GAUSS by F. Schorfheide
+%             and translated to Matlab by R. Wouters
+% 11/18/03 MJ adopted M.Ratto's suggestion for inverse gamma
+%             changed order of input parameters
+% 01/16/04 MJ added invgamma2
+%             for invgamma p2 is now standard error
+% 16/02/04 SA changed beta prior call
diff --git a/tags/v_3.062/matlab/qbeta.m b/tags/v_3.062/matlab/qbeta.m
new file mode 100644
index 0000000000000000000000000000000000000000..d20ce1ad625ef4481e7f505df818fa8b6adcb0d8
--- /dev/null
+++ b/tags/v_3.062/matlab/qbeta.m
@@ -0,0 +1,26 @@
+function x = qbeta(p,a,b)
+%QBETA    The beta inverse distribution function
+%
+%         x = qbeta(p,a,b)
+
+%       Anders Holtsberg, 27-07-95
+%       Copyright (c) Anders Holtsberg
+
+if any(any((a<=0)|(b<=0)))
+   error('Parameter a or b is nonpositive')
+end
+if any(any(abs(2*p-1)>1))
+   error('A probability should be 0<=p<=1, please!')
+end
+b = min(b,100000);
+
+x = a ./ (a+b);
+dx = 1;
+while any(any(abs(dx)>256*eps*max(x,1)))
+   dx = (betainc(x,a,b) - p) ./ dbeta(x,a,b);
+   x = x - dx;
+   x = x + (dx - x) / 2 .* (x<0);
+   x = x + (1 + (dx - x)) / 2 .* (x>1);
+end
+
+
diff --git a/tags/v_3.062/matlab/qchisq.m b/tags/v_3.062/matlab/qchisq.m
new file mode 100644
index 0000000000000000000000000000000000000000..53095656da44d4a9cf3a812a42be73610eff31ec
--- /dev/null
+++ b/tags/v_3.062/matlab/qchisq.m
@@ -0,0 +1,16 @@
+function x = qchisq(p,a)
+%QCHISQ   The chisquare inverse distribution function
+%
+%         x = qchisq(p,DegreesOfFreedom)
+
+%        Anders Holtsberg, 18-11-93
+%        Copyright (c) Anders Holtsberg
+
+if any(any(abs(2*p-1)>1))
+   error('A probability should be 0<=p<=1, please!')
+end
+if any(any(a<=0))
+   error('DegreesOfFreedom is wrong')
+end
+
+x = qgamma(p,a*0.5)*2;
diff --git a/tags/v_3.062/matlab/qgamma.m b/tags/v_3.062/matlab/qgamma.m
new file mode 100644
index 0000000000000000000000000000000000000000..b8086e3e5dff683f12b11f5ab67880dc0000e09d
--- /dev/null
+++ b/tags/v_3.062/matlab/qgamma.m
@@ -0,0 +1,27 @@
+function x = qgamma(p,a)
+%QGAMMA   The gamma inverse distribution function
+%
+%         x = qgamma(p,a)
+
+%        Anders Holtsberg, 18-11-93
+%        Copyright (c) Anders Holtsberg
+
+if any(any(abs(2*p-1)>1))
+   error('A probability should be 0<=p<=1, please!')
+end
+if any(any(a<=0))
+   error('Parameter a is wrong')
+end
+
+x = max(a-1,0.1);
+dx = 1;
+while any(any(abs(dx)>256*eps*max(x,1)))
+   dx = (pgamma(x,a) - p) ./ dgamma(x,a,1);
+   x = x - dx;
+   x = x + (dx - x) / 2 .* (x<0);
+end
+
+I0 = find(p==0);
+x(I0) = zeros(size(I0));
+I1 = find(p==1);
+x(I1) = zeros(size(I1)) + Inf;
diff --git a/tags/v_3.062/matlab/qnorm.m b/tags/v_3.062/matlab/qnorm.m
new file mode 100644
index 0000000000000000000000000000000000000000..953f2a0324ed8fd1c9e49e8002b4c758c0f0fa95
--- /dev/null
+++ b/tags/v_3.062/matlab/qnorm.m
@@ -0,0 +1,20 @@
+function  x = qnorm(p,m,s)
+%QNORM 	  The normal inverse distribution function
+%
+%         x = qnorm(p,Mean,StandardDeviation)
+
+%       Anders Holtsberg, 13-05-94
+%       Copyright (c) Anders Holtsberg
+
+if nargin<3, s=1; end
+if nargin<2, m=0; end
+
+if any(any(abs(2*p-1)>1))
+   error('A probability should be 0<=p<=1, please!')
+end
+if any(any(s<=0))
+   error('Parameter s is wrong')
+end
+
+x = erfinv(2*p-1).*sqrt(2).*s + m;
+
diff --git a/tags/v_3.062/matlab/qr2.m b/tags/v_3.062/matlab/qr2.m
new file mode 100644
index 0000000000000000000000000000000000000000..8355db3bc2748123fd0ce796838d70f362572154
--- /dev/null
+++ b/tags/v_3.062/matlab/qr2.m
@@ -0,0 +1,11 @@
+function [Q,R] = qr2(X)
+% stephane.adjemian@ens.fr [12-07-2005]
+%
+% This routine performs a qr decomposition of matrix X such that the 
+% diagonal scalars of the upper-triangular matrix R are positive.
+[Q,R] = qr(X);
+indx = find(diag(R)<0);
+if ~isempty(indx)
+    Q(:,indx) = -Q(:,indx);
+    R(indx,:) = -R(indx,:);
+end
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/qzdiv.m b/tags/v_3.062/matlab/qzdiv.m
new file mode 100644
index 0000000000000000000000000000000000000000..9ea24723b1d8902c41076f0f62ff1bd2fbb1a710
--- /dev/null
+++ b/tags/v_3.062/matlab/qzdiv.m
@@ -0,0 +1,34 @@
+% from Chris Sims web site
+% http://eco-072399b.princeton.edu/yftp/gensys/mfiles/QZDIV.M
+%
+
+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 
+% corner, while preserving U.T. and orthonormal properties and Q'AZ' and
+% Q'BZ'.
+%
+[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) 
+         m=j;
+         break
+      end
+   end
+   if (m==0) 
+      return 
+   end
+   for k=m:1:i-1
+      [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         
diff --git a/tags/v_3.062/matlab/qzswitch.m b/tags/v_3.062/matlab/qzswitch.m
new file mode 100644
index 0000000000000000000000000000000000000000..350fc9f1609c74226dec6428b2e205ebb8afbecc
--- /dev/null
+++ b/tags/v_3.062/matlab/qzswitch.m
@@ -0,0 +1,64 @@
+% from Chris Sims web site
+% http://eco-072399b.princeton.edu/yftp/gensys/mfiles/QZSWITCH.M
+%
+
+function [A,B,Q,Z] = qzswitch(i,A,B,Q,Z)
+%function [A,B,Q,Z] = qzswitch(i,A,B,Q,Z)
+%
+% Takes U.T. matrices A, B, orthonormal matrices Q,Z, interchanges
+% diagonal elements i and i+1 of both A and B, while maintaining
+% Q'AZ' and Q'BZ' unchanged.  If diagonal elements of A and B
+% are zero at matching positions, the returned A will have zeros at both
+% positions on the diagonal.  This is natural behavior if this routine is used
+% to drive all zeros on the diagonal of A to the lower right, but in this case
+% the qz transformation is not unique and it is not possible simply to switch
+% the positions of the diagonal elements of both A and B.
+ realsmall=sqrt(eps)*10;
+%realsmall=1e-3;
+a = A(i,i); d = B(i,i); b = A(i,i+1); e = B(i,i+1);
+c = A(i+1,i+1); f = B(i+1,i+1);
+		% A(i:i+1,i:i+1)=[a b; 0 c];
+		% B(i:i+1,i:i+1)=[d e; 0 f];
+if (abs(c)<realsmall & abs(f)<realsmall)
+	if abs(a)<realsmall
+		% l.r. coincident 0's with u.l. of A=0; do nothing
+		return
+	else
+		% l.r. coincident zeros; put 0 in u.l. of a
+		wz=[b; -a];
+		wz=wz/sqrt(wz'*wz);
+		wz=[wz [wz(2)';-wz(1)'] ];
+		xy=eye(2);
+	end
+elseif (abs(a)<realsmall & abs(d)<realsmall)
+	if abs(c)<realsmall
+		% u.l. coincident zeros with l.r. of A=0; do nothing
+		return
+	else
+		% u.l. coincident zeros; put 0 in l.r. of A
+		wz=eye(2);
+		xy=[c -b];
+		xy=xy/sqrt(xy*xy');
+		xy=[[xy(2)' -xy(1)'];xy];
+	end
+else
+	% usual case
+	wz = [c*e-f*b, (c*d-f*a)'];
+	xy = [(b*d-e*a)', (c*d-f*a)'];
+	n = sqrt(wz*wz');
+	m = sqrt(xy*xy');
+	if m<eps*100
+		% all elements of A and B proportional
+		return
+	end
+   wz = n\wz;
+   xy = m\xy;
+   wz = [wz; -wz(2)', wz(1)'];
+   xy = [xy;-xy(2)', xy(1)'];
+end
+A(i:i+1,:) = xy*A(i:i+1,:);
+B(i:i+1,:) = xy*B(i:i+1,:);
+A(:,i:i+1) = A(:,i:i+1)*wz;
+B(:,i:i+1) = B(:,i:i+1)*wz;
+Z(:,i:i+1) = Z(:,i:i+1)*wz;
+Q(i:i+1,:) = xy*Q(i:i+1,:);
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/read_variables.m b/tags/v_3.062/matlab/read_variables.m
new file mode 100644
index 0000000000000000000000000000000000000000..38d821291d59b08ea4019c5aa581071b79ac144a
--- /dev/null
+++ b/tags/v_3.062/matlab/read_variables.m
@@ -0,0 +1,25 @@
+% Copyright (C) 2005 Michel Juillard
+%
+% all local variables have complicated names in order to avoid name
+% conflicts with possible user variable names
+
+function dyn_data_01=read_variables(file_name_01,var_names_01,dyn_data_01)
+  
+  dyn_size_01 = size(dyn_data_01,1);
+  
+  if exist(file_name_01)
+    dyn_instr_01 = file_name_01;
+  else
+    dyn_instr_01 = ['load ' file_name_01];
+  end
+  
+  eval(dyn_instr_01);
+
+  
+  for dyn_i_01=1:size(var_names_01,1)
+    dyn_tmp_01 = eval(var_names_01(dyn_i_01,:));
+    if length(dyn_tmp_01) > dyn_size_01 & dyn_size_01 > 0
+      error('data size is too large')
+    end
+    dyn_data_01(:,dyn_i_01) = dyn_tmp_01;
+  end
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/reshapel.m b/tags/v_3.062/matlab/reshapel.m
new file mode 100644
index 0000000000000000000000000000000000000000..8352191e6306cfd7820d497ddb501983cd30b62f
--- /dev/null
+++ b/tags/v_3.062/matlab/reshapel.m
@@ -0,0 +1,22 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function y=reshapel(x,m,n)
+%RESHAPEL Change size.
+%	RESHAPEL(X,M,N) returns the M-by-N matrix whose elements
+%	are taken linewise from X.  An error results if X does
+%	not have M*N elements.
+
+[mm,nn] = size(x);
+
+if mm*nn ~= m*n
+    error('Matrix must have M*N elements.')
+end
+
+[i,j,s] = find(x') ;
+if size(i,2) ~= 1,i = i';end
+k = (j-1)*nn+i ;
+j = rem(k-1,n)+1 ;
+i = (k-j)/n+1 ;
+y = full(sparse(i,j,s,m,n)) ;
+
+return ;
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/resid.m b/tags/v_3.062/matlab/resid.m
new file mode 100644
index 0000000000000000000000000000000000000000..fd1cf89549e7c1270b598844d0e83e8ac2340f44
--- /dev/null
+++ b/tags/v_3.062/matlab/resid.m
@@ -0,0 +1,37 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function resid(iter_)
+  global valf_ ex_ y_ it_ exe_ ys_ ys0_ iy_ ykmin_ ykmax_ endval_ z
+  global fname_ xkmin_ xkmax_
+  
+  ex_ = ones(xkmin_+xkmax_+iter_,1)*exe_';
+  n = size(iy_,2);
+%  if ~ valf_ | size(y_,2) ~= iter_+ykmin_+ykmax_
+  if ~ valf_ 
+    if size(ys_,1) == 1 & ys_ == 0
+      ys_ = zeros(size(ys_,1),1) ;
+    end
+    y_ = ys_*ones(1,iter_+ykmin_+ykmax_) ;
+    if endval_ == 1
+      y_(:,1:ykmin_) = ys0_*ones(1,ykmin_) ;
+    end
+  end
+
+  i = iy_';
+  iyr0 = find(i(:));
+
+  y =y_(:);
+  z = zeros(n,iter_);
+  fh = str2func([fname_ '_ff']);
+  for it_=ykmin_+1:iter_+ykmin_
+    z(:,it_-ykmin_) = feval(fh,y(iyr0));
+    iyr0 = iyr0 + n;
+  end
+
+  disp([[1:iter_]' z']); 
+
+
+
+
+
+
diff --git a/tags/v_3.062/matlab/resid0.m b/tags/v_3.062/matlab/resid0.m
new file mode 100644
index 0000000000000000000000000000000000000000..ec0223c816f36c24268ada4c322163d509b3bab2
--- /dev/null
+++ b/tags/v_3.062/matlab/resid0.m
@@ -0,0 +1,34 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function resid0
+  global iter_ valf_ ex_ y_ it_ exe_ ys_ iy_ ykmin_ ykmax_ endval_ z
+  global fname_
+  
+  n = size(iy_,2);
+%  if ~ valf_ | size(y_,2) ~= iter_+ykmin_+ykmax_
+  if ~ valf_ 
+    if size(ys_,1) == 1 & ys_ == 0
+      ys_ = zeros(size(ys_,1),1) ;
+    end
+    y_ = ys_*ones(1,iter_+ykmin_+ykmax_) ;
+    if endval_ == 1
+      y_(:,1:ykmin_) = ys0_*ones(1,ykmin_) ;
+    end
+  end
+
+  i = iy_';
+  iyr0 = find(i(:));
+
+  y =y_(:);
+  it_ = ykmin_+1;
+  fh = str2func([fname_ '_fff']);
+  z = feval(fh,ys_);
+
+
+  disp(z'); 
+
+
+
+
+
+
diff --git a/tags/v_3.062/matlab/resol.m b/tags/v_3.062/matlab/resol.m
new file mode 100644
index 0000000000000000000000000000000000000000..b53fa179877725546812011c57f65c3d75611213
--- /dev/null
+++ b/tags/v_3.062/matlab/resol.m
@@ -0,0 +1,70 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function [dr,info]=resol(ys,check_flag)
+% info: same as dr1 
+% plus: 
+% 11 .... same as dr1 for dr_algo = 2
+% 20: can't find steady state info(2) contains sum of sqare residuals
+  
+global jacobia_ iy_ ykmin_ ykmax_ gstep_ exo_nbr exo_det_nbr endo_nbr
+global ex_ ex_det_ valf_ it_ exe_ exe_det_ xkmin_ xkmax_ 
+global fname_ means_ stderrs_ lgy_ maxit_
+global dynatol_ options_
+
+options_ = set_default_option(options_,'olr',0);
+info = 0;
+
+it_ = ykmin_ + 1 ;
+
+if exo_nbr == 0
+  exe_ = [] ;
+end
+
+% check if ys is steady state
+tempex = ex_;
+tempexdet = ex_det_;
+ex_ = repmat(exe_',xkmin_+xkmax_+1,1);
+if exo_det_nbr > 0 
+  ex_det_ = ones(ykmin_+1,1)*exe_det_';
+end
+fh = str2func([fname_ '_fff']);
+if max(abs(feval(fh,ys))) > dynatol_ & options_.olr == 0
+  if exist([fname_ '_steadystate'])
+    [dr.ys,check1] = feval([fname_ '_steadystate'],ys);
+  else
+    [dr.ys,check1] = dynare_solve([fname_ '_fff'],ys);
+  end
+  if check1
+    info(1) = 20;
+    resid = feval(fh,ys);
+    info(2) = resid'*resid; % penalty...
+    return
+  end
+else 
+  dr.ys = ys;
+end
+
+dr.fbias = zeros(endo_nbr,1);
+[dr,info] = dr1(dr,check_flag);
+
+if info(1)
+  return
+end
+
+if options_.dr_algo == 1 & options_.order > 1
+  dr.ys = dynare_solve('dr2',ys,dr);
+  dr.fbias = 2*feval([fname_ '_fff'],dr.ys);
+  [dr, info1] = dr1(dr,check_flag);
+  if info1(1)
+    info(1) = info(1)+10;
+    return
+  end
+end
+ex_det_ = tempexdet;
+ex_ = tempex;
+tempex = [];
+
+% 01/01/2003 MJ added dr_algo == 1
+% 08/24/2001 MJ uses Schmitt-Grohe and Uribe (2001) constant correction
+%               in dr.ghs2 
+% 05/26/2003 MJ added temporary values for ex_
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/rfrot.m b/tags/v_3.062/matlab/rfrot.m
new file mode 100644
index 0000000000000000000000000000000000000000..870634bee0057cea424637b3905c53685c0540ac
--- /dev/null
+++ b/tags/v_3.062/matlab/rfrot.m
@@ -0,0 +1,14 @@
+% Copyright (C) 2001 Michel Juillard
+%
+% apply fast Givens rotation to a pair of rows
+
+function [a] = rfrot(a, alph, bet, type)
+     if type == 1
+         tau = bet*a(1,:) + a(2,:);
+         a(2,:) = a(1,:) + alph*a(2,:);
+         a(1,:) = tau;
+     else
+         tau = a(1,:) + bet*a(2,:);
+         a(2,:) = alph*a(1,:) + a(2,:);
+         a(1,:) = tau;
+     end
diff --git a/tags/v_3.062/matlab/rfvar3.m b/tags/v_3.062/matlab/rfvar3.m
new file mode 100644
index 0000000000000000000000000000000000000000..cd16ab1f9f59c97494bc4ba5e0ca16fbb1087205
--- /dev/null
+++ b/tags/v_3.062/matlab/rfvar3.m
@@ -0,0 +1,106 @@
+function var=rfvar3(ydata,lags,xdata,breaks,lambda,mu)
+%function var=rfvar3(ydata,lags,xdata,breaks,lambda,mu)
+% This algorithm goes for accuracy without worrying about memory requirements.
+% ydata:   dependent variable data matrix
+% xdata:   exogenous variable data matrix
+% lags:    number of lags
+% breaks:  rows in ydata and xdata after which there is a break.  This allows for
+%          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 
+%          first lags observations at the top and after each "break" in ydata and xdata as
+%          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,
+%          constant term is not included in the dummy observation, so that stationary models
+%          with means equal to initial ybar do not fit the prior mean.  With lambda>0, the prior
+%          implies that large constants are unlikely if unit roots are present.
+% mu:      weight on "own persistence" prior dummy observation.  Expresses belief
+%          that when y_i has been stable at its initial level, it will tend to persist
+%          at that level, regardless of the values of other variables.  There is
+%          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 
+%      xdata(1:lags,:) are reasonable subsititutes.  These values are used in forming the
+%      persistence priors.
+% Code written by Christopher Sims.  This version 6/15/03.
+[T,nvar]=size(ydata);
+nox=isempty(xdata);
+if ~nox
+   [T2,nx]=size(xdata);
+else
+   T2=T;nx=0;xdata=zeros(T2,0);
+end
+% note that x must be same length as y, even though first part of x will not be used.
+% This is so that the lags parameter can be changed without reshaping the xdata matrix.
+if T2 ~= T, disp('Mismatch of x and y data lengths'),end
+if nargin<4
+   nbreaks=0;breaks=[];
+else
+   nbreaks=length(breaks);
+end
+breaks=[0;breaks;T];
+smpl=[];
+for nb=1:nbreaks+1
+   smpl=[smpl;[breaks(nb)+lags+1:breaks(nb+1)]'];
+end
+Tsmpl=size(smpl,1);
+X=zeros(Tsmpl,nvar,lags);
+for is=1:length(smpl)
+    X(is,:,:)=ydata(smpl(is)-(1:lags),:)';
+end
+X=[X(:,:) xdata(smpl,:)];
+y=ydata(smpl,:);
+% Everything now set up with input data for y=Xb+e 
+% ------------------Form persistence dummies-------------------
+if lambda~=0 | mu>0
+   ybar=mean(ydata(1:lags,:),1);
+   if ~nox 
+      xbar=mean(xdata(1:lags,:),1);
+   else
+      xbar=[];
+   end
+   if lambda~=0
+      if lambda>0
+         xdum=lambda*[repmat(ybar,1,lags) xbar];
+      else
+         lambda=-lambda;
+         xdum=lambda*[repmat(ybar,1,lags) zeros(size(xbar))];
+      end
+      ydum=zeros(1,nvar);
+      ydum(1,:)=lambda*ybar;
+      y=[y;ydum];
+      X=[X(:,:);xdum];
+   end
+   if mu>0
+      xdum=[repmat(diag(ybar),1,lags) zeros(nvar,nx)]*mu;
+      ydum=mu*diag(ybar);
+      X=[X;xdum];
+      y=[y;ydum];
+   end
+end
+[vl,d,vr]=svd(X(:,:),0);
+di=1../diag(d);
+B=vl'*y;
+B=(vr.*repmat(di',nvar*lags+nx,1))*B;
+u=y-X(:,:)*B;
+xxi=vr.*repmat(di',nvar*lags+nx,1);
+xxi=xxi*xxi';
+B=reshape(B,[nvar*lags+nx,nvar]); % rhs variables, equations
+By=B(1:nvar*lags,:);
+By=reshape(By,nvar,lags,nvar);% variables, lags, equations
+By=permute(By,[3,1,2]); %equations, variables, lags to match impulsdt.m
+if nox
+   Bx=[];
+else
+   Bx=B(nvar*lags+(1:nx),:)';
+end
+%logintlh=matrictint(u'*u,xxi,size(X,1)-nvar-1)-.5*nvar*(nvar+1)*log(2*pi);
+var.By=By;var.Bx=Bx;var.u=u;var.xxi=xxi;%var.logintlh=logintlh;  
+% Desired features: 1) automatic dummies for vcv prior
+%                   2) automatic calculation of integrated pdf, accounting
+%                      for the dummy variables as a prior
+%                   3) automatic dummies for "Minnesota prior"
diff --git a/tags/v_3.062/matlab/rndprior.m b/tags/v_3.062/matlab/rndprior.m
new file mode 100644
index 0000000000000000000000000000000000000000..b4b1d6824a87af519f7187b89897f90b46756a88
--- /dev/null
+++ b/tags/v_3.062/matlab/rndprior.m
@@ -0,0 +1,52 @@
+function y = rndprior(bayestopt_)
+
+pshape=bayestopt_.pshape;
+pmean=bayestopt_.pmean;
+p2=bayestopt_.p2;
+p3=bayestopt_.p3;
+p4=bayestopt_.p4;
+ 
+for i=1:length(pmean),
+    
+    switch pshape(i)
+        
+     case 1 %'beta'
+      mu = (pmean(i)-p3(i))/(p4(i)-p3(i));
+      stdd = p2(i)/(p4(i)-p3(i));
+      A = (1-mu)*mu^2/stdd^2 - mu;
+      B = A*(1/mu - 1);
+      y(1,i) = beta_rnd(1, A, B);
+      y(1,i) = y(1,i) * (p4(i)-p3(i)) + p3(i);
+      
+     case 2 %'gamma'
+      mu = pmean(i)-p3(i);
+      B = mu/p2(i)^2;              %gamm_rnd uses 1/B instead of B as param.
+      A = mu/B;
+      y(1,i) = gamm_rnd(1, A, B);
+      y(1,i) = y(1,i) + p3(i);
+      
+     case 3 %'normal'
+      MU = pmean(i);
+      SIGMA = p2(i);
+      y(1,i) = randn*SIGMA+ MU;
+      
+     case 4 %'invgamma'
+      nu = p2(i);
+      mu = pmean(i);
+      a = nu/2;;
+      b = ( gamma( (nu-1)/2 ) / mu / gamma( nu/2 ) )^2;
+      A = b/2;
+      B = 2/a;
+      y(1,i) = gamm_rnd(1, A, B);        
+      y(1,i) = 1/y(1,i)^(0.5);
+      
+     case 5 %'uniform'
+      y(1,i) = rand*(p4(i)-p3(i)) + p3(i);
+      
+    end
+end
+
+% initial version by Marco Ratto
+% 11/17/03 MJ made Uniform case 5
+% 11/17/03 MJ changed pstdd -> p2, lb -> p3, ub -> p4
+
diff --git a/tags/v_3.062/matlab/rows.m b/tags/v_3.062/matlab/rows.m
new file mode 100644
index 0000000000000000000000000000000000000000..86a85d7bb463d1607655b084ed4889bd0571ed77
--- /dev/null
+++ b/tags/v_3.062/matlab/rows.m
@@ -0,0 +1,2 @@
+function nr=rows(x)
+  nr = size(x,1);
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/rplot.m b/tags/v_3.062/matlab/rplot.m
new file mode 100644
index 0000000000000000000000000000000000000000..d3ca8861740d9dfdd6511e45c549827f28f13d6e
--- /dev/null
+++ b/tags/v_3.062/matlab/rplot.m
@@ -0,0 +1,80 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function rplot(s1,rplottype)
+% RPLOT :		RPLOT ( ['var1'; 'var2';  ...] , rplottype )	
+%		This optionnal command creates the plot of the variable
+%		trajectory. By default, the entire simulation period is 
+%		ploted. The instruction DSAMPLE permits to reduce the 
+%		number of periods in the plot.
+		
+global lgy_ lgx_ y_ ykmin_ ykmax_ iter_
+global dsmpl_ ys_
+
+if nargin == 1
+	rplottype = 0;
+end
+
+col = ['y','c','r','g','b','w','m'] ;
+ix = [1 - ykmin_:size(y_,2)-ykmin_]' ;
+
+y = [];
+for k=1:size(s1,1)
+  if isempty(strmatch(s1(k,:),lgy_,'exact'))
+    error (['One of the variable specified does not exist']) ;
+  end
+
+  y = [y; y_(strmatch(s1(k,:),lgy_,'exact'),:)] ;
+end
+
+if dsmpl_ == 0
+        i = [ykmin_:size(y_,2)]' ;
+else
+	i = [dsmpl_(1)+ykmin_:dsmpl_(2)+ykmin_]' ;
+end
+
+t = ['Plot of '] ;
+if rplottype == 0
+	for j = 1:size(y,1)
+		t = [t s1(j,:) ' '] ;
+	end
+        figure ;
+        plot(ix(i),y(:,i)) ;
+	title (t,'Interpreter','none') ;
+	xlabel('Periods') ;
+	if size(s1,1) > 1
+	  legend(s1,0);
+	end
+elseif rplottype == 1
+	for j = 1:size(y,1)
+		figure ;
+		plot(ix(i),y(j,i)) ;
+		title(['Plot of ' s1(:,j)]) ;
+		xlabel('Periods') ;
+	end
+elseif rplottype == 2
+	figure ;
+	nl = max(1,fix(size(y,1)/4)) ;
+	nc = ceil(size(y,1)/nl) ;
+	for j = 1:size(y,1)
+		subplot(nl,nc,j) ;
+		plot(ix(i),y(j,i)) ;
+		hold on ;
+		plot(ix(i),ys_(j)*ones(1,size(i,1)),'w:') ;
+		xlabel('Periods') ;
+		ylabel([s1(:,j)]) ;
+		title(['Plot of ' s1(:,j)]) ;
+	end
+end
+
+% 02/28/01 MJ replaced bseastr by MATLAB's strmatch
+% 06/19/01 MJ added 'exact' to strmatch calls
+% 06/25/03 MJ correction when dsmpl_ ~= 0
+
+
+
+
+
+
+
+
+
diff --git a/tags/v_3.062/matlab/selif.m b/tags/v_3.062/matlab/selif.m
new file mode 100644
index 0000000000000000000000000000000000000000..7c75d589916ccc84c4b316cf05093602cc6dc461
--- /dev/null
+++ b/tags/v_3.062/matlab/selif.m
@@ -0,0 +1,12 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function x = selif(a,b)
+
+if size(b,2) ~= 1
+	error ('The second argument in SELIF must be � column vector') ;
+end
+
+x = a(find(b == 1),:) ;
+
+return ;
+
diff --git a/tags/v_3.062/matlab/set_default_option.m b/tags/v_3.062/matlab/set_default_option.m
new file mode 100644
index 0000000000000000000000000000000000000000..126a19f43f15150897ea681e2e0bd42b16385da9
--- /dev/null
+++ b/tags/v_3.062/matlab/set_default_option.m
@@ -0,0 +1,10 @@
+function options=set_default_option(options,field,default)
+  if ~isfield(options,field)
+    if sscanf(version('-release'),'%d') < 13
+      options = setfield(options,field,default);
+    else
+      eval('options.(field) = default;');
+    end
+  end
+  
+  % 06/07/03 MJ added ; to eval expression
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/set_parameters.m b/tags/v_3.062/matlab/set_parameters.m
new file mode 100644
index 0000000000000000000000000000000000000000..e6b3b7f6ebeb814ac2c6bbe1b8f12a9fe444bd69
--- /dev/null
+++ b/tags/v_3.062/matlab/set_parameters.m
@@ -0,0 +1,18 @@
+function set_parameters(xparam1)
+  global estim_params_ Sigma_e_
+  
+  for i=1:estim_params_.nvx
+    k =estim_params_.var_exo(i,1);
+    Sigma_e_(k,k) = xparam1(i)*xparam1(i);
+  end
+  offset = estim_params_.nvx+estim_params_.nvn;
+  for i=1:estim_params_.ncx
+    k1 =estim_params_.corrx(i,1);
+    k2 =estim_params_.corrx(i,2);
+    Sigma_e_(k1,k2) = xparam1(i+offset)*sqrt(Sigma_e_(k1,k1)*Sigma_e_(k2,k2));
+    Sigma_e_(k2,k1) = Sigma_e_(k1,k2);
+  end
+  offset = offset+estim_params_.ncx+estim_params_.ncn;
+  for i=1:estim_params_.np
+    assignin('base',deblank(estim_params_.param_names(i,:)),xparam1(i+offset));
+  end
diff --git a/tags/v_3.062/matlab/set_prior.m b/tags/v_3.062/matlab/set_prior.m
new file mode 100644
index 0000000000000000000000000000000000000000..c15b01fd7c5f0c94f08ac636342bebb513a1f1f5
--- /dev/null
+++ b/tags/v_3.062/matlab/set_prior.m
@@ -0,0 +1,146 @@
+function [xparam1,estim_params_,bayestopt_,lb,ub]=set_prior(estim_params_)
+  global lgx_ lgy_ options_
+  
+  nvx = size(estim_params_.var_exo,1);
+  nvn = size(estim_params_.var_endo,1);
+  ncx = size(estim_params_.corrx,1);
+  ncn = size(estim_params_.corrn,1);
+  np = size(estim_params_.param_vals,1);
+  
+  estim_params_.nvx = nvx;
+  estim_params_.nvn = nvn;
+  estim_params_.ncx = ncx;
+  estim_params_.ncn = ncn;
+  estim_params_.np = np;
+  
+  xparam1 = [];
+  ub = [];
+  lb = [];
+  bayestopt_.pshape = [];
+  bayestopt_.pmean = [];
+  bayestopt_.pstdev = [];
+  bayestopt_.p1 = [];
+  bayestopt_.p2 = [];
+  bayestopt_.p3 = [];
+  bayestopt_.p4 = [];
+  bayestopt_.jscale = [];
+  bayestopt_.name = [];
+  if nvx
+    xparam1 = estim_params_.var_exo(:,2);
+    ub = estim_params_.var_exo(:,4); 
+    lb = estim_params_.var_exo(:,3); 
+    bayestopt_.pshape =  estim_params_.var_exo(:,5);
+    bayestopt_.pmean =  estim_params_.var_exo(:,6);
+    bayestopt_.pstdev =  estim_params_.var_exo(:,7);
+    bayestopt_.p3 =  estim_params_.var_exo(:,8);
+    bayestopt_.p4 =  estim_params_.var_exo(:,9);
+    bayestopt_.jscale =  estim_params_.var_exo(:,10);
+    bayestopt_.name = cellstr(lgx_(estim_params_.var_exo(:,1),:));
+  end
+  if nvn
+    for i=1:nvn
+      estim_params_.var_endo(i,1) = strmatch(deblank(lgy_(estim_params_.var_endo(i,1),:)),deblank(options_.varobs),'exact');
+    end
+    xparam1 = [xparam1; estim_params_.var_endo(:,2)];
+    ub = [ub; estim_params_.var_endo(:,4)]; 
+    lb = [lb; estim_params_.var_endo(:,3)]; 
+    bayestopt_.pshape = [ bayestopt_.pshape; estim_params_.var_endo(:,5)];
+    bayestopt_.pmean = [ bayestopt_.pmean; estim_params_.var_endo(:,6)];
+    bayestopt_.pstdev = [ bayestopt_.pstdev; estim_params_.var_endo(:,7)];
+    bayestopt_.p3 = [ bayestopt_.p3; estim_params_.var_endo(:,8)];
+    bayestopt_.p4 = [ bayestopt_.p4; estim_params_.var_endo(:,9)];
+    bayestopt_.jscale = [ bayestopt_.jscale; estim_params_.var_endo(:,10)];
+    bayestopt_.name = cellstr(strvcat(char(bayestopt_.name),...
+				      lgy_(estim_params_.var_endo(:,1),:)));
+  end
+  if ncx
+    xparam1 = [xparam1; estim_params_.corrx(:,3)];
+    ub = [ub; max(min(estim_params_.corrx(:,5),1),-1)];
+    lb = [lb; max(min(estim_params_.corrx(:,4),1),-1)];
+    bayestopt_.pshape = [ bayestopt_.pshape; estim_params_.corrx(:,6)];
+    bayestopt_.pmean = [ bayestopt_.pmean; estim_params_.corrx(:,7)];
+    bayestopt_.pstdev = [ bayestopt_.pstdev; estim_params_.corrx(:,8)];
+    bayestopt_.p3 = [ bayestopt_.p3; estim_params_.corrx(:,9)];
+    bayestopt_.p4 = [ bayestopt_.p4; estim_params_.corrx(:,10)];
+    bayestopt_.jscale = [ bayestopt_.jscale; estim_params_.corrx(:,11)];
+    bayestopt_.name = cellstr(strvcat(char(bayestopt_.name),...
+				      char(strcat(cellstr(lgx_(estim_params_.corrx(:,1),:)),...
+						  ',',...
+						  cellstr(lgx_(estim_params_.corrx(:,2),:))))));
+  end
+  if ncn
+    xparam1 = [xparam1; estim_params_.corrn(:,3)];
+    ub = [ub; max(min(estim_params_.corrn(:,5),1),-1)];
+    lb = [lb; max(min(estim_params_.corrn(:,4),1),-1)];
+    bayestopt_.pshape = [ bayestopt_.pshape; estim_params_.corrn(:,6)];
+    bayestopt_.pmean = [ bayestopt_.pmean; estim_params_.corrn(:,7)];
+    bayestopt_.pstdev = [ bayestopt_.pstdev; estim_params_.corrn(:,8)];
+    bayestopt_.p3 = [ bayestopt_.p3; estim_params_.corrn(:,9)];
+    bayestopt_.p4 = [ bayestopt_.p4; estim_params_.corrn(:,10)];
+    bayestopt_.jscale = [ bayestopt_.jscale; estim_params_.corrn(:,11)];
+    bayestopt_.name = cellstr(strvcat(char(bayestopt_.name),...
+				      char(strcat(cellstr(lgy_(estim_params_.corrn(:,1),:)),...
+						  ',',...
+						  cellstr(lgy_(estim_params_.corrn(:,2),:))))));
+  end
+  if np
+    xparam1 = [xparam1; estim_params_.param_vals(:,1)];
+    ub = [ub; estim_params_.param_vals(:,3)];
+    lb = [lb; estim_params_.param_vals(:,2)];
+    bayestopt_.pshape = [ bayestopt_.pshape; estim_params_.param_vals(:,4)];
+    bayestopt_.pmean = [ bayestopt_.pmean; estim_params_.param_vals(:,5)];
+    bayestopt_.pstdev = [ bayestopt_.pstdev; estim_params_.param_vals(:,6)];
+    bayestopt_.p3 = [ bayestopt_.p3; estim_params_.param_vals(:,7)];
+    bayestopt_.p4 = [ bayestopt_.p4; estim_params_.param_vals(:,8)];
+    bayestopt_.jscale = [ bayestopt_.jscale; estim_params_.param_vals(:, ...
+						  9)];
+    bayestopt_.name = cellstr(strvcat(char(bayestopt_.name),estim_params_.param_names));
+  end
+
+  bayestopt_.ub = ub;
+  bayestopt_.lb = lb;
+  
+  bayestopt_.p1 = bayestopt_.pmean;
+  bayestopt_.p2 = bayestopt_.pstdev;
+  
+  % generalized location parameters by default for beta distribution
+  k = find(bayestopt_.pshape == 1);
+  k1 = find(isnan(bayestopt_.p3(k)));
+  bayestopt_.p3(k(k1)) = zeros(length(k1),1);
+  k1 = find(isnan(bayestopt_.p4(k)));
+  bayestopt_.p4(k(k1)) = ones(length(k1),1);
+  
+  % generalized location parameter by default for gamma distribution
+  k = find(bayestopt_.pshape == 2);
+  k1 = find(isnan(bayestopt_.p3(k)));
+  bayestopt_.p3(k(k1)) = zeros(length(k1),1);
+  
+  % truncation parameters by default for normal distribution
+  k = find(bayestopt_.pshape == 3);
+  k1 = find(isnan(bayestopt_.p3(k)));
+  bayestopt_.p3(k(k1)) = -Inf*ones(length(k1),1);
+  k1 = find(isnan(bayestopt_.p4(k)));
+  bayestopt_.p4(k(k1)) = Inf*ones(length(k1),1);
+
+  k = find(bayestopt_.pshape == 4);
+  for i=1:length(k)
+    [bayestopt_.p1(k(i)),bayestopt_.p2(k(i))] = ...
+	inverse_gamma_specification(bayestopt_.pmean(k(i)),bayestopt_.pstdev(k(i)),1);
+  end
+  
+  k = find(bayestopt_.pshape == 5);
+  for i=1:length(k)
+    [bayestopt_.pmean(k(i)),bayestopt_.pstdev(k(i)),bayestopt_.p1(k(i)),bayestopt_.p2(k(i))] = ...
+	uniform_specification(bayestopt_.pmean(k(i)),bayestopt_.pstdev(k(i)),bayestopt_.p3(k(i)),bayestopt_.p4(k(i)));
+  end
+  
+  k = find(bayestopt_.pshape == 6);
+  for i=1:length(k)
+    [bayestopt_.p1(k(i)),bayestopt_.p2(k(i))] = ...
+	inverse_gamma_specification(bayestopt_.pmean(k(i)),bayestopt_.pstdev(k(i)),2);
+  end
+  
+  k = find(isnan(xparam1));
+  xparam1(k) = bayestopt_.pmean(k);
+  
+  
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/set_shocks.m b/tags/v_3.062/matlab/set_shocks.m
new file mode 100644
index 0000000000000000000000000000000000000000..40f74973546622c5814db2ebfe4621fee9044f2a
--- /dev/null
+++ b/tags/v_3.062/matlab/set_shocks.m
@@ -0,0 +1,27 @@
+% Copyright (C) 2003 Michel Juillard
+%
+% set
+function set_shocks(flag,k,ivar,values)
+  global ex_ exe_ ex_det_ exe_det_
+  
+  n1 = size(ex_,1);
+  n2 = size(ex_det_,1);
+  if k(end) > n1 
+    if flag <= 1
+      ex_ = [ex_; ones(k(end)-n1,1)*exe_'];
+    else
+      ex_det_ = [ex_det_; ones(k(end)-n2,1)*exe_det_'];
+    end
+  end  
+  
+  if flag == 0
+    ex_(k,ivar) = ones(length(k),1).*values;
+  elseif flag == 1
+    ex_(k,ivar) = ex_(k,ivar).*values;
+  elseif flag == 2
+    ex_det_(k,ivar) = ones(length(k),1).*values;
+  elseif flag == 3
+    ex_det_(k,ivar) = ex_det_(k,ivar).*values;
+  end
+
+  % 05/29/03 MJ
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/set_start_date.m b/tags/v_3.062/matlab/set_start_date.m
new file mode 100644
index 0000000000000000000000000000000000000000..dde57c0cb74f5b266f71e5414b2651a51866aacd
--- /dev/null
+++ b/tags/v_3.062/matlab/set_start_date.m
@@ -0,0 +1,6 @@
+function set_start_date(y,p,f)
+  global freq_ start_date
+  
+  freq_ = f;
+  start_date = [y;p];
+
diff --git a/tags/v_3.062/matlab/set_state_space.m b/tags/v_3.062/matlab/set_state_space.m
new file mode 100644
index 0000000000000000000000000000000000000000..ac549e99b3dba4b9ceb2421d8524f06c5e2ebe3b
--- /dev/null
+++ b/tags/v_3.062/matlab/set_state_space.m
@@ -0,0 +1,88 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function dr=set_state_space(dr)
+
+global iy_ ykmin_ ykmax_ exo_nbr endo_nbr
+global ex_ valf_ it_ exe_ xkmin_ xkmax_ ys_
+global fname_ lgy_
+
+
+xlen = xkmax_ + xkmin_ + 1;
+klen = ykmin_ + ykmax_ + 1;
+
+if ~ iy_(ykmin_+1,:) > 0
+  error ('Error in model specification: some variables don"t appear as current') ;
+end
+
+fwrd_var = find(any(iy_(ykmin_+2:end,:),1))';
+if ykmin_ > 0
+  pred_var = find(any(iy_(1:ykmin_,:),1))';
+  both_var = intersect(pred_var,fwrd_var);
+  pred_var = setdiff(pred_var,both_var);
+  fwrd_var = setdiff(fwrd_var,both_var);
+  stat_var = setdiff([1:endo_nbr]',union(union(pred_var,both_var),fwrd_var));  % static variables
+else
+  pred_var = [];
+  both_var = [];
+  stat_var = setdiff([1:endo_nbr]',fwrd_var);
+end
+nboth = length(both_var);
+npred = length(pred_var);
+nfwrd = length(fwrd_var);
+nstatic = length(stat_var);
+order_var = [ stat_var; pred_var; both_var; fwrd_var];
+
+% building kmask for z state vector in t+1
+if ykmin_ > 0
+  kmask = [];
+  if ykmax_ > 0 
+    kmask = [cumsum(flipud(iy_(ykmin_+2:end,order_var)),1)] ;
+  end
+  kmask = [kmask; flipud(cumsum(iy_(1:ykmin_,order_var),1))] ;
+else
+  kmask = cumsum(flipud(iy_(ykmin_+2:klen,order_var)),1) ;
+end
+
+kmask = kmask';
+kmask = kmask(:);
+i_kmask = find(kmask);          % index of nonzero entries in kmask
+nd = size(i_kmask,1);           % size of the state vector
+kmask(i_kmask) = [1:nd];
+
+% auxiliary equations
+
+% elements that are both in z(t+1) and z(t)
+k1 = find([kmask(1:end-endo_nbr) & kmask(endo_nbr+1:end)] );
+kad = [];
+kae = [];
+if ~isempty(k1)
+  kad = kmask(k1+endo_nbr);
+  kae = kmask(k1);
+end
+
+% composition of state vector
+% col 1: variable;           col 2: lead/lag in z(t+1); 
+% col 3: A cols for t+1 (D); col 4: A cols for t (E)
+kstate = [ repmat([1:endo_nbr]',klen-1,1) kron([klen:-1:2]',ones(endo_nbr,1)) ...
+	   zeros((klen-1)*endo_nbr,2)];
+kiy = flipud(iy_(:,order_var))';
+kiy = kiy(:);
+kstate(1:ykmax_*endo_nbr,3) = kiy(1:ykmax_*endo_nbr)-endo_nbr;  
+kstate(find(kstate(:,3) < 0),3) = 0;
+kstate(ykmax_*endo_nbr+1:end,4) = kiy((ykmax_+1)*endo_nbr+1:end);  
+% put in E only the current variables that are not already in D
+kstate = kstate(i_kmask,:);
+
+dr.order_var = order_var;
+dr.nstatic = nstatic;
+dr.npred = npred+nboth;
+dr.kstate = kstate;
+dr.kad = kad;
+dr.kae = kae;
+dr.nboth = nboth;
+dr.nfwrd = nfwrd;
+% number of forward variables in the state vector
+dr.nsfwrd = sum(kstate(:,2) > ykmin_+1);
+% number of predetermined variables in the state vector
+dr.nspred = sum(kstate(:,2) <= ykmin_+1);
+
diff --git a/tags/v_3.062/matlab/shocks_file.m b/tags/v_3.062/matlab/shocks_file.m
new file mode 100644
index 0000000000000000000000000000000000000000..c22efe306400b23408c0be6007a2390446612f35
--- /dev/null
+++ b/tags/v_3.062/matlab/shocks_file.m
@@ -0,0 +1,44 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function []=shocks_file(ms_flag)
+  global options_ M_ exo_nbr exo_det_nbr lgx_ lgx_det_ ex_ exe_ ex_det_ exe_det_
+  
+  if isfield(options_,'shocks_file')
+    if exo_det_nbr > 0
+      x = read_variables(options_.shocks_file,lgx_det_,[]);
+      n = size(x,1);
+      M_.ex_det_length = n;
+      if size(ex_det_,1) >= n
+	if ms_flag == 1
+	  ex_det_(1:n,:) = ex_det_(1:n,:).*x;
+	else
+	  ex_det_(1:n,:) = x;
+	end
+      else
+	if ms_flag == 1
+	  ex_det_ = ones(n,1)*exe_det_';
+	  ex_det_ = ex_det_.*x;
+	else
+	  ex_det_ = x;
+	end
+      end
+    else
+      x = read_variables(options_.shocks_file,lgx_det_);
+      n = size(x,1);
+      if size(ex_,1) >= n
+	if ms_flag == 1
+	  ex_(1:n,:) = ex_(1:n,:).*x;
+	else
+	  ex_(1:n,:) = x;
+	end
+      else
+	if ms_flag == 1
+	  ex_ = ones(n,1)*exe_';
+	  ex_ = ex_.*x;
+	else
+	  ex_ = x;
+	end
+      end
+    end
+  end
+  
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/sim1.m b/tags/v_3.062/matlab/sim1.m
new file mode 100644
index 0000000000000000000000000000000000000000..5c3e9459ea45a3ec838475d0be1a87e9f39add11
--- /dev/null
+++ b/tags/v_3.062/matlab/sim1.m
@@ -0,0 +1,98 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function sim1
+
+global iyp iyf dynatol_ slowc_ maxit_ scalv_ it_
+global iy_ ykmin_ ykmax_ xkmin_ xkmax_ ct_ jacobia_ d1_
+global iter_ y_ start_simul fname_
+
+ny = size(y_,1) ;
+nyp = nnz(iy_(1,:)) ;
+nyf = nnz(iy_(3,:)) ;
+nrs = ny+nyp+nyf+1 ;
+nrc = nyf+1 ;
+iyf = find(iy_(3,:)>0) ;
+iyp = find(iy_(1,:)>0) ;
+isp = [1:nyp] ;
+is = [nyp+1:ny+nyp] ;
+isf = iyf+nyp ;
+isf1 = [nyp+ny+1:nyf+nyp+ny+1] ;
+stop = 0 ;
+
+disp (['-----------------------------------------------------']) ;
+disp (['MODEL SIMULATION :']) ;
+fprintf('\n') ;
+
+if isempty(start_simul)
+  it_init = 2 ;
+else
+  it_init = start_simul;
+end
+
+h1 = clock ;
+for iter = 1:maxit_
+	h2 = clock ;
+
+	if ct_ == 0
+		c = zeros(ny*iter_,nrc) ;
+	else
+		c = zeros(ny*(iter_+1),nrc) ;
+	end
+
+	it_ = it_init ;
+	z = [y_(iyp,it_-1) ; y_(:,it_) ; y_(iyf,it_+1)] ;
+	jacob ([fname_ '_ff'],z)
+	jacobia_ = [jacobia_ -d1_] ;
+	ic = [1:ny] ;
+	icp = iyp ;
+	c (ic,:) = jacobia_(:,is)\jacobia_(:,isf1) ;
+	for it_ = it_init+1:iter_+1
+		z = [y_(iyp,it_-1) ; y_(:,it_) ; y_(iyf,it_+1)] ;
+		jacob ([fname_ '_ff'],z)
+		jacobia_ = [jacobia_ -d1_] ;
+		jacobia_(:,[isf nrs]) = jacobia_(:,[isf nrs])-jacobia_(:,isp)*c(icp,:) ;
+		ic = ic + ny ;
+		icp = icp + ny ;
+		c (ic,:) = jacobia_(:,is)\jacobia_(:,isf1) ;
+	end
+
+	if ct_ == 1
+		s = eye(ny) ;
+		s(:,isf) = s(:,isf)+c(ic,1:nyf) ;
+		ic = ic + ny ;
+		c(ic,nrc) = s\c(:,nrc) ;
+		c = bksup1(ny,nrc,iyf,c) ;
+		c = reshape(c,ny,iter_+1) ;
+		y_(:,it_init:iter_+2) = y_(:,it_init:iter_+2)+slowc_*c ;
+	else
+		c = bksup1(ny,nrc,iyf,c) ;
+		c = reshape(c,ny,iter_) ;
+		y_(:,it_init:iter_+1) = y_(:,it_init:iter_+1)+slowc_*c ;
+	end
+
+	err = max(max(abs(c./scalv_')));
+	disp([num2str(iter) ' -	err = ' num2str(err)]) ;
+	disp(['	Time of iteration 	:' num2str(etime(clock,h2))]) ;
+
+	if err < dynatol_
+		stop = 1 ;
+		fprintf('\n') ;
+		disp(['	Total time of simulation 	:' num2str(etime(clock,h1))]) ;
+		fprintf('\n') ;
+		disp(['	Convergency obtained.']) ;
+		fprintf('\n') ;
+		break
+	end
+end
+
+if ~ stop
+	fprintf('\n') ;
+	disp(['	Total time of simulation 	:' num2str(etime(clock,h1))]) ;
+	fprintf('\n') ;
+	disp(['WARNING : maximum number of iterations is reached (modify maxit_).']) ;
+	fprintf('\n') ;
+end
+disp (['-----------------------------------------------------']) ;
+return ;
+
+% 08/24/01 MJ added start_simul
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/simk.m b/tags/v_3.062/matlab/simk.m
new file mode 100644
index 0000000000000000000000000000000000000000..6898a572747baf6c5e367cea63b2ceb274eb4a71
--- /dev/null
+++ b/tags/v_3.062/matlab/simk.m
@@ -0,0 +1,325 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function simk
+
+global dynatol_ maxit_ slowc_ scalv_
+global iy_ ykmin_ ykmax_ iyr0 ct_ jacobia_ d1_
+global gstep_ ys_ y_ it_ iter_
+global ncc timing_ broyden_ fname_
+
+func_name = [fname_ '_ff'];
+nk = ykmin_ + ykmax_ + 1 ;
+ny = size(iy_,2) ;
+icc1 = iy_(nk,:) > 0;
+
+for i = 1:ykmax_ -1
+  icc1 = [iy_(nk-i,:) | icc1(1,:); icc1] ;
+end
+
+icc1 = find(icc1') ;
+iy = iy_ > 0 ;
+isc = cumsum(sum(iy',1))' ;
+iyr0 = find(iy_') ;
+ncc1 = size(icc1,1) ;
+ncc = ncc1 + 1 ;
+ncs = size(iyr0,1) ;
+
+ky = zeros(ny,nk) ;            % indices of variables at each lead or lag
+lky = zeros(nk,1) ;
+for i = 1:nk
+  j = find(iy_(i,:))' ;
+  if isempty(j)
+    lky(i) = 0;
+  else
+    lky(i) = size(j,1) ;
+    ky(1:lky(i),i) = j ;
+  end
+end
+
+jwc = find(iy(2:ykmax_+1,:)') ; % indices of columns for
+                                % triangularization
+				% as many rows as lags in model
+
+if isempty(jwc)
+  jwc = 0 ;
+  ljwc = 0 ;
+  temp = icc1 ;
+else
+  ljwc = size(jwc,1) ;          % length of each row in jwc
+  temp = union(jwc,icc1) ;      % prepares next iteration
+end
+
+j1 = ky(1:lky(1),1) ;
+lj1 = lky(1) ;
+
+for i = 2:ykmin_
+  [j1,lj1] = ffill(j1,lj1,selif(temp+(i-1)*ny,temp <= ny)) ;
+  if ykmax_ == 1
+    if lky(i+ykmax_) > 0
+      [jwc,ljwc] = ffill(jwc,ljwc, ky(1:lky(i+ykmax_),i+ykmax_)+(ykmax_-1)*ny) ;
+      if ljwc(i) == 0
+ 	temp = icc1;
+      else
+ 	temp = union(jwc(1:ljwc(i),i),icc1) ;
+      end
+    else
+      [jwc,ljwc] = ffill(jwc,ljwc,[]) ;
+      temp = icc1 ;
+    end
+  else
+    temp = temp(lj1(i)+1:size(temp,1),:) - ny ;
+    if lky(i+ykmax_) > 0
+      [jwc,ljwc] = ffill(jwc,ljwc,[temp;ky(1:lky(i+ykmax_),i+ykmax_)+(ykmax_-1)*ny]);
+    else
+      [jwc,ljwc] = ffill(jwc,ljwc,temp) ;
+    end
+    temp = union(jwc(1:ljwc(i),i),icc1) ;
+  end
+end
+
+[j1,lj1] = ffill(j1,lj1,selif(temp+ykmin_*ny, temp <= ny)) ;
+ltemp = zeros(ykmin_,1) ;
+jwc1 = zeros(ncc1,ykmin_) ;
+
+for i = 1:ykmin_
+  temp = union(jwc(1:ljwc(i),i),icc1) ;
+  ltemp(i) = size(temp,1) ;
+  if ljwc(i) > 0
+    jwc(1:ljwc(i),i) = indnv(jwc(1:ljwc(i),i),temp) ;
+  end
+  jwc1(:,i) = indnv(icc1,temp) ;
+end
+
+h1 = clock ;
+
+disp (['-----------------------------------------------------']) ;
+disp ('MODEL SIMULATION') ;
+fprintf ('\n') ;
+
+for iter = 1:maxit_
+  h2 = clock ;
+  y_ = y_(:);
+  err_f = 0;
+  
+  fid = fopen('dynare.swp','w+') ;
+
+  it_ = 1+ykmin_ ;
+  ic = [1:ny] ;
+  iyr = iyr0 ;
+  i = ykmin_+1 ;
+  while (i>1) & (it_<=iter_+ykmin_)
+    h3 = clock ;
+    if broyden_ & iter > 1
+      d1_ = -feval(fh,y_(iyr));
+    else
+      jacob(func_name,y_(iyr)) ;
+      d1_ = -d1_ ;
+    end
+    err_f = max(err_f,max(abs(d1_)));
+    if lky(i) ~= 0
+      j1i = ky(1:lky(i),i) ;
+      w0 = jacobia_(:,isc(i-1)+1:isc(i)) ;
+    else
+      w0 = [];
+    end
+    ttemp = iy(i+1:i+ykmax_,:)' ;
+    jwci = find(ttemp) ;
+    if ~ isempty(jwci)
+      w = jacobia_(:,isc(i)+1:isc(i+ykmax_)) ;
+    end
+    j = i ;
+    while j <= ykmin_
+      if ~isempty(w0)
+
+	ofs = ((it_-ykmin_-ykmin_+j-2)*ny)*ncc*8 ;
+	junk = fseek(fid,ofs,-1) ;
+	c = fread(fid,[ncc,ny],'float64') ;
+	c = c' ;
+
+	if isempty(jwci)
+	  w = -w0*c(j1i,1:ncc1) ;
+	  jwci = icc1 ;
+	else
+	  iz = union(jwci,icc1) ;
+	  ix = indnv(jwci,iz) ;
+	  iy__ = indnv(icc1,iz) ;
+	  temp = zeros(size(w,1),size(iz,1)) ;
+	  temp(:,ix) = w ;
+	  temp(:,iy__) = temp(:,iy__)-w0*c(j1i,1:ncc1) ;
+	  w = temp ;
+	  jwci = iz ;
+	  clear temp iz ix iy__ ;
+	end
+	d1_ = d1_-w0*c(j1i,ncc) ;
+	clear c ;
+      end
+      j = j + 1 ;
+      if isempty(jwci)
+	j1i = [];
+	if lky(j+ykmax_) ~= 0
+	  jwci = ky(1:lky(j+ykmax_),j+ykmax_) + (ykmax_-1)*ny ;
+	  w = jacobia_(:,isc(j+ykmax_-1)+1:isc(j+ykmax_)) ;
+	else
+	  jwci = [] ;
+	end
+      else
+	j1i = selif(jwci,jwci<(ny+1)) ;
+	w0 = w(:,1:size(j1i,1)) ;
+	if size(jwci,1) == size(j1i,1)
+	  if lky(j+ykmax_) ~= 0
+	    jwci = ky(1:lky(j+ykmax_),j+ykmax_)+(ykmax_-1)*ny ;
+	    w = jacobia_(:,isc(j+ykmax_-1)+1:isc(j+ykmax_)) ;
+	  else
+	    jwci = [] ;
+	  end
+	else
+	  jwci = jwci(size(j1i,1)+1:size(jwci,1),:)-ny ;
+	  w = w(:,size(j1i,1)+1:size(w,2)) ; 
+	  if lky(j+ykmax_) ~= 0
+	    jwci = [ jwci; ky(1: lky(j+ykmax_),j+ykmax_)+(ykmax_-1)*ny] ;
+	    w = [w jacobia_(:,isc(j+ykmax_-1)+1:isc(j+ykmax_))] ;
+%	  else
+%	    jwci = [] ;
+	  end
+	end
+      end
+    end
+    jwci = [indnv(jwci,icc1);ncc] ;
+    w = [w d1_] ;
+    c = zeros(ny,ncc) ;
+    c(:,jwci) = w0\w ;
+    clear w w0 ;
+
+    junk = fseek(fid,0,1) ;
+    fwrite(fid,c','float64') ;
+    clear c ;
+
+    it_ = it_ + 1;
+    ic = ic + ny ;
+    iyr = iyr + ny ;
+    i = i - 1 ;
+  end
+  icr0 = (it_-ykmin_-ykmin_ -1)*ny ;
+  while it_ <= iter_+ykmin_
+    if broyden_
+      d1_ = -feval(fh,y_(iyr));
+    else
+      jacob(func_name,y_(iyr)) ;
+      d1_ = -d1_ ;
+    end
+    err_f = max(err_f,max(abs(d1_)));
+    w0 = jacobia_(:,1:isc(1)) ;
+    w = jacobia_(:,isc(1)+1:isc(1+ykmax_)) ;
+    j = 1 ;
+    while j <= ykmin_
+      icr = j1(1:lj1(j),j)-(j-1)*ny ;
+
+      ofs = ((icr0+(j-1)*ny+1)-1)*ncc*8 ;
+      junk = fseek(fid,ofs,-1) ;
+      c = fread(fid,[ncc,ny],'float64') ;
+      c = c' ;
+
+      temp = zeros(ny,ltemp(j)) ;
+      if ljwc(j) > 0
+	temp(:,jwc(1:ljwc(j),j)) = w ;
+      end
+      temp(:,jwc1(:,j))=temp(:,jwc1(:,j))-w0*c(icr,1:ncc1) ;
+      w = temp ;
+      clear temp ;
+      d1_ = d1_-w0*c(icr,ncc) ;
+      clear c ;
+      j = j + 1 ;
+      w0 = w(:,1:lj1(j)) ;
+      if ykmax_ == 1
+	w = jacobia_(:,isc(j+ykmax_-1)+1:isc(j+ykmax_)) ;
+      else
+	w = w(:,lj1(j)+1:size(w,2)) ;
+
+	if lky(j+ykmax_) > 0
+	  w = [w jacobia_(:,isc(j+ykmax_-1)+1:isc(j+ykmax_))] ;
+	end
+      end
+    end
+    c = w0\[w d1_] ;
+    d1_ = [] ;
+    clear w w0 ;
+    junk = fseek(fid,0,1) ;
+    fwrite(fid,c','float64') ;
+    clear c ;
+    it_ = it_ + 1 ;
+    ic = ic + ny ;
+    iyr = iyr + ny ;
+    icr0 = icr0 + ny ;
+  end
+  if ct_ == 1
+
+    ofs = (((it_-ykmin_-2)*ny+1)-1)*ncc*8 ;
+    junk = fseek(fid,ofs,-1) ;
+    c = fread(fid,[ncc,ny],'float64') ;
+    c = c' ;
+
+    for i = 1:ykmax_
+      w = tril(triu(ones(ny,ny+ncc1))) ;
+      w(:,jwc1(:,ykmin_)) = w(:,jwc1(:,ykmin_))+c(:,1:ncc1) ;
+      c = [w(:,ny+1:size(w,2))' c(:,ncc)]/w(:,1:ny) ;
+
+      junk = fseek(fid,0,1) ;
+      fwrite(fid,c','float64') ;
+
+      it_ = it_+1 ;
+      ic = ic + ny ;
+
+    end
+  end
+  y_ = reshape(y_,ny,iter_+ykmin_+ykmax_) ;
+  if ct_ == 1
+    hbacsup = clock ;
+    c = bksupk(ny,fid,ncc,icc1) ;
+    hbacsup = etime(clock,hbacsup) ;
+    c = reshape(c,ny,iter_+ykmax_)' ;
+    y(:,1+ykmin_:(iter_+ykmax_+ykmin_)) = y(:,1+ykmin_:(iter_+ykmax_+ykmin_))+slowc_*c' ;
+  else
+    hbacsup = clock ;
+    c = bksupk(ny,fid,ncc,icc1) ;
+    hbacsup = etime(clock,hbacsup) ;
+    c = reshape(c,ny,iter_)' ;
+    y_(:,1+ykmin_:(iter_+ykmin_)) = y_(:,1+ykmin_:(iter_+ykmin_))+slowc_*c' ;
+  end
+
+  fclose(fid) ;
+
+  h2 = etime(clock,h2) ;
+  [junk,i1] = max(abs(c));
+  [junk,i2] = max(junk);
+  global lgy_
+  disp(['variable ' lgy_(i2,:) ' period ' num2str(i1(i2))])
+  err = max(max(abs(c./scalv_'))) ;
+  disp ([num2str(iter) '-	err = ' num2str(err)]) ;
+  disp (['err_f = ' num2str(err_f)])
+  disp (['	Time of this iteration	: ' num2str(h2)]) ;
+  if timing_
+    disp (['	Back substitution		: ' num2str(hbacsup)]) ;
+  end
+  if err < dynatol_
+    h1 = etime(clock,h1) ;
+    fprintf ('\n') ;
+    disp (['	Total time of simulation	: ' num2str(h1)]) ;
+    fprintf ('\n') ;
+    disp (['	Convergence achieved.']) ;
+    disp (['-----------------------------------------------------']) ;
+    fprintf ('\n') ;
+    return ;
+  end
+end
+disp(['WARNING : the maximum number of iterations is reached.']) ;
+fprintf ('\n') ;
+disp (['-----------------------------------------------------']) ;
+return ;
+
+% 2/11/99 MJ took out reshapel
+
+
+
+
+
+
diff --git a/tags/v_3.062/matlab/simul.m b/tags/v_3.062/matlab/simul.m
new file mode 100644
index 0000000000000000000000000000000000000000..c3329ee3507c71cea3c3a5818ddf451352954070
--- /dev/null
+++ b/tags/v_3.062/matlab/simul.m
@@ -0,0 +1,66 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function simul(dr)
+
+global scalv_ ct_ endval_ endo_nbr ex_ exe_
+global iy_ ykmin_ ykmax_ xkmin_ xkmax_
+global valf_ ys_ ys0_ y_ lgy_ iter_ options_
+
+if size(iy_,2)-nnz(iy_(ykmin_+1,:)) > 0
+  mess = ['DYNARE: error in model specification : variable ' lgy_(find(iy_(ykmin_+1,:)==0),:)] ;
+  mess = [mess ' doesn''t appear as current variable.'] ; 
+  error (mess) ;
+end
+
+options_ = set_default_option(options_,'simul_algo',0);
+if ~isfield(options_,'periods') & ~isempty(iter_)
+  options_.periods = iter_
+end
+options_ = set_default_option(options_,'periods',0);
+if options_.periods == 0
+  error('SIMUL: number of periods for the simulation isn''t specified')
+end
+iter_ = options_.periods;
+if options_.simul_algo == 0
+  if ~ valf_
+    make_y_;
+    make_ex_;
+  end
+
+  if isempty(scalv_) | scalv_ == 0
+    scalv_ = ys_ ;
+  end
+
+  scalv_= 1 ;
+
+  if ykmin_ ==1 & ykmax_ <= 1
+    sim1 ;
+  else
+    simk ;
+  end
+else
+  set_default_option('replic',1);
+  set_default_option('simul_seed',1);
+  if isfield(dr,'ghxx')
+    set_default_option('order',2);
+  else
+    set_defaut_option('order',1);
+  end
+  y_=simult(ys_,dr,options_);
+end
+
+dyn2vec;
+
+% 6/18/01 MJ added dyn2vec if 40 variables or less
+% 01/16/03 MJ use dyn2vec whatever the number of variables
+% 02/18/03 MJ added ys_ for calling simult
+% 05/24/03 MJ added options_ and options_.periods
+
+
+
+
+
+
+
+
+
diff --git a/tags/v_3.062/matlab/simult.m b/tags/v_3.062/matlab/simult.m
new file mode 100644
index 0000000000000000000000000000000000000000..8cac65fea2f1038d0a7b0796c0d80d7248bf42de
--- /dev/null
+++ b/tags/v_3.062/matlab/simult.m
@@ -0,0 +1,41 @@
+% Copyright (C) 2001 Michel Juillard
+%
+
+function y_=simult(ys, dr)
+global jacobia_ iy_ ykmin_ ykmax_ gstep_ exo_nbr endo_nbr
+global ex_ valf_ it_ exe_ xkmin_ xkmax_ ys_
+global fname_ means_ Sigma_e_ lgy_ options_
+
+order = options_.order;
+seed = options_.simul_seed;
+iter_ = options_.periods;
+
+it_ = ykmin_ + 1 ;
+
+% eliminate shocks with 0 variance
+i_exo_var = setdiff([1:exo_nbr],find(diag(Sigma_e_) == 0));
+nxs = length(i_exo_var);
+ex_ = zeros(xkmin_+xkmax_+iter_,exo_nbr);
+chol_S = chol(Sigma_e_(i_exo_var,i_exo_var));
+
+if isempty(seed)
+  randn('state',sum(100*clock));
+else
+  randn('state',seed);
+end
+if ~isempty(Sigma_e_)
+  ex_(:,i_exo_var) = randn(xkmin_+xkmax_+iter_,nxs)*chol_S;
+end
+y_ = simult_(ys,dr,ex_,order);
+
+
+
+% 02/20/01 MJ replaced ys by dr.ys
+% 02/22/01 MJ removed commented out lines
+%             removed useless temps
+%             stderr_ replaced by Sigma_e_
+% 02/28/01 MJ changed expression for Sigma_e_
+% 02/18/03 MJ added ys in the calling sequence for arbitrary initial values
+%             suppressed useless calling parameter istoch
+% 05/10/03 MJ removed repmat() in call to simult_() for lag > 1
+% 05/29/03 MJ test for 0 variances
diff --git a/tags/v_3.062/matlab/simult_.m b/tags/v_3.062/matlab/simult_.m
new file mode 100644
index 0000000000000000000000000000000000000000..5e0cc603ebf73859e75120b2dedb6b32dcc31365
--- /dev/null
+++ b/tags/v_3.062/matlab/simult_.m
@@ -0,0 +1,66 @@
+% Copyright (C) 2001 Michel Juillard
+%
+
+function y_ = simult_(y0,dr,ex_,iorder)
+global endo_nbr ykmin_ xkmin_ it_ options_ iy_
+  iter = size(ex_,1)-xkmin_;
+  nx = size(dr.ghu,2);
+  y_ = zeros(size(y0,1),iter+ykmin_);
+  y_(:,1:ykmin_) = y0;
+  k1 = [ykmin_:-1:1];
+  k2 = dr.kstate(find(dr.kstate(:,2) <= ykmin_+1),[1 2]);
+  k2 = k2(:,1)+(ykmin_+1-k2(:,2))*endo_nbr;
+  k3 = iy_(1:ykmin_,:)';
+  k3 = find(k3(:));
+  k4 = dr.kstate(find(dr.kstate(:,2) < ykmin_+1),[1 2]);
+  k4 = k4(:,1)+(ykmin_+1-k4(:,2))*endo_nbr;
+  
+  options_ = set_default_option(options_,'simul_algo',0);
+  if options_.simul_algo == 1
+    o1 = dr.nstatic+1;
+    o2 = dr.nstatic+dr.npred;
+    o3 = o2-dr.nboth+1;
+    [junk, k5] = sort(dr.order_var(o1:o2));
+    [junk, k6] = sort(dr.order_var(o3:end));
+  end
+
+  if iorder == 1
+    for i = ykmin_+1: iter+ykmin_
+      tempx1 = y_(dr.order_var,k1);
+      tempx2 = tempx1-repmat(dr.ys(dr.order_var),1,ykmin_);
+      tempx = tempx2(k2);
+      if options_.simul_algo == 0
+	y_(dr.order_var,i) = dr.ys(dr.order_var)+dr.ghx*tempx+...
+	    dr.ghu*ex_(i+xkmin_-ykmin_,:)';
+      elseif options_.simul_algo == 1
+	it_ = i;
+	m = dr.ys(dr.order_var);
+	[y_(:,i), check] = dynare_solve('ff_simul1',y_(:,i-1),tempx1(k3), ...
+					m(o3:end),tempx(k4),o1,o2,o3,k6);
+      end
+      k1 = k1+1;
+    end
+  elseif iorder == 2
+    for i = ykmin_+1: iter+ykmin_
+      tempx1 = y_(dr.order_var,k1);
+      tempx2 = tempx1-repmat(dr.ys(dr.order_var),1,ykmin_);
+      tempx = tempx2(k2);
+      tempu = ex_(i+xkmin_-ykmin_,:)';
+      tempuu = kron(tempu,tempu);
+      if options_.simul_algo == 0
+	tempxx = kron(tempx,tempx);
+	tempxu = kron(tempx,tempu);
+	y_(dr.order_var,i) = dr.ys(dr.order_var)+dr.ghs2/2+dr.ghx*tempx+ ...
+	    dr.ghu*tempu+0.5*(dr.ghxx*tempxx+dr.ghuu*tempuu)+dr.ghxu*tempxu;
+      elseif options_.simul_algo == 1
+	it_ = i;
+	m = dr.ys(dr.order_var)+dr.ghs2/2;
+	tempx1 = y_(:,k1);
+	[y_(:,i), check] = dynare_solve('ff_simul2',y_(:,i-1),tempx1(k3), ...
+					m(o3:end),tempx(k4),o1,o2,o3,k6);
+      end
+      k1 = k1+1;
+    end
+  end
+
+% MJ 08/30/02 corrected bug at order 2
diff --git a/tags/v_3.062/matlab/simultxdet.m b/tags/v_3.062/matlab/simultxdet.m
new file mode 100644
index 0000000000000000000000000000000000000000..0bd531e9757c267dda63239d40c003bc0e8d1a21
--- /dev/null
+++ b/tags/v_3.062/matlab/simultxdet.m
@@ -0,0 +1,136 @@
+% Copyright (C) 2005 Michel Juillard
+%
+
+function [y_,var_yf]=simultexdet(y0,dr,ex_,ex_det, iorder,var_list)
+  global endo_nbr ykmin_ xkmin_ it_ options_ iy_ M_ exe_det_ Sigma_e_ lgy_
+
+  iter = size(ex_,1)-xkmin_;
+  nx = size(dr.ghu,2);
+  y_ = zeros(size(y0,1),iter+ykmin_);
+  y_(:,1:ykmin_) = y0;
+  k1 = [ykmin_:-1:1];
+  k2 = dr.kstate(find(dr.kstate(:,2) <= ykmin_+1),[1 2]);
+  k2 = k2(:,1)+(ykmin_+1-k2(:,2))*endo_nbr;
+  k3 = iy_(1:ykmin_,:)';
+  k3 = find(k3(:));
+  k4 = dr.kstate(find(dr.kstate(:,2) < ykmin_+1),[1 2]);
+  k4 = k4(:,1)+(ykmin_+1-k4(:,2))*endo_nbr;
+  
+  old_options = options_;
+  options_ = set_default_option(options_,'simul_algo',0);
+  options_ = set_default_option(options_,'conf_sig',0.9);
+  
+  if options_.simul_algo == 1
+    o1 = dr.nstatic+1;
+    o2 = dr.nstatic+dr.npred;
+    o3 = o2-dr.nboth+1;
+    [junk, k5] = sort(dr.order_var(o1:o2));
+    [junk, k6] = sort(dr.order_var(o3:end));
+  end
+  
+  nvar = size(var_list,1);
+  if nvar == 0
+    nvar = endo_nbr;
+    ivar = [1:nvar];
+  else
+    ivar=zeros(nvar,1);
+    for i=1:nvar
+      i_tmp = strmatch(var_list(i,:),lgy_,'exact');
+      if isempty(i_tmp)
+	disp(var_list(i,:));
+	error (['One of the variable specified does not exist']) ;
+      else
+	ivar(i) = i_tmp;
+      end
+    end
+  end
+
+  if iorder == 1
+    for i = ykmin_+1: iter+ykmin_
+      tempx1 = y_(dr.order_var,k1);
+      tempx2 = tempx1-repmat(dr.ys(dr.order_var),1,ykmin_);
+      tempx = tempx2(k2);
+      if options_.simul_algo == 0
+	y_(dr.order_var,i) = dr.ys(dr.order_var)+dr.ghx*tempx+dr.ghu* ...
+	    ex_(i+xkmin_-ykmin_,:)';
+	for j=1:min(iter+ykmin_-i-M_.ex_det_length+1,M_.ex_det_length)
+	  y_(dr.order_var,i) = y_(dr.order_var,i) + dr.ghud{j}*(ex_det(i+j-1,:)'-exe_det_');
+	end
+      elseif options_.simul_algo == 1
+	it_ = i;
+	m = dr.ys(dr.order_var);
+	[y_(:,i), check] = dynare_solve('ff_simul1',y_(:,i-1),tempx1(k3), ...
+					m(o3:end),tempx(k4),o1,o2,o3,k6);
+      end
+	
+      k1 = k1+1;
+    end
+  elseif iorder == 2
+    for i = ykmin_+1: iter+ykmin_
+      tempx1 = y_(dr.order_var,k1);
+      tempx2 = tempx1-repmat(dr.ys(dr.order_var),1,ykmin_);
+      tempx = tempx2(k2);
+      tempu = ex_(i+xkmin_-ykmin_,:)';
+      tempuu = kron(tempu,tempu);
+      if options_.simul_algo == 0
+	tempxx = kron(tempx,tempx);
+	tempxu = kron(tempx,tempu);
+	y_(dr.order_var,i) = dr.ys(dr.order_var)+dr.ghs2/2+dr.ghx*tempx+ ...
+	    dr.ghu*tempu+0.5*(dr.ghxx*tempxx+dr.ghuu*tempuu)+dr.ghxu* ...
+	    tempxu;
+	for j=1:min(iter+ykmin_-i-M_.ex_det_length+1,M_.ex_det_length)
+	  tempud = ex_det(i+j-1,:)'-exe_det_';
+	  tempudud = kron(tempud,tempud);
+	  tempxud = kron(tempx,tempud);
+	  tempuud = kron(tempu,tempud);
+	  y_(dr.order_var,i) = y_(dr.order_var,i) + dr.ghud{j}*tempud + ...
+	      dr.ghxud{j}*tempxud + dr.ghuud{j}*tempuud + ...
+	      0.5*dr.ghudud{j,j}*tempudud;
+	  for k=1:j-1
+	    tempudk = ex_det(i+k-1,:)'-exe_det_';
+	    tempududk = kron(tempudk,tempud);
+	    y_(dr.order_var,i) = y_(dr.order_var,i) + ...
+		dr.ghudud{k,j}*tempududk;
+	  end
+	end
+      elseif options_.simul_algo == 1
+	it_ = i;
+	m = dr.ys(dr.order_var)+dr.ghs2/2;
+	tempx1 = y_(:,k1);
+	[y_(:,i), check] = dynare_solve('ff_simul2',y_(:,i-1),tempx1(k3), ...
+					m(o3:end),tempx(k4),o1,o2,o3,k6);
+      end
+      k1 = k1+1;
+    end
+  end
+
+  [A,B] = kalman_transition_matrix(dr);
+  
+  sigma_u = B*Sigma_e_*B';
+  sigma_y = 0;
+  
+  for i=1:iter
+    sigma_y = sigma_y+sigma_u;
+    var_yf(i,dr.order_var) = diag(sigma_y(1:endo_nbr,1:endo_nbr))';
+    if i == iter
+      break
+    end
+    sigma_u = A*sigma_u*A';
+  end
+
+  fact = qnorm((1-options_.conf_sig)/2,0,1);
+  
+  for i=1:nvar
+    my_subplot(i,nvar,2,3,'Forecasts');
+    
+    interval_width = fact*sqrt(var_yf(:,ivar(i)));
+    
+    plot([-ykmin_+1:0],y0(ivar(i),1:ykmin_),'b-',...
+	 [1:iter],y_(ivar(i),ykmin_+1:end),'g-',...
+	 [1:iter],y_(ivar(i),ykmin_+1:end)'+interval_width,'g:',...
+	 [1:iter],y_(ivar(i),ykmin_+1:end)'-interval_width,'g:',...
+	 [1 iter],repmat(dr.ys(ivar(i)),1,2),'r-');
+    title(lgy_(ivar(i),:));
+  end
+
+  options_ = old_options;
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/solve1.m b/tags/v_3.062/matlab/solve1.m
new file mode 100644
index 0000000000000000000000000000000000000000..9175e892abf8e353d5918b1778472f1753dbf563
--- /dev/null
+++ b/tags/v_3.062/matlab/solve1.m
@@ -0,0 +1,136 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function [x,check] = solve1(func,x,j1,j2,varargin)
+
+  global gstep_ fjac debug_ unit_root_ lgy_
+
+  nn = length(j1);
+  
+  fjac = zeros(nn,nn) ;
+  g = zeros(nn,1) ;
+
+  tolf = 100*eps^(2/3) ;
+  tolmin = 3.7e-11 ;
+  tolx = 3.7e-11 ;
+
+  stpmx = 100 ;
+  maxit = 2000 ;
+
+  check = 0 ;
+
+  fvec = feval(func,x,varargin{:});
+  fvec = fvec(j1);
+  
+  i = find(~isfinite(fvec));
+  
+  if ~isempty(i)
+    disp(['STEADY:  numerical initial values incompatible with the following' ...
+	  ' equations'])
+    disp(j1(i)')
+  end
+  
+  f = 0.5*fvec'*fvec ;
+
+  if max(abs(fvec)) < 0.01*tolf
+    return ;
+  end
+
+  stpmax = stpmx*max([sqrt(x'*x);nn]) ;
+  first_time = 1;
+  for its = 1:maxit
+
+    dh = max(abs(x(j2)),gstep_*ones(nn,1))*eps^(1/3);
+    for j = 1:nn
+      xdh = x ;
+      xdh(j2(j)) = xdh(j2(j))+dh(j) ;
+      t = feval(func,xdh,varargin{:});
+      fjac(:,j) = (t(j1) - fvec)./dh(j) ;
+      g(j) = fvec'*fjac(:,j) ;
+    end
+
+    if debug_
+      disp(['cond(fjac) ' num2str(cond(fjac))])
+    end
+    
+    if unit_root_
+      if first_time
+	first_time = 0;
+	[q,r,e]=qr(fjac);
+	n = sum(abs(diag(r)) < 1e-12);
+	fvec = q'*fvec;
+	p = e*[-r(1:end-n,1:end-n)\fvec(1:end-n);zeros(n,1)];
+	disp(' ')
+	disp('STEADY with unit roots:')
+	disp(' ')
+	if n > 0
+	  disp(['   The following variable(s) kept their value given in INITVAL' ...
+		' or ENDVAL'])
+	  disp(char(e(:,end-n+1:end)'*lgy_))
+	else
+	  disp('   STEADY can''t find any unit root!')
+	end
+      else
+	[q,r]=qr(fjac*e);
+	fvec = q'*fvec;
+	p = e*[-r(1:end-n,1:end-n)\fvec(1:end-n);zeros(n,1)];
+      end	
+%    elseif cond(fjac) > 10*sqrt(eps)
+    elseif cond(fjac) > 1/sqrt(eps)
+	fjac2=fjac'*fjac;
+	p=-(fjac2+sqrt(nn*eps)*max(sum(abs(fjac2)))*eye(nn))\(fjac'*fvec);
+    else
+      p = -fjac\fvec ;
+    end
+    xold = x ;
+    fold = f ;
+
+    [x,f,fvec,check]=lnsrch1(xold,fold,g,p,stpmax,func,j1,j2,varargin{:});
+
+    if debug_
+      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
+	return
+      else
+	disp (' ')
+	disp (['SOLVE: Iteration ' num2str(its)])
+	disp (['Spurious convergence.'])
+	disp (x)
+	return
+      end
+
+      if max(abs(x-xold)./max([abs(x);ones(1,nn)])') < tolx
+	disp (' ')
+	disp (['SOLVE: Iteration ' num2str(its)])
+	disp (['Convergence on dX.'])
+	disp (x)
+	return
+      end
+    elseif f < tolf
+      return
+    end
+  end
+  
+  check = 1;
+  disp(' ')
+  disp('SOLVE: maxit has been reached')
+
+% 01/14/01 MJ lnsearch is now a separate function
+% 01/16/01 MJ added varargin to function evaluation
+% 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/tags/v_3.062/matlab/steady.m b/tags/v_3.062/matlab/steady.m
new file mode 100644
index 0000000000000000000000000000000000000000..b134095e48320e92b12319755a85cf55232dcaf6
--- /dev/null
+++ b/tags/v_3.062/matlab/steady.m
@@ -0,0 +1,28 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function steady(linear)
+
+  global ys_ lgy_ ys0_ ykmin_ ykmax_ y_ options_
+
+  steady_;
+  
+  disp(' ')
+  disp('STEADY-STATE RESULTS:')
+  disp(' ')
+  for i=1:size(ys_,1)
+    disp(sprintf('%s \t\t %g',lgy_(i,:),ys_(i)));
+  end
+  
+% overwrites the initialization of y_ in case it was
+% set by initval
+  if isempty(ys0_)
+    y_(:,1:ykmin_) = ys_ * ones(1,ykmin_);
+  else
+    options_ =set_default_option(options_,'periods',1);
+    y_(:,ykmin_+1:ykmin_+options_.periods+ykmax_) = ys_ * ones(1,options_.periods+ykmax_);
+  end
+  
+% 06/24/01 MJ steady print results; steady_ doesn't
+% 09/22/01 FC corrected lgy(i,:)
+% 05/29/03 MJ sets initial values of y_
+
diff --git a/tags/v_3.062/matlab/steady_.m b/tags/v_3.062/matlab/steady_.m
new file mode 100644
index 0000000000000000000000000000000000000000..295784a73fd5dd8818ba8c14943ccaa250a40892
--- /dev/null
+++ b/tags/v_3.062/matlab/steady_.m
@@ -0,0 +1,43 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function steady_()
+
+  global it_ ex_ exe_ iy_ fname_ ex_det_ exe_det_
+  global ykmin_ ykmax_ ys_ xkmin_ xkmax_ exo_det_nbr
+
+  x = ys_ ;
+  xlen = xkmin_ + xkmax_ + 1 ;
+  nn = size(iy_,2) ;
+  it_ = ykmin_+1 ;
+  temp = ex_ ;
+  ex_ = ones(xlen,1)*exe_' ;
+
+  if exo_det_nbr > 0
+    tempdet = ex_det_ ;
+    ex_det_ = ones(ykmin_+1,1)*exe_det_' ;
+  end
+
+  if exist([fname_ '_steadystate'])
+    [ys_,check] = feval([fname_ '_steadystate'],x);
+  else
+    [ys_,check] = dynare_solve([fname_ '_fff'],x);
+  end
+
+  if check ~= 0
+    error('STEADY: convergence problems')
+  end
+
+  if exo_det_nbr > 0
+    ex_det_ = tempdet;
+  end
+  ex_ = temp ;
+
+% 06/24/01 MJ: steady_ no results printer; steady with printed results
+% 07/31/03 MJ: in case of convergence problem steady stops with an error
+
+
+
+
+
+
+
diff --git a/tags/v_3.062/matlab/stoch_simul.m b/tags/v_3.062/matlab/stoch_simul.m
new file mode 100644
index 0000000000000000000000000000000000000000..bedd0b386a86068bff486d4e086a88d259fada4f
--- /dev/null
+++ b/tags/v_3.062/matlab/stoch_simul.m
@@ -0,0 +1,305 @@
+% Copyright (C) 2001 Michel Juillard
+%
+function info=stoch_simul(var_list)
+  global iter_ ys_ dr_ y_ dr_ exo_nbr lgy_ lgx_ Sigma_e_ ykmin_ ykmax_ 
+  global endo_nbr exo_nbr exe_ ex_ xkmin_ xkmax_ iter_ options_ lgx_orig_ord_
+  global fname_ lgx_TeX_ lgy_TeX_
+
+  options_ = set_default_option(options_,'TeX',0);  
+  options_ = set_default_option(options_,'order',2);
+  options_ = set_default_option(options_,'linear',0);
+  if options_.linear
+    options_.order = 1;
+  end
+  options_ = set_default_option(options_,'ar',5);
+  options_ = set_default_option(options_,'irf',40);
+  options_ = set_default_option(options_,'relative_irf',0);
+  options_ = set_default_option(options_,'dr_algo',0);
+  options_ = set_default_option(options_,'simul_algo',0);
+  options_ = set_default_option(options_,'drop',100);
+  if options_.order == 1
+    options_.replic = 1;
+  else
+    options_ = set_default_option(options_,'replic',50);
+  end
+  options_ = set_default_option(options_,'nomoments',0);
+  options_ = set_default_option(options_,'nocorr',0);
+  options_ = set_default_option(options_,'simul_seed',[]);
+  options_ = set_default_option(options_,'hp_filter',0);
+  options_ = set_default_option(options_,'hp_ngrid',512);
+  options_ = set_default_option(options_,'simul',0);
+  options_ = set_default_option(options_,'periods',0);
+  options_ = set_default_option(options_,'noprint',0);
+
+  TeX = options_.TeX;
+
+  if options_.simul & ~isempty(iter_) & options_.periods == 0
+    options_.periods = iter_;
+  end
+  iter_ = max(options_.periods,1);
+  if exo_nbr > 0
+    ex_= ones(iter_ + xkmin_ + xkmax_,1) * exe_';
+  end
+
+  check_model;
+
+  [dr_, info] = resol(ys_,0);
+
+  if info(1)
+    print_info(info);
+    return
+  end  
+
+  if ~options_.noprint
+    disp(' ')
+    disp('MODEL SUMMARY')
+    disp(' ')
+    disp(['  Number of variables:         ' int2str(endo_nbr)])
+    disp(['  Number of stochastic shocks: ' int2str(exo_nbr)])
+    disp(['  Number of state variables:   ' ...
+	  int2str(length(find(dr_.kstate(:,2) <= ykmin_+1)))])
+    disp(['  Number of jumpers:           ' ...
+	  int2str(length(find(dr_.kstate(:,2) == ykmin_+2)))])
+    disp(['  Number of static variables:  ' int2str(dr_.nstatic)])
+    my_title='MATRIX OF COVARIANCE OF EXOGENOUS SHOCKS';
+    labels = deblank(lgx_);
+    headers = strvcat('Variables',labels);
+    lh = size(labels,2)+2;
+    table(my_title,headers,labels,Sigma_e_,lh,10,6);
+    disp(' ')
+    disp_dr(dr_,options_.order,var_list);
+  end
+
+  if options_.simul == 0 & options_.nomoments == 0
+    disp_th_moments(dr_,var_list); 
+  elseif options_.simul == 1
+    if options_.periods == 0
+      error('STOCH_SIMUL error: number of periods for the simulation isn''t specified')
+    end
+    if options_.periods < options_.drop
+      disp(['STOCH_SIMUL error: The horizon of simulation is shorter' ...
+	    ' than the number of observations to be DROPed'])
+      return
+    end
+    y_ = simult(repmat(dr_.ys,1,ykmin_),dr_);
+    dyn2vec;
+    if options_.nomoments == 0
+      disp_moments(y_,var_list);
+    end
+  end
+
+
+
+  if options_.irf 
+    n = size(var_list,1);
+    if n == 0
+      n = endo_nbr;
+      ivar = [1:n]';
+      var_list = lgy_;
+      if TeX
+	var_listTeX = lgy_TeX_;
+      end
+    else
+      ivar=zeros(n,1);
+      if TeX
+	var_listTeX = [];
+      end
+      for i=1:n
+	i_tmp = strmatch(var_list(i,:),lgy_,'exact');
+	if isempty(i_tmp)
+	  error (['One of the specified variables does not exist']) ;
+	else
+	  ivar(i) = i_tmp;
+	  if TeX
+	    var_listTeX = strvcat(var_listTeX,deblank(lgy_TeX_(i_tmp,:)));
+	  end
+	end
+      end
+    end
+    if TeX
+      fidTeX = fopen([fname_ '_IRF.TeX'],'w');
+      fprintf(fidTeX,'%% TeX eps-loader file generated by stoch_simul.m (Dynare).\n');
+      fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
+      fprintf(fidTeX,' \n');
+    end
+    olditer = iter_;% Est-ce vraiment utile ? Il y a la m�me ligne dans irf... 
+    SS(lgx_orig_ord_,lgx_orig_ord_)=Sigma_e_+1e-14*eye(exo_nbr);
+    cs = transpose(chol(SS));
+    tit(lgx_orig_ord_,:) = lgx_;
+    if TeX
+      titTeX(lgx_orig_ord_,:) = lgx_TeX_;
+    end
+    for i=1:exo_nbr
+      if SS(i,i) > 1e-13
+	y=irf(dr_,cs(lgx_orig_ord_,i), options_.irf, options_.drop, ...
+	      options_.replic, options_.order);
+	if options_.relative_irf
+	  y = 100*y/cs(i,i); 
+	end
+	irfs   = [];
+	mylist = [];
+	if TeX
+	  mylistTeX = [];
+	end
+	for j = 1:n
+	  if max(y(ivar(j),:)) - min(y(ivar(j),:)) > 1e-10
+	    irfs  = cat(1,irfs,y(ivar(j),:));
+	    mylist = strvcat(mylist,deblank(var_list(j,:)));
+	    if TeX
+	      mylistTeX = strvcat(mylistTeX,deblank(var_listTeX(j,:)));
+	    end
+	  end
+	end
+	number_of_plots_to_draw = size(irfs,1);
+	[nbplt,nr,nc,lr,lc,nstar] = pltorg(number_of_plots_to_draw);
+	if nbplt == 0
+	elseif nbplt == 1
+	  if options_.relative_irf
+	    hh = figure('Name',['Relative response to' ...
+				' orthogonalized shock to ' tit(i,:)]);
+	  else
+	    hh = figure('Name',['Orthogonalized shock to' ...
+				' ' tit(i,:)]);
+	  end
+	  for j = 1:number_of_plots_to_draw
+	    subplot(nr,nc,j);
+	    plot(1:options_.irf,transpose(irfs(j,:)),'-k','linewidth',1);
+	    hold on
+	    plot([1 options_.irf],[0 0],'-r','linewidth',0.5);
+	    hold off
+	    xlim([1 options_.irf]);
+	    title(deblank(mylist(j,:)),'Interpreter','none');
+	    assignin('base',[deblank(mylist(j,:)) '_' deblank(tit(i,:))],transpose(irfs(j,:)));
+	  end
+	  eval(['print -depsc2 ' fname_ '_IRF_' deblank(tit(i,:))]);
+	  eval(['print -dpdf ' fname_  '_IRF_' deblank(tit(i,:))]);
+	  saveas(hh,[fname_  '_IRF_' deblank(tit(i,:)) '.fig']);
+	  if TeX
+	    fprintf(fidTeX,'\\begin{figure}[H]\n');
+	    for j = 1:number_of_plots_to_draw
+	      fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{$%s$}\n'],deblank(mylist(j,:)),deblank(mylistTeX(j,:)));
+	    end
+	    fprintf(fidTeX,'\\centering \n');
+	    fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_IRF_%s}\n',fname_,deblank(tit(i,:)));
+	    fprintf(fidTeX,'\\caption{Impulse response functions (orthogonalized shock to $%s$).}',titTeX(i,:));
+	    fprintf(fidTeX,'\\label{Fig:IRF:%s}\n',deblank(tit(i,:)));
+	    fprintf(fidTeX,'\\end{figure}\n');
+	    fprintf(fidTeX,' \n');
+	  end
+	  %				close(hh)
+	else
+	  for fig = 1:nbplt-1
+	    if options_.relative_irf == 1
+	      hh = figure('Name',['Relative response to orthogonalized shock' ...
+				  ' to ' tit(i,:) ' figure ' int2str(fig)]);
+	    else
+	      hh = figure('Name',['Orthogonalized shock to ' tit(i,:) ...
+				  ' figure ' int2str(fig)]);
+	    end
+	    for plt = 1:nstar
+	      subplot(nr,nc,plt);
+	      plot(1:options_.irf,transpose(irfs((fig-1)*nstar+plt,:)),'-k','linewidth',1);
+	      hold on
+	      plot([1 options_.irf],[0 0],'-r','linewidth',0.5);
+	      hold off
+	      xlim([1 options_.irf]);
+	      title(deblank(mylist((fig-1)*nstar+plt,:)),'Interpreter','none');
+	      assignin('base',[deblank(mylist((fig-1)*nstar+plt,:)) '_' deblank(tit(i,:))],transpose(irfs((fig-1)*nstar+plt,:)));
+	    end
+	    eval(['print -depsc2 ' fname_ '_IRF_' deblank(tit(i,:)) int2str(fig)]);
+	    eval(['print -dpdf ' fname_  '_IRF_' deblank(tit(i,:)) int2str(fig)]);
+	    saveas(hh,[fname_  '_IRF_' deblank(tit(i,:)) int2str(fig) '.fig']);
+	    if TeX
+	      fprintf(fidTeX,'\\begin{figure}[H]\n');
+	      for j = 1:nstar
+		fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{$%s$}\n'],deblank(mylist((fig-1)*nstar+j,:)),deblank(mylistTeX((fig-1)*nstar+j,:)));
+	      end
+	      fprintf(fidTeX,'\\centering \n');
+	      fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_IRF_%s%s}\n',fname_,deblank(tit(i,:)),int2str(fig));
+	      if options_.relative_irf
+		fprintf(fidTeX,['\\caption{Relative impulse response' ...
+				' functions (orthogonalized shock to $%s$).}'],deblank(titTeX(i,:)));
+	      else
+		fprintf(fidTeX,['\\caption{Impulse response functions' ...
+				' (orthogonalized shock to $%s$).}'],deblank(titTeX(i,:)));
+	      end
+	      fprintf(fidTeX,'\\label{Fig:BayesianIRF:%s:%s}\n',deblank(tit(i,:)),int2str(fig));
+	      fprintf(fidTeX,'\\end{figure}\n');
+	      fprintf(fidTeX,' \n');
+	    end
+	    %					close(hh);
+	  end
+	  hh = figure('Name',['Orthogonalized shock to ' tit(i,:) ' figure ' int2str(nbplt) '.']);
+	  m = 0; 
+	  for plt = 1:number_of_plots_to_draw-(nbplt-1)*nstar;
+	    m = m+1;
+	    subplot(lr,lc,m);
+	    plot(1:options_.irf,transpose(irfs((nbplt-1)*nstar+plt,:)),'-k','linewidth',1);
+	    hold on
+	    plot([1 options_.irf],[0 0],'-r','linewidth',0.5);
+	    hold off
+	    xlim([1 options_.irf]);
+	    title(deblank(mylist((nbplt-1)*nstar+plt,:)),'Interpreter','none');
+	    assignin('base',[deblank(mylist((nbplt-1)*nstar+plt,:)) '_' deblank(tit(i,:))],transpose(irfs((nbplt-1)*nstar+plt,:)));
+	  end
+	  eval(['print -depsc2 ' fname_ '_IRF_' deblank(tit(i,:)) int2str(nbplt)]);
+	  eval(['print -dpdf ' fname_  '_IRF_' deblank(tit(i,:)) int2str(nbplt)]);
+	  saveas(hh,[fname_  '_IRF_' deblank(tit(i,:)) int2str(nbplt) '.fig']);
+	  if TeX
+	    fprintf(fidTeX,'\\begin{figure}[H]\n');
+	    for j = 1:m
+	      fprintf(fidTeX,['\\psfrag{%s}[1][][0.5][0]{$%s$}\n'],deblank(mylist((nbplt-1)*nstar+j,:)),deblank(mylistTeX((nbplt-1)*nstar+j,:)));
+	    end
+	    fprintf(fidTeX,'\\centering \n');
+	    fprintf(fidTeX,'\\includegraphics[scale=0.5]{%s_IRF_%s%s}\n',fname_,deblank(tit(i,:)),int2str(nbplt));
+	    if options_.relative_irf
+	      fprintf(fidTeX,['\\caption{Relative impulse response functions' ...
+			      ' (orthogonalized shock to $%s$).}'],deblank(titTeX(i,:)));
+	    else
+	      fprintf(fidTeX,['\\caption{Impulse response functions' ...
+			      ' (orthogonalized shock to $%s$).}'],deblank(titTeX(i,:)));
+	    end
+	    fprintf(fidTeX,'\\label{Fig:IRF:%s:%s}\n',deblank(tit(i,:)),int2str(nbplt));
+	    fprintf(fidTeX,'\\end{figure}\n');
+	    fprintf(fidTeX,' \n');
+	  end
+	  %				close(hh);
+	end
+      end
+    end
+    iter_ = olditer;
+    if TeX
+      fprintf(fidTeX,' \n');
+      fprintf(fidTeX,'%% End Of TeX file. \n');
+      fclose(fidTeX);
+    end
+  end
+  % 01/10/01 FC dr_ and y_ made global
+  % 02/20/01 MJ ys_ removed from calling sequence for simult (all in dr_)
+  % 02/23/01 MJ added dyn2vec()
+  % 06/24/01 MJ steady -> steady_
+  % 09/24/01 MJ dr_ made global
+  % 08/28/02 MJ added var_list
+  % 10/09/02 MJ no simulation and theoretical moments for order 1 
+  % 10/14/02 MJ added plot of IRFs
+  % 10/30/02 MJ options_ are now a structure
+  % 01/01/03 MJ added dr_algo
+  % 01/09/03 MJ set default values for options_ (correct absence of autocorr
+  %             when order == 1)
+  % 01/12/03 MJ removed call to steady_ as already checked in resol()
+  % 01/31/03 MJ make IRF global with varname_shockname
+  % 02/09/03 MJ ys_ reset with value declared in initval after computations
+  % 02/18/03 MJ removed above change. ys_ shouldn't be affected by
+  %             computations in this function
+  %             new option SIMUL computes a stochastic simulation and save
+  %             results in y_ and via dyn2vec
+  % 04/03/03 MJ corrected bug for simulation with ykmin_ > 1
+  % 05/20/03 MJ eliminates exogenous shocks with 0 variance
+  % 05/20/03 MJ don't plot IRF if variation < 1e-10
+  % 11/14/03 MJ corrected bug on number of replications for IRF when
+  %             order=2
+  % 11/22/03 MJ replaced IRFs by orthogonalized IRFs
+  % 08/30/04 SA The maximum number of plots is not constrained for the IRFs and 
+  %			  all the plots are saved in *.eps, *.pdf and *.fig files (added
+  %			  fname_ as a global variable).
+  % 09/03/04 SA Tex output for IRFs added
diff --git a/tags/v_3.062/matlab/subset.m b/tags/v_3.062/matlab/subset.m
new file mode 100644
index 0000000000000000000000000000000000000000..a82ab1c9774a574ca8f2e0c088b26c24bfb06cfc
--- /dev/null
+++ b/tags/v_3.062/matlab/subset.m
@@ -0,0 +1,80 @@
+function jndx = subset();
+% stephane.adjemian@ens.fr [11-30-2005]
+global options_ estim_params_ lgx_
+
+ExcludedParamNames = options_.ExcludedParams;
+VarObs = options_.varobs;
+VarExo = lgx_;
+info = options_.ParamSubSet;
+
+nvx = estim_params_.nvx;
+nvn = estim_params_.nvn;
+ncx = estim_params_.ncx;
+ncn = estim_params_.ncn;
+np  = estim_params_.np;
+nx  = nvx+nvn+ncx+ncn+np;
+
+if strcmpi(info,'All')
+  indx = (1:nx)';
+elseif strcmpi(info,'DeepParameters')
+  indx = (nvx+nvn+ncx+ncn+1:nx)';
+elseif strcmpi(info,'StructuralShocks')
+  indx = [(1:nvx),nvx+nvn+1:nvx+nvn+ncx]';
+elseif strcmpi(info,'StructuralShocksWithoutCorrelations')
+  indx = (1:nvx)';
+elseif strcmpi(info,'MeasurementErrors')
+  indx = [(nvx+1:nvx+nvn),(nvx+nvn+ncx+1:nvx+nvn+ncx+ncn)]';
+elseif strcmpi(info,'MeasurementErrorsWithoutCorrelations')
+  indx = (nvx+1:nvx+nvn)';
+elseif strcmpi(info,'AllWithoutMeasurementErrors')
+  indx = [(1:nvx),nvx+nvn+1:nvx+nvn+ncx,nvx+nvn+ncx+ncn+1:nx]';
+elseif strcmpi(info,'None')
+  indx = [];
+end
+
+if isempty(ExcludedParamNames)
+  jndx = indx;
+else
+  tt = [];
+  for i = 1:length(ExcludedParamNames)
+    tmp = strmatch(ExcludedParamNames{i},lgx_);
+    if ~isempty(tmp) & ( strcmpi(info,'All') | strcmpi(info,'StructuralShocks') | ...
+			 strcmpi(info,'StructuralShocksWithoutCorrelations') | ...
+			 strcmpi(info,'AllWithoutMeasurementErros') )
+      % The parameter the user wants to exclude is related to the size of the structural innovations.
+      if ncx
+	disp(['I cannot exclude some the structural variances if the'])
+	disp(['structural innovations are correlated...'])
+	error
+      end
+      tt = [tt;tmp];
+    elseif isempty(tmp) & nvn 
+      tmp = strmatch(ExcludedParamNames{i},options_.varobs);
+      if ~isempty(tmp) & ( strcmpi(info,'All') | strcmpi(info,'MeasurementErrors') | ...
+			 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
+	  disp(['I cannot exclude some the measurement error variances if the'])
+	  disp(['measurement errors are correlated...'])
+	  error
+	end
+	tt = [tt;tmp];
+      end
+    else% Excluded parameters are deep parameters...
+      tmp = strmatch(ExcludedParamNames{i},estim_params_.param_names,'exact');
+      if ~isempty(tmp)
+	tt = [tt;nvx+nvn+ncx+ncn+tmp];
+      else
+	disp('The parameter you want to exclude is unknown!')
+	error
+      end
+    end
+  end
+  jndx = [];
+  for i=1:length(indx)
+    if ~any(indx(i)==tt)
+      jndx = [ jndx ; indx(i) ];
+    end
+  end
+end
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/sylvester3.m b/tags/v_3.062/matlab/sylvester3.m
new file mode 100644
index 0000000000000000000000000000000000000000..d75d01647a19d0ef6159d005a73cb2cc06b306ed
--- /dev/null
+++ b/tags/v_3.062/matlab/sylvester3.m
@@ -0,0 +1,49 @@
+% solves a*x+b*x*c=d
+function x=sylvester3(a,b,c,d)
+  n = size(a,1);
+  m = size(c,1);
+  if n == 1
+    x=d./(a*ones(1,m)+b*c);
+    return
+  end
+  if m == 1
+    x = (a+c*b)\d;
+    return;
+  end
+  x=zeros(n,m);
+  [u,t]=schur(c);
+  [aa,bb,qq,zz]=qz(full(a),full(b),'real'); % available in Matlab version 6.0
+  d=qq*d*u;
+  i = 1;
+  while i < m
+    if t(i+1,i) == 0
+      if i == 1
+	c = zeros(n,1);
+      else
+	c = bb*(x(:,1:i-1)*t(1:i-1,i));
+      end
+      x(:,i)=(aa+bb*t(i,i))\(d(:,i)-c);
+      i = i+1;
+    else
+      if i == n
+	c = zeros(n,1);
+	c1 = zeros(n,1);
+      else
+	c = bb*(x(:,1:i-1)*t(1:i-1,i));
+	c1 = bb*(x(:,1:i-1)*t(1:i-1,i+1));
+      end
+      z = [aa+bb*t(i,i) bb*t(i+1,i); bb*t(i,i+1) aa+bb*t(i+1,i+1)]...
+	  \[d(:,i)-c;d(:,i+1)-c1];
+      x(:,i) = z(1:n);
+      x(:,i+1) = z(n+1:end);
+      i = i + 2;
+    end
+  end
+  if i == m
+    c = bb*(x(:,1:m-1)*t(1:m-1,m));
+    x(:,m)=(aa+bb*t(m,m))\(d(:,m)-c);
+  end
+  x=zz*x*u';
+  
+% 01/25/03 MJ corrected bug for i==m (sign of c in x determination)
+% 01/31/03 MJ added 'real' to qz call
diff --git a/tags/v_3.062/matlab/sylvester3a.m b/tags/v_3.062/matlab/sylvester3a.m
new file mode 100644
index 0000000000000000000000000000000000000000..d2b90b6042b0baa6b9a0d685cc48738f715dd17b
--- /dev/null
+++ b/tags/v_3.062/matlab/sylvester3a.m
@@ -0,0 +1,17 @@
+% solves iteratively ax+bxc=d
+
+function x=sylvester3a(x0,a,b,c,d)
+a_1 = inv(a);
+b = a_1*b;
+d = a_1*d;
+e = 1;
+iter = 1;
+while e > 1e-8 & iter < 500
+  x = d-b*x0*c;
+  e = max(max(abs(x-x0)));
+  x0 = x;
+  iter = iter + 1;
+end
+if iter == 500
+  fprintf('Syvester3a : Only accuracy of %10.8f is achieved after 500 iterations. \n',e)
+end
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/table.m b/tags/v_3.062/matlab/table.m
new file mode 100644
index 0000000000000000000000000000000000000000..cf809b2da82e13fb399b7d3763b4e4e9a61acbc3
--- /dev/null
+++ b/tags/v_3.062/matlab/table.m
@@ -0,0 +1,26 @@
+% Copyright (C) 2002 Michel Juillard
+%
+function table(title,headers,labels,values,label_width,val_width, ...
+	       val_precis)
+  label_width = max(size(deblank(strvcat(headers(1,:),labels)),2)+2, ...
+		    label_width);
+  val_width = max(size(deblank(headers(2:end,:)),2)+2,val_width);
+  label_fmt = sprintf('%%-%ds',label_width);
+  header_fmt = sprintf('%%-%ds',val_width);
+  val_fmt = sprintf('%%%d.%df',val_width,val_precis);
+  if length(title) > 0
+    disp(sprintf('\n\n%s\n',title));
+  end
+  if length(headers) > 0
+    hh = sprintf(label_fmt,headers(1,:));
+    hh = [hh char(32*ones(1,floor(val_width/4)))];
+    for i=2:size(headers,1)
+      hh = [hh sprintf(header_fmt,headers(i,:))];
+    end
+    disp(hh);
+  end
+  for i=1:size(values,1)
+    disp([sprintf(label_fmt,labels(i,:)) sprintf(val_fmt,values(i,:))]);
+  end
+  
+% 10/30/02 MJ
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/testifft.m b/tags/v_3.062/matlab/testifft.m
new file mode 100644
index 0000000000000000000000000000000000000000..3efc8f21108dcc9ee6f4a420f8b8c3414fa01e8a
--- /dev/null
+++ b/tags/v_3.062/matlab/testifft.m
@@ -0,0 +1,21 @@
+a = [0.95 0.025; 0.025 0.95];
+
+ngrid = 512;
+freqs = 0 : ((2*pi)/ngrid) : (2*pi*(1 - .5/ngrid)); 
+
+im = sqrt(-1);
+  mathp_col = [];
+
+    for ig = 1:ngrid,
+      tpos  = exp( im*freqs(ig));
+      tneg  =  exp(-im*freqs(ig));
+      f_omega  =(1/(2*pi))*[inv(eye(2)-a*tneg);eye(2)]* ...
+		Sigma_e_*[inv(eye(2)-a'*tpos) eye(2)];
+      f_hp = f_omega;
+      mathp_col = [mathp_col ; (f_hp(:))'];    % store as matrix row
+                                               % for ifft
+    end;
+
+    % covariance of filtered series
+    imathp_col = real(ifft(mathp_col))*2*pi;
+    reshape(imathp_col(1,:),4,4)
diff --git a/tags/v_3.062/matlab/th_autocovariances.m b/tags/v_3.062/matlab/th_autocovariances.m
new file mode 100644
index 0000000000000000000000000000000000000000..77ed8e861fcc0e8e6ca41700ac8e8e99d9a0abee
--- /dev/null
+++ b/tags/v_3.062/matlab/th_autocovariances.m
@@ -0,0 +1,225 @@
+% Copyright (C) 2001 Michel Juillard
+%
+% 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 (indices in lgy_)
+% Theoretical HP filtering is available as an option
+
+function [Gamma_y,ivar]=th_autocovariances(dr,ivar)
+  global lgy_ endo_nbr exo_nbr Sigma_e_ ykmin_ lgx_orig_ord_ options_
+
+  if sscanf(version('-release'),'%d') < 13
+    warning off
+  else
+    eval('warning off MATLAB:dividebyzero')
+  end
+  nar = options_.ar;
+  Gamma_y = cell(nar+1,1);
+  if isempty(ivar)
+    ivar = [1:endo_nbr]';
+  end
+  nvar = size(ivar,1);
+  
+  ghx = dr.ghx;
+  ghu = dr.ghu;
+  npred = dr.npred;
+  nstatic = dr.nstatic;
+  kstate = dr.kstate;
+  order = dr.order_var;
+  iv(order) = [1:length(order)];
+  nx = size(ghx,2);
+  
+  ikx = [nstatic+1:nstatic+npred];
+  
+  A = zeros(nx,nx);
+  k0 = kstate(find(kstate(:,2) <= ykmin_+1),:);
+  i0 = find(k0(:,2) == ykmin_+1);
+  i00 = i0;
+  n0 = length(i0);
+  A(i0,:) = ghx(ikx,:);
+  AS = ghx(:,i0);
+  ghu1 = zeros(nx,exo_nbr);
+  ghu1(i0,:) = ghu(ikx,:);
+  for i=ykmin_:-1:2
+    i1 = find(k0(:,2) == i);
+    n1 = size(i1,1);
+    j1 = zeros(n1,1);
+    j2 = j1;
+    for k1 = 1:n1
+      j1(k1) = find(k0(i00,1)==k0(i1(k1),1));
+      j2(k1) = find(k0(i0,1)==k0(i1(k1),1));
+    end
+%    A(i1,i0(j2))=eye(n1);
+    AS(:,j1) = AS(:,j1)+ghx(:,i1);
+    i0 = i1;
+  end
+  b = ghu1*Sigma_e_*ghu1';
+
+
+  [A,B] = kalman_transition_matrix(dr);
+  % index of predetermined variables in A
+  i_pred = [nstatic+(1:npred) endo_nbr+1:length(A)];
+  A = A(i_pred,i_pred);
+
+  [v,d] = eig(A);
+  abs_root = abs(diag(d));
+  i_ur = find(abs_root > 2-options_.qz_criterium & ...
+	      abs_root < options_.qz_criterium);
+
+  if ~isempty(i_ur)
+    % non-stationary variables have non-zero entries in eigenvectors
+    % associated with unit roots
+    ns_var = find(any(abs(v(1:npred,i_ur))>1e-7,2));
+
+    %right eigenvectors
+    v1 = inv(v);
+
+    % remove zero frequency from A
+    A = A-real(v(:,i_ur)*d(i_ur,i_ur)*v1(i_ur,:));
+    
+    % return only variance of stationary variables
+    i_ivar = find(~ismember(ivar,dr.order_var(ns_var+nstatic)));
+    ivar = ivar(i_ivar);
+  end
+  % order of variables with preset variances in ghx and ghu
+  iky = iv(ivar);
+  
+  aa = ghx(iky,:);
+  bb = ghu(iky,:);
+
+  if options_.order == 2
+    vx =  lyapunov_symm(A,b); 
+    Ex = (dr.ghs2(ikx)+dr.ghxx(ikx,:)*vx(:)+dr.ghuu(ikx,:)*Sigma_e_(:))/2;
+    Ex = (eye(n0)-AS(ikx,:))\Ex;
+    Gamma_y{nar+3} = AS(iky,:)*Ex+(dr.ghs2(iky)+dr.ghxx(iky,:)*vx(:)+dr.ghuu(iky,:)*Sigma_e_(:))/2;
+  end
+  if options_.hp_filter == 0
+    if options_.order < 2
+      vx =  lyapunov_symm(A,b);
+    end
+    Gamma_y{1} = aa*vx*aa'+ bb*Sigma_e_*bb';
+    k = find(abs(Gamma_y{1}) < 1e-12);
+    Gamma_y{1}(k) = 0;
+    
+    % autocorrelations
+    if nar > 0
+      vxy = (A*vx*aa'+ghu1*Sigma_e_*bb');
+
+      sy = sqrt(diag(Gamma_y{1}));
+      sy = sy *sy';
+      Gamma_y{2} = aa*vxy./sy;
+      
+      for i=2:nar
+	vxy = A*vxy;
+	Gamma_y{i+1} = aa*vxy./sy;
+      end
+    end
+    
+    % variance decomposition
+    if exo_nbr > 1
+      Gamma_y{nar+2} = zeros(length(ivar),exo_nbr);
+      SS(lgx_orig_ord_,lgx_orig_ord_)=Sigma_e_+1e-14*eye(exo_nbr);
+      cs = chol(SS)';
+      b1(:,lgx_orig_ord_) = ghu1;
+      b1 = b1*cs;
+      b2(:,lgx_orig_ord_) = ghu(iky,:);
+      b2 = b2*cs;
+      vx  = lyapunov_symm(A,b1*b1');
+      vv = diag(aa*vx*aa'+b2*b2');
+      for i=1:exo_nbr
+	vx1 = lyapunov_symm(A,b1(:,i)*b1(:,i)');
+	Gamma_y{nar+2}(:,i) = abs(diag(aa*vx1*aa'+b2(:,i)*b2(:,i)'))./vv;
+      end
+    end
+  else
+    lambda = options_.hp_filter;
+    ngrid = options_.hp_ngrid;
+    freqs = 0 : ((2*pi)/ngrid) : (2*pi*(1 - .5/ngrid)); 
+    tpos  = exp( sqrt(-1)*freqs);
+    tneg  =  exp(-sqrt(-1)*freqs);
+    hp1 = 4*lambda*(1 - cos(freqs)).^2 ./ (1 + 4*lambda*(1 - cos(freqs)).^2);
+    
+    mathp_col = [];
+    IA = eye(size(A,1));
+    IE = eye(exo_nbr);
+    for ig = 1:ngrid
+      f_omega  =(1/(2*pi))*( [inv(IA-A*tneg(ig))*ghu1;IE]...
+			     *Sigma_e_*[ghu1'*inv(IA-A'*tpos(ig)) ...
+		    IE]); % state variables
+      g_omega = [aa*tneg(ig) bb]*f_omega*[aa'*tpos(ig); bb']; % selected variables
+      f_hp = hp1(ig)^2*g_omega; % spectral density of selected filtered series
+      mathp_col = [mathp_col ; (f_hp(:))'];    % store as matrix row
+                                               % for ifft
+    end;
+
+    % covariance of filtered series
+    imathp_col = real(ifft(mathp_col))*(2*pi);
+
+    Gamma_y{1} = reshape(imathp_col(1,:),nvar,nvar);
+    
+    % autocorrelations
+    if nar > 0
+      sy = sqrt(diag(Gamma_y{1}));
+      sy = sy *sy';
+      for i=1:nar
+	Gamma_y{i+1} = reshape(imathp_col(i+1,:),nvar,nvar)./sy;
+      end
+    end
+    
+    %variance decomposition
+    if exo_nbr > 1 
+      Gamma_y{nar+2} = zeros(nvar,exo_nbr);
+      SS(lgx_orig_ord_,lgx_orig_ord_)=Sigma_e_+1e-14*eye(exo_nbr);
+      cs = chol(SS)';
+      SS = cs*cs';
+      b1(:,lgx_orig_ord_) = ghu1;
+      b2(:,lgx_orig_ord_) = ghu(iky,:);
+      mathp_col = [];
+      IA = eye(size(A,1));
+      IE = eye(exo_nbr);
+      for ig = 1:ngrid
+	f_omega  =(1/(2*pi))*( [inv(IA-A*tneg(ig))*b1;IE]...
+			       *SS*[b1'*inv(IA-A'*tpos(ig)) ...
+		    IE]); % state variables
+	g_omega = [aa*tneg(ig) b2]*f_omega*[aa'*tpos(ig); b2']; % selected variables
+	f_hp = hp1(ig)^2*g_omega; % spectral density of selected filtered series
+	mathp_col = [mathp_col ; (f_hp(:))'];    % store as matrix row
+						 % for ifft
+      end;
+
+      imathp_col = real(ifft(mathp_col))*(2*pi);
+      vv = diag(reshape(imathp_col(1,:),nvar,nvar));
+      for i=1:exo_nbr
+	mathp_col = [];
+	SSi = cs(:,i)*cs(:,i)';
+	for ig = 1:ngrid
+	  f_omega  =(1/(2*pi))*( [inv(IA-A*tneg(ig))*b1;IE]...
+				 *SSi*[b1'*inv(IA-A'*tpos(ig)) ...
+		    IE]); % state variables
+	  g_omega = [aa*tneg(ig) b2]*f_omega*[aa'*tpos(ig); b2']; % selected variables
+	  f_hp = hp1(ig)^2*g_omega; % spectral density of selected filtered series
+	  mathp_col = [mathp_col ; (f_hp(:))'];    % store as matrix row
+						   % for ifft
+	end;
+
+	imathp_col = real(ifft(mathp_col))*(2*pi);
+	Gamma_y{nar+2}(:,i) = abs(diag(reshape(imathp_col(1,:),nvar,nvar)))./vv;
+      end
+    end
+  end
+  if sscanf(version('-release'),'%d') < 13
+    warning on
+  else
+    eval('warning on MATLAB:dividebyzero')
+  end
+  
+  % 10/18/2002 MJ
+  % 10/30/2002 added autocorrelations, Gamma_y is now a cell array
+  % 01/20/2003 MJ added variance decomposition
+  % 02/18/2003 MJ added HP filtering (Thanks to Jean Chateau for the code)
+  % 04/28/2003 MJ changed handling of options
+  % 05/19/2003 MJ don't assume lags are in increasing order in building A
+  % 05/21/2003 MJ added global i_exo_var_,
+  %               variance decomposition: test exo_nbr > 1
+  % 05/29/2003 MJ removed global i_exo_var_
+  % 06/10/2003 MJ test release for warning syntax
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/transition_matrix.m b/tags/v_3.062/matlab/transition_matrix.m
new file mode 100644
index 0000000000000000000000000000000000000000..4d5e799ed169c75e4f9f1b4f8caedb722f4dc1b7
--- /dev/null
+++ b/tags/v_3.062/matlab/transition_matrix.m
@@ -0,0 +1,24 @@
+% makes transition matrices out of ghx and ghu
+
+function [A,B] = transition_matrix(dr)
+  global ykmin_ exo_nbr 
+  nx = size(dr.ghx,2);
+  kstate = dr.kstate;
+  ikx = [dr.nstatic+1:dr.nstatic+dr.npred];
+  
+  A = zeros(nx,nx);
+  k0 = kstate(find(kstate(:,2) <= ykmin_+1),:);
+  i0 = find(k0(:,2) == ykmin_+1);
+  A(i0,:) = dr.ghx(ikx,:);
+  B = zeros(nx,exo_nbr);
+  B(i0,:) = dr.ghu(ikx,:);
+  for i=ykmin_:-1:2
+    i1 = find(k0(:,2) == i);
+    n1 = size(i1,1);
+    j = zeros(n1,1);
+    for j1 = 1:n1
+      j(j1) = find(k0(i0,1)==k0(i1(j1),1));
+    end
+    A(i1,i0(j))=eye(n1);
+    i0 = i1;
+  end
diff --git a/tags/v_3.062/matlab/uniform_specification.m b/tags/v_3.062/matlab/uniform_specification.m
new file mode 100644
index 0000000000000000000000000000000000000000..5d81f0bf97a88ea582b3960492b363f5535ef5cb
--- /dev/null
+++ b/tags/v_3.062/matlab/uniform_specification.m
@@ -0,0 +1,12 @@
+% Copyright (C) 2004 Michel Juillard
+%
+function [m,s,p1,p2] = uniform_specification(m,s,p3,p4)
+    if ~(isnan(p3) | isnan(p4))
+      p1 = p3;
+      p2 = p4;
+      m = (p3+p4)/2;
+      s = (p4-p3)/(sqrt(12));
+    else
+      p1 = m-s*sqrt(3);
+      p2 = m+s*sqrt(3);
+    end
diff --git a/tags/v_3.062/matlab/union.m b/tags/v_3.062/matlab/union.m
new file mode 100644
index 0000000000000000000000000000000000000000..13fa308f6a3017f911f69673d6f0aff8ec642834
--- /dev/null
+++ b/tags/v_3.062/matlab/union.m
@@ -0,0 +1,12 @@
+function x = union(a,b)
+
+xx = sort([a;b]) ;
+x(1) = xx(1) ;
+for i = 2:size(xx,1)
+	if xx(i) ~= xx(i-1)
+		x =[x;xx(i)];
+	end
+end
+return ;
+
+
diff --git a/tags/v_3.062/matlab/var_index.m b/tags/v_3.062/matlab/var_index.m
new file mode 100644
index 0000000000000000000000000000000000000000..04d6106fe569b93ea5a5d486cc1caabbc54d8f42
--- /dev/null
+++ b/tags/v_3.062/matlab/var_index.m
@@ -0,0 +1,11 @@
+% var_index(vname) returns the index of variable 'vname'
+% in its respective variable list (endogeneous, exogeneous)
+% input:
+%        vname     a string of character
+% output:
+%        i         a positive integer
+% an error message is given if vname isn't in the state vector
+function k=var_index(vname)
+  global lgy_
+  
+  k = strmatch(vname,lgy_,'exact');
diff --git a/tags/v_3.062/matlab/var_state_index.m b/tags/v_3.062/matlab/var_state_index.m
new file mode 100644
index 0000000000000000000000000000000000000000..c3e4f0865dbfd5fddf29a13e763d2f09e68fa389
--- /dev/null
+++ b/tags/v_3.062/matlab/var_state_index.m
@@ -0,0 +1,15 @@
+% var_state_index(vname) returns the index of variable 'vname'
+% in the extended state space representation vector of the system
+% input:
+%        vname     a string of character
+%        order     a vector containing the composition of the state
+%                  vector. Normaly, dr_.order_var 
+
+% output:
+%        i         a positive integer
+% an error message is given if vname isn't in the state vector
+function i=var_state_index(vname,order)
+  global lgy_
+  
+  k = strmatch(vname,lgy_,'exact');
+  i = find(k==order);
\ No newline at end of file
diff --git a/tags/v_3.062/matlab/varprior.m b/tags/v_3.062/matlab/varprior.m
new file mode 100644
index 0000000000000000000000000000000000000000..04db6feea26c43b3433608ef5c449956d16f96f2
--- /dev/null
+++ b/tags/v_3.062/matlab/varprior.m
@@ -0,0 +1,54 @@
+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 
+%                   actual data matrix has T rows, in preparing input for rfvar3
+% nv,nx,lags: VAR dimensions
+% mnprior.tight:Overall tightness of Minnesota prior
+% mnprior.decay:Standard deviations of lags shrink as lag^(-decay)
+% vprior.sig:   Vector of prior modes for diagonal elements of r.f. covariance matrix
+% vprior.w:     Weight on prior on vcv.  1 corresponds to "one dummy observation" weight
+%                   Should be an integer, and will be rounded if not.  vprior.sig is needed
+%                   to scale the Minnesota prior, even if the prior on sigma is not used itself.
+%                   Set vprior.w=0 to achieve this.
+% Note:         The original Minnesota prior treats own lags asymmetrically, and therefore
+%                   cannot be implemented entirely with dummy observations.  It is also usually
+%                   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 
+%                   univariate AR's.
+%-----------------------
+% 
+if ~isempty(mnprior)
+    xdum=zeros(lags+1,nx,lags,nv);
+    ydum=zeros(lags+1,nv,lags,nv);
+    for il=1:lags
+        ydum(il+1,:,il,:)=il^mnprior.decay*diag(vprior.sig);
+    end
+    ydum(1,:,1,:)=diag(vprior.sig);
+    ydum=mnprior.tight*reshape(ydum,[lags+1,nv,lags*nv]);
+    ydum=flipdim(ydum,1);
+    xdum=mnprior.tight*reshape(xdum,[lags+1,nx,lags*nv]);
+    xdum=flipdim(xdum,1);
+    breaks=(lags+1)*[1:(nv*lags)]';
+    lbreak=breaks(end);
+else
+    ydum=[];
+    xdum=[];
+    breaks=[];
+    lbreak=0;
+end
+if ~isempty(vprior) & vprior.w>0
+    ydum2=zeros(lags+1,nv,nv);
+    xdum2=zeros(lags+1,nx,nv);
+    ydum2(end,:,:)=diag(vprior.sig);
+    ydum=cat(3,ydum,ydum2);
+    xdum=cat(3,xdum,xdum2);
+    dimy=size(ydum);
+    ydum=reshape(permute(ydum,[1 3 2]),dimy(1)*dimy(3),nv);
+    xdum=reshape(permute(xdum,[1 3 2]),dimy(1)*dimy(3),nx);
+    breaks=[breaks;(lags+1)*[1:nv-1]'+lbreak];
+end
diff --git a/tags/v_3.062/parser.src/d.h b/tags/v_3.062/parser.src/d.h
new file mode 100644
index 0000000000000000000000000000000000000000..aa223905418d00e85086ee4bfb61a580975ec75a
--- /dev/null
+++ b/tags/v_3.062/parser.src/d.h
@@ -0,0 +1,106 @@
+#define MAX_INDEX_NBR 10
+struct var {
+  char *name;
+  int endo_exo;   /* 0: exogenous; 1: endogenous; 2: loop index (numerical)*/
+  int nbr;
+  int original_nbr;
+};
+
+struct token {
+  int endo_exo;
+  int nbr;        /* >=0: variable, -1: string, -2: loop index, -3 indexed variable */
+  int lead_lag;
+  char *name;     /* string content or variable lead_lag name */
+  struct var *var_ptr; /* only for variables */
+};
+
+struct queue {
+  void **ptr;
+  int flag;
+  int imax;
+};
+
+struct loop {
+  int loop_index;
+  int loop_limit;
+  int loop_increment;
+  char *loop_index_name;
+};
+
+struct s_check{
+  int eq_nbr;
+  int determ;
+  int stoch;
+  int initval;
+  int endval;
+  int histval;
+  int steady;
+  int linear;
+  int stoch_simul;
+  int simul;
+  int check;
+  int olr;
+  int osr;
+};
+
+struct s_runtime_options{
+  int clearall;
+  int debug;
+};
+
+struct s_estim_params{
+  int param_type;
+  int var_type;
+  int var_nbr;
+  int var_nbr2;
+  char* param_name;
+  char* init_val;
+  char* lb;
+  char* ub;
+  char* prior;
+  char* mean;
+  char* std;
+  char* p3;
+  char* p4;
+  char* jscale;
+};
+  
+void add_var(char *, int), print_var(), print_model(struct queue *);
+void set_ll(struct queue *, char *, int), mark_pound(struct queue *);
+struct queue * create_queue(void *);
+struct queue * add_to_queue(struct queue *, void *);
+struct queue * copy_queue(struct queue *, struct queue *);
+struct token * create_var(struct var *); 
+struct token * token(char *, int nbr);
+struct queue * m_del(char *, struct queue *);
+struct var *var_search(const char *);
+struct loop *initial_loop(char *, char *, char *, char *);
+struct queue * do_loop(struct loop *, struct queue *);
+struct queue *operator_loop(struct loop *, struct queue *, char *);
+void var_output(struct token *, int);
+int * periods(char *, char *);
+void p_shocks(struct token *, struct queue *, struct queue *, int);
+void p_init(struct token *, struct queue *);
+void p_initval(void),p_endval(void),p_i_shocks(int);
+void dynare_init(char *, struct s_runtime_options);
+void print_iter(char *);
+void pe_initval(void);
+void pe_endval(void);
+int nbr_tmpvar;
+void print_rplot(void);
+void copy_update_indexed_var(struct token **, struct queue  *, int , char *, int);
+void print_model(struct queue *);
+void print_model1(struct queue *, int);
+void print_param(void);
+void p_optim_weights_init(void);
+void p_optim_weights(struct token *, struct queue *);
+void p_expression(struct queue *);
+void p_osr_params(char *);
+void p_osr(void);
+char* my_strcat(char*, char*);
+void p_estimated_elem(void);
+void estimated_elem_init(void);
+
+/*
+04/06/02 MJ added p_optim_weights_init and p_optim_weights p_expression p_osr_params p_osr
+*/
diff --git a/tags/v_3.062/parser.src/d.y b/tags/v_3.062/parser.src/d.y
new file mode 100644
index 0000000000000000000000000000000000000000..a7a3968678ddb005e2ac9c9dd41788cdc413a0d4
--- /dev/null
+++ b/tags/v_3.062/parser.src/d.y
@@ -0,0 +1,889 @@
+%{
+#include <stdio.h>
+#include <string.h>
+#include "d.h"
+
+  extern FILE *f_out;
+  extern int yylineno, var_nbr, longname, dr_algo, simul_algo, drop, linear, order, replic, iter, nbr_tmpvar, ar, nocorr, nofunctions, nomoments, irf, hp_filter, hp_ngrid, simul, simul_seed;
+  extern double shock_size;
+  extern char * varexo;
+  extern struct s_check check;
+  int ms_flag, varlist_flag, tr_row, tr_col, permit_sigma_e_;
+  struct queue *model;
+  extern struct s_estim_params estim_params;
+  char* optim_string;
+  char* empty_string = "NaN";
+
+%}
+
+%union {
+        char *string;
+	struct queue *p_queue;
+	struct token *p_tok;
+        struct loop *p_loop;
+      }
+
+%token  END ENDVAL INITVAL HISTVAL MODEL PERIODS SHOCKS VALUES VAR VAREXO 
+%token VAREXO_DET VARRECUR EQUAL
+%token VARF VARP DEL SUM PROD TO MSHOCKS LONGNAMES PARAMETERS DYN2VEC RPLOT
+%token DO TO ENDO PROD BY DOLLAR STEADY STDERR DSAMPLE
+%token STOCH_SIMUL DR_ALGO SIMUL_ALGO SOLVE_ALGO 
+%token DROP LINEAR ORDER REPLIC AR
+%token SIGMA_E HP_FILTER HP_NGRID SIMUL_SEED
+%token RESOL SIMUL IRF DISP_DR DISP_MOMENTS D_CORR SHOCK_SIZE OPTIM_WEIGHTS
+%token OSR_PARAMS OSR CALIB_VAR CALIB AUTOCORR COVAR DYNATYPE DYNASAVE
+%token OLR OLR_INST OLR_BETA CHECK
+%token ESTIMATED_PARAMS GAMMA_PDF BETA_PDF NORMAL_PDF INV_GAMMA_PDF UNIFORM_PDF
+%token INV_GAMMA1_PDF INV_GAMMA2_PDF
+%token PREFILTER PRESAMPLE LIK_ALGO LIK_INIT CONF_SIG 
+%token ESTIMATION DATAFILE NOBS FIRST_OBS VAROBS QZ_CRITERIUM MH_REPLIC MH_DROP
+%token MH_JSCALE OPTIM MH_INIT_SCALE MODE_FILE MODE_COMPUTE MODE_CHECK
+%token PRIOR_TRUNC MH_MODE MH_NBLOCKS LOAD_MH_FILE LOGLINEAR
+%token UNIT_ROOT_VARS XTICK XTICKLABEL BAYESIAN_IRF RELATIVE_IRF
+%token TEX FORECAST SMOOTHER MOMENTS_VARENDO FILTERED_VARS 
+%token OBSERVATION_TRENDS ESTIMATED_PARAMS_INIT ESTIMATED_PARAMS_BOUNDS
+%token KALMAN_ALGO KALMAN_TOL DIFFUSE_D NK
+%token CORR MOMENTS FUNCTIONS DIAGNOSTIC PRINT GRAPH
+%token NOCORR NOMOMENTS NOFUNCTIONS NODIAGNOSTIC NOPRINT NOGRAPH
+%token MODEL_COMPARISON MODEL_COMPARISON_APPROXIMATION LAPLACE
+%token MODIFIEDHARMONICMEAN SHOCKS_FILE IRF_TYPE
+%token COMPILE_DEFINE COMPILE_IF COMPILE_ELSEIF COMPILE_ELSE COMPILE_ENDIF
+%token <string> INUMBER DNUMBER NAME OPERATORS POUND EOL INDEX EQ NE LE GE
+%token <p_tok> VAR_ID
+
+%type <p_queue> equation_list equation other_inst p_expr expression elem_exp 
+%type <p_queue> del_exp sum_exp prod_exp period_list value_list
+%type <p_queue> value_list1 value_list2 expr1 do_loop
+%type <p_queue> var_exp var_id_exp indexed_var_exp 
+%type <p_queue> triangular_matrix triangular_row
+%type <p_loop> loop_init
+%type <string> value prior filename filename_elem compile_operator
+%expect 5
+%%
+
+ statement_list: statement
+      | statement_list statement 
+      ;
+
+ statement: periods 
+      | var         
+      | varexo      
+      | varexo_det      
+      | varrecur
+      | model 
+      | initval
+      | endval 
+      | histval
+      | shocks
+      | mshocks
+      | obsolete
+      | longnames    {longname=1;}
+      | parameters
+      | dyn2vec
+      | rplot
+      | steady
+      | stoch_simul
+      | resol
+      | simul
+      | dsample
+      | check
+      | irf
+      | d_corr
+      | disp_dr
+      | disp_moments
+      | optim_weights
+      | osr_params
+      | osr
+      | calib_var
+      | calib
+      | dynatype
+      | dynasave
+      | sigma_e
+      | olr
+      | olr_inst
+      | estimated_params
+      | estimated_params_init
+      | estimated_params_bounds
+      | estimation
+      | varobs
+      | observation_trends
+      | unit_root_vars
+      | model_comparison
+      | compile_statement
+      | forecast
+      ;
+ 
+ longnames : LONGNAMES ';'
+      ;
+
+ periods : PERIODS INUMBER ';'{print_iter($2);}
+      | PERIODS '=' INUMBER ';' {print_iter($3);}
+      ;
+
+var : VAR {varlist_flag=1;} varlist ';' {print_endo();}
+      ;
+
+varexo : VAREXO {varlist_flag=0;} varlist ';' {print_exo();}
+      ;
+
+varexo_det : VAREXO_DET {varlist_flag=5;} varlist ';' {print_exo_det();}
+      ;
+
+ varrecur : VARRECUR {varlist_flag=3;} varlist ';' {print_recur();}
+      ;
+
+ varlist : varlist NAME '-' NAME {add_var_range($2,$4,varlist_flag);}
+      | varlist ',' NAME '-' NAME {add_var_range($3,$5,varlist_flag);}
+      | varlist NAME              {add_var($2,varlist_flag);}
+      | varlist ',' NAME          {add_var($3,varlist_flag);}
+      | NAME '-' NAME              {add_var_range($1,$3,varlist_flag);}
+      | NAME                       {add_var($1,varlist_flag);}
+      ; 
+
+ parameters : PARAMETERS {varlist_flag=4;} varlist ';' {print_param();}
+      ;
+
+ model : MODEL ';' equation_list END   {model=$3;print_model(model);}
+      | MODEL '(' LINEAR ')' ';' equation_list END   {check.linear=1;model=$6;p_option("linear","1");print_model(model);}
+      | MODEL ';' compile_statement equation_list END   {model=$4;print_model(model);}
+      | MODEL '(' LINEAR ')' ';' compile_statement equation_list END   {check.linear=1;model=$7;p_option("linear","1");print_model(model);}
+      ;
+
+ initval : INITVAL ';' {p_initval();} initval_list END 
+     {pe_initval();}
+      ;
+
+ endval : ENDVAL ';' {p_endval();} initval_list END
+     {pe_endval();}
+      ;
+
+ histval : HISTVAL ';' {p_histval();} histval_list END
+      ;
+
+ shocks: SHOCKS ';' {ms_flag=0;p_i_shocks(ms_flag);} shock_list END {p_e_shocks();}
+       | SHOCKS '(' options_shocks ')' ';' 
+                    {ms_flag=0;p_i_shocks(ms_flag);} shock_list END {p_e_shocks();}
+       ;
+
+ mshocks: MSHOCKS ';' {ms_flag=1;p_i_shocks(ms_flag);} shock_list END {p_e_shocks();}
+      | MSHOCKS '(' options_shocks ')' ';' 
+                      {ms_flag=1;p_i_shocks(ms_flag);} shock_list END {p_e_shocks();}
+      ;
+
+ options_shocks: option_shocks
+       | options_shocks ',' option_shocks
+       ;
+
+ option_shocks: o_shocks_file ; 
+
+ equation_list : equation_list equation {$$=add_to_queue($1,$2);}
+      | equation_list other_inst {$$=add_to_queue($1,$2);}
+      | equation_list do_loop {$$=copy_queue($$,$2);}
+      | equation {$$=create_queue($1);}
+      | equation compile_statement {$$=$1;}
+      | other_inst {$$=create_queue($1);}
+      | do_loop
+      ;
+
+ equation : expression EQUAL expression ';' 
+                 {$$=add_to_queue($1,token(" -(",-1));
+		  $$=copy_queue($$,$3);
+		  $$=add_to_queue($$,token(")",-1));}
+      | expression ';'
+      ;
+
+ other_inst : POUND p_expr EOL {$$=$2; mark_pound($$);}
+      ;
+
+ do_loop : DO loop_init ';' equation_list ENDO ';' {$$=do_loop($2,$4);}
+      ;
+
+ loop_init : NAME EQUAL INUMBER TO INUMBER  {$$=initial_loop($1,$3,$5,"1");}
+      | NAME EQUAL INUMBER TO INUMBER BY INUMBER {$$=initial_loop($1,$3,$5,$7);}
+      | INDEX EQUAL INUMBER TO INUMBER  {$$=initial_loop($1,$3,$5,"1");}
+      | INDEX EQUAL INUMBER TO INUMBER BY INUMBER {$$=initial_loop($1,$3,$5,$7);}
+      ;
+
+ p_expr : p_expr ';'  {$$ = $1;}
+      |  p_expr ';' expression  {$$ = add_to_queue($1,token(";",-1)); $$=copy_queue($$,$3);}
+      | expression {$$ = $1;}
+      ;
+
+ expression : expression elem_exp {$$=copy_queue($1,$2);}
+      | elem_exp
+      ;
+
+ elem_exp : '(' expression ')' { $$ = create_queue(token("(",-1));
+				 $$ = copy_queue($$,$2);
+				 $$ = add_to_queue($$,token(")",-1));}
+      | var_exp
+      | expr1
+      ;
+
+ expr1: NAME {$$ = create_queue(token($1,-1));}
+      | ',' {$$ = create_queue(token(",",-1));}
+      | OPERATORS {$$ = create_queue(token($1,-1));}
+      | ':' {$$ = create_queue(token(":",-1));}
+      | INUMBER {$$ = create_queue(token($1,-1));}
+      | DNUMBER {$$ = create_queue(token($1,-1));}
+      | INDEX {$$ = create_queue(token($1,-2));}
+      | del_exp
+      | sum_exp
+      | prod_exp
+      ;
+
+ var_exp : var_id_exp '(' INUMBER ')' {set_ll($1,$3,INUMBER);$$=$1;}
+      | var_id_exp '(' OPERATORS INUMBER ')' {set_ll($1,$4,INUMBER);$$=$1;}
+      | var_id_exp '(' INDEX ')' {set_ll($1,$3,INDEX);$$=$1;}
+      | var_id_exp '(' OPERATORS INDEX ')' {set_ll($1,$4,INDEX);$$=$1;}
+      | var_id_exp {set_ll($1,"0",INUMBER);$$=$1;}
+      ;
+
+ var_id_exp : VAR_ID {$$ = create_queue($1);}
+      | indexed_var_exp
+      ;
+
+ indexed_var_exp : indexed_var_exp DOLLAR INDEX {$$=add_to_queue($1,token($3,-3));}
+      | NAME DOLLAR INDEX {$$=create_queue(token($1,-3));$$=add_to_queue($$,token($3,-3));}
+      ;
+
+ del_exp : DEL '(' INUMBER ':' expression ')' {$$ = m_del($3,$5);}
+      ;
+
+ sum_exp : SUM '(' loop_init ':' expression ')'
+      {$$ = operator_loop($3,$5,"+");}
+      ;
+
+ prod_exp : PROD '(' loop_init ':' expression ')'
+      {$$ = operator_loop($3,$5,"*");}
+      ;
+
+ initval_list : initval_list initval_elem
+      | initval_elem
+      ;
+
+ initval_elem : VAR_ID EQUAL expression ';' {p_init($1,$3);}
+      | compile_statement
+      ;
+
+ histval_list : histval_list histval_elem
+      | histval_elem
+      | compile_statement
+      ;
+
+ histval_elem : VAR_ID '(' INUMBER ')' EQUAL expression ';' {p_hist($1,$3,$6);}
+      ;
+
+ shock_list : shock_list shock_elem
+      | shock_elem
+      ;
+
+ shock_elem : VAR VAR_ID ';' PERIODS period_list ';' VALUES value_list ';'  {p_shocks($2,$5,$8,ms_flag);}
+            | VAR VAR_ID ';' STDERR expression ';' {simul_algo=1; p_stderr($2,$5);}
+            | VAR VAR_ID EQUAL expression ';' {simul_algo=1; p_variance($2,$2,$4);}
+            | VAR VAR_ID ',' VAR_ID EQUAL expression ';' {simul_algo=1; p_variance($2,$4,$6);}
+            | compile_statement
+            ;
+
+ period_list : period_list INUMBER  {$$=add_to_queue($1,periods($2,0));}
+      | period_list ',' INUMBER  {$$=add_to_queue($1,periods($3,0));}
+      | period_list INUMBER ':' INUMBER 
+                                 {$$=add_to_queue($1,periods($2,$4));}
+      | period_list ',' INUMBER ':' INUMBER 
+                                 {$$=add_to_queue($1,periods($3,$5));}
+      | INUMBER ':' INUMBER      {$$=create_queue(periods($1,$3));}
+      | INUMBER                  {$$=create_queue(periods($1,0));}
+      ;
+
+ value_list: value_list1        
+      | value_list2             
+      ;
+
+ value_list1: value_list1 DNUMBER  
+                        {$$=add_to_queue($1,create_queue(token($2,-1)));}
+      | value_list1 INUMBER  
+                        {$$=add_to_queue($1,create_queue(token($2,-1)));}
+      | DNUMBER         {$$=create_queue(create_queue(token($1,-1)));}
+      | INUMBER         {$$=create_queue(create_queue(token($1,-1)));}
+      ;
+
+ value_list2: value_list2 '(' expression ')' 
+                                 {$$=add_to_queue($1,$3);}
+      | '(' expression ')'       {$$=create_queue($2);}
+      ;
+
+ obsolete : VARF varlist3 ';' {fputs("Warning: VARF is an obsolete feature\n",stderr);} 
+      | VARP varlist3 ';' {fputs("Warning: VARP is an obsolete feature\n",stderr);}
+      ;
+
+ varlist3 : varlist3 NAME {;}
+      | varlist3 ',' NAME {;}
+      | NAME {;}
+      ;
+
+ dyn2vec : DYN2VEC ';' {dyn2vec(0);}
+      | DYN2VEC {nbr_tmpvar = 0;} varlist4 ';' {dyn2vec(1);}
+      ;
+
+ varlist4 : varlist4 NAME {add_tmpvar($2,0);}
+      | varlist4 NAME '=' NAME {add_tmpvar($2,$4);}
+      | varlist4 ',' NAME {add_tmpvar($3,0);}
+      | varlist4 ',' NAME '=' NAME {add_tmpvar($3,$5);}
+      | NAME  {nbr_tmpvar = 0; add_tmpvar($1,0);}
+      | NAME '=' NAME {nbr_tmpvar = 0; add_tmpvar($1,$3);}
+      ;
+
+ rplot : RPLOT {nbr_tmpvar = 0;} varlist4 ';' {print_rplot();}
+      ; 
+
+ steady : STEADY ';' {p_steady(model);}
+      | STEADY '(' steady_options ')' ';' {p_steady_linear(model);check.linear=1;}
+      ;
+
+ steady_options: steady_options ',' steady_option
+      | steady_option
+      ;
+
+ steady_option: o_solve_algo
+      | o_print
+      | o_noprint
+      ;
+
+ stoch_simul : STOCH_SIMUL ';' {p_stoch_simul(dr_algo,simul_algo,drop,linear,order,replic,ar,nocorr,nofunctions,nomoments,irf);}
+      | STOCH_SIMUL '(' options_list1 ')' ';' 
+                           {p_stoch_simul();}
+      | STOCH_SIMUL varlist4 ';' {p_stoch_simul();}
+      | STOCH_SIMUL '(' options_list1 ')' varlist4 ';' 
+                           {p_stoch_simul();}
+      ;
+
+ o_dr_algo: DR_ALGO '=' INUMBER {p_option("dr_algo",$3);};
+ o_solve_algo: SOLVE_ALGO '=' INUMBER {p_option("solve_algo",$3);};
+ o_simul_algo: SIMUL_ALGO '=' INUMBER {p_option("simul_algo",$3);};
+ o_linear: LINEAR {p_option("linear","1");};
+ o_order: ORDER '=' INUMBER {p_option("order",$3);};
+ o_replic: REPLIC '=' INUMBER {p_option("replic",$3);};
+ o_drop: DROP '=' INUMBER {p_option("drop",$3);};
+ o_ar: AR '=' INUMBER {p_option("ar",$3);};
+ o_corr: CORR {p_option("nocorr","0");};
+ o_nocorr: NOCORR {p_option("nocorr","1");};
+ o_function: FUNCTIONS {p_option("nofunctions","0");};
+ o_nofunction: NOFUNCTIONS {p_option("nofunctions","1");};
+ o_moments: MOMENTS {p_option("nomoments","0");};
+ o_nomoments: NOMOMENTS {p_option("nomoments","1");};
+ o_irf: IRF '=' INUMBER {p_option("irf",$3);};
+ o_hp_filter: HP_FILTER '=' INUMBER {p_option("hp_filter",$3);};
+ o_hp_ngrid: HP_NGRID '=' INUMBER {p_option("hp_ngrid",$3);};
+ o_periods: PERIODS '=' INUMBER {p_option("periods",$3);p_option("simul","1");};
+ o_simul: SIMUL {p_option("simul","1");};
+ o_simul_seed: SIMUL_SEED '=' INUMBER { p_option("simul_seed",$3)}
+             | SIMUL_SEED '=' '(' expression ')' { p_option_e("simul_seed",$4)}
+             ;
+ o_qz_criterium: QZ_CRITERIUM '=' INUMBER { p_option("qz_criterium",$3)}
+               | QZ_CRITERIUM '=' DNUMBER { p_option("qz_criterium",$3)}
+               ;
+ o_datafile: DATAFILE '=' NAME {p_s_option("datafile",$3);};   
+ o_nobs: NOBS '=' INUMBER {p_option("nobs",$3);}
+       | NOBS '=' '(' expression ')' {p_option_e("nobs",$4);}
+       ;
+/*
+       | NOBS '=' '[' INUMBER ':' INUMBER ']' {p_interval_option("nobs",$4,$6);};
+*/
+ o_first_obs: FIRST_OBS '=' INUMBER {p_option("first_obs",$3);};
+ o_prefilter: PREFILTER '=' INUMBER {p_option("prefilter",$3);};
+ o_presample: PRESAMPLE '=' INUMBER {p_option("presample",$3);};
+ o_lik_algo: LIK_ALGO '=' INUMBER {p_option("lik_algo",$3);}; 
+ o_lik_init: LIK_INIT '=' INUMBER {p_option("lik_init",$3);}; 
+ o_graph: GRAPH {p_option("nograph","0");}; 
+ o_nograph: NOGRAPH {p_option("nograph","1");}; 
+ o_print: PRINT {p_option("print","0");}; 
+ o_noprint: NOPRINT {p_option("noprint","1");}; 
+ o_conf_sig: CONF_SIG '=' DNUMBER {p_option("conf_sig",$3);}; 
+ o_mh_replic: MH_REPLIC '=' INUMBER {p_option("mh_replic",$3);}; 
+ o_mh_drop: MH_DROP '=' DNUMBER {p_option("mh_drop",$3);}; 
+ o_mh_jscale: MH_JSCALE '=' value {p_option("mh_jscale",$3);}; 
+ o_optim: OPTIM {p_optim_options("","",1);} '=' '(' optim_options ')'
+{p_optim_options("","",3);};
+ o_mh_init_scale :MH_INIT_SCALE '=' DNUMBER {p_option("mh_init_scale",$3);};
+ o_mh_init_scale :MH_INIT_SCALE '=' INUMBER {p_option("mh_init_scale",$3);};
+ o_mode_file : MODE_FILE '=' NAME {p_s_option("mode_file",$3);};
+ o_mode_compute : MODE_COMPUTE '=' INUMBER {p_option("mode_compute",$3);};
+ o_mode_check : MODE_CHECK {p_option("mode_check","1");};
+ o_prior_trunc : PRIOR_TRUNC '=' DNUMBER {p_option("prior_trunc",$3);};
+ o_mh_mode : MH_MODE '=' INUMBER {p_option("mh_mode",$3);};
+ o_mh_nblcks : MH_NBLOCKS '=' INUMBER {p_option("mh_nblck",$3);};
+ o_load_mh_file : LOAD_MH_FILE {p_option("load_mh_file","1");};
+ o_loglinear : LOGLINEAR {p_option("loglinear","1");};
+ o_diagnostic : DIAGNOSTIC {p_option("diagnostic","0");};
+ o_nodiagnostic : NODIAGNOSTIC {p_option("nodiagnostic","1");};
+ o_bayesian_irf : BAYESIAN_IRF {p_option("bayesian_irf","1");};
+ o_tex : TEX {p_option("TeX","1");};
+ o_forecast : FORECAST '=' INUMBER {p_option("forecast",$3);};
+ o_smoother : SMOOTHER {p_option("smoother","1");};
+ o_moments_varendo : MOMENTS_VARENDO {p_option("moments_varendo","1");};
+ o_filtered_vars : FILTERED_VARS {p_option("filtered_vars","1");};
+ o_relative_irf : RELATIVE_IRF {p_option("relative_irf","1");};
+ o_kalman_algo : KALMAN_ALGO '=' INUMBER {p_option("kalman_algo",$3);};
+ o_kalman_tol : KALMAN_TOL '=' value {p_option("kalman_tol",$3);};
+ o_diffuse_d : DIFFUSE_D '=' INUMBER {p_option("diffuse_d",$3);};
+ o_nk : NK '=' INUMBER {p_option("nk",$3);};
+ o_model_comparison_approximation: MODEL_COMPARISON_APPROXIMATION '=' LAPLACE {p_s_option("model_comparison_approximation","Laplace");}
+   | MODEL_COMPARISON_APPROXIMATION '=' MODIFIEDHARMONICMEAN {p_s_option("model_comparison_approximation","ModifiedHarmonicMean");}
+ o_olr_beta : OLR_BETA '=' value {p_option("olr_beta",$3);};
+ o_shocks_file : SHOCKS_FILE EQUAL NAME {p_s_option("shocks_file",$3);};
+
+
+ optim_option1: '\'' NAME '\'' ',' '\'' NAME '\'' {p_optim_options($2,$6,2);}
+              | '\'' NAME '\'' ',' value {p_optim_options($2,$5,2);}
+              ;
+
+ optim_options: optim_option1
+              | optim_options ',' optim_option1;
+              ;
+
+ o_list1 : o_dr_algo
+         | o_solve_algo
+         | o_simul_algo
+         | o_linear
+         | o_order
+         | o_replic
+         | o_drop
+         | o_ar
+         | o_corr
+         | o_function
+         | o_moments
+         | o_nocorr
+         | o_nofunction
+         | o_nomoments
+         | o_irf
+         | o_relative_irf
+         | o_hp_filter
+         | o_hp_ngrid
+         | o_periods
+         | o_simul
+         | o_simul_seed
+         | o_qz_criterium
+         | o_print
+         | o_noprint
+         ;
+
+ options_list1: options_list1 ',' o_list1
+              | o_list1
+              ;
+
+ resol : RESOL ';' {p_resol(dr_algo,linear,order,model);}
+      | RESOL '(' options_list2 ')' ';' {p_resol(dr_algo,linear,order,model);}
+      ;
+
+ options_list2 : options_list2 ',' DR_ALGO '=' INUMBER {dr_algo = atoi($5);}
+      | options_list2 ',' LINEAR {linear = 1;}
+      | options_list2 ',' ORDER '=' INUMBER {order = atoi($5);}
+      | DR_ALGO '=' INUMBER {dr_algo = atoi($3);}
+      | LINEAR {linear = 1;}
+      | ORDER '=' INUMBER {order = atoi($3);}
+      ;
+
+ simul : SIMUL ';' {p_simul(0,linear,order,replic);}
+       |SIMUL '(' options_list1 ')' ';' {p_simul(0,linear,order,replic);}
+       ;
+
+ dsample : DSAMPLE ';' {p_dsample(0);}
+         | DSAMPLE INUMBER ';' {p_dsample(1,$2);}
+         | DSAMPLE INUMBER INUMBER ';' {p_dsample(2,$2,$3);}
+         ; 
+
+ check : CHECK ';' {p_check();}
+       | CHECK '(' check_options ')' ';' {p_check();} 
+         ;
+
+ check_options: check_options ',' check_option
+       | check_option
+       ;
+
+ check_option: o_print
+       | o_noprint
+       | o_qz_criterium
+       | o_solve_algo
+       ;
+        
+ irf : IRF ';' {p_irf(varexo,shock_size,iter,drop,replic,order);}
+     | IRF '(' option_list_irf ')' ';' {p_irf(varexo,shock_size,iter,drop,replic,order);}
+     | IRF varlist4 ';' {p_irf(varexo,shock_size,iter,drop,replic,order);}
+     | IRF '(' option_list_irf ')' varlist4 ';' {p_irf(varexo,shock_size,iter,drop,replic,order);}
+     ;
+
+ option_list_irf : option_list_irf ',' VAREXO '=' NAME {varexo = $5;}
+                 | option_list_irf ',' SHOCK_SIZE '=' DNUMBER {shock_size = atof($5);} 
+                 | option_list_irf ',' PERIODS '=' INUMBER {iter = atoi($5);}
+                 | option_list_irf ',' DROP '=' INUMBER {drop = atoi($5);}
+                 | option_list_irf ',' REPLIC '=' INUMBER {replic = atoi($5);}
+                 | option_list_irf ',' ORDER '=' INUMBER {order = atoi($5);}
+                 | VAREXO '=' NAME {varexo = $3;}
+                 | SHOCK_SIZE '=' DNUMBER {shock_size = atof($3);}
+                 | PERIODS '=' INUMBER {iter = atoi($3);}       
+                 | DROP '=' INUMBER {drop = atoi($3);}
+                 | REPLIC '=' INUMBER {replic = atoi($3);}         
+                 | ORDER '=' INUMBER {order = atoi($3);}
+                 ;
+
+ d_corr : D_CORR ';' {p_d_corr();}
+        | D_CORR varlist4  ';' {p_d_corr();}
+        ;
+
+ disp_dr : DISP_DR ';' {p_disp_dr(order);}
+         | DISP_DR '(' ORDER '=' INUMBER ')' ';' {p_disp_dr(atoi($5));}
+         | DISP_DR varlist4 ';' {p_disp_dr(order);}
+         | DISP_DR '(' ORDER '=' INUMBER ')' varlist4 ';' {p_disp_dr(atoi($5));}
+         ;
+
+ disp_moments : DISP_MOMENTS ';' {p_disp_moments(drop,order);}
+              | DISP_MOMENTS '(' option_list_disp_moments ')' ';' {p_disp_moments(drop,order);}
+              | DISP_MOMENTS varlist4 ';' {p_disp_moments(drop,order);}
+              | DISP_MOMENTS '(' option_list_disp_moments ')' varlist4 ';' {p_disp_moments(drop,order);}
+              ;
+
+ option_list_disp_moments : option_list_disp_moments ',' DROP '=' INUMBER {drop = atoi($5);}  
+                          | option_list_disp_moments ',' ORDER '=' INUMBER {order = atoi($5);}
+                          | DROP '=' INUMBER {drop = atoi($3);}   
+                          | ORDER '=' INUMBER {order = atoi($3);}
+                          ;
+
+ optim_weights : OPTIM_WEIGHTS ';' {p_optim_weights_init();} optim_weights_list END
+               ;
+
+ optim_weights_list : optim_weights_list VAR_ID expression ';' {p_optim_weights1($2, $3);}
+                    | optim_weights_list VAR_ID ',' VAR_ID expression ';' {p_optim_weights2($2, $4, $5);}
+                    | VAR_ID expression ';' {p_optim_weights1($1, $2);}
+                    | VAR_ID ',' VAR_ID expression ';' {p_optim_weights2($1, $3, $4);}
+                    | compile_statement
+                    ;
+
+ osr_params : OSR_PARAMS osr_params_list ';'
+            ;
+
+ osr_params_list : osr_params_list ',' NAME {p_osr_params($3);}
+                 | osr_params_list NAME {p_osr_params($2);}
+                 | NAME {p_osr_params($1);}
+                 | compile_statement   
+                 ;
+
+ osr : OSR ';' {p_osr();}
+     | OSR '(' olr_options ')' ';' {p_osr();}
+     | OSR varlist4 ';' {p_osr();}
+     | OSR '(' olr_options ')' varlist4 ';' {p_osr();}
+     ;
+ 
+ olr : OLR ';' {p_olr();}
+     | OLR '(' olr_options ')' ';' {p_olr();}
+     | OLR varlist4 ';' {p_olr();}
+     | OLR '(' olr_options ')' varlist4 ';' {p_olr();}
+     ;
+ 
+ olr_option : o_olr_beta
+     | options_list1
+     ;
+ 
+ olr_options : olr_option
+     | olr_options ',' olr_option
+     ;
+
+ olr_inst : OLR_INST {p_olr_inst_init();} olr_inst_list ';'
+          ;
+
+ olr_inst_list : olr_inst_list ',' NAME {p_olr_inst($3);}
+              | olr_inst_list NAME {p_olr_inst($2);}
+              | NAME {p_olr_inst($1);}
+              ;
+
+ calib_var : CALIB_VAR ';' {p_calib_init();} calib_var_list END
+           ;
+
+ calib_var_list : calib_var_list VAR_ID EQUAL expression ';' {p_calib_var($2, $4,"1");}
+                | calib_var_list VAR_ID '(' DNUMBER ')' EQUAL expression ';' {p_calib_var($2,$7,$4);}
+                | calib_var_list VAR_ID '(' INUMBER ')' EQUAL  expression ';' {p_calib_var($2,$7,$4);}
+                |  calib_var_list VAR_ID ',' VAR_ID EQUAL expression ';' {p_calib_covar($2,$4,$6,"1");}
+                | calib_var_list VAR_ID ',' VAR_ID '(' DNUMBER ')' EQUAL expression ';' {p_calib_covar($2,$4,$9,$6);}
+                | calib_var_list VAR_ID ',' VAR_ID '(' INUMBER ')' EQUAL  expression ';' {p_calib_covar($2,$4,$9,$6);}
+                | calib_var_list AUTOCORR VAR_ID '(' INUMBER ')' EQUAL expression ';' {p_calib_ac($3,$5,$8,"1");}
+                | calib_var_list AUTOCORR VAR_ID '(' INUMBER ')' '(' DNUMBER ')' EQUAL expression ';' {p_calib_ac($3,$5,$11,$8);}
+                | calib_var_list AUTOCORR VAR_ID '(' INUMBER ')' '(' INUMBER ')' EQUAL  expression ';' {p_calib_ac($3,$5,$11,$8);}
+                | VAR_ID '(' DNUMBER ')' EQUAL expression ';' {p_calib_var($1,$6,$3);}
+                | VAR_ID '(' INUMBER ')' EQUAL expression ';' {p_calib_var($1,$6,$3);}
+                | VAR_ID EQUAL expression ';' {p_calib_var($1, $3, "1");}
+                | VAR_ID ',' VAR_ID '(' DNUMBER ')' EQUAL expression ';' {p_calib_covar($1,$3,$8,$5);}
+                | VAR_ID ',' VAR_ID '(' INUMBER ')' EQUAL expression ';' {p_calib_covar($1,$3,$8,$5);}
+                | VAR_ID ',' VAR_ID EQUAL expression ';' {p_calib_covar($1,$3,$5,"1");}
+                | AUTOCORR VAR_ID '(' INUMBER ')' '(' DNUMBER ')' EQUAL expression ';' {p_calib_ac($2,$4,$10,$7);}
+                | AUTOCORR VAR_ID '(' INUMBER ')' '(' INUMBER ')' EQUAL expression ';' {p_calib_ac($2,$4,$10,$7);}
+                | AUTOCORR VAR_ID '(' INUMBER ')' EQUAL expression ';' {p_calib_ac($2,$4,$7,"1");}
+                | compile_statement
+                ;
+
+ calib : CALIB ';' {p_calib(0);}
+       | CALIB '(' COVAR ')' ';' {p_calib(1);}
+       ;
+
+ dynatype : DYNATYPE '(' NAME ')'';' {p_dynatype($3,"");}
+          | DYNATYPE '(' NAME ')' varlist4 ';' {p_dynatype($3,"");}
+          | DYNATYPE NAME ';' {p_dynatype($2,"");}
+          | DYNATYPE '(' NAME '.' NAME ')'';' {p_dynatype($3,$5);}
+          | DYNATYPE '(' NAME '.' NAME ')' varlist4 ';' {p_dynatype($3,$5);}
+          | DYNATYPE NAME '.' NAME ';' {p_dynatype($2,$4);};
+
+ dynasave : DYNASAVE '(' NAME ')'';' {p_dynasave($3,"");}
+          | DYNASAVE '(' NAME ')' varlist4 ';' {p_dynasave($3,"");}
+          | DYNASAVE NAME ';' {p_dynasave($2,"");}
+          | DYNASAVE '(' NAME '.' NAME ')'';' {p_dynasave($3,$5);}
+          | DYNASAVE '(' NAME '.' NAME ')' varlist4 ';' {p_dynasave($3,$5);}
+          | DYNASAVE NAME '.' NAME ';' {p_dynasave($2,$4);};
+
+ sigma_e : SIGMA_E '=' '[' {tr_row = 0;} triangular_matrix ']' ';' {p_sigma_e($5);}
+         ;
+
+ triangular_matrix : triangular_matrix ';' {tr_col = 0;} triangular_row {++tr_row;tr_check(tr_row,tr_col);$$=add_to_queue($1,$4);}
+                   | {tr_col = 0;} triangular_row {++tr_row;tr_check(tr_row,tr_col);$$=create_queue($2);}
+                   ;
+
+ triangular_row : triangular_row ',' '(' expression ')' {$$=add_to_queue($1,$4);++tr_col;}
+                | triangular_row ',' DNUMBER {$$=add_to_queue($1,create_queue(token($3,-1)));++tr_col;}
+                | triangular_row ',' INUMBER {$$=add_to_queue($1,create_queue(token($3,-1)));++tr_col;}
+                | triangular_row '(' expression ')' {$$=add_to_queue($1,$3);++tr_col;}
+                | triangular_row DNUMBER {$$=add_to_queue($1,create_queue(token($2,-1)));++tr_col;}
+                | triangular_row INUMBER {$$=add_to_queue($1,create_queue(token($2,-1)));++tr_col;}
+                | '(' expression ')' {$$=create_queue($2);++tr_col;}
+                | DNUMBER {$$=create_queue(token($1,-1));$$=create_queue($$);++tr_col;}
+                | INUMBER {$$=create_queue(token($1,-1));$$=create_queue($$);++tr_col;}
+                ;
+
+ estimated_params : ESTIMATED_PARAMS ';' {p_estimated_init();} estimated_list END
+                  ;
+
+ estimated_list : estimated_list {estim_params_init();} estimated_elem {p_estimated_elem();}
+                | {estim_params_init();} estimated_elem {p_estimated_elem();}
+                | compile_statement
+                ;
+
+ estimated_elem : estimated_elem1 ',' estimated_elem2 ';'
+                ;
+
+ estimated_elem1 : STDERR VAR_ID {estim_params.param_type = 1; estim_params.var_nbr = $2->nbr+1; estim_params.var_type = $2->endo_exo;}
+                 | VAR_ID {estim_params.param_type = 2; estim_params.param_name = $1->name;}
+                 | CORR VAR_ID ',' VAR_ID {estim_params.param_type = 3; estim_params.var_nbr = $2->nbr+1; estim_params.var_nbr2 = $4->nbr+1; estim_params.var_type = $2->endo_exo;}
+                 ;
+
+ estimated_elem2 : value {estim_params.init_val=strdup($1);}
+                 | value ',' value ',' value {estim_params.init_val=strdup($1);estim_params.lb=strdup($3);estim_params.ub=strdup($5);}
+                 | prior ',' estimated_elem3 {estim_params.prior=strdup($1);}
+                 | value ',' prior ',' estimated_elem3 {estim_params.init_val=strdup($1);estim_params.prior=strdup($3);}
+                 | value ',' value ',' value ',' prior ',' estimated_elem3 {estim_params.init_val=strdup($1);estim_params.lb=strdup($3);estim_params.ub=strdup($5);estim_params.prior=strdup($7);}
+                 ;
+
+ estimated_elem3 : value ',' value {estim_params.mean=strdup($1);estim_params.std=strdup($3);}
+                 | value ',' value ',' value ',' value {estim_params.mean=strdup($1);estim_params.std=strdup($3);estim_params.p3=strdup($5);estim_params.p4=strdup($7);}
+                 | value ',' value ',' value ',' value ',' value {estim_params.mean=strdup($1);estim_params.std=strdup($3);estim_params.p3=strdup($5);estim_params.p4=strdup($7);estim_params.jscale=strdup($9);}
+                 ;
+
+ estimated_params_init: ESTIMATED_PARAMS_INIT ';' estimated_init_list END
+                      ;
+
+ estimated_init_list : estimated_init_list estimated_init_elem
+                     | estimated_init_elem
+                     | compile_statement
+                     ;
+
+ estimated_init_elem : STDERR VAR_ID ',' value ';' {p_estimated_init_elem1($2,$4);}
+                     | CORR VAR_ID ',' VAR_ID ',' value ';' {p_estimated_init_elem2($2,$4,$6);}
+                     | VAR_ID ',' value ';' {p_estimated_init_elem3($1,$3);}
+                     ;
+
+ estimated_params_bounds: ESTIMATED_PARAMS_BOUNDS ';' estimated_bounds_list END
+                      ;
+
+ estimated_bounds_list : estimated_bounds_list estimated_bounds_elem
+                     | estimated_bounds_elem
+                     | compile_statement
+                     ;
+
+ estimated_bounds_elem : STDERR VAR_ID ',' value ',' value ';' {p_estimated_bounds_elem1($2,$4,$6);}
+  | CORR VAR_ID ',' VAR_ID ',' value ',' value ';' {p_estimated_bounds_elem2($2,$4,$6,$8);}
+  | VAR_ID ',' value ',' value ';' {p_estimated_bounds_elem3($1,$3,$5);}
+  ;
+
+ prior : BETA_PDF {$$ = "1";}
+       | GAMMA_PDF {$$ = "2";}
+       | NORMAL_PDF {$$ = "3";}
+       | INV_GAMMA_PDF {$$ = "4";}
+       | INV_GAMMA1_PDF {$$ = "4";}
+       | UNIFORM_PDF {$$ = "5";}
+       | INV_GAMMA2_PDF {$$ = "6";}
+       ;
+
+ value : {$$ = empty_string;} /* empty */ 
+       | INUMBER
+       | DNUMBER
+       | NAME
+       | OPERATORS NAME {$$ = my_strcat($1,$2);}
+       ;
+
+ estimation : ESTIMATION ';' {p_estimation();}
+            | ESTIMATION '(' estimation_options ')' ';' {p_estimation();}
+            | ESTIMATION varlist4 ';' {p_estimation();}
+            | ESTIMATION '(' estimation_options ')' varlist4 ';' {p_estimation();}
+            ;
+
+ estimation_options : estimation_options ',' estimation_option
+                    | estimation_option
+                    | estimation_options ',' o_list1
+                    | o_list1
+                    ;
+
+ estimation_option : o_datafile
+                   | o_nobs
+                   | o_first_obs
+                   | o_prefilter
+                   | o_presample
+                   | o_lik_algo 
+                   | o_lik_init 
+                   | o_graph
+                   | o_nograph
+                   | o_conf_sig 
+                   | o_mh_replic
+                   | o_mh_drop
+                   | o_mh_jscale
+                   | o_optim
+                   | o_mh_init_scale 
+                   | o_mode_file 
+                   | o_mode_compute 
+                   | o_mode_check
+                   | o_prior_trunc 
+                   | o_mh_mode 
+                   | o_mh_nblcks 
+                   | o_load_mh_file 
+                   | o_loglinear
+                   | o_diagnostic
+                   | o_nodiagnostic
+                   | o_bayesian_irf
+                   | o_tex
+                   | o_forecast
+                   | o_smoother
+                   | o_moments_varendo
+                   | o_filtered_vars
+                   | o_kalman_algo
+                   | o_kalman_tol
+                   | o_diffuse_d
+                   | o_nk
+                   ;
+
+ varobs : VAROBS {nbr_tmpvar = 0;} varlist4 ';' {print_varobs();}
+        ;
+
+ observation_trends : OBSERVATION_TRENDS ';' {p_trend_init();} trend_list END
+                    ;
+
+ trend_list : trend_list trend_element
+            | trend_element
+            | compile_statement
+            ;
+
+ trend_element :  VAR_ID '(' expression ')' ';' {p_trend_element($1,$3);}
+               ;
+
+
+ unit_root_vars : UNIT_ROOT_VARS {nbr_tmpvar = 0;} varlist4 ';' {print_unit_root_vars();}
+                ;
+
+ model_comparison : MODEL_COMPARISON {nbr_tmpvar=0;} model_comparison_args
+ ;
+
+ model_comparison_args : filename_list1 ';' {p_model_comparison(0);}
+              | filename_list2 ';' {p_model_comparison(1);}
+              | '(' model_comparison_options ')' filename_list1 ';' {p_model_comparison(0);}
+              | '(' model_comparison_options ')' filename_list2 ';' {p_model_comparison(1);}
+              ;
+
+ model_comparison_options: model_comparison_options ',' model_comparison_option
+              | model_comparison_option
+              ;
+
+ model_comparison_option : o_model_comparison_approximation
+              | o_print
+              | o_noprint
+              ;
+
+ filename_list1 : filename {add_tmpvar($1,"");}
+        | filename_list1 ',' filename {add_tmpvar($3,"");}
+        ;
+
+ filename_list2 : filename '(' value ')' {add_tmpvar($1,$3);}
+        | filename_list2 ',' filename '(' value ')' {add_tmpvar($3,$5);}
+        ;
+
+ filename : filename_elem {$$=$1;}
+        | filename filename_elem {$$ = my_strcat($1,$2);}
+        ;
+
+ filename_elem : NAME
+        | '\\' {$$ = "\\";}
+        | '/' {$$ = "/";}
+        | ':' {$$ = ":";}
+        | '.' {$$ = ".";}
+        ;
+
+  compile_statement : compile_define_statement
+        | compile_if_statement
+        | compile_elseif_statement
+        | COMPILE_ELSE {compile_else();}
+        | COMPILE_ENDIF {compile_endif();}
+        ;
+
+  compile_define_statement:
+            COMPILE_DEFINE NAME ';' {compile_define($2);}
+          | COMPILE_DEFINE NAME INUMBER ';'{compile_define($2,$3);}
+	  ;
+
+  compile_operator: EQ 
+          | '<' {$$=strdup("<");} 
+          | '>' {$$=strdup(">");} 
+          | NE
+          | LE
+          | GE
+          ; 
+
+  compile_if_statement: 
+    COMPILE_IF NAME compile_operator INUMBER ';' {compile_if($2,$3,$4);};
+
+  compile_elseif_statement: 
+    COMPILE_ELSEIF NAME compile_operator INUMBER ';' {compile_elseif($2,$3,$4);};
+
+  forecast: FORECAST ';' {p_forecast();}
+          | FORECAST '(' forecast_options ')' ';' {p_forecast();}
+          | FORECAST varlist4 ';' {p_forecast();}
+          | FORECAST '(' forecast_options ')' varlist4 ';' {p_forecast();}
+          ;
+
+  forecast_options: forecast_option
+          | forecast_options ',' forecast_option
+          ;
+
+  forecast_option: o_periods
+          | o_conf_sig
+          ;
+
+
+%%
+int yyerror (char *s)
+     
+{
+  fprintf (stdout, "%s at line %d\n", s, yylineno);
+  exit(1);
+}
+
+/*
+03/15/03 MJ added varexo_st and option LINEAR for STEADY
+01/01/03 MJ corrected dynatype for filename extension and added dynasave
+04/06/02 MJ added optim_weights and optim_weights_list osr_params 
+            osr_params_list osr
+10/09/02 MJ added calib_var calib_var_list calib
+05/26/03 MJ added option LINEAR to MODEL
+08/28/03 MJ added option SOLVE_ALGO
+*/
diff --git a/tags/v_3.062/parser.src/dyn.l b/tags/v_3.062/parser.src/dyn.l
new file mode 100644
index 0000000000000000000000000000000000000000..e62f6e057f5cc0148ac7a690f5b55942f3a835ac
--- /dev/null
+++ b/tags/v_3.062/parser.src/dyn.l
@@ -0,0 +1,309 @@
+%{
+#include <string.h>
+#include "d_tab.h"
+#include "d.h"
+int previous_state;
+int comment_level = 0;
+int lineno = 1;
+void yyerror(char *);
+int name_var(char *);
+%}
+
+
+
+%option stack
+%option yylineno
+%x CMT
+%x DYNARE1
+%x DYNARE2
+%x DYNARE3
+%x DYNARE4
+%x SKIP
+%x THRU
+
+%%
+
+
+
+ /* literal keywords token */
+
+_longnames {BEGIN DYNARE1; return LONGNAMES;}
+initvalf {BEGIN THRU; ECHO;}
+endval {BEGIN DYNARE2; return ENDVAL;}	       
+initval {BEGIN DYNARE2; return INITVAL;}
+histval {BEGIN DYNARE2; return HISTVAL;}
+model {BEGIN DYNARE2; return MODEL;}
+periods {BEGIN DYNARE1; return PERIODS;}
+shocks {BEGIN DYNARE2; return SHOCKS;}
+mshocks {BEGIN DYNARE2; return MSHOCKS;}
+var {BEGIN DYNARE1; return VAR;}
+varexo {BEGIN DYNARE1; return VAREXO;}
+varexo_det {BEGIN DYNARE1; return VAREXO_DET;}
+varrecur {BEGIN DYNARE1; return VARRECUR;}
+parameters {BEGIN DYNARE1; return PARAMETERS;}
+dyn2vec {BEGIN DYNARE1; return DYN2VEC;}
+dyn2gau {BEGIN DYNARE1; return DYN2VEC;}
+rplot {BEGIN DYNARE1; return RPLOT;}
+steady {BEGIN DYNARE1; return STEADY;}
+stoch_simul {BEGIN DYNARE1; return STOCH_SIMUL;}
+resol {BEGIN DYNARE1; return RESOL;}
+disp_dr {BEGIN DYNARE1; return DISP_DR;}
+disp_moments {BEGIN DYNARE1; return DISP_MOMENTS;}
+irf {BEGIN DYNARE1; return IRF;}
+d_corr {BEGIN DYNARE1; return D_CORR;}
+simul {BEGIN DYNARE1; return SIMUL;}
+dsample {BEGIN DYNARE1; return DSAMPLE;}
+check {BEGIN DYNARE1;  yylval.string=strdup(yytext); return CHECK;}
+optim_weights {BEGIN DYNARE2; return OPTIM_WEIGHTS;}
+osr_params {BEGIN DYNARE1; return OSR_PARAMS;}
+osr {BEGIN DYNARE1; return OSR;}
+calib_var {BEGIN DYNARE2; return CALIB_VAR;}
+calib {BEGIN DYNARE1; return CALIB;}
+dynatype {BEGIN DYNARE1; return DYNATYPE;}
+dynasave {BEGIN DYNARE1; return DYNASAVE;}
+sigma_e_ {BEGIN THRU; ECHO;}
+sigma_e {BEGIN DYNARE3; return SIGMA_E;}
+olr {BEGIN DYNARE1; return OLR;}
+olr_inst {BEGIN DYNARE1; return OLR_INST;}
+estimation {BEGIN DYNARE1; return ESTIMATION;}
+varobs {BEGIN DYNARE1; return VAROBS;}
+observation_trends {BEGIN DYNARE2; return OBSERVATION_TRENDS;}
+estimated_params_init {BEGIN DYNARE2; return ESTIMATED_PARAMS_INIT;}
+estimated_params_bounds {BEGIN DYNARE2; return ESTIMATED_PARAMS_BOUNDS;}
+estimated_params {BEGIN DYNARE2; return ESTIMATED_PARAMS;}
+unit_root_vars {BEGIN DYNARE1; return UNIT_ROOT_VARS;}
+model_comparison {BEGIN DYNARE1; return MODEL_COMPARISON;}
+forecast {BEGIN DYNARE1; return FORECAST;}
+
+<*>@define {yy_push_state(DYNARE1); return COMPILE_DEFINE;}
+<*>@if {yy_push_state(DYNARE1); return COMPILE_IF;}
+<*>@elseif {yy_push_state(DYNARE1); return COMPILE_ELSEIF;}
+<*>@else[ \t\n]*; {return COMPILE_ELSE;}
+<*>@endif[ \t\n]*; {return COMPILE_ENDIF;}
+
+<SKIP>. ;
+
+ /* \r is always ignored */
+<*>\r ;
+
+ /* comments */
+<*>[/][/].* ;
+<*>"/*" {yy_push_state(CMT); ECHO;}
+<CMT>[^*\n]* {ECHO;}
+<CMT>"*"+[^*/\n]* {ECHO;}
+<CMT>"*"+"/" {yy_pop_state(); ECHO;}
+<CMT>[\n] {ECHO;}
+
+ /* a semicolon in INITIAL state doesn't modify this state */
+; ECHO;
+
+ /* initial spaces or tabs are ignored */
+
+[ \t] ;
+
+ /* everything which is not a DYNARE command or a comment is ECHOED*/
+[^ \t\n;] {BEGIN THRU;ECHO;}
+<THRU>[^;\n] ECHO;
+<THRU>[;\n] {BEGIN INITIAL; ECHO;}
+ 
+<DYNARE1>; {BEGIN INITIAL; return yytext[0];}
+<DYNARE2,DYNARE3,DYNARE4>; {return yytext[0];}
+<DYNARE1,DYNARE2,DYNARE3,DYNARE4>[\(\)] {return yytext[0];}
+
+ /* var, periods and values in shock statements */
+<DYNARE2>var {return VAR;}
+<DYNARE2>periods {return PERIODS;}
+<DYNARE2>values {return VALUES;}
+<DYNARE2>stderr {return STDERR;}
+
+<DYNARE1>varexo {return VAREXO;}
+
+<DYNARE1,DYNARE2,DYNARE3>end[ \t\n]*; {BEGIN INITIAL; return END;}
+
+ /* lines starting with '#' */
+<DYNARE2>^# {BEGIN DYNARE4; return POUND;}
+<DYNARE4>[\n] {BEGIN DYNARE2; return EOL;}
+
+ /* do loops in models */
+<DYNARE2>do {return DO;}
+<DYNARE2>to {return TO;}
+<DYNARE2>by {return BY;}
+<DYNARE2>endo {return ENDO;}
+<DYNARE2>sum {return SUM;}
+<DYNARE2>prod {return PROD;}
+
+ /* options */
+<DYNARE1>dr_algo {return DR_ALGO;}
+<DYNARE1>simul_algo {return SIMUL_ALGO;}
+<DYNARE1>solve_algo {return SOLVE_ALGO;}
+<DYNARE1>drop {return DROP;}
+<DYNARE1,DYNARE2>linear {return LINEAR;}
+<DYNARE1>order {return ORDER;}
+<DYNARE1>replic {return REPLIC;}
+<DYNARE1>shock_size {return SHOCK_SIZE;}
+<DYNARE1>moments {return MOMENTS;}
+<DYNARE1>nomoments {return NOMOMENTS;}
+<DYNARE1>corr {return CORR;}
+<DYNARE1>nocorr {return NOCORR;}
+<DYNARE1>ar {return AR;}
+<DYNARE1>functions {return FUNCTIONS;}
+<DYNARE1>nofunctions {return NOFUNCTIONS;}
+<DYNARE1>irf {return IRF;}
+<DYNARE1>irf_type {return IRF_TYPE;}
+<DYNARE1>hp_filter {return HP_FILTER;}
+<DYNARE1>hp_ngrid {return HP_NGRID;}
+<DYNARE1>simul_seed {return SIMUL_SEED;}
+<DYNARE1>simul {return SIMUL;}
+<DYNARE1>periods {return PERIODS;}
+<DYNARE1>qz_criterium {return QZ_CRITERIUM;}
+<DYNARE1>optim {return OPTIM;}
+<DYNARE2>shocks_file {return SHOCKS_FILE;}
+
+ /* calib options */
+<DYNARE2>autocorr {return AUTOCORR;}
+
+ /* olr options */
+<DYNARE1>olr_beta {return OLR_BETA;}
+
+ /* estimation options */
+<DYNARE1>datafile {return DATAFILE;}
+<DYNARE1>nobs {return NOBS;}
+<DYNARE1>first_obs {return FIRST_OBS;}
+<DYNARE1>prefilter {return PREFILTER;} 
+<DYNARE1>presample {return PRESAMPLE;} 
+<DYNARE1>lik_algo  {return LIK_ALGO;}  
+<DYNARE1>lik_init  {return LIK_INIT;}  
+<DYNARE1>nograph   {return NOGRAPH;}  	  
+<DYNARE1>graph   {return GRAPH;}  	  
+<DYNARE1>noprint   {return NOPRINT;}  	  
+<DYNARE1>print   {return PRINT;}  	  
+<DYNARE1>conf_sig  {return CONF_SIG;}  
+<DYNARE1>mh_replic {return MH_REPLIC;} 
+<DYNARE1>mh_drop   {return MH_DROP;}   
+<DYNARE1>mh_jscale   {return MH_JSCALE;}   
+<DYNARE1>mh_init_scale {return MH_INIT_SCALE;}
+<DYNARE1>mode_file {return MODE_FILE;}
+<DYNARE1>mode_compute {return MODE_COMPUTE;}
+<DYNARE1>mode_check {return MODE_CHECK;}
+<DYNARE1>prior_trunc {return PRIOR_TRUNC;}
+<DYNARE1>mh_mode {return MH_MODE;}
+<DYNARE1>mh_nblocks {return MH_NBLOCKS;}
+<DYNARE1>load_mh_file {return LOAD_MH_FILE;}
+<DYNARE1>loglinear {return LOGLINEAR;}
+<DYNARE1>diagnostic {return DIAGNOSTIC;}
+<DYNARE1>nodiagnostic {return NODIAGNOSTIC;}
+<DYNARE1>xtick {return XTICK;}
+<DYNARE1>xticklabel {return XTICKLABEL;}
+<DYNARE1>bayesian_irf {return BAYESIAN_IRF;}
+<DYNARE1>tex {return TEX;}
+<DYNARE1>forecast {return FORECAST;}
+<DYNARE1>smoother {return SMOOTHER;}
+<DYNARE1>moments_varendo {return MOMENTS_VARENDO;}
+<DYNARE1>filtered_vars {return FILTERED_VARS;}
+<DYNARE1>relative_irf {return RELATIVE_IRF;}
+<DYNARE1>kalman_algo {return KALMAN_ALGO;}
+<DYNARE1>kalman_tol {return KALMAN_TOL;}
+<DYNARE1>diffuse_d {return DIFFUSE_D;}
+<DYNARE1>nk {return NK;}
+<DYNARE1>model_comparison_approximation {return MODEL_COMPARISON;}
+<DYNARE1>laplace {return LAPLACE;}
+<DYNARE1>modifiedharmonicmean {return MODIFIEDHARMONICMEAN;}
+
+ /* estimated_params priors */
+ <DYNARE2>gamma_pdf {return GAMMA_PDF;}
+ <DYNARE2>beta_pdf {return BETA_PDF;}
+ <DYNARE2>normal_pdf {return NORMAL_PDF;}
+ <DYNARE2>inv_gamma_pdf {return INV_GAMMA_PDF;}
+ <DYNARE2>inv_gamma1_pdf {return INV_GAMMA_PDF;}
+ <DYNARE2>inv_gamma2_pdf {return INV_GAMMA_PDF;}
+ <DYNARE2>uniform_pdf {return UNIFORM_PDF;}
+ <DYNARE2>corr {return CORR;}
+
+ /* spaces, tabs and EOL are ignored */ 
+<DYNARE1,DYNARE2,DYNARE3>[ \t\n] ;
+
+ /* names */
+<DYNARE1,DYNARE3>[A-Za-z_][A-Za-z0-9_]* {
+  yylval.string=strdup(yytext);
+  return NAME;}
+
+<DYNARE2,DYNARE4>[A-Za-z_][A-Za-z0-9_]* {
+  return name_var(strdup(yytext));}
+
+ /* floating-point numbers */
+<DYNARE1,DYNARE2,DYNARE3,DYNARE4>-?((([0-9]*\.[0-9]+)|([0-9]+\.))([edED][-+]?[0-9]+)?)|([0-9]+[edED][-+]?[0-9]+) {
+  yylval.string=strdup(yytext);
+  return DNUMBER;}
+
+ /* integer number */
+<DYNARE1,DYNARE2,DYNARE3,DYNARE4>-?[0-9]+ {
+  yylval.string=strdup(yytext); 
+  return INUMBER;}
+ 
+<DYNARE1,DYNARE2>: {return yytext[0];}
+<DYNARE2>= {return EQUAL;}
+<DYNARE1>"="+"=" {yylval.string=strdup(yytext); return EQ;}
+<DYNARE1>"<"+"=" {yylval.string=strdup(yytext); return LE;}
+<DYNARE1>">"+"=" {yylval.string=strdup(yytext); return GE;}
+<DYNARE1>"!"+"=" {yylval.string=strdup(yytext); return NE;}
+<DYNARE1,DYNARE3>= {return yytext[0];}
+<DYNARE2>, {return yytext[0];}
+<DYNARE2,DYNARE4>\$ {return DOLLAR;}
+<DYNARE1>\$ {return yytext[0];}
+<DYNARE3>] {BEGIN DYNARE1; return yytext[0];}
+<DYNARE3>\[ {return yytext[0];}
+<DYNARE1>, {return yytext[0];}
+<DYNARE1>' {return yytext[0];}
+<DYNARE1,DYNARE2,DYNARE3,DYNARE4>. {yylval.string=strdup(yytext); return OPERATORS;}
+<*>. {return yytext[0];}
+
+%%
+
+int yywrap()
+{
+ return 1;
+}
+ 
+ 
+int name_var(char *s)
+{
+  struct var *p;
+
+  p=var_search(s);
+  if (p == NULL){
+    yylval.string=s;
+    return NAME;
+  }
+  else if (p->endo_exo == 2){
+    yylval.string=s;
+    return INDEX;
+  }
+  else{
+    yylval.p_tok=create_var(p);
+    return VAR_ID;
+  }
+}
+ 
+void start_skipping(void)
+{
+  yy_push_state(SKIP);
+}
+
+void pop_flex_state(void)
+{
+  yy_pop_state();
+}
+
+/*
+01/01/03 MJ added DYNASAVE
+12/31/02 MJ corrected THRU mode to permit native lines without a final ;
+         MJ put back CMT mode for Gauss style comments (/ *...* /)
+04/06/02 MJ added OPTIM_WEIGHTS OSR_PARAMS OSR
+*/
+
+/*
+*/
+
+
+
+
diff --git a/tags/v_3.062/parser.src/dynare.c b/tags/v_3.062/parser.src/dynare.c
new file mode 100644
index 0000000000000000000000000000000000000000..56e2413680e4b83201921fce0befa5d202f75d26
--- /dev/null
+++ b/tags/v_3.062/parser.src/dynare.c
@@ -0,0 +1,3216 @@
+#ifdef MATLAB
+#undef GAUSS
+#undef SCILAB
+#define PLATEFORM "MATLAB"
+#define OPEN_COMMENTS "%"
+#define CLOSE_COMMENTS ""
+#define LEFT_PAREN "("
+#define RIGHT_PAREN ")"
+#define FILE_EXT "m"
+#elif defined GAUSS
+#undef MATLAB
+#undef SCILAB
+#define PLATEFORM "GAUSS"
+#define OPEN_COMMENTS "/*"
+#define CLOSE_COMMENTS "*/"
+#define LEFT_PAREN "["
+#define RIGHT_PAREN "]"
+#define FILE_EXT "gau"
+#elif defined SCILAB
+#undef GAUSS
+#undef MATLAB
+#define PLATEFORM "SCILAB"
+#define OPEN_COMMENTS "//"
+#define CLOSE_COMMENTS ""
+#define LEFT_PAREN "("
+#define RIGHT_PAREN ")"
+#define FILE_EXT "sci"
+#endif
+
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include "d.h"
+#include "d_tab.h"
+
+typedef struct var * t_var_p;
+typedef struct queue * t_q_p;
+typedef struct token * t_t_p;
+
+int yydebug = 0;
+
+/* global for parser program */
+t_var_p var_list;
+t_q_p do_loop_list;
+int var_nbr, longname;
+int endo_nbr, exo_nbr, exo_det_nbr, recur_nbr, y_max_lead, y_max_lag, x_max_lead, x_max_lag, z_max_lead, z_max_lag;
+int *iy,*initval_check,*endval_check,*initval_check1;
+char **tmpvar_list;
+char * varexo;
+int var_order_alpha = 0;
+int stoch_shock_first_time = 1;
+int ex_det_length = 0;
+#if defined MATLAB || defined SCILAB
+int param_nbr=0;
+#endif
+struct s_check check;
+struct s_estim_params estim_params;
+int inst_nbr = 0;
+
+/* options, initialized in dynare_init */
+int dr_algo, simul_algo, drop, linear, order, replic, iter, nbr_tmpvar;
+int ar, irf, shock_size, nocorr, nofunctions, nomoments, hp_filter, hp_ngrid;
+int simul, simul_seed;
+
+int yyparse(void);
+int var_comp1(const void *, const void *);
+int var_comp2(const void *, const void *);
+void str_output(char *);
+void p_check(void);
+void run_checks(void);
+void set_options(int, char**,struct s_runtime_options*);
+void make_empty(char *);
+void p_model_comparison(int);
+
+FILE *f_out;
+char fname[200];
+
+int main(int argc, char **argv)
+{
+  extern FILE *yyin,*yyout;
+  char fn_in[200],fn_out[200],*cp,buffer[2000];
+  struct s_runtime_options runtime_options;
+  struct s_runtime_options* p_ro;
+  p_ro = &runtime_options;
+#ifdef GAUSS
+  char fn_in2[200];
+#endif
+  if (argc > 1){
+    strcpy(fname,argv[1]);
+#ifdef GAUSS
+    if ( (cp=strchr(fname,'.')) != NULL){
+      if (strcasecmp(cp,".MDL")==0 || strcasecmp(cp,".MOD")==0 ){
+	*cp='\0';
+      }
+      else{
+	fprintf(stdout,
+		"Error: %s is an invalid filename for DYNARE\n",
+		argv[1]);
+	exit(1);
+      }
+    }
+    strcpy(fn_in,fname);
+    strcpy(fn_out,fn_in);
+    strcat(fn_in,".mod");
+    strcat(fn_out,".gau");
+
+    yyin = fopen(fn_in,"r");
+    if (!yyin){
+      strcpy(fn_in2,fname);
+      strcat(fn_in2,".mdl");
+      yyin = fopen(fn_in2,"r");
+      if (!yyin){
+	fprintf(stdout,"DYNARE: could not open %s or %s\n",fn_in,fn_in2);
+	exit(1);
+      }
+    }
+#elif defined MATLAB || defined SCILAB
+    if ( (cp=strchr(fname,'.')) != NULL){
+      if (strcasecmp(cp,".MOD")==0){
+	*cp='\0';
+      }
+      else if (strcasecmp(cp,".DYN")==0){
+	*cp='\0';
+      }
+      else{
+	fprintf(stdout,
+		"Error: %s is an invalid filename for DYNARE with %s\n",
+		argv[1],PLATEFORM);
+	exit(1);
+      }
+    }
+
+    strcpy(fn_in,fname);
+    strcat(fn_in,".dyn");
+    yyin = fopen(fn_in,"r");
+    if (!yyin)
+      {
+	strcpy(fn_in,fname);
+	strcat(fn_in,".mod");
+	yyin = fopen(fn_in,"r");
+      }
+    if (!yyin){
+      fprintf(stdout,"DYNARE: could not open %s\n",fn_in);
+      exit(1);
+    }
+
+    strcpy(fn_out,fname);
+#ifdef MATLAB
+    strcat(fn_out,".m");
+#elif defined SCILAB
+    strcat(fn_out,".sci");
+#endif
+
+#endif
+    
+    yyout = fopen(fn_out,"w");
+    if (!yyout){
+      fprintf(stdout,"DYNARE: could not open %s\n",fn_out);
+      exit(1);
+    }
+    f_out=yyout;
+    /* set runtime options */
+    set_options(argc,argv,p_ro);
+  }
+  else{
+    fprintf(stdout,"Error: DYNARE needs the name of the model file\n");
+    exit(1);
+  }
+  if (runtime_options.debug == 1)
+    {
+      yydebug = 1;
+    }
+  dynare_init(fname,runtime_options);
+  yyparse();
+#if defined MATLAB
+  sprintf(buffer,"save('%s_results','oo_','dr_');\n",fname);
+  str_output(buffer);
+  str_output("diary off\n");
+#elif defined SCILAB
+  str_output("mclose(fh_log);\n");
+#elif defined GAUSS
+  str_output("end;\n");
+#endif
+  run_checks();
+  return 0;
+}
+
+void add_var(char *name,int endo_exo)
+{
+  var_list = (t_var_p)realloc(var_list,(var_nbr+1)*sizeof(struct var));
+  var_list[var_nbr].name=strdup(name);
+  var_list[var_nbr].endo_exo=endo_exo;
+  var_nbr++;
+}
+
+void add_var_range(char *name1, char *name2, int endo_exo)
+{
+  int i1, i2, i3;
+  char name[200],*p1,*p2;
+
+  p1=name1;
+  p2=name2;
+  i1=0;
+  while (*p1 == *p2)
+    {
+      p1++;
+      p2++;
+      i1++;
+    }
+
+  if (*p1 >= '0' && *p1 <= '9')
+    {
+      if (sscanf(p1,"%d",&i2) != 1)
+	{
+	  fprintf(stdout,"VAR, VAREXO or VARRECUR: error in name range expression\n");
+	  return;
+	}    
+      if (sscanf(p2,"%d",&i3) != 1)
+	{
+	  fprintf(stdout,"VAR, VAREXO or VARRECUR: error in name range expression\n");
+	  return;
+	}    
+      if (i3 < i2)
+	{
+	  fprintf(stdout,"VAR, VAREXO or VARRECUR: error in name range expression\n");
+	  return;
+	}
+    
+      var_list = (t_var_p)realloc(var_list,(var_nbr+i3-i2+1)*sizeof(struct var));
+      strncpy(name,name1,i1);
+      while (i2 <= i3)
+	{
+	  sprintf(name+i1,"%d\0",i2);
+	  var_list[var_nbr].name=strdup(name);
+	  var_list[var_nbr].endo_exo=endo_exo;
+	  var_nbr++;
+	  i2++;
+	}
+    }
+  else
+    {
+      fprintf(stdout,"VAR, VAREXO or VARRECUR: error in name range expression\n");
+      return;
+    }
+  return;
+}
+
+void sort_var()
+{
+  qsort(var_list,var_nbr,sizeof(struct var),var_comp1);
+}
+
+int var_comp1(const void *x1, const void *x2)
+{
+  return strcasecmp(((t_var_p)x1)->name,((t_var_p)x2)->name);
+}
+
+struct var *var_search(const char *key)
+{
+  return (t_var_p)bsearch(key,var_list,var_nbr,sizeof(struct var),var_comp2);
+}
+
+int var_comp2(const void *key, const void *element)
+{
+  return strcasecmp((char *)key,((t_var_p)element)->name);
+}
+
+struct queue *create_queue(void *p1)
+{
+  struct queue *p2;
+  p2=(struct queue *)calloc(1,sizeof(struct queue));
+  p2->ptr=(void **)calloc(1,sizeof(void *));
+  (p2->ptr)[0] = p1;
+  p2->imax = 1;
+  p2->flag = 0;
+  return p2;
+}
+
+struct queue *add_to_queue(struct queue *p, void *p1)
+{
+  p->ptr=(void **)realloc(p->ptr,(p->imax+1)*sizeof(void *));
+  (p->ptr)[p->imax]=p1;
+  p->imax++;
+  return p;
+}
+
+
+void free_queue(struct queue *p)
+{
+  free(p->ptr);
+  free(p);
+}
+
+struct queue *copy_queue(struct queue *p1, struct queue *p2)
+{
+  p1->ptr=(void **)realloc(p1->ptr,(p1->imax+p2->imax)*sizeof(void *));
+  memcpy(p1->ptr+p1->imax,p2->ptr,p2->imax*sizeof(void *));
+  p1->imax += p2->imax;
+  free_queue(p2);
+  return p1;
+}
+
+struct token *create_var(struct var *p)
+{ 
+    struct token *p1;
+    p1 = (struct token *)calloc(1,sizeof(struct token));
+    p1->endo_exo = p->endo_exo;
+    p1->nbr = p->nbr;
+    if (p1->endo_exo == 4){
+      p1->name = p->name; /* It's a parameter */
+    }
+    else {
+      p1->var_ptr = p; /* MJ 01/12/03 */
+      p1->name = NULL;  /* It's a variable, not a string */
+    }
+    return p1;
+}
+
+void set_ll1(struct token *p_v, int i)
+{
+  int *temp;
+
+  p_v->lead_lag=i;
+  if (p_v->endo_exo == 1){
+    if (i < -y_max_lag){
+      temp=(int *)calloc(y_max_lead-i+1,endo_nbr*sizeof(int));
+      memcpy(temp+(-i-y_max_lag)*endo_nbr,iy,(y_max_lag+y_max_lead+1)*endo_nbr*sizeof(int));
+      free(iy);
+      iy=temp;
+      y_max_lag = -i;
+    }
+    else if (i > y_max_lead){
+      iy=(int *)realloc(iy,(y_max_lag+i+1)*endo_nbr*sizeof(int));
+      memset(iy+(y_max_lag+y_max_lead+1)*endo_nbr,0,(i-y_max_lead)*endo_nbr*sizeof(int));
+      y_max_lead = i;
+    }
+    iy[p_v->nbr+(i+y_max_lag)*endo_nbr]=1;
+  }
+  else if (p_v->endo_exo == 0){
+    if (i < -x_max_lag) x_max_lag = -i;
+    else if (i > x_max_lead) x_max_lead = i;
+    }
+  else if (p_v->endo_exo == 3){
+    if (i < -z_max_lag) z_max_lag = -i;
+    else if (i > z_max_lead) z_max_lead = i;
+    }
+}
+
+void set_ll(struct queue *p_q, char *s, int c)
+{
+  int i;
+  struct token *p_v;
+
+  p_v = *(struct token **)p_q->ptr;
+  switch(c){
+  case INUMBER:
+    i=atoi(s);
+    set_ll1(p_v, i);
+    break;
+  case INDEX:
+    p_v->name=s;
+  }
+}
+
+struct queue *m_del(char *s, struct queue *p_q)
+{
+;
+}
+
+struct token *token(char *s, int nbr)
+{
+  struct token *p;
+  p=(struct token *)calloc(1,sizeof(struct token));
+  p->name = s;
+  p->nbr = nbr; /* > 0 : variable, -1: string, -2: loop index, -3: indexed variable */
+  p->endo_exo = 0;
+  return p;
+}
+
+void mark_pound(struct queue *p)
+{
+  p->flag=1;
+}
+
+int * periods(char *s1, char *s2)
+{
+  int *i;
+  i=(int *)calloc(2,sizeof(int));
+  i[0]=atoi(s1);
+  if (s2 == 0) i[1]=0;
+  else i[1]=atoi(s2);
+  return i;
+}
+
+void p_shocks(struct token *var, struct queue *per, struct queue *val, int ms_flag)
+{
+  int i,j,i1,i2,i_par,flag;
+  struct queue *p_q;
+  struct token **p_t;
+  char buffer[2000];
+  char* name;
+
+  check.determ = 1;
+  if (var->endo_exo != 0 && var->endo_exo != 5){
+    if (var->var_ptr != 0) name = var->var_ptr->name;
+    else name = var->name;
+    fprintf(stdout,"Error in SHOCKS: %s isn't an exogenous variable\n",name); 
+    return;
+  }
+  if (per->imax != val->imax){
+    fprintf(stdout,"Error in SHOCKS: periods and values don't match for shocks on variable %s\n",var->var_ptr->name);
+    return;
+  }
+  for (i=0; i < per->imax;i++){
+    i_par=0;
+    p_q = (struct queue *)val->ptr[i];
+    if (var->endo_exo == 0)
+      {
+	i1= ((int *)(per->ptr[i]))[0]+x_max_lag;
+	i2= ((int *)(per->ptr[i]))[1]+x_max_lag;
+	flag = 0;
+      }
+    else
+      {
+	i1= ((int *)(per->ptr[i]))[0];
+	i2= ((int *)(per->ptr[i]))[1];
+	ex_det_length = (i1 > ex_det_length) ? i1 : ex_det_length; 
+	ex_det_length = (i2 > ex_det_length) ? i2 : ex_det_length;
+	i1 += y_max_lag;
+	i2 += y_max_lag;
+	flag = 2;
+      }
+    if (i2 == x_max_lag){
+      if (ms_flag == 0)              /* mshocks */
+	{
+#ifdef GAUSS
+	  sprintf(buffer,"_ex[%d,%d]=",i1,var->nbr+1);
+#elif defined MATLAB || defined SCILAB
+	  sprintf(buffer,"set_shocks(%d,%d,%d,",flag,i1,var->nbr+1);
+	  i_par = 1;
+#endif
+	  str_output(buffer);
+	}
+      else
+	{
+#ifdef GAUSS
+	  sprintf(buffer,"_ex[%d,%d]=_ex[%d,%d]*(",i1,var->nbr+1,i1,var->nbr+1);
+	  i_par=1;
+#elif defined MATLAB || defined SCILAB
+	  sprintf(buffer,"set_shocks(%d,%d,%d,",flag+1,i1,var->nbr+1);
+	  i_par = 1;
+#endif
+	  str_output(buffer);
+	}
+    }
+    else{
+      if (ms_flag == 0)              /* mshocks */
+	{
+#ifdef GAUSS
+	  sprintf(buffer,"_ex[%d:%d,%d]=ones(%d,1).*",i1,i2+x_max_lag,var->nbr+1,i2-i1+x_max_lag+1);
+#elif defined MATLAB || defined SCILAB
+	  sprintf(buffer,"set_shocks(%d,[%d:%d],%d,",flag,i1,i2,var->nbr+1);
+	  i_par = 1;
+#endif
+	  str_output(buffer);
+	}
+      else{
+#ifdef GAUSS
+	sprintf(buffer,"_ex[%d:%d,%d]=_ex[%d:%d,%d].*(",i1,i2+x_max_lag,var->nbr+1,i1,i2+x_max_lag,var->nbr+1);
+#elif defined MATLAB || defined SCILAB
+	sprintf(buffer,"set_shocks(%d,[%d:%d],%d,",flag+1,i1,i2,var->nbr+1);
+#endif
+	i_par=1;
+	str_output(buffer);
+      }
+    }
+    p_t=(struct token **) p_q->ptr;
+    for (j=0;j < p_q->imax;j++){
+      if ((*p_t)->nbr == -1)  str_output((*p_t)->name);
+      else fprintf(stdout,"Reference to variable name isn't allowed in (m)shocks value statement");
+      p_t++;
+    }
+    if (i_par) str_output(")");
+    str_output(";\n");
+  }
+}
+
+void p_stderr(struct token  *var, struct queue *expression)
+{
+  char buffer[200];
+  check.stoch = 1;
+#ifdef GAUSS
+  if (stoch_shock_first_time)
+    {
+      sprintf(buffer,"_Sigma_e = zeros(%d,%d);\n",exo_nbr,exo_nbr);
+      str_output(buffer);
+      stoch_shock_first_time = 0;
+    }
+  sprintf(buffer,"_Sigma_e[%d,%d] = (",var->nbr+1,var->nbr+1);
+  str_output(buffer);
+  p_expression(expression);
+  str_output(")^2;\n");
+#elif defined MATLAB || defined SCILAB
+  if (stoch_shock_first_time)
+    {
+      sprintf(buffer,"Sigma_e_ = zeros(%d,%d);\n",exo_nbr,exo_nbr);
+      str_output(buffer);
+      stoch_shock_first_time = 0;
+    }
+  sprintf(buffer,"Sigma_e_(%d,%d) = (",var->nbr+1,var->nbr+1);
+  str_output(buffer);
+  p_expression(expression);
+  str_output(")^2;\n");
+#endif
+}
+
+void p_variance(struct token  *var1, struct token  *var2, struct queue *expression)
+{
+  char buffer[200];
+  check.stoch = 1;
+#ifdef GAUSS
+  if (stoch_shock_first_time)
+    {
+      sprintf(buffer,"_Sigma_e = zeros(%d,%d);\n",exo_nbr,exo_nbr);
+      str_output(buffer);
+      stoch_shock_first_time = 0;
+    }
+  sprintf(buffer,"_Sigma_e[%d,%d] = ",var1->nbr+1,var2->nbr+1);
+  str_output(buffer);
+  p_expression(expression);
+  str_output(";\n");
+  if (var1->nbr != var2->nbr)
+    {
+      sprintf(buffer,"_Sigma_e[%d,%d] = _Sigma_e[%d,%d];\n",var2->nbr+1,var1->nbr+1,var1->nbr+1,var2->nbr+1);
+      str_output(buffer);
+    }
+#elif defined MATLAB || defined SCILAB
+  if (stoch_shock_first_time)
+    {
+      sprintf(buffer,"Sigma_e_ = zeros(%d,%d);\n",exo_nbr,exo_nbr);
+      str_output(buffer);
+      stoch_shock_first_time = 0;
+    }
+  sprintf(buffer,"Sigma_e_(%d,%d) = ",var1->nbr+1,var2->nbr+1);
+  str_output(buffer);
+  p_expression(expression);
+  str_output(";\n");
+  if (var1->nbr != var2->nbr)
+    {
+      sprintf(buffer,"Sigma_e_(%d,%d) = Sigma_e_(%d,%d);\n",var2->nbr+1,var1->nbr+1,var1->nbr+1,var2->nbr+1);
+      str_output(buffer);
+    }
+#endif
+}
+
+void p_init(struct token *v, struct queue *q)
+{
+  char buffer[200];
+  int offset;
+
+  offset = v->var_ptr-var_list;
+  if (v->endo_exo == 1)
+    {
+      initval_check1[offset] = 1;
+#ifdef GAUSS
+      sprintf(buffer,"_ys[%d]=",v->nbr+1);
+#elif defined MATLAB || defined SCILAB
+      sprintf(buffer,"ys_(%d)=",v->nbr+1);
+#endif
+    }
+  else if (v->endo_exo == 0)
+    {
+      initval_check1[offset] = 1;
+#ifdef GAUSS
+      sprintf(buffer,"_exe[%d]=",v->nbr+1);
+#elif defined MATLAB || defined SCILAB
+      sprintf(buffer,"exe_(%d)=",v->nbr+1);
+#endif
+    }
+  else if (v->endo_exo == 3)
+    {
+#ifdef GAUSS
+      sprintf(buffer,"_recurs[%d]=",v->nbr+1);
+#elif defined MATLAB || defined SCILAB
+      sprintf(buffer,"recurs_(%d)=",v->nbr+1);
+#endif
+    }
+    else if (v->endo_exo == 5)
+    {
+#ifdef GAUSS
+      sprintf(buffer,"_exe_det[%d]=",v->nbr+1);
+#elif defined MATLAB || defined SCILAB
+      sprintf(buffer,"exe_det_(%d)=",v->nbr+1);
+#endif
+    }
+  str_output(buffer);
+
+  p_expression(q);
+  str_output(";\n");
+}
+
+void p_initval(void)
+{
+  char buffer[200];
+
+  check.initval = 1;
+  initval_check = (int *)calloc(var_nbr,sizeof(int));
+  initval_check1 = initval_check;
+
+#ifdef GAUSS
+  str_output("/* INITVAL */\n");
+  str_output("_valf = 0;\n_endval=0;\n");
+#elif defined MATLAB || defined SCILAB
+#ifdef MATLAB
+  str_output("% ");
+#else
+  str_output("// ");
+#endif
+  str_output("INITVAL \n");
+  str_output("valf_ = 0;\nendval_=0;\n");
+#endif
+  if(recur_nbr > 0){
+#ifdef GAUSS
+    sprintf(buffer,"_recurs = zeros(%d,1);\n",recur_nbr);
+#elif defined MATLAB || defined SCILAB
+    sprintf(buffer,"recurs_ = zeros(%d,1);\n",recur_nbr);
+#endif
+    str_output(buffer);
+  }
+#ifdef GAUSS
+  str_output("_ys0 = 0;\n");
+  str_output("_ex0 = 0;\n");
+  str_output("_recurs0 = 0;\n");
+#endif
+}
+
+void pe_initval(void)
+{
+#ifdef GAUSS
+  fputs("if exo_nbr > 0;\n",f_out);
+  fputs("  _ex=ones(_iter+_xkmin+_xkmax,1).*_exe';\n",f_out);
+  fputs("endif;\n",f_out);
+#elif defined MATLAB || defined SCILAB
+  fputs("y_=[ys_*ones(1,ykmin_)];\n",f_out);
+  fputs("if exo_nbr > 0;\n",f_out);
+  fputs("  ex_=[ones(xkmin_,1)*exe_'];\n",f_out);
+  fputs("end;\n",f_out);
+  fputs("if exo_det_nbr > 0;\n",f_out);
+  fputs("  ex_det_=[ones(ykmin_+1,1)*exe_det_'];\n",f_out);
+  fputs("end;\n",f_out);
+#endif
+}
+
+void p_endval(void)
+{
+  check.endval = 1;
+  endval_check = (int *)calloc(var_nbr,sizeof(int));
+  initval_check1 = endval_check;
+
+#ifdef GAUSS  
+  str_output("/* ENDVAL */\n");
+  str_output("_ys0=_ys;\n_ex0=_exe;\n_recurs0=_recurs;\n_endval=1;\n");
+#elif defined MATLAB || defined SCILAB
+#ifdef MATLAB
+  str_output("% ");
+#else
+  str_output("// ");
+#endif
+  str_output("ENDVAL \n");
+  str_output("ys0_=ys_;\nex0_=exe_;\nex_det0_=exe_det_;\nrecurs0_=recurs_;\nendval_=1;\n");
+#endif
+}
+
+void pe_endval(void)
+{
+#ifdef GAUSS
+  fputs("if exo_nbr > 0;\n",f_out);
+  fputs("  _ex[_xkmin+1:_iter+_xkmin+_xkmax,.]=ones(_iter+_xkmax,1).*_exe';\n",f_out);
+  fputs("endif;\n",f_out);
+#elif defined MATLAB || defined SCILAB
+  fputs("y_=[y_ ys_*ones(1,iter_+ykmax_)];\n",f_out);
+  fputs("if exo_nbr > 0;\n",f_out);
+  fputs("  ex_=[ones(xkmin_,1)*ex0_';ones(iter_+xkmax_,1)*exe_'];\n",f_out);
+  fputs("end;\n",f_out);
+  fputs("if exo_det_nbr > 0;\n",f_out);
+  fputs("  ex_det_=[ones(ykmin_+1,1)*ex_det0_';ones(iter_+ykmax_,1)*exe_det_'];\n",f_out);
+  fputs("end;\n",f_out);
+#endif
+}
+
+void p_hist(struct token *v, char *lag, struct queue *q)
+{
+  char buffer[200];
+  int offset;
+
+  offset = v->var_ptr-var_list;
+  if (v->endo_exo == 1)
+    {
+#ifdef GAUSS
+      sprintf(buffer,"_y[%d,_ykmin+(%s)]=",v->nbr+1,lag);
+#elif defined MATLAB || defined SCILAB
+      sprintf(buffer,"y_(%d,ykmin_+(%s))=",v->nbr+1,lag);
+#endif
+    }
+  else if (v->endo_exo == 0)
+    {
+      initval_check1[offset] = 1;
+#ifdef GAUSS
+      sprintf(buffer,"_ex[_xkmin+(%s),%d]=",lag,v->nbr+1);
+#elif defined MATLAB || defined SCILAB
+      sprintf(buffer,"ex_(xkmin_+(%s),%d)=",lag,v->nbr+1);
+#endif
+    }
+  else if (v->endo_exo == 5)
+    {
+      initval_check1[offset] = 1;
+#ifdef GAUSS
+      sprintf(buffer,"_ex_det[_xkmin+(%s),%d]=",lag,v->nbr+1);
+#elif defined MATLAB || defined SCILAB
+      sprintf(buffer,"ex_det_(ykmin_+(%s),%d)=",lag,v->nbr+1);
+#endif
+    }
+/*   else if (v->endo_exo == 3) */
+/*     { */
+/* #ifdef GAUSS */
+/*       sprintf(buffer,"_recurs[%d]=",v->nbr+1); */
+/* #elif defined MATLAB || defined SCILAB */
+/*       sprintf(buffer,"recurs_(%d)=",v->nbr+1); */
+/* #endif */
+/*     } */
+  str_output(buffer);
+
+  p_expression(q);
+  str_output(";\n");
+}
+
+void p_histval(void)
+{
+  char buffer[200];
+
+  check.histval = 1;
+
+#ifdef GAUSS
+  str_output("/* HISTVAL */\n");
+#elif defined MATLAB || defined SCILAB
+#ifdef MATLAB
+  str_output("% ");
+#else
+  str_output("// ");
+#endif
+  str_output("HISTVAL \n");
+#endif
+}
+  
+void print_endo()
+{
+  char buff[2000];
+  int i;
+  sort_var();
+
+#ifdef GAUSS  
+  str_output("\nlet");
+  if (longname) 
+    str_output(" string");
+  str_output(" _lgy = ");
+
+  for (i=0; i < var_nbr;i++)
+    {
+      if (var_list[i].endo_exo == 1)
+	{
+	  var_list[i].nbr=endo_nbr;
+	  if (endo_nbr > 0) str_output(", ");
+	  strcpy(buff,"\"");
+	  strcat(buff,var_list[i].name);
+	  strcat(buff,"\"");
+	  str_output(buff);
+	  endo_nbr++;
+	}
+    }
+  str_output(";\n");
+#elif defined MATLAB || defined SCILAB
+  for (i=0; i < var_nbr; i++)
+    {
+      if ( var_list[i].endo_exo == 1)
+	{
+	  if ( endo_nbr == 0 )
+	    {
+	      sprintf(buff,"lgy_ = '%s';\n",var_list[i].name);
+	    }
+	  else
+	    {
+#ifdef MATLAB
+	      sprintf(buff,"lgy_ = str2mat(lgy_,'%s');\n",var_list[i].name);
+#else
+	      sprintf(buff,"lgy_ = [lgy_;'%s'];\n",var_list[i].name);
+#endif
+	    }
+	  str_output(buff) ;
+	  var_list[i].nbr=endo_nbr ;
+	  endo_nbr++ ;
+	}
+    }
+#endif
+
+  sprintf(buff,"endo_nbr = %d;\n",endo_nbr);
+  str_output(buff);
+  iy=(int *)calloc(endo_nbr,sizeof(int));
+}      
+  
+void print_exo()
+{
+  char buff[2000];
+  int i;
+  int n = 0;
+
+  for(i = 0; i < var_nbr; ++i)
+    {
+      if (var_list[i].endo_exo == 0)
+	{
+	  var_list[i].original_nbr = n++;
+	}
+    }
+
+  sort_var();
+
+#ifdef GAUSS  
+  str_output("\nlet");
+  if (longname) 
+    str_output(" string");
+  str_output(" _lgx = ");
+
+  for (i=0; i < var_nbr; i++){
+    if (var_list[i].endo_exo == 0){
+      var_list[i].nbr=endo_nbr;
+      if (exo_nbr > 0) str_output(", ");
+      strcpy(buff,"\"");
+      strcat(buff,var_list[i].name);
+      strcat(buff,"\"");
+      str_output(buff);
+      exo_nbr++;
+    }
+  }
+  str_output(";\n");
+#elif defined MATLAB || defined SCILAB
+  for (i=0; i < var_nbr; i++)
+    {
+      if ( var_list[i].endo_exo == 0)
+	{
+	  if ( exo_nbr == 0 )
+	    {
+	      sprintf(buff,"lgx_ = '%s';\n",var_list[i].name);
+	    }
+	  else
+	    {
+#ifdef MATLAB
+	      sprintf(buff,"lgx_ = str2mat(lgx_,'%s');\n",var_list[i].name);
+#else
+	      sprintf(buff,"lgx_ = [lgx_;'%s'];\n",var_list[i].name);
+#endif
+	    }
+	  str_output(buff) ;
+	  var_list[i].nbr=exo_nbr ;
+	  exo_nbr++ ;
+	}
+    }
+  for (i=0; i < var_nbr; i++)
+    {
+      if ( var_list[i].endo_exo == 0)
+        {
+          if ( var_list[i].nbr == 0 )
+            {
+              sprintf(buff,"lgx_orig_ord_ = [%d",var_list[i].original_nbr+1);
+            }
+          else
+            {
+              sprintf(buff," %d",var_list[i].original_nbr+1);
+            }
+          str_output(buff);
+        }
+    }
+  if (exo_nbr > 0)
+    {
+      str_output("];\n");
+    }
+#endif
+
+  sprintf(buff,"exo_nbr = %d;\n",exo_nbr);
+  str_output(buff);
+}      
+  
+void print_exo_det()
+{
+  char buff[2000];
+  int i;
+
+  sort_var();
+
+#ifdef GAUSS  
+  str_output("\nlet");
+  if (longname) 
+    str_output(" string");
+  str_output(" _lgx_det = ");
+
+  for (i=0; i < var_nbr;i++){
+    if (var_list[i].endo_exo == 5){
+      var_list[i].nbr=exo_det_nbr;
+      if (exo_det_nbr > 0) str_output(", ");
+      strcpy(buff,"\"");
+      strcat(buff,var_list[i].name);
+      strcat(buff,"\"");
+      str_output(buff);
+      exo_det_nbr++;
+    }
+  }
+  str_output(";\n");
+#elif defined MATLAB || defined SCILAB
+  for (i=0; i < var_nbr; i++)
+    {
+      if ( var_list[i].endo_exo == 5)
+	{
+	  if ( exo_det_nbr == 0 )
+	    {
+	      sprintf(buff,"lgx_det_ = '%s';\n",var_list[i].name);
+	    }
+	  else
+	    {
+#ifdef MATLAB
+	      sprintf(buff,"lgx_det_ = str2mat(lgx_det_,'%s');\n",var_list[i].name);
+#else
+	      sprintf(buff,"lgx_det_ = [lgx_det_;'%s'];\n",var_list[i].name);
+#endif
+	    }
+	  str_output(buff) ;
+	  var_list[i].nbr=exo_det_nbr ;
+	  exo_det_nbr++ ;
+	}
+    }
+#endif
+
+  sprintf(buff,"exo_det_nbr = %d;\n",exo_det_nbr);
+  str_output(buff);
+}      
+  
+void print_recur()
+{
+  char buff[2000];
+  int i;
+
+  sort_var();
+
+#ifdef GAUSS  
+  str_output("\nlet");
+  if (longname) 
+    str_output(" string");
+  str_output(" _lgr = ");
+
+  for (i =0; < var_nbr, ++i){
+    if (var_list[i].endo_exo == 3){
+      var_list[i].nbr=endo_nbr;
+      if (recur_nbr > 0) str_output(", ");
+      strcpy(buff,"\"");
+      strcat(buff,var_list[i].name);
+      strcat(buff,"\"");
+      str_output(buff);
+      recur_nbr++;
+    }
+  }
+  str_output(";\n");
+#elif defined MATLAB || defined SCILAB
+  for (i=0; i < var_nbr; i++)
+    {
+      if ( var_list[i].endo_exo == 3)
+	{
+	  if ( recur_nbr == 0 )
+	    {
+	      sprintf(buff,"lgr_ = '%s';\n",var_list[i].name);
+	    }
+	  else
+	    {
+#ifdef MATLAB
+	      sprintf(buff,"lgr_ = str2mat(lgr_,'%s');\n",var_list[i].name);
+#else
+	      sprintf(buff,"lgr_ = [lgr_;'%s'];\n",var_list[i].name);
+#endif
+	    }
+	  str_output(buff) ;
+	  var_list[i].nbr=recur_nbr ;
+	  recur_nbr++ ;
+	}
+    }
+#endif
+
+  sprintf(buff,"recur_nbr = %d;\n",recur_nbr);
+  str_output(buff);
+}      
+  
+
+void str_output(char *str)
+{
+  int static column=0,p;
+  char *ps;
+  ps=str;
+  p=0;
+  while (*ps != '\n' && *ps != '\0') 
+    {
+      p++;
+      ps++;
+    }
+#ifdef GAUSS
+  if (column > 0 && (column+p) > 80)
+    {
+      fputc('\n',f_out);
+      column=0;
+    }
+#elif defined MATLAB
+  if (column > 0 && (column+p) > 76)
+    {
+      fputs(" ...\n",f_out);
+      column=0;
+    }
+#endif
+  fputs(str,f_out);
+  if (*ps == '\n')
+    {
+      while (*ps != '\0')
+	{
+	  if (*ps == '\n') p = 0;
+	  p++;
+	  ps++;
+	}
+      column=p;
+    }
+  else column += p;
+}
+
+void i_output(int i)
+{
+  char s[20];
+  sprintf(s,"%d",i);
+  str_output(s);
+}
+
+void print_model(struct queue *p)
+{
+  int i,j,k,m;
+  char buffer[200];
+
+  i=0;
+  j=1;
+  for ( k=1; k <= (y_max_lag+y_max_lead+1); k++)
+    {
+      if (k == 1)
+	{
+#ifdef GAUSS
+	  str_output("let _iy = ");
+#elif defined MATLAB || defined SCILAB
+	  str_output("iy_ = [");
+#endif
+	}
+      else
+	{
+#ifdef GAUSS
+	  str_output("let temp =");
+#elif defined MATLAB || defined SCILAB
+	  str_output("temp = [");
+#endif
+	}
+      for( m=0 ; m < endo_nbr ; m++ )
+	{
+	  if (iy[i] == 1)
+	    {
+	      iy[i] = j;
+	      str_output(" ");
+	      i_output(j);
+	      j++;
+	    }
+	  else 
+	    {
+	      str_output(" 0");
+	    }
+	  i++;
+	}
+#ifdef GAUSS
+      str_output(";\n");
+#elif defined MATLAB || defined SCILAB
+      str_output("];\n");
+#endif
+      if (k==1) 
+	{
+#ifdef GAUSS
+	  str_output("_iy = _iy';\n");
+#endif
+	}
+      else
+	{
+#ifdef GAUSS
+	  str_output("_iy = _iy | (temp');\n");
+#elif defined MATLAB || defined SCILAB
+	  str_output("iy_ = [ iy_ ; temp ];\n");
+#endif
+	}
+    }
+
+#ifdef GAUSS
+  str_output("_ykmin = ");
+  i_output(y_max_lag);
+  str_output(";\n_ykmax = ");
+  i_output(y_max_lead);
+  str_output(";\n_xkmin = ");
+  i_output(x_max_lag);
+  str_output(";\n_xkmax = ");
+  i_output(x_max_lead);
+  str_output(";\n_zkmin = ");
+  i_output(z_max_lag);
+  str_output(";\n_zkmax = ");
+  i_output(z_max_lead);
+  str_output(";\n");
+  sprintf(buffer,"_ys = zeros(%d,1);\n",endo_nbr);
+  str_output(buffer);
+  if (exo_nbr > 0)
+    {
+      sprintf(buffer,"_exe = zeros(%d,1);\n",exo_nbr);
+      str_output(buffer);
+    }
+#elif defined MATLAB || defined SCILAB
+  str_output("ykmin_ = ");
+  i_output(y_max_lag);
+  str_output(";\nykmax_ = ");
+  i_output(y_max_lead);
+  str_output(";\nxkmin_ = ");
+  i_output(x_max_lag);
+  str_output(";\nxkmax_ = ");
+  i_output(x_max_lead);
+  str_output(";\nzkmin_ = ");
+  i_output(z_max_lag);
+  str_output(";\nzkmax_ = ");
+  i_output(z_max_lead);
+  str_output(";\n");
+  sprintf(buffer,"ys_ = zeros(%d,1);\n",endo_nbr);
+  str_output(buffer);
+  if (exo_nbr)
+    {
+      sprintf(buffer,"exe_ = zeros(%d,1);\n",exo_nbr);
+      str_output(buffer);
+    }
+  if (exo_det_nbr)
+    {
+      sprintf(buffer,"exe_det_ = zeros(%d,1);\n",exo_det_nbr);
+      str_output(buffer);
+    }
+
+#endif
+print_model1(p,0);
+print_model1(p,1);
+}
+
+void print_model1(struct queue *p, int flag_steady)
+{
+  struct queue **p_q;
+  struct token **p_t;
+  int i,j,k;
+
+#ifdef GAUSS
+  if (flag_steady == 0)
+    {
+      str_output("\nproc _ff(y);\n");
+    }
+  else
+    {
+      str_output("\nproc _fff(y);\n");
+    }
+  str_output("local z;\n");
+
+  str_output("z=zeros(");
+  i_output(endo_nbr);
+  str_output(",1);\n");
+#elif defined MATLAB || defined SCILAB
+  FILE *f_temp;
+  char fmod_name[200];
+  
+  f_temp = f_out;
+  if (flag_steady == 0)
+    {
+      strcpy(fmod_name,fname);
+      strcat(fmod_name,"_ff.");
+      strcat(fmod_name,FILE_EXT);
+      f_out = fopen(fmod_name,"w");
+      strcpy(fmod_name,"\nfunction z=");
+      strcat(fmod_name,fname);
+      strcat(fmod_name,"_ff(y)\n");
+      str_output(fmod_name);
+    }
+  else
+    {
+      strcpy(fmod_name,fname);
+      strcat(fmod_name,"_fff.");
+      strcat(fmod_name,FILE_EXT);
+      f_out = fopen(fmod_name,"w");
+      strcpy(fmod_name,"\nfunction z=");
+      strcat(fmod_name,fname);
+      strcat(fmod_name,"_fff(y)\n");
+      str_output(fmod_name);
+    }
+
+  str_output("z=zeros(");
+  i_output(endo_nbr);
+  str_output(",1);\n");
+
+#ifdef MATLAB
+  str_output("global ex_ ex_det_ it_ recur_\n");
+#endif
+
+  param_nbr = 0;
+  for ( i=0; i < var_nbr; i++ )
+    {
+      if (var_list[i].endo_exo == 4){
+	var_list[i].nbr=param_nbr;
+	if ((param_nbr % 10)== 0 ) str_output("\nglobal ");
+	str_output(var_list[i].name);
+	str_output(" ");
+	param_nbr++;
+      }
+    }
+  str_output("\n");
+#endif
+
+  p_q=(struct queue **)p->ptr;
+  k=1;
+  for (i=0;i < p->imax;i++){
+    p_t=(struct token **)(*p_q)->ptr;
+    if ((*p_q)->flag == 0){
+#ifdef GAUSS
+      str_output("z[");
+      i_output(k);
+      str_output("] = ");
+#elif defined MATLAB || defined SCILAB
+      str_output("z(");
+      i_output(k);
+      str_output(") = ");
+#endif
+      k++;
+    }
+    for (j=0;j < (*p_q)->imax;j++){
+      if ((*p_t)->nbr == -1)  str_output((*p_t)->name);
+      else var_output(*p_t,flag_steady);
+      p_t++;
+    }
+    str_output(";\n");
+    p_q++;
+  }
+  // check number of equations
+  check.eq_nbr = k-1;
+#ifdef GAUSS
+  str_output("retp(z);\n");
+  str_output("endp;\n");
+#elif defined MATLAB || defined SCILAB
+  if (flag_steady == 1)
+    {
+      str_output("if ~isreal(z)\n");
+      str_output("  z = real(z)+imag(z).^2;\n");
+      str_output("end\n");
+    }
+  fclose(f_out);
+  f_out = f_temp;
+#endif
+}
+
+void var_output(struct token * p_t, int flag_steady)
+{
+  char buffer[200];
+  int i;
+  if (p_t->endo_exo == 1){
+#ifdef GAUSS
+    if (flag_steady == 0)
+      {      
+	sprintf(buffer,"y[%d]",iy[(y_max_lag+p_t->lead_lag)*(endo_nbr)+(p_t->nbr)]);
+      }
+    else
+      {
+	sprintf(buffer,"y[%d]",p_t->nbr+1);
+      }
+#elif defined MATLAB || defined SCILAB
+    if (flag_steady == 0)
+      {      
+	sprintf(buffer,"y(%d)",iy[(y_max_lag+p_t->lead_lag)*(endo_nbr)+(p_t->nbr)]);
+      }
+    else
+      {
+	sprintf(buffer,"y(%d)",p_t->nbr+1);
+      }
+#endif
+    str_output(buffer);
+  }
+  else if (p_t->endo_exo == 0){
+    i=p_t->lead_lag+x_max_lag-y_max_lag;
+#ifdef GAUSS
+    if (flag_steady == 1) sprintf(buffer,"_exe[%d]",p_t->nbr+1);
+    else if (i == 0) sprintf(buffer,"_ex[_it,%d]",p_t->nbr+1);
+    else sprintf(buffer,"_ex[_it%+d,%d]",i,p_t->nbr+1);
+#elif defined MATLAB || defined SCILAB
+    if (flag_steady == 1) sprintf(buffer,"exe_[%d]",p_t->nbr+1);
+    if (i == 0) sprintf(buffer,"ex_(it_,%d)",p_t->nbr+1);
+    else sprintf(buffer,"ex_(it_%+d,%d)",i,p_t->nbr+1);
+#endif
+    str_output(buffer);
+  }
+  else if (p_t->endo_exo == 3){
+    i=p_t->lead_lag+z_max_lag-y_max_lag;
+#ifdef GAUSS
+    if (flag_steady == 1) sprintf(buffer,"_recurs[%d]",p_t->nbr+1);
+    else if (i == 0) sprintf(buffer,"_recur[_it,%d]",p_t->nbr+1);
+    else sprintf(buffer,"_recur[_it%+d,%d]",i,p_t->nbr+1);
+#elif defined MATLAB || defined SCILAB
+    if (flag_steady == 1) sprintf(buffer,"recurs_[%d]",p_t->nbr+1);
+    else if (i == 0) sprintf(buffer,"recur_(it_,%d)",p_t->nbr+1);
+    else sprintf(buffer,"recur_(it_%+d,%d)",i,p_t->nbr+1);
+#endif
+    str_output(buffer);
+  }
+  else if (p_t->endo_exo == 4){
+    str_output(p_t->name);
+  }
+  else if (p_t->endo_exo == 5){
+    i=p_t->lead_lag;
+#ifdef GAUSS
+    if (flag_steady == 1) sprintf(buffer,"_exe_det[%d]",p_t->nbr+1);
+    else if (i == 0) sprintf(buffer,"_ex_det[_it,%d]",p_t->nbr+1);
+    else sprintf(buffer,"_ex_det[_it%+d,%d]",i,p_t->nbr+1);
+#elif defined MATLAB || defined SCILAB
+    if (flag_steady == 1) sprintf(buffer,"exe_det_[%d]",p_t->nbr+1);
+    if (i == 0) sprintf(buffer,"ex_det_(it_,%d)",p_t->nbr+1);
+    else sprintf(buffer,"ex_det_(it_%+d,%d)",i,p_t->nbr+1);
+#endif
+    str_output(buffer);
+  }
+}
+
+void p_i_shocks(ms_flag)
+{
+  char buff[2000];
+#ifdef GAUSS
+  str_output("/* (M)SHOCKS */\n");
+  str_output("if not _valf;\n");
+  str_output("  _ex[_xkmin+1:_iter+_xkmin+_xkmax,.]=ones(_iter+_xkmax,1).*_exe';\n");
+  str_output("endif;\n");
+#elif defined MATLAB
+  str_output("% (M)SHOCKS \n");
+  str_output("make_ex_;\n");
+  sprintf(buff,"shocks_file(%d);\n",ms_flag);
+  str_output(buff);
+#elif defined SCILAB
+  str_output("// (M)SHOCKS \n");
+  str_output("make_ex_();\n");
+#endif
+}
+
+void p_e_shocks(void)
+{
+  char buffer[2000];
+#if defined MATLAB || defined SCILAB
+  if (ex_det_length > 0)
+    {
+      sprintf(buffer,"M_.ex_det_length = %d;\n",ex_det_length);
+      str_output(buffer);
+    }
+#endif
+}
+
+void dynare_init(char* fname,struct s_runtime_options runtime_options)
+{
+  char buf[200];
+#ifdef GAUSS
+#ifdef OXGAUSS_GNU
+  str_output("library pgraph_gnu;\n");
+#else
+  str_output("library pgraph;\n");
+#endif
+#ifdef OXGAUSS
+  str_output("#include dynare1.src;\n");
+  str_output("#include dynare2.src;\n");
+  str_output("#include dynare3.src;\n");
+#endif
+  str_output("clear _scalv,_ex,_ys,_y,_exe,_recur,_recurs,_lgy,_lgx,_lgr;\n");
+  str_output("_dsmpl=0;\n_dynatol=0.00001;\n_maxit=10;\n_slowc=1;\n");
+  sprintf(buf,"_logname = \"%s.log\";\n",fname);
+  str_output(buf);
+  sprintf(buf,"output file = %s.log reset;\n",fname);
+  str_output(buf);
+#elif defined MATLAB
+  if (runtime_options.clearall == 1)
+    {
+      str_output("clear all\n");
+    }
+  str_output("global scalv_ ex_ ex_det_ recur_ recurs_ ys_ y_ exe_ exe_det_ lgy_ lgx_ lgx_det_ lgr_ dsmpl_ endval_\n");
+  str_output("global endo_nbr exo_nbr exo_det_nbr iy_  ykmin_  ykmax_  xkmin_  xkmax_ zkmin_ zkmax_ iter_\n"); 
+  str_output("global dynatol_ slowc_ maxit_ valf_ ys0_ recurs0_ ex0_ timing_ ct_ gstep_ Sigma_e_ fname_ lgx_orig_ord_ iter_ options_ dr_ oo_ trend_coeff_ eigenvalues_\n");
+  str_output("global M_\n");
+  str_output("M_.ex_det_length = 0;\n");
+  str_output("M_.dname = '");
+  str_output(fname);
+  str_output("';\n");
+  str_output("endo_nbr=0;exo_nbr=0;exo_det_nbr=0;\n");
+  str_output("dsmpl_=0;\ndynatol_=0.00001;\nmaxit_=10;\nslowc_=1;\ntiming_=0;\nct_=0;\ngstep_=1e-2;\n");
+  str_output("endval_=0;rplottype_=0;\nvalf_=0;\n");
+  str_output("y_=[];\nex_=[];\nex_det_=[];\n");
+  sprintf(buf,"fname_ = '%s';\n",fname);
+  str_output(buf);
+  sprintf(buf,"logname_ = '%s.log';\n",fname);
+  str_output(buf);
+  sprintf(buf,"diary off;\nwarning off;\ndelete %s.log;\nwarning on;\nwarning backtrace;\n",fname);
+  str_output(buf);
+  sprintf(buf,"diary %s.log;\n",fname);
+  str_output(buf);
+  str_output("options_ = [];\n");
+#elif defined SCILAB
+  str_output("clear\nclearglobal()\n");
+  str_output("global ex_ ex_det_ y_ ys_ dsmpl_ i_exo_var_ iter_ options_ dr_\n");
+  str_output("dsmpl_=0;\ndynatol_=0.00001;\nmaxit_=10;\nslowc_=1;\ntiming_=0;\nct_=0;\ngstep_=1e-2;\ndebug_=0;\nrecurs_=[];\nstart_simul=[];\n");
+  str_output("endval_=0;rplottype_=0;\nvalf_=0;\n");
+  sprintf(buf,"fname_ = '%s';\n",fname);
+  str_output(buf);
+  sprintf(buf,"logname_ = '%s.log';\n",fname);
+  str_output(buf);
+  str_output("fh_log=mopen(logname_,'w');\n");
+  sprintf(buf,"getf('%s_ff.sci');\n",fname);
+  str_output(buf);
+  sprintf(buf,"getf('%s_fff.sci');\n",fname);
+  str_output(buf);
+  str_output("options_=tlist('opt');\n");
+#endif
+
+  varexo=strdup("");
+  
+}
+
+
+void add_tmpvar(name1,name2)
+char *name1,*name2;
+{
+  int static tmpvar_size = 0;
+
+  if ( nbr_tmpvar+2 > tmpvar_size )
+    {
+      tmpvar_list = realloc(tmpvar_list, 200*sizeof(char *));
+      tmpvar_size += 200;
+    }
+
+  tmpvar_list[nbr_tmpvar] = name1;
+  nbr_tmpvar++;
+  tmpvar_list[nbr_tmpvar] = name2;
+  nbr_tmpvar++;
+}
+
+void dyn2vec(flag)
+     int flag;                           /* flag: one or two names */
+{
+  int i;
+  char buffer[200];
+  if (flag == 0)
+    {
+#if defined GAUSS
+      str_output("dyn2vec;\n");
+#elif defined MATLAB || defined SCILAB
+      str_output("global ");
+      for(i=0;i < var_nbr; i++)
+	{
+	  if (var_list[i].endo_exo == 1)
+	    {
+	      str_output(var_list[i].name);
+	      str_output(" ");
+	    }
+	}
+      str_output("\ndyn2vec;\n");
+#endif
+    }
+  else
+    {
+#ifdef GAUSS
+      str_output("clear ");
+      str_output(tmpvar_list[(tmpvar_list[1]?1:0)]);
+      for( i = 2; i < nbr_tmpvar; i+=2)
+	{
+	  str_output(", ");
+	  str_output(tmpvar_list[i+(tmpvar_list[i+1]?1:0)]);
+	}
+      str_output(";\n");
+      for( i = 0; i < nbr_tmpvar; i+=2)
+	{
+	  if (tmpvar_list[i+1])
+	    {
+	      sprintf(buffer,"dyn2vec %s %s;\n",tmpvar_list[i],tmpvar_list[i+1]);
+	    }
+	  else
+	    {
+	      sprintf(buffer,"dyn2vec %s;\n",tmpvar_list[i]);
+	    }
+	  str_output(buffer);
+	}
+#elif defined MATLAB || defined SCILAB
+      str_output("global ");
+      for( i = 0; i < nbr_tmpvar; i+=2)
+	{
+	  str_output(tmpvar_list[i+(tmpvar_list[i+1]?1:0)]);
+	  str_output(" ");
+	}
+      str_output("\n");
+      for( i = 0; i < nbr_tmpvar; i+=2)
+	{
+	  if (tmpvar_list[i+1] > 0)
+	    {
+	      sprintf(buffer,"dyn2vec('%s', '%s');\n",tmpvar_list[i],tmpvar_list[i+1]);
+	    }
+	  else
+	    {
+	      sprintf(buffer,"dyn2vec('%s');\n",tmpvar_list[i]);
+	    }
+	  str_output(buffer);
+	}
+#endif
+    }
+
+}
+
+void print_rplot(void)
+{
+  int i;
+  char buffer[200];
+
+#ifdef GAUSS
+  strcpy(buffer,"rplot");
+  for(i=0;i<nbr_tmpvar;i+=2)
+    {
+      strcat(buffer," ");
+      strcat(buffer,tmpvar_list[i]);
+    }
+  strcat(buffer," ;\n");
+#elif defined MATLAB || defined SCILAB
+  strcpy(buffer,"plot_list_ = '");
+  strcat(buffer,tmpvar_list[0]);
+  strcat(buffer,"';\n");
+  for(i=2;i<nbr_tmpvar;i+=2)
+    {
+#ifdef MATLAB
+      strcat(buffer,"plot_list_ = str2mat(plot_list_,'");
+      strcat(buffer,tmpvar_list[i]);
+      strcat(buffer,"');\n");
+#else
+      strcat(buffer,"plot_list_ = [plot_list_;'");
+      strcat(buffer,tmpvar_list[i]);
+      strcat(buffer,"'];\n");
+#endif
+    }
+  strcat(buffer,"rplot(plot_list_, rplottype_) ;\n");
+#endif
+  str_output(buffer);
+}
+
+
+void print_iter(char *s)
+{
+#ifdef GAUSS
+  fprintf(f_out,"\n_iter = %s;\n",s);
+#elif defined MATLAB || defined SCILAB
+  fprintf(f_out,"\niter_ = %s;\n",s);
+  fprintf(f_out,"options_.periods = %s;\n",s);
+#endif
+}
+
+struct loop *initial_loop (char *name, char *initial, char *limit, char *increment)
+{
+  struct loop *loop;
+
+  loop = (struct loop *)calloc(1,sizeof(struct loop));
+
+  loop->loop_index = atoi(initial);
+  loop->loop_limit = atoi(limit);
+  loop->loop_increment = atoi(increment);
+  loop->loop_index_name = strdup(name);
+
+  add_var(name,2);
+  var_list[var_nbr-1].nbr = 0;
+  sort_var();
+
+  return loop;
+}
+
+struct queue *do_loop(struct loop *loop, struct queue *q_eq1)
+{
+  struct queue *q_eq2,**p_q1,**p_q2;
+  int i;
+
+  q_eq2 = (struct queue *)calloc(1,sizeof(struct queue));
+
+  q_eq2->ptr = (void **)calloc(1,sizeof(void *));
+  q_eq2->imax = 0;
+  while (loop->loop_index <= loop->loop_limit)
+    {
+      q_eq2->ptr=(void **)realloc(q_eq2->ptr,(q_eq2->imax+q_eq1->imax)*sizeof(void *));
+      p_q1=(struct queue **)q_eq1->ptr;
+      p_q2=(struct queue **)q_eq2->ptr+q_eq2->imax;
+      q_eq2->imax += q_eq1->imax;
+      for (i=0;i < q_eq1->imax;i++){
+	*p_q2=(struct queue *)calloc(1,sizeof(struct queue));
+	(*p_q2)->flag=(*p_q1)->flag;
+	(*p_q2)->ptr=(void **)calloc((*p_q1)->imax,sizeof(struct token *));
+	(*p_q2)->imax=0;
+	copy_update_indexed_var((struct token **)(*p_q1)->ptr, *p_q2,(*p_q1)->imax,loop->loop_index_name,loop->loop_index);
+	p_q1++;
+	p_q2++;
+      }
+      loop->loop_index++;
+    }
+
+  return q_eq2;
+}
+
+void copy_update_indexed_var(struct token **p_t1, struct queue  *q2, int imax, char *index_name, int index)
+{
+  struct token **p_t3,**p_end;
+  char buffer[200];
+  int j, flag;
+  struct var *p_var;
+
+  p_end = p_t1+imax;
+  for (j=0;j < imax;j++){
+    if ((*p_t1)->nbr == -3){
+      flag=1;
+      for (p_t3=p_t1+1; p_t3 < p_end; p_t3++){
+	if ((*p_t3)->nbr != -3){
+	  break;
+	}
+	if ((*p_t3)->name != NULL ){
+	  if (strcmp(index_name,(*p_t3)->name) == 0){
+	    (*p_t3)->lead_lag = index;
+	  }
+	  else{
+	    flag=0;
+	  }
+	}
+      }
+      p_t3=p_t1;
+      if (flag == 1){
+	strcpy(buffer,(*p_t3)->name);
+	flag = 0;
+	for (p_t3=p_t1+1; p_t3 < p_end; p_t3++){
+	  if ((*p_t3)->nbr != -3){
+	    break;
+	  }
+	  if ((*p_t3)->name == NULL || strcmp(index_name,(*p_t3)->name) == 0){
+	    if (flag == 0){
+	      sprintf(buffer+strlen(buffer),"%d\0",(*p_t3)->lead_lag);
+	      flag = 1;
+	    }
+	    else{
+	      sprintf(buffer+strlen(buffer),"_%d\0",(*p_t3)->lead_lag);
+	    }
+	  }
+	  else{
+	    strcat(buffer,(*p_t3)->name);
+	  }
+	}
+	p_var=var_search(buffer);
+	if (p_var == NULL){
+	  fprintf(stdout,"%s is not an indexed variable\n",buffer);
+	}
+	else if (p_var->endo_exo == 3){
+	  add_to_queue(q2,token(p_var->name,-1));
+	}
+	else{
+	  add_to_queue(q2,create_var(p_var));
+	}
+	set_ll1((struct token *)(q2->ptr)[q2->imax-1],(*p_t1)->lead_lag);
+      }
+      else{
+	add_to_queue(q2,token((*p_t3)->name,(*p_t3)->nbr));
+	for (p_t3=p_t1+1; p_t3 < p_end; p_t3++){
+	  if ((*p_t3)->nbr != -3){
+	    break;
+	  }
+	  if ((*p_t3)->name == NULL || strcmp(index_name,(*p_t3)->name) == 0){
+	    add_to_queue(q2,token(NULL,-3));
+	    ((struct token *)(q2->ptr)[q2->imax-1])->lead_lag=(*p_t3)->lead_lag;
+	  }
+	  else{
+	    add_to_queue(q2,token((*p_t3)->name,-3));
+	  }
+	}
+      }      
+      j += p_t3-p_t1-1;
+      p_t1 = p_t3-1;
+    }
+    else if ((*p_t1)->nbr == -2 && strcmp(index_name,(*p_t1)->name) == 0){
+      sprintf(buffer,"%d\0",index);
+      add_to_queue(q2,token(strdup(buffer),-1));
+      ((struct token *)(q2->ptr)[q2->imax-1])->lead_lag=(*p_t1)->lead_lag;
+      ((struct token *)(q2->ptr)[q2->imax-1])->endo_exo=(*p_t1)->endo_exo;
+    }
+    else if ((*p_t1)->nbr == -1){
+      add_to_queue(q2,token((*p_t1)->name,-1));
+      ((struct token *)(q2->ptr)[q2->imax-1])->lead_lag=(*p_t1)->lead_lag;
+      ((struct token *)(q2->ptr)[q2->imax-1])->endo_exo=(*p_t1)->endo_exo;
+    }
+    else {
+      if ((*p_t1)->name == NULL || (strcmp(index_name,(*p_t1)->name) != 0)){
+	add_to_queue(q2,token((*p_t1)->name,(*p_t1)->nbr));
+	((struct token *)(q2->ptr)[q2->imax-1])->lead_lag=(*p_t1)->lead_lag;
+      }
+      else{
+	add_to_queue(q2,token(NULL,(*p_t1)->nbr));
+	set_ll1((struct token *)(q2->ptr)[q2->imax-1],index);
+      }
+      ((struct token *)(q2->ptr)[q2->imax-1])->lead_lag=(*p_t1)->lead_lag;
+      ((struct token *)(q2->ptr)[q2->imax-1])->endo_exo=(*p_t1)->endo_exo;
+    }
+    p_t1++;
+  }
+}
+
+struct queue *operator_loop(struct loop *loop, struct queue *q1, char *oper)
+{
+  struct queue *q2;
+
+  q2=create_queue(token("((",-1));
+  copy_update_indexed_var((struct token **)q1->ptr, q2,q1->imax,loop->loop_index_name,loop->loop_index);
+  loop->loop_index++;
+  add_to_queue(q2,token(")",-1));
+  while (loop->loop_index <= loop->loop_limit){
+      add_to_queue(q2,token(oper,-1));
+      q2=add_to_queue(q2,token("(",-1));
+      copy_update_indexed_var((struct token **)q1->ptr, q2,q1->imax,loop->loop_index_name,loop->loop_index);
+      add_to_queue(q2,token(")",-1));
+      loop->loop_index++;
+  }
+  add_to_queue(q2,token(")",-1));
+     
+  return q2;
+}
+
+void p_steady(struct queue *p)
+{
+  //  print_model1(p,1);
+  str_output("steady(0);\n");
+}
+
+void p_steady_linear(struct queue *p)
+{
+  //  print_model1(p,1);
+  str_output("steady(1);\n");
+}
+
+void print_param(void)
+{
+  int i;
+
+  sort_var();
+
+#if defined MATLAB || defined SCILAB
+  param_nbr = 0;
+  for ( i=0; i < var_nbr; i++ )
+    {
+      if (var_list[i].endo_exo == 4){
+	var_list[i].nbr=param_nbr;
+	if ((param_nbr % 10)== 0 ) str_output("\nglobal ");
+	str_output(var_list[i].name);
+	str_output(" ");
+	param_nbr++;
+      }
+    }
+  str_output("\n");
+#endif
+}
+
+void p_stoch_simul()
+{
+  char buffer[2000];
+  int i;
+  check.stoch_simul = 1;
+#ifdef SCILAB
+  str_output("global ");
+  for(i=0;i < var_nbr; i++)
+    {
+      if (var_list[i].endo_exo == 1)
+	{
+	  str_output(var_list[i].name);
+	  str_output(" ");
+	}
+    }
+  str_output("\n");
+#endif
+#if defined MATLAB || defined SCILAB
+  if (nbr_tmpvar == 0)
+    {
+      str_output("var_list_ = [];\n");
+    }
+  else
+    {
+      strcpy(buffer,"var_list_ = '");
+      strcat(buffer,tmpvar_list[0]);
+      strcat(buffer,"';\n");
+      for(i=2;i<nbr_tmpvar;i+=2)
+	{
+#ifdef MATLAB
+	  strcat(buffer,"var_list_ = str2mat(var_list_,'");
+	  strcat(buffer,tmpvar_list[i]);
+	  strcat(buffer,"');\n");
+#else
+	  strcat(buffer,"var_list_ = [var_list_;'");
+	  strcat(buffer,tmpvar_list[i]);
+	  strcat(buffer,"'];\n");
+#endif
+	}
+      str_output(buffer);
+    }
+  str_output("info=stoch_simul(var_list_);\n");
+#endif
+}
+
+void p_resol(int dr_algo, int linear, int order, struct queue *p)
+{
+  char buffer[200];
+  //  print_model1(p,1);
+  sprintf(buffer,"dr_ = resol(ys_,%d,%d,%d);\n",dr_algo,linear,order);
+  str_output(buffer);
+}
+
+void p_simul( void )
+{
+  check.simul = 1;
+  str_output("simul(dr_);\n");
+}
+
+void p_dsample(int nargs, char *arg1, char *arg2)
+{
+#ifdef GAUSS
+  str_output("dsample ");
+  if (nargs > 0)
+    {
+      str_output(arg1);
+    }
+  if (nargs > 1)
+    {
+      str_output(" ");
+      str_output(arg2);
+    }
+#elif defined MATLAB || defined SCILAB
+  str_output("dsample");
+  if (nargs > 0)
+    {
+      str_output("(");
+      str_output(arg1);
+      if (nargs > 1)
+	{
+	  str_output(",");
+	  str_output(arg2);
+	}
+      str_output(")");
+    }
+#endif  
+  str_output(";\n");
+}
+
+void p_check(void)
+{
+  check.check = 1;
+#if defined MATLAB || defined GAUSS
+  str_output("check;\n");
+#else
+  str_output("check();\n");
+#endif
+}
+
+void p_irf(char * varexo, double shock_size, int iter, int drop, int replic, int order)
+{
+  char buffer[200];
+  int i;
+#if defined MATLAB || defined SCILAB
+  if (nbr_tmpvar == 0)
+    {
+      str_output("var_list_ = '';\n");
+    }
+  else
+    {
+      strcpy(buffer,"var_list_ = '");
+      strcat(buffer,tmpvar_list[0]);
+      strcat(buffer,"';\n");
+      for(i=2;i<nbr_tmpvar;i+=2)
+	{
+#ifdef MATLAB
+	  strcat(buffer,"var_list_ = str2mat(var_list_,'");
+	  strcat(buffer,tmpvar_list[i]);
+	  strcat(buffer,"');\n");
+#else
+	  strcat(buffer,"var_list_ = [var_list_;'");
+	  strcat(buffer,tmpvar_list[i]);
+	  strcat(buffer,"'];\n");
+#endif
+	}
+      str_output(buffer);
+    }
+  sprintf(buffer,"y_=irf(dr_,'%s',%f,%d,%d,%d,%d,var_list_);\n",varexo,shock_size,iter+drop,drop,replic,order);
+#endif
+  str_output(buffer);
+}
+
+void p_d_corr()
+{
+  char buffer[2000];
+  int i,flag;
+  strcpy(buffer,"d_corr(");
+  flag = 0;
+  if (nbr_tmpvar == 0)
+    {
+      for (i=0; i < var_nbr; i++)
+	{
+	  if ( var_list[i].endo_exo == 1)
+	    {
+	      if (flag > 0)
+		{
+		  strcat(buffer,",");
+		}
+	      strcat(buffer,"'");
+	      strcat(buffer,var_list[i].name);
+	      strcat(buffer,"'");
+	      flag = 1;
+	    }
+	}
+    }
+  else
+    {
+      for(i=0;i<nbr_tmpvar;i+=2)
+	{
+	  if (flag > 0)
+	    {
+	      strcat(buffer,",");
+	    }
+	  strcat(buffer,"'");
+	  strcat(buffer,tmpvar_list[i]);
+	  strcat(buffer,"'");
+	  flag = 1;
+	}
+    }
+  strcat(buffer,");\n");
+  str_output(buffer);
+}
+
+void p_disp_dr(order)
+{
+  char buffer[200];
+  int i;
+#if defined MATLAB || defined SCILAB
+  if (nbr_tmpvar == 0)
+    {
+      str_output("var_list_ = '';\n");
+    }
+  else
+    {
+      strcpy(buffer,"var_list_ = '");
+      strcat(buffer,tmpvar_list[0]);
+      strcat(buffer,"';\n");
+      for(i=2;i<nbr_tmpvar;i+=2)
+	{
+#ifdef MATLAB
+	  strcat(buffer,"var_list_ = str2mat(var_list_,'");
+	  strcat(buffer,tmpvar_list[i]);
+	  strcat(buffer,"');\n");
+#else
+	  strcat(buffer,"var_list_ = [var_list_;'");
+	  strcat(buffer,tmpvar_list[i]);
+	  strcat(buffer,"'];\n");
+#endif
+	}
+      str_output(buffer);
+    }
+  sprintf(buffer,"disp_dr(dr_,%d,var_list_);\n",order);
+#endif
+  str_output(buffer);
+}
+
+void p_disp_moments(order)
+{
+  char buffer[200];
+  int i;
+#if defined MATLAB || defined SCILAB
+  if (nbr_tmpvar == 0)
+    {
+      str_output("var_list_ = '';\n");
+    }
+  else
+    {
+      strcpy(buffer,"var_list_ = '");
+      strcat(buffer,tmpvar_list[0]);
+      strcat(buffer,"';\n");
+      for(i=2;i<nbr_tmpvar;i+=2)
+	{
+#ifdef MATLAB
+	  strcat(buffer,"var_list_ = str2mat(var_list_,'");
+	  strcat(buffer,tmpvar_list[i]);
+	  strcat(buffer,"');\n");
+#else
+	  strcat(buffer,"var_list_ = [var_list_;'");
+	  strcat(buffer,tmpvar_list[i]);
+	  strcat(buffer,"'];\n");
+#endif
+	}
+      str_output(buffer);
+    }
+  sprintf(buffer,"disp_moments(y_,%d,var_list_);\n",order);
+#endif
+  str_output(buffer);
+}
+
+void p_optim_weights_init(void)
+{
+  str_output(OPEN_COMMENTS);
+  str_output(" OPTIM_WEIGHTS\n");
+  str_output(CLOSE_COMMENTS);
+
+#if defined MATLAB
+  str_output("optim_weights_ = sparse(endo_nbr,endo_nbr);\n");
+  str_output("obj_var_ = [];\n\n");
+#endif
+}
+
+void p_optim_weights1(struct token* p_t, struct queue* p_q)
+{
+  char buffer[200];
+
+  if (p_t->endo_exo != 1 && p_t->endo_exo != 3)
+    {
+      fprintf(stdout,"OPTIM_WEIGHTS ERROR: only endogenous variables can have weights" );
+      exit(1);
+    }
+
+  sprintf(buffer,"optim_weights_(%d,%d) = ",p_t->nbr+1,p_t->nbr+1);
+  str_output(buffer);
+  p_expression(p_q);
+  str_output(";\n");
+  sprintf(buffer,"obj_var_ = [obj_var_; %d];\n",p_t->nbr+1);
+  str_output(buffer);
+}
+
+void p_optim_weights2(struct token* p_t1, struct token* p_t2, struct queue* p_q)
+{
+  char buffer[200];
+
+  if ((p_t1->endo_exo != 1 && p_t1->endo_exo != 3) || (p_t2->endo_exo != 1 && p_t2->endo_exo != 3))
+    {
+      fprintf(stdout,"OPTIM_WEIGHTS ERROR: only endogenous variables can have weights" );
+      exit(1);
+    }
+
+  sprintf(buffer,"optim_weights_(%d,%d) = ",p_t1->nbr+1,p_t2->nbr+1);
+  str_output(buffer);
+  p_expression(p_q);
+  str_output(";\n");
+  sprintf(buffer,"optim_weights_(%d,%d) = optim_weights_(%d,%d);\n",p_t2->nbr+1,p_t1->nbr+1,p_t1->nbr+1,p_t2->nbr+1);
+  str_output(buffer);
+  sprintf(buffer,"obj_var_ = [obj_var_; %d];\n",p_t1->nbr+1);
+  sprintf(buffer,"obj_var_ = [obj_var_; %d];\n",p_t2->nbr+1);
+}
+
+void p_expression(struct queue* q)
+{
+  struct token** p_t;
+  char buffer[200];
+  int j;
+
+  p_t=(struct token **)q->ptr;
+  for (j=0;j < q->imax;j++){
+    if ((*p_t)->nbr == -1)  str_output((*p_t)->name);
+    else if ((*p_t)->endo_exo == 1)
+      {
+#ifdef GAUSS
+	sprintf(buffer,"_ys[%d]",(*p_t)->nbr+1);
+#elif defined MATLAB || defined SCILAB
+	sprintf(buffer,"ys_(%d)",(*p_t)->nbr+1);
+#endif
+	str_output(buffer);
+      }
+    else if ((*p_t)->endo_exo == 0)
+      {
+#ifdef GAUSS
+	sprintf(buffer,"_exe[%d]",(*p_t)->nbr+1);
+#elif defined MATLAB || defined SCILAB
+	sprintf(buffer,"exe_(%d)",(*p_t)->nbr+1);
+#endif
+ 	str_output(buffer);
+      }
+    else if ((*p_t)->endo_exo == 3)
+      {
+#ifdef GAUSS
+	sprintf(buffer,"_recurs[%d]",(*p_t)->nbr+1);
+#elif defined MATLAB || defined SCILAB
+	sprintf(buffer,"recurs_(%d)",(*p_t)->nbr+1);
+#endif
+ 	str_output(buffer);
+      }
+    else if ((*p_t)->endo_exo == 4)
+      {
+	sprintf(buffer,"%s",(*p_t)->name);
+ 	str_output(buffer);
+      }
+    else if ((*p_t)->endo_exo == 5)
+      {
+#ifdef GAUSS
+	sprintf(buffer,"_exe_det[%d]",(*p_t)->nbr+1);
+#elif defined MATLAB || defined SCILAB
+	sprintf(buffer,"exe_det_(%d)",(*p_t)->nbr+1);
+#endif
+ 	str_output(buffer);
+      }
+    p_t++;
+  }
+}
+
+void p_osr_params(char * name)
+{
+  static int flag = 0;
+  char buffer[200];
+
+#ifdef GAUSS
+  if ( flag == 0)
+    {
+      sprintf(buffer,"let string _osr_params = \"%s\";\n",name);
+      flag = 1;
+    }
+  else
+    {
+      sprintf(buffer,"osr_params = _osr_params | \"%s\";\n",name);
+    }
+#elif defined MATLAB
+  if ( flag == 0)
+    {
+      sprintf(buffer,"osr_params_ = '%s';\n",name);
+      flag = 1;
+    }
+  else
+    {
+      sprintf(buffer,"osr_params_ = str2mat(osr_params_,'%s');\n",name);
+    }
+#elif defined SCILAB
+  if ( flag == 0)
+    {
+      sprintf(buffer,"osr_params_ = '%s';\n",name);
+      flag = 1;
+    }
+  else
+    {
+      sprintf(buffer,"osr_params_ = [osr_params_;'%s'];\n",name);
+    }
+#endif
+  str_output(buffer);
+  str_output("\n");
+}
+
+void p_calib_init(void)
+{
+  int i;
+  char buffer[200];
+
+  str_output(OPEN_COMMENTS);
+  str_output(" CALIB_VAR ");
+  str_output(CLOSE_COMMENTS);
+  str_output("\n\n");
+
+#if defined MATLAB || defined SCILAB
+  for(i=1;i<4;++i)
+    {
+      sprintf(buffer,"calib_var_index{%d} = [];\ncalib_targets{%d} = [];\ncalib_weights{%d}=[];\n",i,i,i);
+      str_output(buffer);
+    }
+#endif
+}
+
+void p_calib_var(struct token* p_t, struct queue* p_q, char * weight)
+{
+  char buffer[200];
+  if (p_t->endo_exo == 1 || p_t->endo_exo == 3)
+    {
+      sprintf(buffer,"calib_var_index{1} = [calib_var_index{1};%d];\n",p_t->nbr+1);
+      str_output(buffer);
+      str_output("calib_targets{1} =[calib_targets{1}; ");
+      p_expression(p_q);
+      str_output("];\n");
+      sprintf(buffer,"calib_weights{1} = [calib_weights{1}; %s];\n",weight);
+      str_output(buffer);
+    }
+  else if (p_t->endo_exo == 0)
+    {
+      sprintf(buffer,"calib_var_index{3} = [calib_var_index{3};%d %d];\n",p_t->nbr+1,p_t->nbr+1);
+      str_output(buffer);
+      str_output("calib_targets{3} =[calib_targets{3}; ");
+      p_expression(p_q);
+      str_output("];\n");
+      sprintf(buffer,"calib_weights{3} = [calib_weights{3}; %s];\n",weight);
+      str_output(buffer);
+    }
+  else
+    {
+      printf("ERROR in CALIB: one of the targets isn't legitimate\n");
+    }
+}
+
+void p_calib_covar(struct token* p_t1, struct token* p_t2, struct queue* p_q, char * weight)
+{
+  char buffer[200];
+  if ((p_t1->endo_exo == 0 && p_t2->endo_exo == 1)|| (p_t1->endo_exo == 1 && p_t2->endo_exo == 0))
+    {
+      printf("ERROR in CALIB: can't target correlation between an endogenous and an exogenous variable\n");
+      exit(1);
+    }
+  else if (p_t1->endo_exo == 1 || p_t1->endo_exo == 3)
+    {
+      sprintf(buffer,"calib_var_index{2} = [calib_var_index{2};%d %d];\n",p_t1->nbr+1,p_t2->nbr+1);
+      str_output(buffer);
+      str_output("calib_targets{2} =[calib_targets{2}; ");
+      p_expression(p_q);
+      str_output("];\n");
+      sprintf(buffer,"calib_weights{2} = [calib_weights{2}; %s];\n",weight);
+      str_output(buffer);
+    }
+  else if (p_t1->endo_exo == 0)
+    {
+      sprintf(buffer,"calib_var_index{3} = [calib_var_index{2};%d %d];\n",p_t1->nbr+1,p_t2->nbr+1);
+      str_output(buffer);
+      str_output("calib_targets{3} =[calib_targets{3}; ");
+      p_expression(p_q);
+      str_output("];\n");
+      sprintf(buffer,"calib_weights{3} = [calib_weights{3}; %s];\n",weight);
+      str_output(buffer);
+    }
+  else
+    {
+      printf("ERROR in CALIB: one of the targets isn''t legitimate\n");
+      exit(1);
+    }
+}
+ 
+static int max_iar = 3;
+void p_calib_ac(struct token* p_t, char * ar, struct queue* p_q, char * weight)
+{
+  char buffer[200];
+  int i, iar;
+
+  iar = atoi(ar)+3;
+  if (iar > max_iar)
+    {
+      for(i=max_iar+1; i <= iar; ++i)
+	{
+	  sprintf(buffer,"calib_var_index{%d} = [];\ncalib_targets{%d} = [];\ncalib_weights{%d}=[];\n",i,i,i);
+	  str_output(buffer);
+	}
+      max_iar = iar;
+    }
+  sprintf(buffer,"calib_var_index{%d} = [calib_var_index{%d};%d];\n",iar,iar,p_t->nbr+1);
+  str_output(buffer);
+  sprintf(buffer,"calib_targets{%d} =[calib_targets{%d}; ",iar,iar);
+  str_output(buffer);
+  p_expression(p_q);
+  str_output("];\n");
+  sprintf(buffer,"calib_weights{%d} = [calib_weights{%d}; %s];\n",iar,iar,weight);
+  str_output(buffer);
+}
+
+void p_calib(int cova)
+{
+  char buffer[200];
+  sprintf(buffer,"Sigma_e_=calib(calib_var_index,calib_targets,calib_weights,%d,%d,Sigma_e_);\n",max_iar-3,cova);
+  str_output(buffer);
+}
+
+void p_dynatype(char *fname, char *ext)
+{
+  char buffer[2000];
+  int i;
+#ifdef SCILAB
+  str_output("global ");
+  for(i=0;i < var_nbr; i++)
+    {
+      if (var_list[i].endo_exo == 1)
+	{
+	  str_output(var_list[i].name);
+	  str_output(" ");
+	}
+    }
+  str_output("\n");
+#endif
+#if defined MATLAB || defined SCILAB
+  if (nbr_tmpvar == 0)
+    {
+      str_output("var_list_ = [];\n");
+    }
+  else
+    {
+      strcpy(buffer,"var_list_ = '");
+      strcat(buffer,tmpvar_list[0]);
+      strcat(buffer,"';\n");
+      for(i=2;i<nbr_tmpvar;i+=2)
+	{
+#ifdef MATLAB
+	  strcat(buffer,"var_list_ = str2mat(var_list_,'");
+	  strcat(buffer,tmpvar_list[i]);
+	  strcat(buffer,"');\n");
+#else
+	  strcat(buffer,"var_list_ = [var_list_;'");
+	  strcat(buffer,tmpvar_list[i]);
+	  strcat(buffer,"'];\n");
+#endif
+	}
+      str_output(buffer);
+    }
+  if (strlen(ext) == 0)
+    {
+      sprintf(buffer,"dynatype('%s',var_list_);\n",fname);
+    }
+  else
+    {
+      sprintf(buffer,"dynatype('%s.%s',var_list_);\n",fname,ext);
+    }
+#else
+  if (strlen(ext) == 0)
+    {
+      sprintf(buffer,"dynatype %s;\n",fname);
+    }
+  else
+    {
+      sprintf(buffer,"dynatype %s.%s;\n",fname,ext);
+    }
+
+#endif
+  str_output(buffer);
+}
+
+void p_dynasave(char *fname, char *ext)
+{
+  char buffer[2000];
+  int i;
+#ifdef SCILAB
+  str_output("global ");
+  for(i=0;i < var_nbr; i++)
+    {
+      if (var_list[i].endo_exo == 1)
+	{
+	  str_output(var_list[i].name);
+	  str_output(" ");
+	}
+    }
+  str_output("\n");
+#endif
+#if defined MATLAB || defined SCILAB
+  if (nbr_tmpvar == 0)
+    {
+      str_output("var_list_ = [];\n");
+    }
+  else
+    {
+      strcpy(buffer,"var_list_ = '");
+      strcat(buffer,tmpvar_list[0]);
+      strcat(buffer,"';\n");
+      for(i=2;i<nbr_tmpvar;i+=2)
+	{
+#ifdef MATLAB
+	  strcat(buffer,"var_list_ = str2mat(var_list_,'");
+	  strcat(buffer,tmpvar_list[i]);
+	  strcat(buffer,"');\n");
+#else
+	  strcat(buffer,"var_list_ = [var_list_;'");
+	  strcat(buffer,tmpvar_list[i]);
+	  strcat(buffer,"'];\n");
+#endif
+	}
+      str_output(buffer);
+    }
+  if (strlen(ext) == 0)
+    {
+      sprintf(buffer,"dynasave('%s',var_list_);\n",fname);
+    }
+  else
+    {
+      sprintf(buffer,"dynasave('%s.%s',var_list_);\n",fname,ext);
+    }
+#else
+  if (strlen(ext) == 0)
+    {
+      sprintf(buffer,"dynasave %s;\n",fname);
+    }
+  else
+    {
+      sprintf(buffer,"dynasave %s.%s;\n",fname,ext);
+    }
+
+#endif
+  str_output(buffer);
+}
+
+void p_sigma_e(struct queue *p_q)
+{
+  int up, i, j, i1, j1, p1, p2;
+  int* order;
+  int* po;
+  struct queue **p_q1;
+#if defined MATLAB || defined SCILAB
+  order = (int*)calloc(exo_nbr,sizeof(int));
+  po = order;
+  for (i = 0; i < var_nbr; ++i)
+    {
+      if (var_list[i].endo_exo == 0)
+	{
+	  *po++ = var_list[i].original_nbr;
+	}
+    }
+  str_output("Sigma_e_ = [\n");
+  p_q1 = (struct queue **)(p_q->ptr);
+  up = ((*p_q1)->imax > 1) ? 1 : 0;
+  for(i1=0; i1 < exo_nbr; ++i1)
+    {
+      if (i1 > 0)
+	{
+	  str_output(";\n");
+	}
+      i = order[i1];
+      for(j1=0; j1 < exo_nbr; ++j1)
+	{
+	  if (j1 > 0)
+	    {
+	      str_output(", ");
+	    }
+	  j = order[j1];
+	  if (j <= i)
+	    {
+	      if (up)
+		{
+		  p1 = j;
+		  p2 = i-j;
+		}
+	      else
+		{
+		  p1 = i;
+		  p2 = j;
+		}
+	    }
+	  else
+	    {
+	      if (up)
+		{
+		  p1 = i;
+		  p2 = j-i;
+		}
+	      else
+		{
+		  p1 = j;
+		  p2 = i;
+		}
+	    }
+		  p_expression(*(struct queue**)((*(struct queue**)(p_q1+p1))->ptr+p2));
+	}
+    }
+  str_output("\n];\n");
+  free(order);
+#endif
+}
+
+void tr_check(int row, int col)
+{
+  static int old_col = 0;
+  static int up_down = 0;
+  if (col == 0)
+    {
+      fprintf(stdout,"ERROR: empty row in Sigma_e!\n");
+      exit(1);
+    }
+  if ( row > exo_nbr || col > exo_nbr)
+    {
+      fprintf(stdout,"ERROR: Sigma_e has more rows or columns than exogenous variables in the model!\n");
+      exit(1);
+    }
+  if (old_col == 0)
+    {
+      old_col = col;
+      up_down = (col > 1) ? -1 : 1;
+    }
+  else
+    {
+      old_col += up_down;
+      if ( col != old_col)
+	{
+	  fprintf(stdout,"ERROR: Sigma_e isn't in triangular form!\n");
+	  exit(1);
+	}
+    }
+}
+
+void p_option(char *name, char *value)
+{
+  char buffer[2000];
+  sprintf(buffer,"options_.%s=%s;\n",name,value);
+  str_output(buffer);
+}
+
+void p_option_e(char *name, struct queue* expression)
+{
+  char buffer[2000];
+  sprintf(buffer,"options_.%s=",name);
+  str_output(buffer);
+  p_expression(expression);
+  str_output(";\n");
+}
+
+void p_s_option(char *name, char *value)
+{
+  char buffer[2000];
+  sprintf(buffer,"options_.%s='%s';\n",name,value);
+  str_output(buffer);
+}
+
+void p_osr()
+{
+  char buffer[2000];
+  int i;
+  check.osr = 1;
+#ifdef SCILAB
+  str_output("global ");
+  for(i=0;i < var_nbr; i++)
+    {
+      if (var_list[i].endo_exo == 1)
+	{
+	  str_output(var_list[i].name);
+	  str_output(" ");
+	}
+    }
+  str_output("\n");
+#endif
+#if defined MATLAB || defined SCILAB
+  if (nbr_tmpvar == 0)
+    {
+      str_output("var_list_ = [];\n");
+    }
+  else
+    {
+      strcpy(buffer,"var_list_ = '");
+      strcat(buffer,tmpvar_list[0]);
+      strcat(buffer,"';\n");
+      for(i=2;i<nbr_tmpvar;i+=2)
+	{
+#ifdef MATLAB
+	  strcat(buffer,"var_list_ = str2mat(var_list_,'");
+	  strcat(buffer,tmpvar_list[i]);
+	  strcat(buffer,"');\n");
+#else
+	  strcat(buffer,"var_list_ = [var_list_;'");
+	  strcat(buffer,tmpvar_list[i]);
+	  strcat(buffer,"'];\n");
+#endif
+	}
+      str_output(buffer);
+    }
+  str_output("osr(var_list_,osr_params_,optim_weights_);\n");
+#endif
+}
+
+void p_olr()
+{
+  char buffer[2000];
+  int i;
+  check.olr = 1;
+#ifdef SCILAB
+  str_output("global ");
+  for(i=0;i < var_nbr; i++)
+    {
+      if (var_list[i].endo_exo == 1)
+	{
+	  str_output(var_list[i].name);
+	  str_output(" ");
+	}
+    }
+  str_output("\n");
+#endif
+#if defined MATLAB || defined SCILAB
+  if (nbr_tmpvar == 0)
+    {
+      str_output("var_list_ = [];\n");
+    }
+  else
+    {
+      strcpy(buffer,"var_list_ = '");
+      strcat(buffer,tmpvar_list[0]);
+      strcat(buffer,"';\n");
+      for(i=2;i<nbr_tmpvar;i+=2)
+	{
+#ifdef MATLAB
+	  strcat(buffer,"var_list_ = str2mat(var_list_,'");
+	  strcat(buffer,tmpvar_list[i]);
+	  strcat(buffer,"');\n");
+#else
+	  strcat(buffer,"var_list_ = [var_list_;'");
+	  strcat(buffer,tmpvar_list[i]);
+	  strcat(buffer,"'];\n");
+#endif
+	}
+      str_output(buffer);
+    }
+  str_output("options_.olr = 1;\n");
+  str_output("options_.olr_w = optim_weights_;\n");
+  str_output("options_.olr_inst = olr_inst_;\n");
+  str_output("info = stoch_simul(var_list_);\n");
+  //  str_output("olr(var_list_,olr_inst_,obj_var_,optim_weights_);\n");
+#endif
+}
+
+void p_olr_inst_init()
+{
+  str_output("%OLR_INST\n");
+  str_output("olr_inst_ = [];\n");
+}
+
+void p_olr_inst(char* name)
+{
+  char buffer[2000];
+  sprintf(buffer,"olr_inst_ = strvcat(olr_inst_,'%s');\n",name);
+  str_output(buffer);
+  inst_nbr++;
+}
+
+void run_checks(void)
+ {
+  int i,flag;
+  if (check.olr && check.eq_nbr != endo_nbr - inst_nbr)
+    {
+      printf("ERROR: for OLR there must be %d equations for %d endogenous variables less %d instruments\n",endo_nbr-inst_nbr,endo_nbr,inst_nbr);
+      exit(1);
+    }
+  else if (check.eq_nbr != endo_nbr - inst_nbr)
+    {
+      printf("ERROR: there are %d equations for %d endogenous variables\n",check.eq_nbr,endo_nbr);
+      exit(1);
+    }
+
+  if (!check.linear && !check.initval)
+    {
+      printf("WARNING: there is no INITVAL, all variables initialized at 0\n");
+    }
+
+  if (!check.linear && check.initval)
+    {
+      flag = 1;
+      for(i=0;i<var_nbr;++i)
+	{
+	  if (initval_check[i] == 0 && ((var_list[i].endo_exo == 0 && check.determ) || var_list[i].endo_exo == 1))
+	    {
+	      if (flag)
+		{
+		  printf("WARNING: the following variables aren't initialized in INITVAL and therefore set to 0\n");
+		  flag =  0;
+		}
+	      printf("\t%s\n",var_list[i].name);
+	    }
+	}
+    }             
+
+  if (!check.linear && check.endval)
+    {
+      flag = 1;
+      for(i=0;i<var_nbr;++i)
+	{
+	  if (endval_check[i] == 0 && ((var_list[i].endo_exo == 0 && check.determ) || var_list[i].endo_exo == 1))
+	    {
+	      if (flag)
+		{
+		  printf("WARNING: the following variables aren't initialized in ENDVAL and therefore set to 0\n");
+		  flag =  0;
+		}
+	      printf("\t%s\n",var_list[i].name);
+	    }
+	}
+              
+    }
+}
+
+void p_estimated_init(void)
+{
+  str_output("global estim_params_\n");
+  str_output("estim_params_.var_exo = [];\nestim_params_.var_endo = [];\nestim_params_.corrx = [];\nestim_params_.corrn = [];\nestim_params_.param_names = [];\nestim_params_.param_vals = [];\n");
+}
+
+void estim_params_init(void)
+{
+  estim_params.var_nbr = 0;
+  estim_params.param_name=strdup("");
+  estim_params.init_val=strdup("NaN");
+  estim_params.mean=strdup("NaN");
+  estim_params.std=strdup("NaN");
+  estim_params.prior=strdup("NaN");
+  estim_params.lb=strdup("-Inf");
+  estim_params.ub=strdup("Inf");
+  estim_params.p3=strdup("NaN");
+  estim_params.p4=strdup("NaN");
+  estim_params.jscale=strdup("NaN");
+}
+
+void p_estimated_elem(void)
+{
+      /* missing tests for arguments */
+  char buffer[2000];
+
+  if (estim_params.param_type == 1 && estim_params.var_type == 0)
+    {
+      str_output("estim_params_.var_exo = [estim_params_.var_exo; ");
+      sprintf(buffer," %d,",estim_params.var_nbr);
+      str_output(buffer);
+    }
+  else if(estim_params.param_type == 1 && estim_params.var_type == 1)
+    {
+      str_output("estim_params_.var_endo = [estim_params_.var_endo; ");
+      sprintf(buffer," %d,",estim_params.var_nbr);
+      str_output(buffer);
+    }
+  else if(estim_params.param_type == 2)
+    {
+      sprintf(buffer,"estim_params_.param_names = strvcat(estim_params_.param_names,'%s');\n",estim_params.param_name);
+      str_output(buffer);
+      str_output("estim_params_.param_vals = [estim_params_.param_vals;");
+    }
+  else if (estim_params.param_type == 3 && estim_params.var_type == 0)
+    {
+      str_output("estim_params_.corrx = [estim_params_.corrx; ");
+      sprintf(buffer," %d,",estim_params.var_nbr);
+      str_output(buffer);
+      sprintf(buffer," %d,",estim_params.var_nbr2);
+      str_output(buffer);
+    }
+  else if(estim_params.param_type == 3 && estim_params.var_type == 1)
+    {
+      str_output("estim_params_.corrn = [estim_params_.corrn; ");
+      sprintf(buffer," %d,",estim_params.var_nbr);
+      str_output(buffer);
+      sprintf(buffer," %d,",estim_params.var_nbr2);
+      str_output(buffer);
+    }
+  sprintf(buffer," %s",estim_params.init_val);
+  str_output(buffer);
+  sprintf(buffer,", %s",estim_params.lb);
+  str_output(buffer);
+  sprintf(buffer,", %s",estim_params.ub);
+  str_output(buffer);
+  sprintf(buffer,", %s",estim_params.prior);
+  str_output(buffer);
+  sprintf(buffer,", %s",estim_params.mean);
+  str_output(buffer);
+  sprintf(buffer,", %s",estim_params.std);
+  str_output(buffer);
+  sprintf(buffer,", %s",estim_params.p3);
+  str_output(buffer);
+  sprintf(buffer,", %s",estim_params.p4);
+  str_output(buffer);
+  sprintf(buffer,", %s",estim_params.jscale);
+  str_output(buffer);
+  str_output("];\n");
+}
+  
+void p_estimated_elem1(struct token* id_var, char* init_val, char* lo_bound, char* up_bound, char* prior, char* p1, char *p2, char* p3, char *p4, char* jscale)
+{
+  char buffer[2000];
+  if (id_var->endo_exo == 0)
+    {
+      /* missing tests for arguments */
+      sprintf(buffer,"estim_params_.var_exo = [estim_params_.var_exo; %d %s %s %s %s %s %s %s %s %s];\n",id_var->nbr+1,init_val, lo_bound, up_bound, prior, p1, p2, p3, p4, jscale);
+    }
+  else if(id_var->endo_exo == 1)
+    {
+      /* missing tests for arguments */
+      sprintf(buffer,"estim_params_.var_endo = [estim_params_.var_endo; %d %s %s %s %s %s %s %s %s %s];\n",id_var->nbr+1,init_val, lo_bound, up_bound, prior, p1, p2, p3, p4, jscale);
+    }
+  str_output(buffer);
+}
+ 
+void p_estimated_elem2(struct token* id_var1, struct token* id_var2, char* init_val, char* lo_bound, char* up_bound, char* prior, char* p1, char *p2, char* p3, char *p4, char* jscale)
+{
+  char buffer[2000];
+  /* missing tests for arguments */
+  if (id_var1->endo_exo == 0 && id_var2->endo_exo == 0)
+    {
+      sprintf(buffer,"estim_params_.corrx = [estim_params_.corrx; %d %d %s %s %s %s %s %s %s %s %s];\n",id_var1->nbr+1,id_var2->nbr+1,init_val, lo_bound, up_bound, prior, p1, p2, p3, p4, jscale);
+    }
+  else if (id_var1->endo_exo == 1 && id_var2->endo_exo == 1)
+    {
+      sprintf(buffer,"estim_params_.corrn = [estim_params_.corrn; %d %d %s %s %s %s %s %s %s %s %s];\n",id_var1->nbr+1,id_var2->nbr+1,init_val, lo_bound, up_bound, prior, p1, p2, p3, p4, jscale);
+    }
+  else
+    {
+      printf("Shocks and measurement errors can't be correlated\n");
+      exit(1);
+    }
+  str_output(buffer);
+}
+ 
+void p_estimated_elem3(struct token* id_var, char* init_val, char* lo_bound, char* up_bound, char* prior, char* p1, char *p2, char* p3, char *p4, char *jscale)
+{
+  char buffer[2000];
+  sprintf(buffer,"estim_params_.param_names = strvcat(estim_params_.param_names,'%s');\n",id_var->name);
+  str_output(buffer);
+  /* missing tests for arguments */
+  sprintf(buffer,"estim_params_.param_vals = [estim_params_.param_vals; %s %s %s %s %s %s %s %s %s];\n",init_val, lo_bound, up_bound, prior, p1, p2, p3, p4, jscale);
+  str_output(buffer);
+}
+ 
+void p_estimated_elem1a(struct token* id_var, char* prior, char* p1, char *p2, char* p3, char *p4, char* jscale)
+{
+  char buffer[2000];
+  if (id_var->endo_exo == 0)
+    {
+      /* missing tests for arguments */
+      sprintf(buffer,"estim_params_.var_exo = [estim_params_.var_exo; %d %s -Inf Inf %s %s %s %s %s %s];\n",id_var->nbr+1, p1, prior, p1, p2, p3, p4, jscale);
+    }
+  else if(id_var->endo_exo == 1)
+    {
+      /* missing tests for arguments */
+      sprintf(buffer,"estim_params_.var_endo = [estim_params_.var_endo; %d %s -Inf Inf %s %s %s %s %s %s];\n",id_var->nbr+1, p1, prior, p1, p2, p3, p4, jscale);
+    }
+  str_output(buffer);
+}
+ 
+void p_estimated_elem2a(struct token* id_var1, struct token* id_var2, char* prior, char* p1, char *p2, char* p3, char *p4, char* jscale)
+{
+  char buffer[2000];
+  /* missing tests for arguments */
+  if (id_var1->endo_exo == 0 && id_var2->endo_exo == 0)
+    {
+      sprintf(buffer,"estim_params_.corrx = [estim_params_.corrx; %d %d %s -Inf Inf %s %s %s %s %s %s];\n",id_var1->nbr+1,id_var2->nbr+1, p1, prior, p1, p2, p3, p4, jscale);
+    }
+  else if (id_var1->endo_exo == 1 && id_var2->endo_exo == 1)
+    {
+      sprintf(buffer,"estim_params_.corrn = [estim_params_.corrn; %d %d %s -Inf Inf %s %s %s %s %s %s];\n",id_var1->nbr+1,id_var2->nbr+1, p1, prior, p1, p2, p3, p4, jscale);
+    }
+  else
+    {
+      printf("Shocks and measurement errors can't be correlated\n");
+      exit(1);
+    }
+  str_output(buffer);
+}
+ 
+void p_estimated_elem3a(struct token* id_var, char* prior, char* p1, char *p2, char* p3, char *p4, char *jscale)
+{
+  char buffer[2000];
+  sprintf(buffer,"estim_params_.param_names = strvcat(estim_params_.param_names,'%s');\n",id_var->name);
+  str_output(buffer);
+  /* missing tests for arguments */
+  sprintf(buffer,"estim_params_.param_vals = [estim_params_.param_vals; %s -Inf Inf %s %s %s %s %s %s];\n", p1, prior, p1, p2, p3, p4, jscale);
+  str_output(buffer);
+}
+
+void p_estimated_init_elem1(struct token* id_var, char* value)
+{
+  char buffer[2000];
+  if (id_var->endo_exo == 0)
+    {
+      /* missing tests for arguments */
+      sprintf(buffer,"tmp1 = find(estim_params_.var_exo(:,1)==%d);\nestim_params_.var_exo(tmp1,2) = %s;\n",id_var->nbr+1,value);
+    }
+  else if(id_var->endo_exo == 1)
+    {
+      /* missing tests for arguments */
+      sprintf(buffer,"tmp1 = find(estim_params_.var_endo(:,1)==%d);\nestim_params_.var_endo(tmp1,2) = %s;\n",id_var->nbr+1,value);
+    }
+  str_output(buffer);
+}
+ 
+void p_estimated_init_elem2(struct token* id_var1, struct token* id_var2, char* value)
+{
+  char buffer[2000];
+  /* missing tests for arguments */
+  if (id_var1->endo_exo == 0 && id_var2->endo_exo == 0)
+    {
+      sprintf(buffer,"tmp1 = find(estim_params_.corrx(:,1)==%d & estim_params.corrx(:,2)==%d);\nestim_params_.corrx(tmp1,3) = %s;\n",id_var1->nbr+1,id_var2->nbr+1,value);
+    }
+  else if (id_var1->endo_exo == 1 && id_var2->endo_exo == 1)
+    {
+      sprintf(buffer,"tmp1 = find(estim_params_.corrn(:,1)==%d & estim_params.corrn(:,2)==%d);\nestim_params_.corrn(tmp1,3) = %s;\n",id_var1->nbr+1,id_var2->nbr+1,value);
+    }
+  else
+    {
+      printf("Shocks and measurement errors can't be correlated\n");
+      exit(1);
+    }
+  str_output(buffer);
+}
+ 
+void p_estimated_init_elem3(struct token* id_var, char* value)
+{
+  char buffer[2000];
+  /* missing tests for arguments */
+  sprintf(buffer,"tmp1 = strmatch('%s',estim_params_.param_names,'exact');\nestim_params_.param_vals(tmp1,1) = %s;\n",id_var->name,value);
+  str_output(buffer);
+}
+ 
+void p_estimated_bounds_elem1(struct token* id_var, char* value1, char* value2)
+{
+  char buffer[2000];
+  if (id_var->endo_exo == 0)
+    {
+      /* missing tests for arguments */
+      sprintf(buffer,"tmp1 = find(estim_params_.var_exo(:,1)==%d);\nestim_params_.var_exo(tmp1,3) = %s;\nestim_params_.var_exo(tmp1,4) = %s;\n",id_var->nbr+1,value1,value2);
+    }
+  else if(id_var->endo_exo == 1)
+    {
+      /* missing tests for arguments */
+      sprintf(buffer,"tmp1 = find(estim_params_.var_endo(:,1)==%d);\nestim_params_.var_endo(tmp1,3) = %s;\nestim_params_.var_endo(tmp1,4) = %s;\n",id_var->nbr+1,value1,value2);
+    }
+  str_output(buffer);
+}
+ 
+void p_estimated_bounds_elem2(struct token* id_var1, struct token* id_var2, char* value1, char* value2)
+{
+  char buffer[2000];
+  /* missing tests for arguments */
+  if (id_var1->endo_exo == 0 && id_var2->endo_exo == 0)
+    {
+      sprintf(buffer,"tmp1 = find(estim_params_.corrx(:,1)==%d & estim_params.corrx(:,2)==%d);\nestim_params_.corrx(tmp1,4) = %s;\nestim_params_.corrx(tmp1,5) = %s;\n",id_var1->nbr+1,id_var2->nbr+1,value1,value2);
+    }
+  else if (id_var1->endo_exo == 1 && id_var2->endo_exo == 1)
+    {
+      sprintf(buffer,"tmp1 = find(estim_params_.corrn(:,1)==%d & estim_params.corrn(:,2)==%d);\nestim_params_.corrn(tmp1,4) = %s;\nestim_params_.corrn(tmp1,5) = %s;\n",id_var1->nbr+1,id_var2->nbr+1,value1,value2);
+    }
+  else
+    {
+      printf("Shocks and measurement errors can't be correlated\n");
+      exit(1);
+    }
+  str_output(buffer);
+}
+ 
+void p_estimated_bounds_elem3(struct token* id_var, char* value1, char* value2)
+{
+  char buffer[2000];
+  /* missing tests for arguments */
+  sprintf(buffer,"tmp1 = strmatch('%s',estim_params_.param_names,'exact');\nestim_params_.param_vals(tmp1,2) = %s;\nestim_params_.param_vals(tmp1,3) = %s;\n",id_var->name,value1,value2);
+  str_output(buffer);
+}
+ 
+void p_trend_init()
+{
+  str_output("trend_coeff_ = {};\n");
+}
+
+void p_trend_element(struct token* id_var, struct queue* expression)
+{
+  char buffer[20000];
+  struct token** p_t;
+  int j;
+
+  sprintf(buffer,"tmp1 = strmatch('%s',options_.varobs,'exact');\n",id_var->var_ptr->name);
+  str_output(buffer);
+  sprintf(buffer,"trend_coeff_{tmp1} = sprintf('");
+  p_t=(struct token **)expression->ptr;
+  for (j=0;j < expression->imax;j++)
+    {
+      strcat(buffer,(*p_t)->name);
+      ++p_t;
+    }
+  strcat(buffer,"');");
+  str_output(buffer);
+}
+
+void p_estimation(void)
+{
+  char buffer[2000];
+  int i;
+#ifdef SCILAB
+  str_output("global ");
+  for(i=0;i < var_nbr; i++)
+    {
+      if (var_list[i].endo_exo == 1)
+	{
+	  str_output(var_list[i].name);
+	  str_output(" ");
+	}
+    }
+  str_output("\n");
+#endif
+#if defined MATLAB || defined SCILAB
+  if (nbr_tmpvar == 0)
+    {
+      str_output("var_list_ = [];\n");
+    }
+  else
+    {
+      strcpy(buffer,"var_list_ = '");
+      strcat(buffer,tmpvar_list[0]);
+      strcat(buffer,"';\n");
+      for(i=2;i<nbr_tmpvar;i+=2)
+	{
+#ifdef MATLAB
+	  strcat(buffer,"var_list_ = str2mat(var_list_,'");
+	  strcat(buffer,tmpvar_list[i]);
+	  strcat(buffer,"');\n");
+#else
+	  strcat(buffer,"var_list_ = [var_list_;'");
+	  strcat(buffer,tmpvar_list[i]);
+	  strcat(buffer,"'];\n");
+#endif
+	}
+      str_output(buffer);
+    }
+  str_output("dynare_estimation(var_list_);\n");
+#endif
+}
+
+void print_varobs(void)
+{
+  int i;
+  char buffer[2000];
+  str_output("options_.varobs = [];\n");
+  for(i=0; i < nbr_tmpvar; i +=2)
+    {
+      sprintf(buffer,"options_.varobs = strvcat(options_.varobs,'%s');\n",tmpvar_list[i]);
+      str_output(buffer);
+    }
+}
+
+void print_unit_root_vars(void)
+{
+  int i;
+  char buffer[2000];
+  str_output("options_.unit_root_vars = {");
+  for(i=0; i < nbr_tmpvar; i +=2)
+    {
+      if (i != 0)
+	{
+	  str_output("; ");
+	}
+      sprintf(buffer,"'%s'",tmpvar_list[i]);
+      str_output(buffer);
+    }
+  str_output("};\n");
+}
+
+void p_optim_options(char* str1, char* str2, int task)
+{
+  static char optim_string[2000];
+  static int start;
+  switch(task){
+  case 1:
+    strcpy(optim_string,"options_.optim_opt = '");
+    start = 0;
+    return;
+  case 2:
+    if (start > 0)
+      {
+	strcat(optim_string,",");
+      }
+    else
+      {
+	start = 1;
+      }
+    strcat(optim_string,"''");
+    strcat(optim_string,str1);
+    strcat(optim_string,"'',");
+    if (str2[0] >= 'A' && str2[0] <= 'z')
+      {
+	strcat(optim_string,"''");
+	strcat(optim_string,str2);
+	strcat(optim_string,"''");
+      }
+    else
+      {
+	strcat(optim_string,str2);
+      }
+    return;
+  case 3:
+    strcat(optim_string,"';\n");
+    str_output(optim_string);
+  }
+}
+
+char* my_strcat(char* s1, char* s2)
+{
+  char* result;
+  result = calloc(strlen(s1)+strlen(s2),1);
+  strcpy(result,s1);
+  strcat(result,s2);
+  return result;
+}
+
+void set_options(int argc, char** argv,struct s_runtime_options* runtime_options)
+{
+  int i;
+  
+  /* default values */
+
+  runtime_options->clearall = 1;
+  runtime_options->debug = 0;
+
+
+  /* runtime arguments */
+  for (i=2; i < argc; ++i)
+    {
+      if (strcasecmp(argv[i],"NOCLEARALL") == 0)
+	{
+	  runtime_options->clearall = 0;
+	}
+      if (strcasecmp(argv[i],"DEBUG") == 0)
+	{
+	  runtime_options->debug = 1;
+	}
+    }
+}
+
+void p_model_comparison(int flag_model_prior)
+{
+  int i;
+  char buffer[2000];
+  str_output("ModelNames_ = {");
+  for(i=0; i < nbr_tmpvar; i +=2)
+    {
+      if (i != 0)
+	{
+	  str_output("; ");
+	}
+      sprintf(buffer,"'%s'",tmpvar_list[i]);
+      str_output(buffer);
+    }
+  str_output("};\n");
+  str_output("ModelPriors_ = [");
+  if (flag_model_prior)
+    {
+      for(i=1; i < nbr_tmpvar; i +=2)
+	{
+	  if (i != 0)
+	    {
+	      str_output("; ");
+	  }
+	  sprintf(buffer,"%s",tmpvar_list[i]);
+	  str_output(buffer);
+	}
+    }
+  str_output("];\n");
+  str_output("model_comparison(ModelNames_,ModelPriors_);\n");
+}
+
+void p_forecast()
+{
+  char buffer[2000];
+  int i;
+#ifdef SCILAB
+  str_output("global ");
+  for(i=0;i < var_nbr; i++)
+    {
+      if (var_list[i].endo_exo == 1)
+	{
+	  str_output(var_list[i].name);
+	  str_output(" ");
+	}
+    }
+  str_output("\n");
+#endif
+#if defined MATLAB || defined SCILAB
+  if (nbr_tmpvar == 0)
+    {
+      str_output("var_list_ = [];\n");
+    }
+  else
+    {
+      strcpy(buffer,"var_list_ = '");
+      strcat(buffer,tmpvar_list[0]);
+      strcat(buffer,"';\n");
+      for(i=2;i<nbr_tmpvar;i+=2)
+	{
+#ifdef MATLAB
+	  strcat(buffer,"var_list_ = str2mat(var_list_,'");
+	  strcat(buffer,tmpvar_list[i]);
+	  strcat(buffer,"');\n");
+#else
+	  strcat(buffer,"var_list_ = [var_list_;'");
+	  strcat(buffer,tmpvar_list[i]);
+	  strcat(buffer,"'];\n");
+#endif
+	}
+      str_output(buffer);
+    }
+  str_output("forecast(var_list_);\n");
+#endif
+}
+
+/*
+02/22/01 MJ added test for nbr of equations != nbr endogenous variables
+            replaced stderr_ by Sigma_e_
+02/23/01 MJ added global statement for all endogenous variables before 
+            stoch_simul in MATLAB version
+	    added p_dsample
+02/28/01 MJ added "clear all" on top of MATLAB file
+            corrected expression for Sigma_e_ in p_shocks
+09/25/01 MJ added Scilab code
+09/26/01 MJ added p_keyword
+04/05/02 MJ corrected all compile warnings except m_del and \0 in format
+04/06/02 MJ added p_optim_weights() p_optim_weights_init() p_expression()
+            p_osr_params() p_osr()
+            LEFT_PAREN RIGHT_PAREN OPEN_COMMENTS CLOSE_COMMENTS
+10/09/02 MJ added p_calib_init() p_calib_var() p_calib()
+            removed ";\n" from p_expression, corrected calling functions
+10/20/02 MJ added automatic diary main() dynare_init()
+01/16/03 MJ corrected bug in dyn2vec without argument
+04/02/03 MJ added p_steady_linear()
+            now ys_,exe_,exe_stoch_ are set in print_model() instead of 
+	    p_initval()
+04/28/03 MJ added p_option() and changed handling of options
+05/02/03 MJ added p_olr(), p_olr_inst(), p_olr_inst_init()
+            modified p_optim_weights1() and added p_optim_weights2()
+05/18/03 MJ removed p_keyword(), modified p_steady() and p_steady_linear() 
+            added p_check(); 
+05/26/03 MJ added struct check and run_checks()
+05/29/03 MJ p_shocks write set_shocks(flag,periods,ivar,values)
+06/23/03 MJ added estimated_params and estimation
+07/25/03 MJ added test for no exogenous for GAUSS version
+10/31/03 MJ added oo for output variables
+*/
diff --git a/tags/v_3.062/parser.src/makefile b/tags/v_3.062/parser.src/makefile
new file mode 100644
index 0000000000000000000000000000000000000000..1e3263de2aced400d5a64652b13fe9eb9f6bee34
--- /dev/null
+++ b/tags/v_3.062/parser.src/makefile
@@ -0,0 +1,56 @@
+all: dynare_m.exe dynare_s.exe dynare_g.exe dynare_OxPro.exe dynare_Oxcons.exe
+
+precompiler.o: precompiler.cc precompiler.hh d_ll.c d_tab.c
+	g++ -mno-cygwin -c precompiler.cc
+
+dynare_mb: dynare_m.o
+	gcc -mno-cygwin -g -o dynare_m.exe dynare_m.o d_tab.o d_ll.o -lefence
+dynare_m.exe: dynare_m.o d_tab.o d_ll.o precompiler.o
+	gcc -mno-cygwin -g -o dynare_m.exe dynare_m.o d_tab.o d_ll.o precompiler.o -lstdc++
+	cp dynare_m.exe ../matlab
+
+dynare_m.o: dynare.c d.h d_tab.h
+	gcc -mno-cygwin -g  -c dynare.c -o dynare_m.o -DMATLAB -Wall #-DDEBUG
+
+dynare_s.exe: dynare_s.o d_tab.o d_ll.o
+	gcc -mno-cygwin -g  -o dynare_s.exe dynare_s.o d_tab.o d_ll.o
+	cp dynare_s.exe ../scilab
+
+dynare_s.o: dynare.c d.h d_tab.h
+	gcc -mno-cygwin -g  -c dynare.c -o dynare_s.o -DSCILAB -Wall
+
+dynare_g.exe: dynare_g.o d_tab.o d_ll.o
+	gcc -mno-cygwin -g  -o dynare_g.exe dynare_g.o d_tab.o d_ll.o
+	cp dynare_g.exe ../gauss
+
+dynare_g.o: dynare.c d.h d_tab.h
+	gcc -mno-cygwin -g  -c dynare.c -o dynare_g.o -DGAUSS -Wall #-DDEBUG
+
+dynare_OxPro.exe: dynare_OxPro.o d_tab.o d_ll.o
+	gcc -mno-cygwin -g  -o dynare_OxPro.exe dynare_OxPro.o d_tab.o d_ll.o
+	cp dynare_OxPro.exe ../gauss
+
+dynare_OxPro.o: dynare.c d.h d_tab.h
+	gcc -mno-cygwin -g  -c dynare.c -o dynare_OxPro.o -DGAUSS -DOXGAUSS -Wall
+
+dynare_Oxcons.exe: dynare_Oxcons.o d_tab.o d_ll.o
+	gcc -mno-cygwin -g  -o dynare_Oxcons.exe dynare_Oxcons.o d_tab.o d_ll.o
+	cp dynare_Oxcons.exe ../gauss
+
+dynare_Oxcons.o: dynare.c d.h d_tab.h
+	gcc -mno-cygwin -g  -c dynare.c -o dynare_Oxcons.o -DGAUSS -DOXGAUSS -DOXGAUSS_GNU -Wall
+
+d_ll.o: d_ll.c d_tab.h
+	gcc -mno-cygwin -g -c d_ll.c
+
+
+d_tab.o: d_tab.c
+	gcc -mno-cygwin -g -c -DYYDEBUG=1 d_tab.c
+
+d_tab.c d_tab.h: d.y d.h
+	bison -d --verbose -od_tab.c d.y
+
+d_ll.c: dyn.l d_tab.h
+	flex -i -od_ll.c dyn.l
+
+
diff --git a/tags/v_3.062/parser.src/makefile.linux b/tags/v_3.062/parser.src/makefile.linux
new file mode 100644
index 0000000000000000000000000000000000000000..107217ddd8aad4f57dd8dc8b3126b79c0e388aa7
--- /dev/null
+++ b/tags/v_3.062/parser.src/makefile.linux
@@ -0,0 +1,57 @@
+all: dynare_m
+
+precompiler.o: precompiler.cc precompiler.hh d_ll.c d_tab.c
+	g++ -g -c precompiler.cc
+
+dynare_mb: dynare_m.o
+	gcc  -g -o dynare_m.exe dynare_m.o d_tab.o d_ll.o -lefence
+
+dynare_m: dynare_m.o d_tab.o d_ll.o precompiler.o
+	gcc  -g -o dynare_m dynare_m.o d_tab.o d_ll.o precompiler.o -lstdc++
+	cp dynare_m ../matlab
+
+dynare_m.o: dynare.c d.h d_tab.h
+	gcc  -g  -c dynare.c -o dynare_m.o -DMATLAB -Wall #-DDEBUG
+
+dynare_s: dynare_s.o d_tab.o d_ll.o
+	gcc -g  -o dynare_s dynare_s.o d_tab.o d_ll.o
+	cp dynare_s ../scilab
+
+dynare_s.o: dynare.c d.h d_tab.h
+	gcc -g  -c dynare.c -o dynare_s.o -DSCILAB -Wall
+
+dynare_g.exe: dynare_g.o d_tab.o d_ll.o
+	gcc  -g  -o dynare_g.exe dynare_g.o d_tab.o d_ll.o
+	cp dynare_g.exe ../gauss
+
+dynare_g.o: dynare.c d.h d_tab.h
+	gcc  -g  -c dynare.c -o dynare_g.o -DGAUSS -Wall #-DDEBUG
+
+dynare_OxPro.exe: dynare_OxPro.o d_tab.o d_ll.o
+	gcc  -g  -o dynare_OxPro.exe dynare_OxPro.o d_tab.o d_ll.o
+	cp dynare_OxPro.exe ../gauss
+
+dynare_OxPro.o: dynare.c d.h d_tab.h
+	gcc  -g  -c dynare.c -o dynare_OxPro.o -DGAUSS -DOXGAUSS -Wall
+
+dynare_Oxcons.exe: dynare_Oxcons.o d_tab.o d_ll.o
+	gcc  -g  -o dynare_Oxcons.exe dynare_Oxcons.o d_tab.o d_ll.o
+	cp dynare_Oxcons.exe ../gauss
+
+dynare_Oxcons.o: dynare.c d.h d_tab.h
+	gcc  -g  -c dynare.c -o dynare_Oxcons.o -DGAUSS -DOXGAUSS -DOXGAUSS_GNU -Wall
+
+d_ll.o: d_ll.c d_tab.h
+	gcc  -g -c d_ll.c
+
+
+d_tab.o: d_tab.c
+	gcc  -g -c -DYYDEBUG=1 d_tab.c
+
+d_tab.c d_tab.h: d.y d.h
+	bison -d --verbose -od_tab.c d.y
+
+d_ll.c: dyn.l d_tab.h
+	flex -i -od_ll.c dyn.l
+
+
diff --git a/tags/v_3.062/parser.src/precompiler.cc b/tags/v_3.062/parser.src/precompiler.cc
new file mode 100644
index 0000000000000000000000000000000000000000..7a99e5e91e6198773d7b16bfdb1a2831f7776ff9
--- /dev/null
+++ b/tags/v_3.062/parser.src/precompiler.cc
@@ -0,0 +1,180 @@
+#include <map>
+#include <stack>
+#include <iostream>
+
+#include "precompiler.hh"
+
+extern "C" void start_skipping(void);
+extern "C" void pop_flex_state(void);
+
+static precompiler dyn_pc;
+
+void precompiler::comp_define(std::string name, std::string integer)
+{
+  // go back to previous state before @define
+  pop_flex_state();
+
+  if (dyn_pc.macros.find(name) != dyn_pc.macros.end())
+    {
+      std::cout << "Warning: symbol " << name << " redefined" << "\n";
+    }
+  dyn_pc.macros[name]=std::atoi(integer.c_str());
+}
+
+void precompiler::comp_if(std::string name, std::string op, std::string integer)
+{
+  //go back to previous state before @if
+  pop_flex_state();
+
+  dyn_pc.precompiler_state.push(dyn_pc.current_state);
+  dyn_pc.previous_skip_else.push(dyn_pc.skip_else);
+
+  bool state;
+  int value = atoi(integer.c_str());
+
+  if ( op == "==" )
+    {
+      state = (dyn_pc.macros[name] == value);
+    }
+  else if ( op == "!=" )
+    {
+      state = (dyn_pc.macros[name] != value);
+    }
+  else if ( op == "<" )
+    {
+      state = (dyn_pc.macros[name] < value);
+    }
+  else if ( op == ">" )
+    {
+      state = (dyn_pc.macros[name] > value);
+    }
+  else if ( op == "<=" )
+    {
+      state = (dyn_pc.macros[name] <= value);
+    }
+  else if ( op == ">=" )
+    {
+      state = (dyn_pc.macros[name] >= value);
+    }
+  else
+    {
+      std::cout << "Precompiler: unkown operator";
+    }
+
+  dyn_pc.precompiler_state.push(dyn_pc.current_state);
+  if ( dyn_pc.current_state == true && state == false)
+    {
+      start_skipping();
+    }
+
+  // it is possible to skip following else and elseif statements
+  // if the previous state is already false (skipping is on)
+  dyn_pc.skip_else = (dyn_pc.current_state) ? false : true;
+  dyn_pc.current_state = state && dyn_pc.current_state;
+
+}
+  
+void precompiler::comp_elseif(std::string name, std::string op, std::string integer)
+{
+  // go back to previous state before @elseif
+  pop_flex_state();
+
+  if (dyn_pc.skip_else)
+    {
+      return;
+    }
+
+  if (dyn_pc.current_state)
+    {
+      start_skipping();
+      dyn_pc.current_state = false;
+      dyn_pc.skip_else = true;
+    }
+  
+  bool state;
+  int value = atoi(integer.c_str());
+
+  if ( op == "==" )
+    {
+      state = (dyn_pc.macros[name] == value);
+    }
+  else if ( op == "!=" )
+    {
+      state = (dyn_pc.macros[name] != value);
+    }
+  else if ( op == "<" )
+    {
+      state = (dyn_pc.macros[name] < value);
+    }
+  else if ( op == ">" )
+    {
+      state = (dyn_pc.macros[name] > value);
+    }
+  else if ( op == "<=" )
+    {
+      state = (dyn_pc.macros[name] <= value);
+    }
+  else if ( op == ">=" )
+    {
+      state = (dyn_pc.macros[name] >= value);
+    }
+  else
+    {
+      std::cout << "Precompiler: unkown operator";
+    }
+
+  if (state)
+    {
+      pop_flex_state();
+      dyn_pc.current_state = true;
+    }
+}
+
+void precompiler::comp_else(void)
+{
+  if (dyn_pc.skip_else)
+    {
+      return;
+    }
+
+  if (dyn_pc.current_state)
+    {
+      start_skipping();
+      dyn_pc.current_state = false;
+      dyn_pc.skip_else = true;
+    }
+  else  
+    {
+      pop_flex_state();
+      dyn_pc.current_state = true;
+    }
+}  
+
+void precompiler::comp_endif(void)
+{
+  if (!dyn_pc.current_state && dyn_pc.precompiler_state.top())
+    {
+      pop_flex_state();
+    }
+
+  dyn_pc.precompiler_state.pop();
+  dyn_pc.current_state = dyn_pc.precompiler_state.top();
+
+  dyn_pc.previous_skip_else.pop();
+  dyn_pc.skip_else = dyn_pc.previous_skip_else.top();
+}
+
+
+extern "C" void compile_define(char* name, char* integer)
+                                   { dyn_pc.comp_define(name, integer); }
+
+extern "C" void compile_if(char* name, char* op, char* integer)
+                                   { dyn_pc.comp_if(name,op,integer);}
+
+extern "C" void compile_elseif(char* name, char* op, char* integer)
+                                   { dyn_pc.comp_elseif(name,op,integer);}
+
+extern "C" void compile_else(void) { dyn_pc.comp_else();}
+
+extern "C" void compile_endif(void) { dyn_pc.comp_endif();}
+
diff --git a/tags/v_3.062/parser.src/precompiler.hh b/tags/v_3.062/parser.src/precompiler.hh
new file mode 100644
index 0000000000000000000000000000000000000000..d2d3f78e086f7f911f5841fc45c70d1df431ee68
--- /dev/null
+++ b/tags/v_3.062/parser.src/precompiler.hh
@@ -0,0 +1,31 @@
+#include<string>
+
+class precompiler {
+  std::map<std::string,int> macros;
+  std::stack<bool> precompiler_state;
+  std::stack<bool> previous_skip_else;
+  bool current_state;
+  bool skip_else;
+public:
+  precompiler() 
+  {
+    current_state = true;
+    skip_else = false;
+    precompiler_state.push(current_state);
+    previous_skip_else.push(skip_else);
+  }
+
+  void comp_define(std::string name, std::string integer);
+  void comp_if(std::string name, std::string op, std::string integer);
+  void comp_elseif(std::string name, std::string op, std::string integer);
+  void comp_else(void);
+  void comp_endif(void);
+};
+
+extern "C" void compile_define(char* name, char* integer);
+extern "C" void compile_if(char* name, char* op, char* integer);
+extern "C" void compile_elseif(char* name, char* op, char* integer);
+extern "C" void compile_else(void);
+extern "C" void compile_endif(void);
+
+
diff --git a/tags/v_3.062/tests/arima/mod1.mod b/tags/v_3.062/tests/arima/mod1.mod
new file mode 100644
index 0000000000000000000000000000000000000000..7a8dabf2b5cc6cb72a2d3839e0658df66f8f9a80
--- /dev/null
+++ b/tags/v_3.062/tests/arima/mod1.mod
@@ -0,0 +1,23 @@
+var dx dy x y;
+varexo e_x e_y;
+
+parameters rho_x rho_y;
+
+rho_x = 0.5;
+rho_y = -0.3;
+
+model;
+dx = rho_x*dx(-1)+e_x;
+dy = rho_y*dy(-1)+e_y;
+x = x(-1)+dx;
+y = y(-1)+dy;
+end;
+
+shocks;
+var e_x; stderr 0.01;
+var e_y; stderr 0.01;
+end;
+
+stoch_simul(order=1,periods=1000,irf=0,nomoments);
+
+save data1 dx dy x y;
\ No newline at end of file
diff --git a/tags/v_3.062/tests/arima/mod1a.mod b/tags/v_3.062/tests/arima/mod1a.mod
new file mode 100644
index 0000000000000000000000000000000000000000..9f63405d7c1d837d6f471ded54f586cc95721778
--- /dev/null
+++ b/tags/v_3.062/tests/arima/mod1a.mod
@@ -0,0 +1,23 @@
+var dx dy;
+varexo e_x e_y;
+
+parameters rho_x rho_y;
+
+rho_x = 0.5;
+rho_y = -0.3;
+
+model;
+dx = rho_x*dx(-1)+e_x;
+dy = rho_y*dy(-1)+e_y;
+end;
+
+estimated_params;
+rho_x,NORMAL_PDF,0.5,0.1;
+rho_y,NORMAL_PDF,-0.3,0.1;
+stderr e_x,INV_GAMMA_PDF,0.01,inf;
+stderr e_y,INV_GAMMA_PDF,0.01,inf;
+end;
+
+varobs dx dy;
+check;
+estimation(datafile=data1,nobs=1000,mh_replic=2000);
\ No newline at end of file
diff --git a/tags/v_3.062/tests/arima/mod1b.mod b/tags/v_3.062/tests/arima/mod1b.mod
new file mode 100644
index 0000000000000000000000000000000000000000..94b55f14823042fc422579d855007021a9b56b37
--- /dev/null
+++ b/tags/v_3.062/tests/arima/mod1b.mod
@@ -0,0 +1,25 @@
+var dx dy x y;
+varexo e_x e_y;
+
+parameters rho_x rho_y;
+
+rho_x = 0.5;
+rho_y = -0.3;
+
+model;
+dx = rho_x*dx(-1)+e_x;
+dy = rho_y*dy(-1)+e_y;
+x = x(-1)+dx;
+y = y(-1)+dy;
+end;
+
+estimated_params;
+rho_x,NORMAL_PDF,0.5,0.1;
+rho_y,NORMAL_PDF,-0.3,0.1;
+stderr e_x,INV_GAMMA_PDF,0.01,inf;
+stderr e_y,INV_GAMMA_PDF,0.01,inf;
+end;
+
+varobs x y;
+unit_root_vars  x y;
+estimation(datafile=data1,nobs=1000,mh_replic=10000);
\ No newline at end of file
diff --git a/tags/v_3.062/tests/arima/mod1c.mod b/tags/v_3.062/tests/arima/mod1c.mod
new file mode 100644
index 0000000000000000000000000000000000000000..a77478a856f9ecbf719817cfba29e6e5a212f52f
--- /dev/null
+++ b/tags/v_3.062/tests/arima/mod1c.mod
@@ -0,0 +1,27 @@
+var dx dy x y;
+varexo e_x e_y;
+
+parameters rho_x rho_y;
+
+rho_x = 0.5;
+rho_y = -0.3;
+
+model;
+dx = rho_x*dx(-1)+e_x;
+dy = rho_y*dy(-1)+e_y;
+x = x(-1)+dx;
+y = y(-1)+dy;
+end;
+
+estimated_params;
+rho_x,NORMAL_PDF,0.5,0.1;
+rho_y,NORMAL_PDF,-0.3,0.1;
+stderr e_x,INV_GAMMA_PDF,0.01,inf;
+stderr e_y,INV_GAMMA_PDF,0.01,inf;
+stderr x,INV_GAMMA_PDF,0.01,inf;
+stderr y,INV_GAMMA_PDF,0.01,inf;
+end;
+
+varobs x y;
+options_.unit_root_vars = {'x'; 'y'};
+estimation(datafile=data1,nobs=1000,mh_replic=2000,lik_init=2);
\ No newline at end of file
diff --git a/tags/v_3.062/tests/arima/mod2.mod b/tags/v_3.062/tests/arima/mod2.mod
new file mode 100644
index 0000000000000000000000000000000000000000..c84df189282c1422a5fbdcd2a2d4e0f545eaa70a
--- /dev/null
+++ b/tags/v_3.062/tests/arima/mod2.mod
@@ -0,0 +1,26 @@
+var dx dy x y;
+varexo e_x e_y;
+
+parameters rho_x rho_y b a1 a2;
+
+rho_x = 0.5;
+rho_y = -0.3;
+b = 1;
+a1 = -0.1;
+a2 = 0.2;
+
+model;
+dx = rho_x*dx(-1)+a1*(x(-1)-b*y(-1))+e_x;
+dy = rho_y*dy(-1)+a2*(x(-1)-b*y(-1))+e_y;
+x = x(-1)+dx;
+y = y(-1)+dy;
+end;
+
+shocks;
+var e_x; stderr 0.01;
+var e_y; stderr 0.01;
+end;
+
+stoch_simul(order=1,periods=1000,irf=0,nomoments);
+
+save data2 dx dy x y;
\ No newline at end of file
diff --git a/tags/v_3.062/tests/arima/mod2a.mod b/tags/v_3.062/tests/arima/mod2a.mod
new file mode 100644
index 0000000000000000000000000000000000000000..9414afa902c6cc374bb157d969cad8927db5120c
--- /dev/null
+++ b/tags/v_3.062/tests/arima/mod2a.mod
@@ -0,0 +1,33 @@
+var dx dy x y;
+varexo e_x e_y;
+
+parameters rho_x rho_y b a1 a2;
+
+rho_x = 0.5;
+rho_y = -0.3;
+b = 1;
+a1 = -0.1;
+a2 = 0.2;
+
+model;
+dx = rho_x*dx(-1)+a1*(x(-1)-b*y(-1))+e_x;
+dy = rho_y*dy(-1)+a2*(x(-1)-b*y(-1))+e_y;
+x = x(-1)+dx;
+y = y(-1)+dy;
+end;
+
+estimated_params;
+rho_x,NORMAL_PDF,0.5,0.1;
+rho_y,NORMAL_PDF,-0.3,0.1;
+b,NORMAL_PDF,1,0.1;
+a1,NORMAL_PDF,-0.1,0.1;
+a2,NORMAL_PDF,0.2,0.1;
+
+stderr e_x,INV_GAMMA_PDF,0.01,inf;
+stderr e_y,INV_GAMMA_PDF,0.01,inf;
+end;
+
+varobs dx dy;
+
+options_.unit_root_vars = {'x'; 'y'};
+estimation(datafile=data2,nobs=100,mh_replic=0,lik_init=2);
diff --git a/tags/v_3.062/tests/arima/mod2b.mod b/tags/v_3.062/tests/arima/mod2b.mod
new file mode 100644
index 0000000000000000000000000000000000000000..d2465a22c31088d51f0fb62a78470df1399e7a66
--- /dev/null
+++ b/tags/v_3.062/tests/arima/mod2b.mod
@@ -0,0 +1,33 @@
+var dx dy x y;
+varexo e_x e_y;
+
+parameters rho_x rho_y b a1 a2;
+
+rho_x = 0.5;
+rho_y = -0.3;
+b = 1;
+a1 = -0.1;
+a2 = 0.2;
+
+model;
+dx = rho_x*dx(-1)+a1*(x(-1)-b*y(-1))+e_x;
+dy = rho_y*dy(-1)+a2*(x(-1)-b*y(-1))+e_y;
+x = x(-1)+dx;
+y = y(-1)+dy;
+end;
+
+estimated_params;
+rho_x,NORMAL_PDF,0.5,0.1;
+rho_y,NORMAL_PDF,-0.3,0.1;
+b,NORMAL_PDF,1,0.1;
+a1,NORMAL_PDF,-0.1,0.1;
+a2,NORMAL_PDF,0.2,0.1;
+
+stderr e_x,INV_GAMMA_PDF,0.01,inf;
+stderr e_y,INV_GAMMA_PDF,0.01,inf;
+end;
+
+varobs x y;
+
+options_.unit_root_vars = {'x'; 'y'};
+estimation(datafile=data2,nobs=100,mh_replic=0,lik_init=2);
diff --git a/tags/v_3.062/tests/arima/mod2c.mod b/tags/v_3.062/tests/arima/mod2c.mod
new file mode 100644
index 0000000000000000000000000000000000000000..8ce2cae8ef608b6cdd6c1772929306410dd83ad0
--- /dev/null
+++ b/tags/v_3.062/tests/arima/mod2c.mod
@@ -0,0 +1,31 @@
+var dx dy coint_err;
+varexo e_x e_y;
+
+parameters rho_x rho_y b a1 a2;
+
+rho_x = 0.5;
+rho_y = -0.3;
+b = 1;
+a1 = -0.1;
+a2 = 0.2;
+
+model;
+dx = rho_x*dx(-1)+a1*coint_err(-1)+e_x;
+dy = rho_y*dy(-1)+a2*coint_err(-1)+e_y;
+coint_err = dx-b*dy+coint_err(-1);
+end;
+
+estimated_params;
+rho_x,NORMAL_PDF,0.5,0.1;
+rho_y,NORMAL_PDF,-0.3,0.1;
+b,NORMAL_PDF,1,0.1;
+a1,NORMAL_PDF,-0.1,0.1;
+a2,NORMAL_PDF,0.2,0.1;
+
+stderr e_x,INV_GAMMA_PDF,0.01,inf;
+stderr e_y,INV_GAMMA_PDF,0.01,inf;
+end;
+
+varobs dx dy;
+
+estimation(datafile=data2,nobs=100,mh_replic=0);
diff --git a/tags/v_3.062/tests/example1.mod b/tags/v_3.062/tests/example1.mod
new file mode 100644
index 0000000000000000000000000000000000000000..334ef7906a06896d36370214e328291cf94bfd00
--- /dev/null
+++ b/tags/v_3.062/tests/example1.mod
@@ -0,0 +1,44 @@
+// example 1 from Collard's guide to Dynare
+var y, c, k, a, h, b;
+varexo e,u;
+
+parameters beta, rho, beta, 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*(((exp(b)*c)/(exp(b(+1))*c(+1)))
+    *(exp(b(+1))*alpha*y(+1)+(1-delta)*k));
+y = exp(a)*(k(-1)^alpha)*(h^(1-alpha));
+k = exp(b)*(y-c)+(1-delta)*k(-1);
+a = rho*a(-1)+tau*b(-1) + e;
+b = tau*a(-1)+rho*b(-1) + u;
+end;
+
+initval;
+y = 1.08068253095672;
+c = 0.80359242014163;
+h = 0.29175631001732;
+k = 5;
+a = 0;
+b = 0;
+e = 0;
+u = 0;
+end;
+
+shocks;
+var e; stderr 0.009;
+var u; stderr 0.009;
+var e, u = phi*0.009*0.009;
+end;
+
+stoch_simul(periods=2100);
diff --git a/tags/v_3.062/tests/example2.mod b/tags/v_3.062/tests/example2.mod
new file mode 100644
index 0000000000000000000000000000000000000000..e2c4eeb1b6b52e50bfbbd794e3a51db26221ed8a
--- /dev/null
+++ b/tags/v_3.062/tests/example2.mod
@@ -0,0 +1,44 @@
+// example 2 from Collard's guide to Dynare
+var y, c, k, a, h, b;
+varexo e,u;
+
+parameters beta, rho, beta, 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;
+
+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 = 0.1;
+c = -0.2;
+h = -1.2;
+k =  2.4;
+a = 0;
+b = 0;
+e = 0;
+u = 0;
+end;
+
+steady;
+
+shocks;
+var e = 0.009^2;
+var u = 0.009^2;
+end;
+
+stoch_simul(dr_algo=1,drop=200);
+
diff --git a/tags/v_3.062/tests/fs2000/fs2000.mod b/tags/v_3.062/tests/fs2000/fs2000.mod
new file mode 100644
index 0000000000000000000000000000000000000000..ef702751376d98a0397e9efac1e5c6cf9120ba6f
--- /dev/null
+++ b/tags/v_3.062/tests/fs2000/fs2000.mod
@@ -0,0 +1,89 @@
+// This file replicates the estimation of the CIA model from 
+// Frank Schorfheide (2000) "Loss function-based evaluation of DSGE models" 
+// Journal of  Applied Econometrics, 15, 645-670.
+// the data are the ones provided on Schorfheide's web site with the programs.
+// http://www.econ.upenn.edu/~schorf/programs/dsgesel.ZIP
+// You need to have fsdat.m in the same directory as this file.
+// This file replicates: 
+// -the posterior mode as computed by Frank's Gauss programs
+// -the parameter mean posterior estimates reported in the paper
+// -the model probability (harmonic mean) reported in the paper
+// This file was tested with dyn_mat_test_0218.zip
+// the smooth shocks are probably stil buggy
+//
+// The equations are taken from J. Nason and T. Cogley (1994) 
+// "Testing the implications of long-run neutrality for monetary business
+// cycle models" Journal of Applied Econometrics, 9, S37-S70.
+// Note that there is an initial minus sign missing in equation (A1), p. S63.
+//
+// Michel Juillard, February 2004
+
+var m P c e W R k d n l gy_obs gp_obs y dA;
+varexo e_a e_m;
+
+parameters alp bet gam mst rho psi del;
+
+alp = 0.33;
+bet = 0.99;
+gam = 0.003;
+mst = 1.011;
+rho = 0.7;
+psi = 0.787;
+del = 0.02;
+
+model;
+dA = exp(gam+e_a);
+log(m) = (1-rho)*log(mst) + rho*log(m(-1))+e_m;
+-P/(c(+1)*P(+1)*m)+bet*P(+1)*(alp*exp(-alp*(gam+log(e(+1))))*k^(alp-1)*n(+1)^(1-alp)+(1-del)*exp(-(gam+log(e(+1)))))/(c(+2)*P(+2)*m(+1))=0;
+W = l/n;
+-(psi/(1-psi))*(c*P/(1-n))+l/n = 0;
+R = P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(-alp)/W;
+1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)/(m*l*c(+1)*P(+1)) = 0;
+c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1);
+P*c = m;
+m-1+d = l;
+e = exp(e_a);
+y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a));
+gy_obs = dA*y/y(-1);
+gp_obs = (p/p(-1))*m(-1)/dA;
+end;
+
+initval;
+k = 6;
+m = mst;
+P = 2.25;
+c = 0.45;
+e = 1;
+W = 4;
+R = 1.02;
+d = 0.85;
+n = 0.19;
+l = 0.86;
+y = 0.6;
+gy_obs = exp(gam);
+gp_obs = exp(-gam); 
+dA = exp(gam);
+end;
+
+shocks;
+var e_a; stderr 0.014;
+var e_m; stderr 0.005;
+end;
+
+steady;
+
+estimated_params;
+alp, beta_pdf, 0.356, 0.02; 
+bet, beta_pdf, 0.993, 0.002;
+gam, normal_pdf, 0.0085, 0.003;
+mst, normal_pdf, 1.0002, 0.007;
+rho, beta_pdf, 0.129, 0.223;
+psi, beta_pdf, 0.65, 0.05;
+del, beta_pdf, 0.01, 0.005;
+stderr e_a, inv_gamma_pdf, 0.035449, inf;
+stderr e_m, inv_gamma_pdf, 0.008862, inf;
+end;
+
+varobs gp_obs gy_obs;
+
+estimation(datafile=fsdat,nobs=192,loglinear,mh_replic=2000,mh_nblocks=2,mh_jscale=0.8);
\ No newline at end of file
diff --git a/tags/v_3.062/tests/fs2000/fs2000a.mod b/tags/v_3.062/tests/fs2000/fs2000a.mod
new file mode 100644
index 0000000000000000000000000000000000000000..f9593da2d93b7f85f771a93583f7be8fc5427b24
--- /dev/null
+++ b/tags/v_3.062/tests/fs2000/fs2000a.mod
@@ -0,0 +1,103 @@
+// This file replicates the estimation of the CIA model from 
+// Frank Schorfheide (2000) "Loss function-based evaluation of DSGE models" 
+// Journal of  Applied Econometrics, 15, 645-670.
+// the data are the ones provided on Schorfheide's web site with the programs.
+// http://www.econ.upenn.edu/~schorf/programs/dsgesel.ZIP
+// You need to have fsdat.m in the same directory as this file.
+// This file replicates: 
+// -the posterior mode as computed by Frank's Gauss programs
+// -the parameter mean posterior estimates reported in the paper
+// -the model probability (harmonic mean) reported in the paper
+// This file was tested with dyn_mat_test_0218.zip
+// the smooth shocks are probably stil buggy
+//
+// The equations are taken from J. Nason and T. Cogley (1994) 
+// "Testing the implications of long-run neutrality for monetary business
+// cycle models" Journal of Applied Econometrics, 9, S37-S70.
+// Note that there is an initial minus sign missing in equation (A1), p. S63.
+//
+// Michel Juillard, February 2004
+
+var m P c e W R k d n l gy_obs gp_obs Y_obs P_obs y dA;
+varexo e_a e_m;
+
+parameters alp bet gam mst rho psi del;
+
+alp = 0.33;
+bet = 0.99;
+gam = 0.003;
+mst = 1.011;
+rho = 0.7;
+psi = 0.787;
+del = 0.02;
+
+model;
+dA = exp(gam+e_a);
+log(m) = (1-rho)*log(mst) + rho*log(m(-1))+e_m;
+-P/(c(+1)*P(+1)*m)+bet*P(+1)*(alp*exp(-alp*(gam+log(e(+1))))*k^(alp-1)*n(+1)^(1-alp)+(1-del)*exp(-(gam+log(e(+1)))))/(c(+2)*P(+2)*m(+1))=0;
+W = l/n;
+-(psi/(1-psi))*(c*P/(1-n))+l/n = 0;
+R = P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(-alp)/W;
+1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)/(m*l*c(+1)*P(+1)) = 0;
+c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1);
+P*c = m;
+m-1+d = l;
+e = exp(e_a);
+y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a));
+gy_obs = dA*y/y(-1);
+gp_obs = (p/p(-1))*m(-1)/dA;
+Y_obs/Y_obs(-1) = gy_obs;
+P_obs/P_obs(-1) = gp_obs;
+end;
+
+initval;
+k = 6;
+m = mst;
+P = 2.25;
+c = 0.45;
+e = 1;
+W = 4;
+R = 1.02;
+d = 0.85;
+n = 0.19;
+l = 0.86;
+y = 0.6;
+gy_obs = exp(gam);
+gp_obs = exp(-gam); 
+dA = exp(gam);
+end;
+
+shocks;
+var e_a; stderr 0.014;
+var e_m; stderr 0.005;
+end;
+
+steady;
+
+check;
+
+estimated_params;
+alp, beta_pdf, 0.356, 0.02; 
+bet, beta_pdf, 0.993, 0.002;
+gam, normal_pdf, 0.0085, 0.003;
+mst, normal_pdf, 1.0002, 0.007;
+rho, beta_pdf, 0.129, 0.223;
+psi, beta_pdf, 0.65, 0.05;
+del, beta_pdf, 0.01, 0.005;
+stderr e_a, inv_gamma_pdf, 0.035449, inf;
+stderr e_m, inv_gamma_pdf, 0.008862, inf;
+end;
+
+varobs P_obs Y_obs;
+
+observation_trends;
+P_obs (log(exp(gam)/mst));
+Y_obs (gam);
+end;
+
+options_.unit_root_vars = {'P_obs'; 'Y_obs'};
+
+//stoch_simul(order=1,nomoments,irf=0);
+//estimation(datafile=fsdat,nobs=192,loglinear,mh_replic=2000,mh_nblocks=2,mh_drop=0.45,smoother,forecast=5,bayesian_irf,moments_varendo,filtered_vars,load_mh_file,mode_compute=0,mode_file=fs2000a_mode,nodiagnostic) P_obs Y_obs gp_obs gy_obs c;
+//estimation(datafile=fsdat,nobs=192,loglinear,mh_replic=0,mh_nblocks=2,mh_drop=0.45,forecast=5,load_mh_file,mode_compute=0,mode_file=fs2000a_mode,nodiagnostic) P_obs Y_obs gp_obs gy_obs c;
+estimation(datafile=fsdat,nobs=192,loglinear,mh_replic=0,mh_nblocks=2,mh_drop=0.45,bayesian_irf,moments_varendo,load_mh_file,mode_compute=0,mode_file=fs2000a_mode,nodiagnostic) P_obs Y_obs gp_obs gy_obs c;
diff --git a/tags/v_3.062/tests/fs2000/fs2000a_steadystate.m b/tags/v_3.062/tests/fs2000/fs2000a_steadystate.m
new file mode 100644
index 0000000000000000000000000000000000000000..849c04b26d38bd4417ce8b022d92920b1b814617
--- /dev/null
+++ b/tags/v_3.062/tests/fs2000/fs2000a_steadystate.m
@@ -0,0 +1,53 @@
+% computes the steady state of fs2000 analyticaly
+% largely inspired by the program of F. Schorfheide
+function [ys,check] = fs2000a_steadystate(junk,ys)
+  global alp bet gam mst rho psi del;
+
+  check = 0;
+  
+  dA = exp(gam);
+  gst = 1/dA;
+  m = mst;
+  
+  khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1));
+  xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1);
+  nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp );
+  n  = xist/(nust+xist);
+  p  = xist + nust;
+  k  = khst*n;
+
+  l  = psi*mst*n/( (1-psi)*(1-n) );
+  c  = mst/p;
+  d  = l - mst + 1;
+  y  = k^alp*n^(1-alp)*gst^alp;
+  r  = mst/bet;
+  w  = l/n;
+  ist  = y-c;
+  q  = 1 - d;
+
+  e = 1;
+  
+  gp_obs = m/dA;
+  gy_obs = dA;
+  
+  P_obs = 1;
+  Y_obs = 1;
+  
+  ys =[
+      c
+      d
+      dA
+      e
+      gp_obs
+      gy_obs
+      k
+      l
+      m
+      n
+      p
+      P_obs
+      r
+      w
+      y
+      Y_obs
+      ];
\ No newline at end of file
diff --git a/tags/v_3.062/tests/fs2000/fsdat.m b/tags/v_3.062/tests/fs2000/fsdat.m
new file mode 100644
index 0000000000000000000000000000000000000000..5a0e3658d4031fe8f32bee59f33c515549b8ee23
--- /dev/null
+++ b/tags/v_3.062/tests/fs2000/fsdat.m
@@ -0,0 +1,210 @@
+data_q = [
+18.02 1474.5 150.2
+17.94 1538.2 150.9
+18.01 1584.5 151.4
+18.42 1644.1 152
+18.73 1678.6 152.7
+19.46 1693.1 153.3
+19.55 1724   153.9
+19.56 1758.2 154.7
+19.79 1760.6 155.4
+19.77 1779.2 156
+19.82 1778.8 156.6
+20.03 1790.9 157.3
+20.12 1846   158
+20.1  1882.6 158.6
+20.14 1897.3 159.2
+20.22 1887.4 160
+20.27 1858.2 160.7
+20.34 1849.9 161.4
+20.39 1848.5 162
+20.42 1868.9 162.8
+20.47 1905.6 163.6
+20.56 1959.6 164.3
+20.62 1994.4 164.9
+20.78 2020.1 165.7
+21    2030.5 166.5
+21.2  2023.6 167.2
+21.33 2037.7 167.9
+21.62 2033.4 168.7
+21.71 2066.2 169.5
+22.01 2077.5 170.2
+22.15 2071.9 170.9
+22.27 2094   171.7
+22.29 2070.8 172.5
+22.56 2012.6 173.1
+22.64 2024.7 173.8
+22.77 2072.3 174.5
+22.88 2120.6 175.3
+22.92 2165   176.045
+22.91 2223.3  176.727
+22.94 2221.4  177.481
+23.03 2230.95 178.268
+23.13 2279.22 179.694
+23.22 2265.48 180.335
+23.32 2268.29 181.094
+23.4  2238.57 181.915
+23.45 2251.68 182.634
+23.51 2292.02 183.337
+23.56 2332.61 184.103
+23.63 2381.01 184.894
+23.75 2422.59 185.553
+23.81 2448.01 186.203
+23.87 2471.86 186.926
+23.94 2476.67 187.68
+24    2508.7  188.299
+24.07 2538.05 188.906
+24.12 2586.26 189.631
+24.29 2604.62 190.362
+24.35 2666.69 190.954
+24.41 2697.54 191.56
+24.52 2729.63 192.256
+24.64 2739.75 192.938
+24.77 2808.88 193.467
+24.88 2846.34 193.994
+25.01 2898.79 194.647
+25.17 2970.48 195.279
+25.32 3042.35 195.763
+25.53 3055.53 196.277
+25.79 3076.51 196.877
+26.02 3102.36 197.481
+26.14 3127.15 197.967
+26.31 3129.53 198.455
+26.6  3154.19 199.012
+26.9  3177.98 199.572
+27.21 3236.18 199.995
+27.49 3292.07 200.452
+27.75 3316.11 200.997
+28.12 3331.22 201.538
+28.39 3381.86 201.955
+28.73 3390.23 202.419
+29.14 3409.65 202.986
+29.51 3392.6  203.584
+29.94 3386.49 204.086
+30.36 3391.61 204.721
+30.61 3422.95 205.419
+31.02 3389.36 206.13
+31.5  3481.4  206.763
+31.93 3500.95 207.362
+32.27 3523.8  208
+32.54 3533.79 208.642
+33.02 3604.73 209.142
+33.2  3687.9  209.637
+33.49 3726.18 210.181
+33.95 3790.44 210.737
+34.36 3892.22 211.192
+34.94 3919.01 211.663
+35.61 3907.08 212.191
+36.29 3947.11 212.708
+37.01 3908.15 213.144
+37.79 3922.57 213.602
+38.96 3879.98 214.147
+40.13 3854.13 214.7
+41.05 3800.93 215.135
+41.66 3835.21 215.652
+42.41 3907.02 216.289
+43.19 3952.48 216.848
+43.69 4044.59 217.314
+44.15 4072.19 217.776
+44.77 4088.49 218.338
+45.57 4126.39 218.917
+46.32 4176.28 219.427
+47.07 4260.08 219.956
+47.66 4329.46 220.573
+48.63 4328.33 221.201
+49.42 4345.51 221.719
+50.41 4510.73 222.281
+51.27 4552.14 222.933
+52.35 4603.65 223.583
+53.51 4605.65 224.152
+54.65 4615.64 224.737
+55.82 4644.93 225.418
+56.92 4656.23 226.117
+58.18 4678.96 226.754
+59.55 4566.62 227.389
+61.01 4562.25 228.07
+62.59 4651.86 228.689
+64.15 4739.16 229.155
+65.37 4696.82 229.674
+66.65 4753.02 230.301
+67.87 4693.76 230.903
+68.86 4615.89 231.395
+69.72 4634.88 231.906
+70.66 4612.08 232.498
+71.44 4618.26 233.074
+72.08 4662.97 233.546
+72.83 4763.57 234.028
+73.48 4849    234.603
+74.19 4939.23 235.153
+75.02 5053.56 235.605
+75.58 5132.87 236.082
+76.25 5170.34 236.657
+76.81 5203.68 237.232
+77.63 5257.26 237.673
+78.25 5283.73 238.176
+78.76 5359.6  238.789
+79.45 5393.57 239.387
+79.81 5460.83 239.861
+80.22 5466.95 240.368
+80.84 5496.29 240.962
+81.45 5526.77 241.539
+82.09 5561.8  242.009
+82.68 5618    242.52
+83.33 5667.39 243.12
+84.09 5750.57 243.721
+84.67 5785.29 244.208
+85.56 5844.05 244.716
+86.66 5878.7  245.354
+87.44 5952.83 245.966
+88.45 6010.96 246.46
+89.39 6055.61 247.017
+90.13 6087.96 247.698
+90.88 6093.51 248.374
+92    6152.59 248.928
+93.18 6171.57 249.564
+94.14 6142.1  250.299
+95.11 6078.96 251.031
+96.27 6047.49 251.65
+97    6074.66 252.295
+97.7  6090.14 253.033
+98.31 6105.25 253.743
+99.13 6175.69 254.338
+99.79 6214.22 255.032
+100.17 6260.74 255.815
+100.88 6327.12 256.543
+101.84 6327.93 257.151
+102.35 6359.9  257.785
+102.83 6393.5  258.516
+103.51 6476.86 259.191
+104.13 6524.5  259.738
+104.71 6600.31 260.351
+105.39 6629.47 261.04
+106.09 6688.61 261.692
+106.75 6717.46 262.236
+107.24 6724.2  262.847
+107.75 6779.53 263.527
+108.29 6825.8  264.169
+108.91 6882    264.681
+109.24 6983.91 265.258
+109.74 7020    265.887
+110.23 7093.12 266.491
+111    7166.68 266.987
+111.43 7236.5  267.545
+111.76 7311.24 268.171
+112.08 7364.63 268.815
+];
+%GDPD  GDPQ   GPOP
+
+series = zeros(193,2);
+series(:,2) = data_q(:,1);
+series(:,1) = 1000*data_q(:,2)./data_q(:,3);
+
+Y_obs = series(:,1);
+P_obs = series(:,2);
+
+series = series(2:193,:)./series(1:192,:);
+
+gy_obs = series(:,1);
+gp_obs = series(:,2);
+
+ti = [1950:0.25:1997.75];
\ No newline at end of file
diff --git a/tags/v_3.062/tests/fs2000/test.m b/tags/v_3.062/tests/fs2000/test.m
new file mode 100644
index 0000000000000000000000000000000000000000..f05f5f1c45875b0508f622724647c0285081f9e1
--- /dev/null
+++ b/tags/v_3.062/tests/fs2000/test.m
@@ -0,0 +1,4 @@
+function test(a,b,n)
+  if max(max(abs(a)-abs(b))) > 1e-5
+    error(['Test error in test ' int2str(n)])
+  end
\ No newline at end of file
diff --git a/tags/v_3.062/tests/ls2003/data_ca1.m b/tags/v_3.062/tests/ls2003/data_ca1.m
new file mode 100644
index 0000000000000000000000000000000000000000..b0b4f054613b41ebd91b9492f4edca5d38f6cb26
--- /dev/null
+++ b/tags/v_3.062/tests/ls2003/data_ca1.m
@@ -0,0 +1,100 @@
+data = [0.928467646476  11.8716889412   20  0.418037507392  0.227382377518 ...
+-0.705994063083 11.7522582094   21.25   1.09254424511   -1.29488274994 ...
+-0.511895351926 9.68144025625   17.25   -1.66150408407  0.331508393098 ...
+-0.990955971267 10.0890781236   17  1.43016275252   -2.43589670141 ...
+-0.981233061806 12.1094840679   18.25   2.91293288733   -0.790246576864 ...
+-0.882182844512 8.54559460406   15  0.419579139481  0.358729719566 ...
+-0.930893002836 6.19238374422   12.5    -1.48847457959  0.739779938797 ...
+1.53158206947   2.76544271886   11.5    -0.336216769682 0.455559918769 ...
+2.2659052834    5.47418162513   11  0.306436789767  -0.0707985731221 ...
+1.05419803797   6.35698426189   11  0.140700250477  0.620401487202 ...
+1.20161076793   3.4253301593    11  0.461296492351  0.14354323987 ...
+1.73934077971   4.70926070322   11.5    1.35798282982   0.38564694435 ...
+1.71735262584   3.54232079749   12.5    2.9097529155    -0.804308583301 ...
+0.426343657844  3.32719108897   13  1.64214862652   -1.18214664701 ...
+1.67751812324   2.93444727338   11.25   0.344434910651  -1.6529373719 ...
+1.37013301099   4.72303361923   11.75   2.61511526582   0.327684243041 ...
+0.281231073781  4.4893853071    10.5    1.17043449257   1.12855106649 ...
+1.53638992834   3.7325309699    10.25   -0.683947046728 0.11943538737 ...
+1.68081431462   3.34729969129   10  1.41159342106   -1.59065680853 ...
+-0.343321601133 5.05563513564   12  1.75117366498   -2.40127764642 ...
+0.873415608666  3.2779996255    10.25   -1.39895866711  0.0971444398216 ...
+0.26399696544   4.78229419828   9.75    0.0914692438124 0.299310457612 ...
+-0.562233624818 3.88598638237   9.75    -0.0505384765105    0.332826708151 ...
+2.15161914936   3.84859710132   8.75    -3.44811080489  0.789138678784 ...
+1.2345093726    5.62225030942   9.5 -0.366945407434 2.32974981198 ...
+1.62554967459   4.24667132831   10  -0.800958371402 0.0293183770935 ...
+1.33035402527   2.75248979249   9.75    -0.855723113225 0.852493939813 ...
+1.52078814077   3.53415985826   9.75    -3.37963469203  -1.05133958119 ...
+1.16704983697   4.92754079464   10.75   -3.0142303324   0.459907431978 ...
+0.277213572101  4.55532133037   11.75   -0.851995599415 2.03242034852 ...
+0.842215068977  3.11164509647   12.25   -1.08290421696  0.014323281961 ...
+1.05325028606   4.92882647578   13.5    -1.1953883867   0.706764750654 ...
+0.453051253568  6.82998950103   13.5    0.111803656462  0.088462593153 ...
+0.199885995525  5.82643354662   13.5    -0.920501518421 -0.26504958666 ...
+0.137907999624  2.66076369132   13.5    -1.17122929812  -0.995642430514 ...
+0.721949686709  5.70497876823   14.25   1.19378169018   -1.10644839651 ...
+-0.418465249225 3.75861110232   14.75   -1.03131674824  0.188507675831 ...
+-0.644028342116 4.15104788154   13.75   -1.48911756546  0.204560913792 ...
+-0.848213852668 5.65580324027   12.75   0.677011703877  -0.849628054542 ...
+-1.51954076928  11.4866911266   11.25   -0.446024680774 -0.456342350765 ...
+0.265275055215  2.85472749592   9.75    -0.598778202436 -0.907311640831 ...
+0.356162529063  2.29614015658   9.5 -0.46820788432  -1.22130883441 ...
+0.368308864363  -0.539083504685 8   -0.781333991956 0.374007246518 ...
+-0.145751412732 1.61507621789   8.25    3.68291932628   1.32438399845 ...
+0.285457283664  2.14334055993   7   1.42819405379   -0.00818660844123 ...
+0.372390129412  1.60000213334   6.25    0.626106424052  -0.10136772765 ...
+0.382720203063  1.72614243263   7.25    4.89631941021   -1.10060711916 ...
+0.737957515573  2.90430582851   6   -0.0422721010314    0.4178952497 ...
+0.649532581668  0.657135682543  6   0.692066153971  0.422299120276 ...
+0.627159201987  1.70352689913   5.75    2.62066711305   -1.29237304034 ...
+0.905441299817  1.95663197267   5.5 1.5949697565    -0.27115830703 ...
+1.49322577898   -2.08741765309  6.25    1.23027694802   0.418336889527 ...
+1.48750731567   -1.57274121871  8   3.01660550994   -0.893958254365 ...
+1.39783858087   2.22623066426   7   -0.80842319214  1.47625453886 ...
+0.89274836317   1.30378081742   8   -0.249485058661 0.159871204185 ...
+0.920652246088  4.1437741965    9.75    2.8204453623    0.178149239655 ...
+-0.00264276644799   3.07989972052   8.75    -2.56342461535  2.105998353 ...
+0.0198190461681 0.766283759256  8   -1.15838865989  1.56888883418 ...
+0.440050515311  0.127570085801  7.5 0.0400753569995 0.028914333532 ...
+0.129536637901  1.78174141526   6.75    0.959943962785  0.307781224401 ...
+0.398549827172  3.03606770667   6.5 -0.340209794742 0.100979469478 ...
+1.17174775425   0.629625188037  5.75    0.403003686814  0.902394579377 ...
+0.991163981251  2.50862910684   4.75    -1.44963996982  1.16150986945 ...
+0.967603566096  2.12003739013   4.75    0.610846030775  -0.889994896068 ...
+1.14689383604   1.24185011459   4.75    2.01098091308   -1.73846431001 ...
+1.32593824054   0.990713820685  4.75    -0.0955142989332    -0.0369257308362 ...
+0.861135002644  -0.24744943605  6   1.72793107135   -0.691506789639 ...
+1.26870850151   2.09844764887   6.5 1.50720217572   -1.31399187077 ...
+0.260364987715  1.10650139716   6.5 1.13659047496   0.0720441664643 ...
+1.09731242214   0.490796381346  7.25    4.59123894147   -2.14073070763 ...
+1.63792841781   0.612652594286  6.75    1.79604605035   -0.644363995357 ...
+1.48465576034   0.978295808687  6.75    -2.00753620902  1.39437534964 ...
+1.0987608663    4.25212569087   6.25    -2.58901196498  2.56054320803 ...
+1.42592178132   2.76984518311   6.25    0.888195752358  1.03114549274 ...
+1.52958239462   1.31795955491   6.5 -0.902907564082 -0.0952198893776 ...
+1.0170168994    2.14733589918   7   -1.3054866978   2.68803738466 ...
+0.723253652257  3.43552889347   7.5 1.8213700853    0.592593586195 ...
+1.24720806008   3.87383806577   7.5 0.0522300654168 0.988871238698 ...
+0.482531471239  2.67793287032   7.5 2.9693944293    -0.108591166081 ...
+0.154056100439  0.927269031704  6.75    0.119222057561  3.30489209451 ...
+0.0694865769274 6.65916526788   6.25    0.889014476084  -2.83976849035 ...
+-0.121267434867 0.341442615696  5.25    0.323053239216  -3.49289229012 ...
+0.726473690375  -3.5423730964   4   2.19149290449   -3.20855054004 ...
+1.39271709108   2.63121085718   3.75    0.88406577736   0.75622580197 ...
+1.07502077727   5.88578836799   4.25    -2.55088273352  2.89018116374 ...
+0.759049251607  4.24703604223   4.5 0.575687665685  -0.388292506167 ...
+]; 
+ 
+data = reshape(data,5,86)'; 
+y_obs = data(:,1); 
+pie_obs = data(:,2); 
+R_obs = data(:,3); 
+de = data(:,4); 
+dq = data(:,5); 
+ 
+%Country: Canada 
+%Sample Range: 1981:2 to 2002:3 
+%Observations: 86 
+%Variables: Real GDP Growth [%], Inflation [annualized %], Nom Rate [%], 
+%           Exchange Rate Change [%], Terms of Trade Change [%] 
diff --git a/tags/v_3.062/tests/ls2003/ls2003.mod b/tags/v_3.062/tests/ls2003/ls2003.mod
new file mode 100644
index 0000000000000000000000000000000000000000..1d2ec9de496e1e9010bdfeaef796b258735eaccc
--- /dev/null
+++ b/tags/v_3.062/tests/ls2003/ls2003.mod
@@ -0,0 +1,65 @@
+var y y_s R pie dq pie_s de A y_obs pie_obs R_obs;
+varexo e_R e_q e_ys e_pies e_A;
+
+parameters psi1 psi2 psi3 rho_R tau alpha rr k rho_q rho_A rho_ys rho_pies;
+
+psi1 = 1.54;
+psi2 = 0.25;
+psi3 = 0.25;
+rho_R = 0.5;
+alpha = 0.3;
+rr = 2.51;
+k = 0.5;
+tau = 0.5;
+rho_q = 0.4;
+rho_A = 0.2;
+rho_ys = 0.9;
+rho_pies = 0.7;
+
+
+model(linear);
+y = y(+1) - (tau +alpha*(2-alpha)*(1-tau))*(R-pie(+1))-alpha*(tau +alpha*(2-alpha)*(1-tau))*dq(+1) + alpha*(2-alpha)*((1-tau)/tau)*(y_s-y_s(+1))-A(+1);
+pie = exp(-rr/400)*pie(+1)+alpha*exp(-rr/400)*dq(+1)-alpha*dq+(k/(tau+alpha*(2-alpha)*(1-tau)))*y+alpha*(2-alpha)*(1-tau)/(tau*(tau+alpha*(2-alpha)*(1-tau)))*y_s;
+pie = de+(1-alpha)*dq+pie_s;
+R = rho_R*R(-1)+(1-rho_R)*(psi1*pie+psi2*(y+alpha*(2-alpha)*((1-tau)/tau)*y_s)+psi3*de)+e_R;
+dq = rho_q*dq(-1)+e_q;
+y_s = rho_ys*y_s(-1)+e_ys;
+pie_s = rho_pies*pie_s(-1)+e_pies;
+A = rho_A*A(-1)+e_A;
+y_obs = y-y(-1)+A;
+pie_obs = 4*pie;
+R_obs = 4*R;
+end;
+
+shocks;
+var e_R = 1.25^2;
+var e_q = 2.5^2;
+var e_A = 1.89;
+var e_ys = 1.89;
+var e_pies = 1.89;
+end;
+
+varobs y_obs R_obs pie_obs dq de;
+
+estimated_params;
+psi1 , gamma_pdf,1.5,0.5;
+psi2 , gamma_pdf,0.25,0.125;
+psi3 , gamma_pdf,0.25,0.125;
+rho_R ,beta_pdf,0.5,0.2;
+alpha ,beta_pdf,0.3,0.1;
+rr ,gamma_pdf,2.5,1;
+k , gamma_pdf,0.5,0.25;
+tau ,gamma_pdf,0.5,0.2;
+rho_q ,beta_pdf,0.4,0.2;
+rho_A ,beta_pdf,0.5,0.2;
+rho_ys ,beta_pdf,0.8,0.1;
+rho_pies,beta_pdf,0.7,0.15;
+stderr e_R,inv_gamma_pdf,1.2533,0.6551;
+stderr e_q,inv_gamma_pdf,2.5066,1.3103;
+stderr e_A,inv_gamma_pdf,1.2533,0.6551;
+stderr e_ys,inv_gamma_pdf,1.2533,0.6551;
+stderr e_pies,inv_gamma_pdf,1.88,0.9827;
+end;
+
+estimation(datafile=data_ca1,first_obs=8,nobs=79,mh_nblocks=10,prefilter=1,mh_jscale=0.5,mh_replic=0);
+
diff --git a/tags/v_3.062/tests/ls2003/ls2003a.mod b/tags/v_3.062/tests/ls2003/ls2003a.mod
new file mode 100644
index 0000000000000000000000000000000000000000..1d2ec9de496e1e9010bdfeaef796b258735eaccc
--- /dev/null
+++ b/tags/v_3.062/tests/ls2003/ls2003a.mod
@@ -0,0 +1,65 @@
+var y y_s R pie dq pie_s de A y_obs pie_obs R_obs;
+varexo e_R e_q e_ys e_pies e_A;
+
+parameters psi1 psi2 psi3 rho_R tau alpha rr k rho_q rho_A rho_ys rho_pies;
+
+psi1 = 1.54;
+psi2 = 0.25;
+psi3 = 0.25;
+rho_R = 0.5;
+alpha = 0.3;
+rr = 2.51;
+k = 0.5;
+tau = 0.5;
+rho_q = 0.4;
+rho_A = 0.2;
+rho_ys = 0.9;
+rho_pies = 0.7;
+
+
+model(linear);
+y = y(+1) - (tau +alpha*(2-alpha)*(1-tau))*(R-pie(+1))-alpha*(tau +alpha*(2-alpha)*(1-tau))*dq(+1) + alpha*(2-alpha)*((1-tau)/tau)*(y_s-y_s(+1))-A(+1);
+pie = exp(-rr/400)*pie(+1)+alpha*exp(-rr/400)*dq(+1)-alpha*dq+(k/(tau+alpha*(2-alpha)*(1-tau)))*y+alpha*(2-alpha)*(1-tau)/(tau*(tau+alpha*(2-alpha)*(1-tau)))*y_s;
+pie = de+(1-alpha)*dq+pie_s;
+R = rho_R*R(-1)+(1-rho_R)*(psi1*pie+psi2*(y+alpha*(2-alpha)*((1-tau)/tau)*y_s)+psi3*de)+e_R;
+dq = rho_q*dq(-1)+e_q;
+y_s = rho_ys*y_s(-1)+e_ys;
+pie_s = rho_pies*pie_s(-1)+e_pies;
+A = rho_A*A(-1)+e_A;
+y_obs = y-y(-1)+A;
+pie_obs = 4*pie;
+R_obs = 4*R;
+end;
+
+shocks;
+var e_R = 1.25^2;
+var e_q = 2.5^2;
+var e_A = 1.89;
+var e_ys = 1.89;
+var e_pies = 1.89;
+end;
+
+varobs y_obs R_obs pie_obs dq de;
+
+estimated_params;
+psi1 , gamma_pdf,1.5,0.5;
+psi2 , gamma_pdf,0.25,0.125;
+psi3 , gamma_pdf,0.25,0.125;
+rho_R ,beta_pdf,0.5,0.2;
+alpha ,beta_pdf,0.3,0.1;
+rr ,gamma_pdf,2.5,1;
+k , gamma_pdf,0.5,0.25;
+tau ,gamma_pdf,0.5,0.2;
+rho_q ,beta_pdf,0.4,0.2;
+rho_A ,beta_pdf,0.5,0.2;
+rho_ys ,beta_pdf,0.8,0.1;
+rho_pies,beta_pdf,0.7,0.15;
+stderr e_R,inv_gamma_pdf,1.2533,0.6551;
+stderr e_q,inv_gamma_pdf,2.5066,1.3103;
+stderr e_A,inv_gamma_pdf,1.2533,0.6551;
+stderr e_ys,inv_gamma_pdf,1.2533,0.6551;
+stderr e_pies,inv_gamma_pdf,1.88,0.9827;
+end;
+
+estimation(datafile=data_ca1,first_obs=8,nobs=79,mh_nblocks=10,prefilter=1,mh_jscale=0.5,mh_replic=0);
+
diff --git a/tags/v_3.062/tests/objectives/CVS/Entries b/tags/v_3.062/tests/objectives/CVS/Entries
new file mode 100644
index 0000000000000000000000000000000000000000..6957afc35a314fad83a584bd15c3b9960ae7d6cf
--- /dev/null
+++ b/tags/v_3.062/tests/objectives/CVS/Entries
@@ -0,0 +1,7 @@
+/sgu_ex1.log/1.1.2.1/Sun Feb  6 15:45:32 2005//Tv3_03
+/sgu_ex1.m/1.1.2.1/Sun Feb  6 15:45:32 2005//Tv3_03
+/sgu_ex1.mat/1.1.2.1/Sun Feb  6 15:45:32 2005//Tv3_03
+/sgu_ex1.mod/1.1.2.1/Sun Feb  6 15:45:32 2005//Tv3_03
+/sgu_ex1_ff.m/1.1.2.1/Sun Feb  6 15:45:32 2005//Tv3_03
+/sgu_ex1_fff.m/1.1.2.1/Sun Feb  6 15:45:32 2005//Tv3_03
+D
diff --git a/tags/v_3.062/tests/objectives/CVS/Repository b/tags/v_3.062/tests/objectives/CVS/Repository
new file mode 100644
index 0000000000000000000000000000000000000000..f3767c29d568ddf175fc4ec68390da52739037df
--- /dev/null
+++ b/tags/v_3.062/tests/objectives/CVS/Repository
@@ -0,0 +1 @@
+dynare_test/tests/objectives
diff --git a/tags/v_3.062/tests/objectives/CVS/Root b/tags/v_3.062/tests/objectives/CVS/Root
new file mode 100644
index 0000000000000000000000000000000000000000..880aa979000a219390a445093572d46f0d1b3f2b
--- /dev/null
+++ b/tags/v_3.062/tests/objectives/CVS/Root
@@ -0,0 +1 @@
+:ext:pythie.cepremap.cnrs.fr/var/lib/cvs
diff --git a/tags/v_3.062/tests/objectives/CVS/Tag b/tags/v_3.062/tests/objectives/CVS/Tag
new file mode 100644
index 0000000000000000000000000000000000000000..9f3656bd3b4a39dcd6440c00fecf83cce6150bc7
--- /dev/null
+++ b/tags/v_3.062/tests/objectives/CVS/Tag
@@ -0,0 +1 @@
+Tv3_03
diff --git a/tags/v_3.062/tests/objectives/sgu_ex1.log b/tags/v_3.062/tests/objectives/sgu_ex1.log
new file mode 100644
index 0000000000000000000000000000000000000000..5ec8763027a5fd734c104390dbc7b958a4af30df
--- /dev/null
+++ b/tags/v_3.062/tests/objectives/sgu_ex1.log
@@ -0,0 +1,15 @@
+
+
+MATRIX OF COVARIANCE OF EXOGENOUS SHOCKS
+
+Variables    e         
+e            1.000000
+POLICY AND TRANSITION FUNCTIONS
+                                       k               a               c
+Constant                   -1.552215               0       -0.969516
+(correction)                0.241022               0       -0.096072
+k(-1)                       0.419109               0        0.252523
+e                           1.397031        1.000000        0.841743
+k(-1)k(-1)                 -0.003501               0       -0.002559
+e e                        -0.038899               0       -0.028434
+k(-1) e                    -0.023340               0       -0.017061
diff --git a/tags/v_3.062/tests/objectives/sgu_ex1.m b/tags/v_3.062/tests/objectives/sgu_ex1.m
new file mode 100644
index 0000000000000000000000000000000000000000..01307659c5e17b2acb804ee9f44ca5fd910d8a28
--- /dev/null
+++ b/tags/v_3.062/tests/objectives/sgu_ex1.m
@@ -0,0 +1,98 @@
+clear all
+global scalv_ ex_ recur_ recurs_ ys_ y_ exe_ lgy_ lgx_ lgr_ dsmpl_ endval_
+ ...
+global endo_nbr exo_nbr iy_  ykmin_  ykmax_  xkmin_  xkmax_ zkmin_ zkmax_ iter_
+ ...
+global dynatol_ slowc_ maxit_ valf_ ys0_ recurs0_ timing_ ct_ gstep_ Sigma_e_ fname_ lgx_orig_ord_
+dsmpl_=0;
+dynatol_=0.00001;
+maxit_=10;
+slowc_=1;
+timing_=0;
+ct_=0;
+gstep_=1e-2;
+endval_=0;rplottype_=0;
+fname_ = 'sgu_ex1';
+logname_ = 'sgu_ex1.log';
+diary off;
+warning off;
+delete sgu_ex1.log;
+warning on;
+warning backtrace;
+diary sgu_ex1.log;
+
+iter_ = 20000;
+
+
+
+
+global alpha beta delta gamma rho 
+
+
+beta = 0.95;
+delta = 1;
+alpha = 0.3;
+rho = 0;
+gamma = 2;
+
+lgy_ = 'a';
+lgy_ = str2mat(lgy_,'c');
+lgy_ = str2mat(lgy_,'k');
+lgx_ = 'e';
+lgx_orig_ord_ = [1];
+endo_nbr = 3;
+exo_nbr = 1;
+recur_nbr = 0;
+iy_ = [ 1 0 2];
+temp = [ 3 4 5];
+iy_ = [ iy_ ; temp ];
+temp = [ 6 7 0];
+iy_ = [ iy_ ; temp ];
+ykmin_ = 1;
+ykmax_ = 1;
+xkmin_ = 0;
+xkmax_ = 0;
+zkmin_ = 0;
+zkmax_ = 0;
+
+
+% INITVAL 
+valf_ = 0;
+endval_=0;
+ys_ = zeros(3,1);
+exe_ = zeros(1,1);
+ys0_ = 0;
+ex0_ = 0;
+recurs0_ = 0;
+ys_(3)=0;
+ys_(2)=0;
+ys_(1)=0;
+exe_(1)=0;
+if exo_nbr > 0;
+  ex_ =ones(iter_ + xkmin_ + xkmax_,1) * exe_';
+end;
+
+
+Sigma_e_ = 1;
+
+var_list_ = [];
+options.ar = 0;
+options.dr_algo = 0;
+options.simul_algo = 0;
+options.nocorr = 1;
+options.drop = 100;
+options.linear = 0;
+options.nofunctions = 0;
+options.nomoments = 1;
+options.irf = 0;
+options.order = 2;
+options.replic = 0;
+stoch_simul(options,var_list_);
+
+
+global dr_
+dr_obj_ = dr_;
+
+save sgu_ex1 dr_obj_;
+
+diary off
diff --git a/tags/v_3.062/tests/objectives/sgu_ex1.mat b/tags/v_3.062/tests/objectives/sgu_ex1.mat
new file mode 100644
index 0000000000000000000000000000000000000000..69413985099ccb48f898c4ba4808132bda33c23e
Binary files /dev/null and b/tags/v_3.062/tests/objectives/sgu_ex1.mat differ
diff --git a/tags/v_3.062/tests/objectives/sgu_ex1.mod b/tags/v_3.062/tests/objectives/sgu_ex1.mod
new file mode 100644
index 0000000000000000000000000000000000000000..36e5500303d3f04db5a309199e9fe9d300054451
--- /dev/null
+++ b/tags/v_3.062/tests/objectives/sgu_ex1.mod
@@ -0,0 +1,33 @@
+periods 20000;
+var c k a;
+varexo e;
+parameters alpha beta delta gamma rho;
+
+beta = 0.95;
+delta = 1;
+alpha = 0.3;
+rho = 0;
+gamma = 2;
+
+model;
+exp(c) + exp(k) = (1-delta) * exp(k(-1)) + exp(a) * exp(k(-1))^alpha;
+exp(c)^(-gamma) = beta * exp(c(+1))^(-gamma) * (exp(a(+1)) * alpha * exp(k)^(alpha-1) + 1 - delta);
+a = rho * a(-1) + e;
+end;
+
+initval;
+k=0;
+c=0;
+a=0;
+e=0;
+end;
+
+Sigma_e_ = 1;
+
+stoch_simul(nomoments,irf=0,nocorr,ar=0);
+
+global dr_
+dr_obj_ = dr_;
+
+save sgu_ex1 dr_obj_;
+
diff --git a/tags/v_3.062/tests/objectives/sgu_ex1_ff.m b/tags/v_3.062/tests/objectives/sgu_ex1_ff.m
new file mode 100644
index 0000000000000000000000000000000000000000..0b7777363042da2de18e233ed4e83462da95d2bc
--- /dev/null
+++ b/tags/v_3.062/tests/objectives/sgu_ex1_ff.m
@@ -0,0 +1,11 @@
+
+function z=sgu_ex1_ff(y)
+z=zeros(3,1);
+global ex_ it_ recur_
+
+global alpha beta delta gamma rho 
+z(1) = exp(y(4))+exp(y(5)) -((1-delta)*exp(y(2))+exp(y(3))*exp(y(2))^alpha) ...
+;
+z(2) = exp(y(4))^(-gamma) -(beta*exp(y(7))^(-gamma)*(exp(y(6))*alpha*exp( ...
+y(5))^(alpha-1)+1-delta));
+z(3) = y(3) -(rho*y(1)+ex_(it_-1,1));
diff --git a/tags/v_3.062/tests/objectives/sgu_ex1_fff.m b/tags/v_3.062/tests/objectives/sgu_ex1_fff.m
new file mode 100644
index 0000000000000000000000000000000000000000..bf6325be4dc236f069906f508c48d682d86cc310
--- /dev/null
+++ b/tags/v_3.062/tests/objectives/sgu_ex1_fff.m
@@ -0,0 +1,11 @@
+
+function z=sgu_ex1_fff(y)
+z=zeros(3,1);
+global ex_ it_ recur_
+
+global alpha beta delta gamma rho 
+z(1) = exp(y(2))+exp(y(3)) -((1-delta)*exp(y(3))+exp(y(1))*exp(y(3))^alpha) ...
+;
+z(2) = exp(y(2))^(-gamma) -(beta*exp(y(2))^(-gamma)*(exp(y(1))*alpha*exp( ...
+y(3))^(alpha-1)+1-delta));
+z(3) = y(1) -(rho*y(1)+ex_(it_-1,1));
diff --git a/tags/v_3.062/tests/pi2004/idata.m b/tags/v_3.062/tests/pi2004/idata.m
new file mode 100644
index 0000000000000000000000000000000000000000..9ce34b9eb76be9241efcb6ad422f93be370f4fec
--- /dev/null
+++ b/tags/v_3.062/tests/pi2004/idata.m
@@ -0,0 +1,5 @@
+load ych.dat;
+data = log(ych);
+oy = data(:,1);
+oc = data(:,2);
+oh = data(:,3);
\ No newline at end of file
diff --git a/tags/v_3.062/tests/pi2004/ireland.mod b/tags/v_3.062/tests/pi2004/ireland.mod
new file mode 100644
index 0000000000000000000000000000000000000000..51ef3508ffa68fe754bdc337bc4e690aa7c55ad3
--- /dev/null
+++ b/tags/v_3.062/tests/pi2004/ireland.mod
@@ -0,0 +1,90 @@
+var y a k c i h eoy eoc eoh oy oc oh;
+varexo e eeoy eeoc eeoh;
+
+parameters theta rho eta gam bet delta aa r11 r12 r13 r21 r22 r23 r31 r32 r33 scy shc shy;
+
+bet = 0.99;
+delta = 0.025;
+theta = 0.2;
+rho = 0.9959; 
+eta = 1.0051;  
+gam = 0.0045;
+aa = 1.8;
+r11 = 0.99;
+r12 = 0;
+r13 = 0;
+r21 = 0;
+r22 = 0.99;
+r23 = 0;
+r31 = 0;
+r32 = 0;
+r33 = 0.99;
+scy = 0.0040;
+shy = 0.0015;
+shc = 0.0010;
+
+model;
+exp(y) = exp(a)*exp(k(-1))^theta*exp(h)^(1-theta);
+a = (1-rho)*aa+rho*a(-1)+e;
+exp(y) = exp(c) + exp(i);
+eta*exp(k) = (1-delta)*exp(k(-1))+exp(i);
+gam*exp(c)*exp(h) = (1-theta)*exp(y);
+eta/exp(c) = bet*(1/exp(c(+1)))*(theta*(exp(y(+1))/exp(k))+1-delta);
+eoy = r11*eoy(-1) + r12*eoc(-1) + r13*eoh(-1) + eeoy; 
+eoc = r21*eoy(-1) + r22*eoc(-1) + r23*eoh(-1) + scy*eeoy+eeoc; 
+eoh = r31*eoy(-1) + r32*eoc(-1) + r33*eoh(-1) + shy*eeoy+shc*eeoc+eeoh; 
+oy = y + eoy;
+oc = c + eoc;
+oh = h + eoh;
+end;
+
+initval;
+a = 1.7;
+y = 8;
+c = 8;
+k = 10;
+i = 5;
+h = 4;
+eoy = 0;
+eoc = 0;
+eoh = 0;
+oy = y;
+oc = c;
+oh = h;
+end;
+
+steady;
+check;
+
+estimated_params;
+theta , 0.22, 0.1, 0.5;
+rho , 0.99, 0.7, 0.9999; 
+eta , 1.0051, 1, 1.03;  
+gam , 0.0045, 0.001, 0.01;
+aa , 1.8, 0.1, 4;
+r11 , 1.4187, -2, 2;
+r12 , 0.2251, -2, 2;
+r13 , -0.4441, -2, 2;
+r21 , 0.0935, -2, 2;
+r22 , 1.0236, -2, 2;
+r23 , -0.0908, -2, 2;
+r31 , 0.7775, -2, 2;
+r32 , 0.3706, -2, 2;
+r33 , 0.2398, -2, 2;
+scy , 0.0040, -2, 2;
+shy , 0.0015, -2, 2;
+shc , 0.0010, -2, 2;
+stderr e , 0.0056, 0, 0.2;
+stderr eeoy , 0.0070, 0, 0.1;
+stderr eeoc , 0.0069, 0, 0.1;
+stderr eeoh , 0.0018, 0, 0.1;
+end;
+
+varobs oy oc oh;
+
+observation_trends;
+oy (log(eta));
+oc (log(eta));
+end;
+
+estimation(datafile=idata,mode_compute=1,nograph);
\ No newline at end of file
diff --git a/tags/v_3.062/tests/pi2004/ireland1.mod b/tags/v_3.062/tests/pi2004/ireland1.mod
new file mode 100644
index 0000000000000000000000000000000000000000..3d402a5b26fa1ab5316f3b4998bb4d38d5eae148
--- /dev/null
+++ b/tags/v_3.062/tests/pi2004/ireland1.mod
@@ -0,0 +1,90 @@
+var y a k c i h eoy eoc eoh oy oc oh;
+varexo e eeoy eeoc eeoh;
+
+parameters theta rho eta gam bet delta aa r11 r12 r13 r21 r22 r23 r31 r32 r33 scy shc shy;
+
+bet = 0.99;
+delta = 0.025;
+theta = 0.2;
+rho = 0.9959; 
+eta = 1.0051;  
+gam = 0.0045;
+aa = 1.8;
+r11 = 0.99;
+r12 = 0;
+r13 = 0;
+r21 = 0;
+r22 = 0.99;
+r23 = 0;
+r31 = 0;
+r32 = 0;
+r33 = 0.99;
+scy = 0.0040;
+shy = 0.0015;
+shc = 0.0010;
+
+model;
+exp(y) = exp(a)*exp(k(-1))^theta*exp(h)^(1-theta);
+a = (1-rho)*aa+rho*a(-1)+e;
+exp(y) = exp(c) + exp(i);
+eta*exp(k) = (1-delta)*exp(k(-1))+exp(i);
+gam*exp(c)*exp(h) = (1-theta)*exp(y);
+eta/exp(c) = bet*(1/exp(c(+1)))*(theta*(exp(y(+1))/exp(k))+1-delta);
+eoy = r11*eoy(-1) + r12*eoc(-1) + r13*eoh(-1) + eeoy; 
+eoc = r21*eoy(-1) + r22*eoc(-1) + r23*eoh(-1) + scy*eeoy+eeoc; 
+eoh = r31*eoy(-1) + r32*eoc(-1) + r33*eoh(-1) + shy*eeoy+shc*eeoc+eeoh; 
+oy = y + eoy;
+oc = c + eoc;
+oh = h + eoh;
+end;
+
+initval;
+a = 6;
+y = 8;
+c = 7;
+k = 10;
+i = 5;
+h = 4;
+eoy = 0;
+eoc = 0;
+eoh = 0;
+oy = y;
+oc = c;
+oh = h;
+end;
+
+steady;
+check;
+
+estimated_params;
+theta , 0.22;
+rho , 0.99; 
+eta , 1.0051;
+gam , 0.0045;
+aa , 1.8;
+r11 , 1.4187;
+r12 , 0.2251;
+r13 , -0.4441;
+r21 , 0.0935;
+r22 , 1.0236;
+r23 , -0.0908;
+r31 , 0.7775;
+r32 , 0.3706;
+r33 , 0.2398;
+scy , 0.0040;
+shy , 0.0015;
+shc , 0.0010;
+stderr e , 0.0055;
+stderr eeoy , 0.0072;
+stderr eeoc , 0.0057;
+stderr eeoh , 0;
+end;
+
+varobs oy oc oh;
+
+observation_trends;
+oy (log(eta));
+oc (log(eta));
+end;
+
+estimation(datafile=idata,nograph);
\ No newline at end of file
diff --git a/tags/v_3.062/tests/pi2004/ych.dat b/tags/v_3.062/tests/pi2004/ych.dat
new file mode 100644
index 0000000000000000000000000000000000000000..cda9d789d893506bdf43c4bcbef9c402fb20767d
--- /dev/null
+++ b/tags/v_3.062/tests/pi2004/ych.dat
@@ -0,0 +1,218 @@
+    2912.874 2402.117 198.8318
+    2959.229 2423.837 197.3532
+    2955.961 2420.605    198.6
+    2944.613 2436.721 196.7741
+     2865.54 2435.214 192.1405
+    2837.352 2466.823 187.9169
+    2866.923 2465.011 185.2876
+     2869.69 2492.395 182.3583
+    3000.477  2527.61 183.9728
+    3085.831 2561.171 189.8728
+    3255.871 2686.503 196.8083
+    3261.025 2613.773 200.6933
+    3261.223  2681.19 204.7635
+    3206.972 2610.838 206.4334
+    3190.085 2639.831 205.2288
+    3153.084 2650.442 204.8585
+    3168.886 2654.884 207.0878
+    3173.132 2702.447 205.2592
+    3199.558 2706.406 206.3172
+    3320.152 2792.021 211.0694
+    3333.583 2800.407 211.3402
+     3346.44 2812.085 211.4742
+    3319.499 2799.617 209.1935
+    3248.271 2771.542 205.3107
+    3243.519 2772.147 200.5438
+    3268.486 2799.347 198.4387
+    3321.089 2829.358 196.7325
+    3391.751 2878.587 198.3282
+    3498.798 2932.503 201.0089
+    3576.754 2976.939 204.5467
+    3609.954 3003.859 206.0148
+    3649.965 3032.826 207.8803
+    3625.207 3030.321 208.5925
+     3618.86 3032.152  207.818
+    3608.703 3030.239 205.7291
+    3633.863 3063.106 207.7698
+    3634.522 3075.089 207.3511
+    3628.888 3071.301 205.2741
+     3654.03 3085.679 203.4572
+     3594.76 3076.223 198.9135
+    3503.293 3024.868 193.4752
+     3506.06 3040.773 189.2161
+    3580.923  3079.37 190.8325
+    3649.701  3103.69 193.5263
+    3722.726 3149.563 197.1324
+    3809.309 3187.886 200.4534
+    3787.083  3210.28 198.4483
+    3798.375 3203.989 198.1458
+    3865.427 3211.443 199.3042
+    3828.074 3242.787 198.7233
+    3799.687 3219.673 196.7171
+     3719.52 3211.349  193.664
+    3716.143 3198.191 190.8133
+    3789.954 3235.106 190.6975
+    3841.155 3241.368 192.1397
+    3910.574  3301.88 194.0709
+    3974.538 3330.997 194.6404
+    3994.347 3359.016 196.8206
+    4014.564 3370.705 196.2717
+    4017.905 3399.337  194.901
+    4053.971 3405.746 194.5344
+    4080.082 3423.602 195.9045
+    4131.421 3455.826 195.9157
+    4150.544 3470.287  195.917
+    4229.112 3524.024 195.5849
+     4272.24  3572.78 197.0242
+    4336.042 3623.155 197.4885
+    4332.184 3617.237  198.811
+    4465.719 3681.029 200.7368
+    4488.039 3707.114 201.7553
+    4563.691 3758.136 202.7332
+    4657.963 3851.754 205.0265
+    4769.576 3898.869 207.5881
+    4751.946 3898.531 208.8921
+    4775.072 3931.495 209.8688
+    4783.388 3936.299 210.2431
+    4770.091  3946.92 209.1094
+    4766.574 3984.883 207.6639
+    4783.135  3985.69 208.0611
+    4801.834 3991.937 208.7085
+    4894.604 4068.425 208.3597
+    4975.616 4118.065 209.5735
+    5005.671 4179.017 210.9004
+    5009.407 4177.453 211.3179
+    5086.308 4204.501 212.5445
+    5084.863  4213.54 213.6703
+    5100.858 4214.495 214.3839
+    5063.156 4226.537 213.5259
+    5036.423 4230.978 211.4778
+    5032.681 4228.959 208.3091
+    5053.799 4241.721 205.5294
+     4965.09 4203.845 202.0428
+    5116.926 4261.198 201.5087
+    5152.069  4275.63 201.2279
+    5167.576 4284.769 200.0614
+    5180.986 4331.279 201.1027
+    5237.217 4339.349 201.0968
+    5342.982 4395.387 202.4846
+    5397.077 4438.577 202.6435
+    5484.454 4521.399 204.6093
+    5599.656 4580.229 206.5316
+    5605.247 4551.878  207.638
+    5560.139 4547.278  207.561
+    5550.477 4512.704 208.2113
+    5422.633 4450.734 207.0236
+    5407.967 4444.172 205.7419
+    5341.599 4438.929 204.6589
+    5248.491 4344.377  200.536
+    5098.451 4356.942 193.2349
+    5127.117  4412.68    190.6
+    5224.673 4451.618 191.7895
+    5266.744 4478.207 193.5049
+    5416.411 4553.764 195.7526
+    5473.807 4575.388 195.9103
+    5496.508 4600.334 195.6317
+    5542.322  4642.48 195.9109
+    5620.583 4677.803 197.1447
+    5681.448 4680.833 199.7234
+    5754.575 4702.857 200.9543
+    5776.808 4752.082  202.373
+    5794.987 4757.858 202.3499
+    5938.233 4839.798 206.8288
+    5965.396 4842.542 207.8288
+    6002.337 4857.874 209.0832
+    6006.791 4867.903 210.1847
+    5974.557 4840.912 209.8585
+    5971.562  4863.66 210.2244
+    5937.051 4856.383 209.8079
+    5897.765 4830.827 208.8941
+    5669.422 4702.666 204.6229
+    5622.784 4730.812 202.7781
+    5752.439 4771.074 204.9687
+    5847.447  4774.81 206.1936
+    5783.328 4762.645 205.2802
+    5845.223 4768.572 204.8371
+    5751.495 4715.179 203.0329
+    5654.764 4729.383 200.2751
+    5646.146 4728.229 197.5565
+    5648.711 4745.201 195.2339
+    5635.351 4810.282 192.9487
+    5692.631 4841.503  192.931
+    5864.656 4929.513 194.9285
+    5984.689 4993.857 197.5937
+    6150.889 5061.722 201.0485
+    6296.581 5094.102 203.5924
+    6389.626 5150.168 205.4862
+    6433.069 5172.136  206.615
+    6460.989 5223.355 207.6607
+    6486.085 5290.602 208.5043
+     6538.91 5326.746 209.0396
+    6606.849  5410.05 209.3752
+    6653.043 5412.688  210.214
+     6664.94 5432.911 210.1493
+    6680.737  5476.91 209.3983
+    6715.628 5557.117 209.6171
+    6733.646 5578.244 210.0342
+    6748.714 5562.734 211.4856
+    6800.924 5617.672 212.5146
+    6840.249 5664.805 214.0241
+    6928.494  5662.19 214.9892
+    6947.701 5745.585 215.7109
+    6995.117 5771.484 216.8663
+     7031.88 5804.469 217.7172
+    7095.824 5858.734 219.2336
+    7145.561 5863.484 220.1136
+    7138.196 5874.486  220.269
+    7157.869 5912.841 220.1049
+    7154.805 5921.098  220.317
+    7161.057 5922.459  220.214
+    7161.636 5926.962 219.8513
+     7140.38 5935.485 218.7281
+    6988.206 5869.524 216.6599
+    6901.448 5830.479 214.2069
+    6921.772 5861.221 212.7658
+    6951.212 5865.776 212.5561
+    6964.494 5837.183 211.8733
+    7013.679 5915.408 210.9388
+    7101.702 5930.574 211.8948
+    7139.773 5958.446 211.5333
+    7240.504 6024.693 212.2314
+    7263.686 6021.066 213.0739
+    7309.617  6067.04 214.1464
+    7357.691 6122.096 215.3232
+    7460.728  6162.81 216.6132
+    7552.707 6204.697 217.5596
+    7666.317 6243.449 220.1539
+    7671.023 6273.154 221.4916
+     7773.38 6317.792 222.8923
+    7800.103 6331.551 223.6901
+    7801.608 6378.859  223.503
+    7819.518 6412.249 224.1399
+    7881.173 6435.988 224.4756
+    7942.145 6475.127 224.7463
+    8067.358 6527.758 226.5057
+    8135.065 6540.091 227.7462
+    8160.041 6567.023 228.9124
+    8246.348 6609.208 229.6994
+    8351.972 6625.695 231.2019
+    8446.197 6714.596 232.3205
+    8514.464 6751.037 233.8458
+    8708.139 6820.495 235.1582
+    8756.497 6905.883 235.4095
+    8849.165  6951.56 236.1083
+    8972.445  7016.94 236.9981
+     9053.37 7071.144 236.9439
+    9103.359 7150.307 237.5947
+    9209.004 7210.145 238.3943
+    9335.028 7276.898 239.4022
+    9429.358 7361.761 240.6652
+    9547.745 7400.777 240.4972
+    9558.757 7450.665 240.0893
+     9550.45 7466.543 239.5769
+    9462.932 7494.242 239.0031
+    9373.848 7502.387 237.5366
+    9349.589 7507.978 235.3389
+    9346.637 7595.472 232.4265
+    9459.937 7637.787 231.5627
+    9511.663 7656.648 231.0083
\ No newline at end of file
diff --git a/tags/v_3.062/tests/precompiler.mod b/tags/v_3.062/tests/precompiler.mod
new file mode 100644
index 0000000000000000000000000000000000000000..5c9acfd88ffc2c66d166feae61114584783fcc15
--- /dev/null
+++ b/tags/v_3.062/tests/precompiler.mod
@@ -0,0 +1,43 @@
+var c k;
+varexo x;
+
+parameters alph gam delt bet aa;
+alph=0.5;
+gam=0.5;
+delt=0.02;
+bet=0.05;
+aa=0.5;
+@define version 0;
+@if version == 1;
+aa = 0.3;
+@elseif version >= 2;
+aa = 0.5;
+@else;
+aa = 0.6;
+@endif;
+
+model;
+c + k - aa*x*k(-1)^alph - (1-delt)*k(-1);
+c^(-gam) - (1+bet)^(-1)*(aa*alph*x(+1)*k^(alph-1) + 1 - delt)*c(+1)^(-gam);
+end;
+
+initval;
+x = 1;
+k = ((delt+bet)/(1.0*aa*alph))^(1/(alph-1));
+c = aa*k^alph-delt*k;
+end;
+
+steady;
+
+check;
+
+shocks;
+var x;
+periods 1;
+values 1.2;
+end;
+
+simul(periods=200);
+
+rplot c;
+rplot k;
diff --git a/tags/v_3.062/tests/ramst.mod b/tags/v_3.062/tests/ramst.mod
new file mode 100644
index 0000000000000000000000000000000000000000..9fa14019dec64864710ad3b4a1338291f49fc8f0
--- /dev/null
+++ b/tags/v_3.062/tests/ramst.mod
@@ -0,0 +1,36 @@
+var c k;
+varexo x;
+
+parameters alph gam delt bet aa;
+alph=0.5;
+gam=0.5;
+delt=0.02;
+bet=0.05;
+aa=0.5;
+
+
+model;
+c + k - aa*x*k(-1)^alph - (1-delt)*k(-1);
+c^(-gam) - (1+bet)^(-1)*(aa*alph*x(+1)*k^(alph-1) + 1 - delt)*c(+1)^(-gam);
+end;
+
+initval;
+x = 1;
+k = ((delt+bet)/(1.0*aa*alph))^(1/(alph-1));
+c = aa*k^alph-delt*k;
+end;
+
+steady;
+
+check;
+
+shocks;
+var x;
+periods 1;
+values 1.2;
+end;
+
+simul(periods=200);
+
+rplot c;
+rplot k;
diff --git a/tags/v_3.062/tests/ramst_a.mod b/tags/v_3.062/tests/ramst_a.mod
new file mode 100644
index 0000000000000000000000000000000000000000..74d3a5f5f427c607b277dce015b6c04a33932779
--- /dev/null
+++ b/tags/v_3.062/tests/ramst_a.mod
@@ -0,0 +1,37 @@
+// check shocks on several periods
+var c k;
+varexo x;
+
+parameters alph gam delt bet aa;
+alph=0.5;
+gam=0.5;
+delt=0.02;
+bet=0.05;
+aa=0.5;
+
+
+model;
+c + k - aa*x*k(-1)^alph - (1-delt)*k(-1);
+c^(-gam) - (1+bet)^(-1)*(aa*alph*x(+1)*k^(alph-1) + 1 - delt)*c(+1)^(-gam);
+end;
+
+initval;
+x = 1;
+k = ((delt+bet)/(1.0*aa*alph))^(1/(alph-1));
+c = aa*k^alph-delt*k +1 ;
+end;
+
+steady;
+
+check;
+
+shocks;
+var x;
+periods 1:4 ;
+values ([1.1, 1.2, 1.3, 1.4]') ;
+end;
+
+simul(periods=200);
+
+rplot c;
+rplot k;
diff --git a/tags/v_3.062/tests/run_test.m b/tags/v_3.062/tests/run_test.m
new file mode 100644
index 0000000000000000000000000000000000000000..ab0294ae0abe2ca758bb5bbe6e713ddcce09dcd1
--- /dev/null
+++ b/tags/v_3.062/tests/run_test.m
@@ -0,0 +1,44 @@
+function run_test()
+
+test_files = {
+'.' 'precompiler';
+'.'  'ramst';
+'.'  'ramst_a';
+'.' 'example1';
+'.' 'example2';
+'.' 't_sgu_ex1';
+'arima' 'mod1';
+'arima' 'mod1a';
+'arima' 'mod1b';
+'arima' 'mod1c';
+'arima' 'mod2';
+'arima' 'mod2a';
+'arima' 'mod2b';
+'arima' 'mod2c';
+'fs2000' 'fs2000';
+'fs2000' 'fs2000a';
+}
+
+diary run_test.log
+results = cell(length(test_files),1);
+
+for i=1:length(test_files)
+     results{i}= run_test1(test_files{i,1},test_files{i,2});
+end
+
+for i=1:length(test_files)
+  disp(test_files{i,2})
+  disp(results{i})
+end
+diary off
+
+function msg=run_test1(path1,mod_file)
+     global options_
+     clear options_
+     old_path = pwd;
+     cd(path1);
+     msg = 'OK';
+     expr = ['disp(''error in ' mod_file ''');msg=lasterr;disp(msg)'];
+     eval(['dynare ' mod_file ' noclearall'],'eval(expr)');
+     cd(old_path)
+     
diff --git a/tags/v_3.062/tests/t_lag2.mod b/tags/v_3.062/tests/t_lag2.mod
new file mode 100644
index 0000000000000000000000000000000000000000..02b68e59a0e81ad9353c717aea4fc73b6397cfc1
--- /dev/null
+++ b/tags/v_3.062/tests/t_lag2.mod
@@ -0,0 +1,40 @@
+// example 1 from Collard's guide to Dynare
+var y, c, k, a, h, b;
+varexo e,u;
+
+parameters beta, rho, beta, 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*(((exp(b)*c)/(exp(b(+1))*c(+1)))
+    *(exp(b(+1))*alpha*y(+1)+(1-delta)*k));
+y = exp(a)*(k(-1)^alpha)*(h^(1-alpha));
+k = exp(b)*(y-c)+(1-delta)*k(-1);
+a = rho*a(-1)+tau*b(-2) + e;
+b = tau*a(-1)+rho*b(-2) + u;
+end;
+
+initval;
+y = 1.08068253095672;
+c = 0.80359242014163;
+h = 0.29175631001732;
+k = 5;
+a = 0;
+b = 0;
+e = 0;
+u = 0;
+end;
+
+Sigma_e = [ 0.000081; (phi*0.009*0.009) 0.000081];
+
+stoch_simul(order=2,irf=0,periods=50000,simul_seed=1);
diff --git a/tags/v_3.062/tests/t_lag2_check.mod b/tags/v_3.062/tests/t_lag2_check.mod
new file mode 100644
index 0000000000000000000000000000000000000000..ffdd8be23598c66abb847a9491477a62252769da
--- /dev/null
+++ b/tags/v_3.062/tests/t_lag2_check.mod
@@ -0,0 +1,44 @@
+// example 1 from Collard's guide to Dynare
+periods 400;
+
+var y, c, k, a, h, b, b1;
+varexo e,u;
+
+parameters beta, rho, beta, 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*(((exp(b)*c)/(exp(b(+1))*c(+1)))
+    *(exp(b(+1))*alpha*y(+1)+(1-delta)*k));
+y = exp(a)*(k(-1)^alpha)*(h^(1-alpha));
+k = exp(b)*(y-c)+(1-delta)*k(-1);
+a = rho*a(-1)+tau*b1(-1) + e;
+b = tau*a(-1)+rho*b1(-1) + u;
+b1 = b(-1);
+end;
+
+initval;
+y = 1.08068253095672;
+c = 0.80359242014163;
+h = 0.29175631001732;
+k = 5;
+b1 = 0;
+a = 0;
+b = 0;
+e = 0;
+u = 0;
+end;
+
+Sigma_e = [ 0.000081; (phi*0.009*0.009) 0.000081];
+
+stoch_simul(order=2,irf=0,simul,simul_seed=1);
diff --git a/tags/v_3.062/tests/t_lag2_checka.mod b/tags/v_3.062/tests/t_lag2_checka.mod
new file mode 100644
index 0000000000000000000000000000000000000000..755d593d8bad14452457e4a20884b617bc842b47
--- /dev/null
+++ b/tags/v_3.062/tests/t_lag2_checka.mod
@@ -0,0 +1,44 @@
+// example 1 from Collard's guide to Dynare
+periods 400;
+
+var y, c, k, a, h, b, b1;
+varexo e,u;
+
+parameters beta, rho, beta, 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*(((exp(b)*c)/(exp(b(+1))*c(+1)))
+    *(exp(b(+1))*alpha*y(+1)+(1-delta)*k));
+y = exp(a)*(k(-1)^alpha)*(h^(1-alpha));
+k = exp(b)*(y-c)+(1-delta)*k(-1);
+a = rho*a(-1)+tau*b1(-1) + e;
+b = tau*a(-1)+rho*b1(-1) + u;
+b1 = b(-1);
+end;
+
+initval;
+y = 1.08068253095672;
+c = 0.80359242014163;
+h = 0.29175631001732;
+k = 5;
+b1 = 0;
+a = 0;
+b = 0;
+e = 0;
+u = 0;
+end;
+
+Sigma_e = [ 0.000081; (phi*0.009*0.009) 0.000081];
+
+stoch_simul(order=1,irf=0,simul,simul_seed=1);
diff --git a/tags/v_3.062/tests/t_lag2a.mod b/tags/v_3.062/tests/t_lag2a.mod
new file mode 100644
index 0000000000000000000000000000000000000000..3e781e07a7b652f1deb06524648b7f61c113013c
--- /dev/null
+++ b/tags/v_3.062/tests/t_lag2a.mod
@@ -0,0 +1,44 @@
+// example 1 from Collard's guide to Dynare
+periods 400;
+
+var y, c, k, a, h, b, b1;
+varexo e,u;
+
+parameters beta, rho, beta, 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*(((exp(b)*c)/(exp(b(+1))*c(+1)))
+    *(exp(b(+1))*alpha*y(+1)+(1-delta)*k));
+y = exp(a)*(k(-1)^alpha)*(h^(1-alpha));
+k = exp(b)*(y-c)+(1-delta)*k(-1);
+a = rho*a(-1)+tau*b1(-1) + e;
+b = tau*a(-1)+rho*b1(-1) + u;
+b1 = b(-1);
+end;
+
+initval;
+y = 1.08068253095672;
+c = 0.80359242014163;
+h = 0.29175631001732;
+k = 5;
+a = 0;
+b = 0;
+b1 = 0;
+e = 0;
+u = 0;
+end;
+
+Sigma_e = [ 0.000081; (phi*0.009*0.009) 0.000081];
+
+stoch_simul(irf=0,order=1);
diff --git a/tags/v_3.062/tests/t_lag2b.mod b/tags/v_3.062/tests/t_lag2b.mod
new file mode 100644
index 0000000000000000000000000000000000000000..364ec4fd1dcf6d2d1bc86f33af5e284aa6d4ba66
--- /dev/null
+++ b/tags/v_3.062/tests/t_lag2b.mod
@@ -0,0 +1,42 @@
+// example 1 from Collard's guide to Dynare
+periods 400;
+
+var y, c, k, a, h, b, b1;
+varexo e,u;
+
+parameters beta, rho, beta, 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*(((exp(b)*c)/(exp(b(+1))*c(+1)))
+    *(exp(b(+1))*alpha*y(+1)+(1-delta)*k));
+y = exp(a)*(k(-1)^alpha)*(h^(1-alpha));
+k = exp(b)*(y-c)+(1-delta)*k(-1);
+a = rho*a(-1)+tau*b1(-1) + e;
+b = tau*a(-1)+rho*b1(-1) + u;
+b1 = b(-1);
+end;
+
+initval;
+y = 1.08068253095672;
+c = 0.80359242014163;
+h = 0.29175631001732;
+k = 5;
+a = 0;
+b = 0;
+b1 = 0;
+end;
+
+Sigma_e = [ 0.000081; (phi*0.009*0.009) 0.000081];
+
+stoch_simul(irf=0,periods=10000,order=2);
diff --git a/tags/v_3.062/tests/t_periods.mod b/tags/v_3.062/tests/t_periods.mod
new file mode 100644
index 0000000000000000000000000000000000000000..6dfe365736779a7e83f6af4f7a0dfe7f08c99135
--- /dev/null
+++ b/tags/v_3.062/tests/t_periods.mod
@@ -0,0 +1,44 @@
+// example 1 from Collard's guide to Dynare
+// test options.periods
+
+var y, c, k, a, h, b;
+varexo e,u;
+
+parameters beta, rho, beta, 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*(((exp(b)*c)/(exp(b(+1))*c(+1)))
+    *(exp(b(+1))*alpha*y(+1)+(1-delta)*k));
+y = exp(a)*(k(-1)^alpha)*(h^(1-alpha));
+k = exp(b)*(y-c)+(1-delta)*k(-1);
+a = rho*a(-1)+tau*b(-2) + e;
+b = tau*a(-1)+rho*b(-2) + u;
+end;
+
+initval;
+y = 1.08068253095672;
+c = 0.80359242014163;
+h = 0.29175631001732;
+k = 5;
+a = 0;
+b = 0;
+e = 0;
+u = 0;
+end;
+
+Sigma_e = [ 0.000081; (phi*0.009*0.009) 0.000081];
+
+check;
+
+stoch_simul(order=2,irf=0,periods=400,simul_seed=1);
diff --git a/tags/v_3.062/tests/t_periods_a.mod b/tags/v_3.062/tests/t_periods_a.mod
new file mode 100644
index 0000000000000000000000000000000000000000..f20cf09ca83a412efa3bbb2c89ecd04a559d87ac
--- /dev/null
+++ b/tags/v_3.062/tests/t_periods_a.mod
@@ -0,0 +1,36 @@
+var c k;
+varexo x;
+
+parameters alph gam delt bet aa;
+alph=0.5;
+gam=0.5;
+delt=0.02;
+bet=0.05;
+aa=0.5;
+
+
+model;
+c + k - aa*x*k(-1)^alph - (1-delt)*k(-1);
+c^(-gam) - (1+bet)^(-1)*(aa*alph*x(+1)*k^(alph-1) + 1 - delt)*c(+1)^(-gam);
+end;
+
+initval;
+x = 1;
+k = ((delt+bet)/(1.0*aa*alph))^(1/(alph-1));
+c = aa*k^alph-delt*k +1 ;
+end;
+
+steady;
+
+check;
+
+shocks;
+var x;
+periods 1;
+values 1.2;
+end;
+
+simul(periods=200);
+
+rplot c;
+rplot k;
diff --git a/tags/v_3.062/tests/t_sgu_ex1.mod b/tags/v_3.062/tests/t_sgu_ex1.mod
new file mode 100644
index 0000000000000000000000000000000000000000..a4fe6e8c9ec759553d8c783f234ee8d2321888c8
--- /dev/null
+++ b/tags/v_3.062/tests/t_sgu_ex1.mod
@@ -0,0 +1,38 @@
+periods 20000;
+var c k a;
+varexo e;
+parameters alpha beta delta gamma rho;
+
+beta = 0.95;
+delta = 1;
+alpha = 0.3;
+rho = 0;
+gamma = 2;
+
+model;
+exp(c) + exp(k) = (1-delta) * exp(k(-1)) + exp(a) * exp(k(-1))^alpha;
+exp(c)^(-gamma) = beta * exp(c(+1))^(-gamma) * (exp(a(+1)) * alpha * exp(k)^(alpha-1) + 1 - delta);
+a = rho * a(-1) + e;
+end;
+
+initval;
+k=0;
+c=0;
+a=0;
+e=0;
+end;
+
+Sigma_e_ = 1;
+
+stoch_simul(nomoments,nocorr,ar=0,irf=0);
+
+global dr_
+load objectives/sgu_ex1;
+
+test(dr_.ghx,dr_obj_.ghx,1);
+test(dr_.ghu,dr_obj_.ghu,2);
+test(dr_.ghxx,dr_obj_.ghxx,3);
+test(dr_.ghxu,dr_obj_.ghxu,4);
+test(dr_.ghuu,dr_obj_.ghuu,5);
+
+disp('TESTS OK');
\ No newline at end of file
diff --git a/tags/v_3.062/tests/test.m b/tags/v_3.062/tests/test.m
new file mode 100644
index 0000000000000000000000000000000000000000..f05f5f1c45875b0508f622724647c0285081f9e1
--- /dev/null
+++ b/tags/v_3.062/tests/test.m
@@ -0,0 +1,4 @@
+function test(a,b,n)
+  if max(max(abs(a)-abs(b))) > 1e-5
+    error(['Test error in test ' int2str(n)])
+  end
\ No newline at end of file
diff --git a/tags/v_3.062/tests/test_matlab.mod b/tags/v_3.062/tests/test_matlab.mod
new file mode 100644
index 0000000000000000000000000000000000000000..68d344448355d84dfb46017f8f8b31fb0f01c121
--- /dev/null
+++ b/tags/v_3.062/tests/test_matlab.mod
@@ -0,0 +1,40 @@
+periods 200;
+var y, c, k, a, h, b;
+varexo e,u;
+
+parameters beta, rho, beta, alpha, delta, theta, psi, tau, phi;
+
+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*(((exp(b)*c)/(exp(b(+1))*c(+1)))*(exp(b(+1))*alpha*y(+1)+(1-delta)*k));
+y = exp(a)*(k(-1)^alpha)*(h^(1-alpha));
+k = exp(b)*(y-c)+(1-delta)*k(-1);
+a = rho*a(-1)+tau*b(-1) + e;
+b = tau*a(-1)+rho*b(-1) + u;
+end;
+
+initval;
+y = 1;
+c = 0.7;
+h = 0.1;
+k = 11;
+a = 0;
+b = 0;
+e = 0;
+u = 0;
+end;
+
+Sigma_e = [ 0.01 0.005; 0.01];
+
+stoch_simul(irf=0);
+
diff --git a/tags/v_3.062/tests/variance_0.mod b/tags/v_3.062/tests/variance_0.mod
new file mode 100644
index 0000000000000000000000000000000000000000..6fc272e7bddf38bafc9d5a28fa26615ac2808432
--- /dev/null
+++ b/tags/v_3.062/tests/variance_0.mod
@@ -0,0 +1,42 @@
+// test setting variance to 0
+periods 400;
+
+var y, c, k, a, h, b;
+varexo e,u;
+
+parameters beta, rho, beta, 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*(((exp(b)*c)/(exp(b(+1))*c(+1)))
+    *(exp(b(+1))*alpha*y(+1)+(1-delta)*k));
+y = exp(a)*(k(-1)^alpha)*(h^(1-alpha));
+k = exp(b)*(y-c)+(1-delta)*k(-1);
+a = rho*a(-1)+tau*b(-1) + e;
+b = tau*a(-1)+rho*b(-1) + u;
+end;
+
+initval;
+y = 1.08068253095672;
+c = 0.80359242014163;
+h = 0.29175631001732;
+k = 5;
+a = 0;
+b = 0;
+e = 0;
+u = 0;
+end;
+
+Sigma_e = [ 0.000081; (phi*0.009*0.009) 0];
+
+stoch_simul(order=1,irf=0,simul);