From 762f31bafd4b3a58c5a31c4e7d538d232e15a094 Mon Sep 17 00:00:00 2001
From: Michel Juillard <michel.juillard@mjui.fr>
Date: Wed, 28 Sep 2011 22:08:45 +0200
Subject: [PATCH] preprocessor, auxiliary variables: fixes ordering issue
 introduced in 347ab4d0c0c79ae9a42898c1d5409d78708bb8a8 and corrects the
 earlier ordering problem.

---
 preprocessor/DynamicModel.cc | 10 ++++++++--
 preprocessor/StaticModel.cc  |  4 ++--
 2 files changed, 10 insertions(+), 4 deletions(-)

diff --git a/preprocessor/DynamicModel.cc b/preprocessor/DynamicModel.cc
index eccc4e9c5..de35ef8d4 100644
--- a/preprocessor/DynamicModel.cc
+++ b/preprocessor/DynamicModel.cc
@@ -4018,8 +4018,14 @@ DynamicModel::substituteLeadLagInternal(aux_var_t type, bool deterministic_model
   for (int i = 0; i < (int) neweqs.size(); i++)
     addEquation(neweqs[i]);
 
-  // Add the new set of equations at the *beginning* of aux_equations
-  copy(neweqs.rbegin(), neweqs.rend(), front_inserter(aux_equations));
+  // Order of auxiliary variable definition equations:
+  //  - expectation (entered before this function is called)
+  //  - lead variables from lower lead to higher lead (need to be listed in reverse order)
+  //  - lag variables from lower lag to higher lag
+  if ((type == avEndoLead) || (type == avExoLead))
+    copy(neweqs.rbegin(), neweqs.rend(), back_inserter(aux_equations));
+  else
+    copy(neweqs.begin(), neweqs.end(), back_inserter(aux_equations));
 
   if (neweqs.size() > 0)
     {
diff --git a/preprocessor/StaticModel.cc b/preprocessor/StaticModel.cc
index adc84c23e..2b8c15842 100644
--- a/preprocessor/StaticModel.cc
+++ b/preprocessor/StaticModel.cc
@@ -1702,7 +1702,7 @@ StaticModel::writeLatexFile(const string &basename) const
 void
 StaticModel::writeAuxVarInitval(ostream &output, ExprNodeOutputType output_type) const
 {
-  for (int i = (int) aux_equations.size()-1; i >= 0; i--)
+  for (int i = 0; i < (int) aux_equations.size(); i++)
     {
       dynamic_cast<ExprNode *>(aux_equations[i])->writeOutput(output, output_type);
       output << ";" << endl;
@@ -1730,7 +1730,7 @@ void StaticModel::writeAuxVarRecursiveDefinitions(const string &basename) const
          << "%           from model file (.mod)" << endl
          << endl;
 
-  for (int i = (int) aux_equations.size()-1; i >= 0; i--)
+  for (int i = 0; i < (int) aux_equations.size(); i++)
     {
       dynamic_cast<ExprNode *>(aux_equations[i])->writeOutput(output, oMatlabStaticModel);
       output << ";" << endl;
-- 
GitLab