diff --git a/BlockTriangular.cc b/BlockTriangular.cc
index d0cffcd4175664d71fe4f095083beab99f8a13b7..b50a06ca392aff3369177f5aa0c9e22b4f2c5df1 100644
--- a/BlockTriangular.cc
+++ b/BlockTriangular.cc
@@ -31,9 +31,9 @@ using namespace std;
 //------------------------------------------------------------------------------
 
 BlockTriangular::BlockTriangular(const SymbolTable &symbol_table_arg) :
-  symbol_table(symbol_table_arg),
-  normalization(symbol_table_arg),
-  incidencematrix(symbol_table_arg)
+    symbol_table(symbol_table_arg),
+    normalization(symbol_table_arg),
+    incidencematrix(symbol_table_arg)
 {
   bt_verbose = 0;
   ModelBlock = NULL;
@@ -51,15 +51,15 @@ BlockTriangular::Prologue_Epilogue(bool* IM, int* prologue, int* epilogue, int n
   int i, j, k, l = 0;
   /*Looking for a prologue */
   *prologue = 0;
-  while(modifie)
+  while (modifie)
     {
       modifie = 0;
-      for(i = *prologue;i < n;i++)
+      for (i = *prologue;i < n;i++)
         {
           k = 0;
-          for(j = *prologue;j < n;j++)
+          for (j = *prologue;j < n;j++)
             {
-              if(IM[i*n + j])
+              if (IM[i*n + j])
                 {
                   k++;
                   l = j;
@@ -75,15 +75,15 @@ BlockTriangular::Prologue_Epilogue(bool* IM, int* prologue, int* epilogue, int n
     }
   *epilogue = 0;
   modifie = 1;
-  while(modifie)
+  while (modifie)
     {
       modifie = 0;
-      for(i = *prologue;i < n - *epilogue;i++)
+      for (i = *prologue;i < n - *epilogue;i++)
         {
           k = 0;
-          for(j = *prologue;j < n - *epilogue;j++)
+          for (j = *prologue;j < n - *epilogue;j++)
             {
-              if(IM[j*n + i])
+              if (IM[j*n + i])
                 {
                   k++;
                   l = j;
@@ -101,7 +101,7 @@ BlockTriangular::Prologue_Epilogue(bool* IM, int* prologue, int* epilogue, int n
 
 
 void
-BlockTriangular::Allocate_Block(int size, int *count_Equ, int *count_Block, BlockType type, Model_Block * ModelBlock)
+BlockTriangular::Allocate_Block(int size, int *count_Equ, int count_Block, BlockType type, BlockSimulationType SimType, Model_Block * ModelBlock)
 {
   int i, j, k, l, ls, m, i_1, Lead, Lag, first_count_equ, i1, li;
   int *tmp_size, *tmp_size_other_endo, *tmp_size_exo, *tmp_var, *tmp_endo, *tmp_other_endo, *tmp_exo, tmp_nb_other_endo, tmp_nb_exo, nb_lead_lag_endo;
@@ -110,709 +110,497 @@ BlockTriangular::Allocate_Block(int size, int *count_Equ, int *count_Block, Bloc
   bool *IM, OK;
   ModelBlock->Periods = periods;
   int Lag_Endo, Lead_Endo, Lag_Exo, Lead_Exo, Lag_Other_Endo, Lead_Other_Endo;
-  if ((type == PROLOGUE) || (type == EPILOGUE))
+
+  ModelBlock->Block_List[count_Block].is_linear=true;
+  ModelBlock->Block_List[count_Block].Size = size;
+  ModelBlock->Block_List[count_Block].Type = type;
+  ModelBlock->Block_List[count_Block].Temporary_terms=new temporary_terms_type ();
+  ModelBlock->Block_List[count_Block].Temporary_terms->clear();
+  ModelBlock->Block_List[count_Block].Temporary_InUse=new temporary_terms_inuse_type ();
+  ModelBlock->Block_List[count_Block].Temporary_InUse->clear();
+  ModelBlock->Block_List[count_Block].Simulation_Type = SimType;
+  ModelBlock->Block_List[count_Block].Equation = (int*)malloc(ModelBlock->Block_List[count_Block].Size * sizeof(int));
+  ModelBlock->Block_List[count_Block].Variable = (int*)malloc(ModelBlock->Block_List[count_Block].Size * sizeof(int));
+  ModelBlock->Block_List[count_Block].Own_Derivative = (int*)malloc(ModelBlock->Block_List[count_Block].Size * sizeof(int));
+  Lead = Lag = 0;
+  first_count_equ = *count_Equ;
+  tmp_var = (int*)malloc(size * sizeof(int));
+  tmp_endo = (int*)malloc((incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1) * sizeof(int));
+  tmp_other_endo = (int*)malloc(symbol_table.endo_nbr * sizeof(int));
+  tmp_size = (int*)malloc((incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1) * sizeof(int));
+  //cout << "tmp_size = (int*)malloc((incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1= " << incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1 << ") * sizeof(int))\n";
+  tmp_size_other_endo = (int*)malloc((incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1) * sizeof(int));
+  tmp_size_exo = (int*)malloc((incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1) * sizeof(int));
+  memset(tmp_size_exo, 0, (incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1)*sizeof(int));
+  memset(tmp_size_other_endo, 0, (incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1)*sizeof(int));
+  memset(tmp_size, 0, (incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1)*sizeof(int));
+  memset(tmp_endo, 0, (incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1)*sizeof(int));
+  memset(tmp_other_endo, 0, symbol_table.endo_nbr*sizeof(int));
+  nb_lead_lag_endo = 0;
+  Lag_Endo = Lead_Endo = Lag_Other_Endo = Lead_Other_Endo = Lag_Exo = Lead_Exo = 0;
+
+  //Variable by variable looking for all leads and lags its occurence in each equation of the block
+  tmp_variable_evaluated = (bool*)malloc(symbol_table.endo_nbr*sizeof(bool));
+  memset(tmp_variable_evaluated, 0, symbol_table.endo_nbr*sizeof(bool));
+  for (i = 0;i < size;i++)
     {
-      for(i = 0;i < size;i++)
+      ModelBlock->Block_List[count_Block].Equation[i] = Index_Equ_IM[*count_Equ].index;
+      ModelBlock->Block_List[count_Block].Variable[i] = Index_Var_IM[*count_Equ].index;
+      i_1 = Index_Var_IM[*count_Equ].index;
+      for (k = -incidencematrix.Model_Max_Lag_Endo; k<=incidencematrix.Model_Max_Lead_Endo; k++)
         {
-          ModelBlock->Block_List[*count_Block].is_linear=true;
-          ModelBlock->Block_List[*count_Block].Size = 1;
-          ModelBlock->Block_List[*count_Block].Type = type;
-          ModelBlock->Block_List[*count_Block].Simulation_Type = UNKNOWN;
-          ModelBlock->Block_List[*count_Block].Temporary_terms=new temporary_terms_type ();
-          ModelBlock->Block_List[*count_Block].Temporary_terms->clear();
-          tmp_endo = (int*)malloc((incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1) * sizeof(int));
-          tmp_other_endo = (int*)malloc(symbol_table.endo_nbr * sizeof(int));
-          tmp_size_other_endo = (int*)malloc((incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1) * sizeof(int));
-          tmp_size = (int*)malloc((incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1) * sizeof(int));
-          tmp_var = (int*)malloc(sizeof(int));
-          tmp_size_exo = (int*)malloc((incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1) * sizeof(int));
-
-          memset(tmp_size_exo, 0, (incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1)*sizeof(int));
-          memset(tmp_size, 0, (incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1)*sizeof(int));
-          memset(tmp_endo, 0, (incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1)*sizeof(int));
-          memset(tmp_size_other_endo, 0, (incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1)*sizeof(int));
-          memset(tmp_other_endo, 0, symbol_table.endo_nbr*sizeof(int));
-
-
-          nb_lead_lag_endo = Lead = Lag = 0;
-          Lag_Endo = Lead_Endo = Lag_Exo = Lead_Exo = Lag_Other_Endo = Lead_Other_Endo = 0;
-
-          tmp_variable_evaluated = (bool*)malloc(symbol_table.endo_nbr*sizeof(bool));
-          memset(tmp_variable_evaluated, 0, symbol_table.endo_nbr*sizeof(bool));
-          for(k = -incidencematrix.Model_Max_Lag_Endo; k<=incidencematrix.Model_Max_Lead_Endo; k++)
+          Cur_IM = incidencematrix.Get_IM(k, eEndogenous);
+          if (Cur_IM)
             {
-              Cur_IM = incidencematrix.Get_IM(k, eEndogenous);
-              if(Cur_IM)
+              OK = false;
+              if (k >= 0)
                 {
-                  i_1 = Index_Equ_IM[*count_Equ].index * symbol_table.endo_nbr;
-                  if(k > 0)
+                  for (j = 0;j < size;j++)
                     {
-                      if(Cur_IM[i_1 + Index_Var_IM[*count_Equ].index])
+                      if (Cur_IM[i_1 + Index_Equ_IM[first_count_equ + j].index*symbol_table.endo_nbr])
                         {
-                          tmp_variable_evaluated[Index_Var_IM[*count_Equ].index] = true;
-                          nb_lead_lag_endo++;
+                          tmp_variable_evaluated[i_1] = true;
                           tmp_size[incidencematrix.Model_Max_Lag_Endo + k]++;
-                          if(k > Lead)
+                          if (!OK)
+                            {
+                              tmp_endo[incidencematrix.Model_Max_Lag + k]++;
+                              nb_lead_lag_endo++;
+                              OK = true;
+                            }
+                          if (k > Lead)
                             Lead = k;
                         }
                     }
-                  else
-                    {
-                      if(Cur_IM[i_1 + Index_Var_IM[*count_Equ].index])
-                        {
-                          tmp_variable_evaluated[Index_Var_IM[*count_Equ].index] = true;
-                          tmp_size[incidencematrix.Model_Max_Lag_Endo + k]++;
-                          nb_lead_lag_endo++;
-                          if(-k > Lag)
-                            Lag = -k;
-                        }
-                    }
                 }
-            }
-
-          Lag_Endo = Lag;
-          Lead_Endo = Lead;
-
-          tmp_nb_other_endo = 0;
-          for(k = -incidencematrix.Model_Max_Lag_Endo; k<=incidencematrix.Model_Max_Lead_Endo; k++)
-            {
-              Cur_IM = incidencematrix.Get_IM(k, eEndogenous);
-              if(Cur_IM)
+              else
                 {
-                  i_1 = Index_Equ_IM[*count_Equ].index * symbol_table.endo_nbr;
-                  for(j = 0;j < symbol_table.endo_nbr;j++)
+                  for (j = 0;j < size;j++)
                     {
-                      int ij = Index_Var_IM[j].index;
-                      if(Cur_IM[i_1 + ij])
+                      if (Cur_IM[i_1 + Index_Equ_IM[first_count_equ + j].index*symbol_table.endo_nbr])
                         {
-                          if(!tmp_variable_evaluated[ij])
+                          tmp_variable_evaluated[i_1] = true;
+                          tmp_size[incidencematrix.Model_Max_Lag_Endo + k]++;
+                          if (!OK)
                             {
-                              if(!tmp_other_endo[ij])
-                                {
-                                  tmp_other_endo[ij] = 1;
-                                  tmp_nb_other_endo++;
-                                }
-                              if(k>0 && k>Lead_Other_Endo)
-                                Lead_Other_Endo = k;
-                              else if(k<0 && (-k)>Lag_Other_Endo)
-                                Lag_Other_Endo = -k;
-                              if(k>0 && k>Lead)
-                                Lead = k;
-                              else if(k<0 && (-k)>Lag)
-                               Lag = -k;
-                              tmp_size_other_endo[k+incidencematrix.Model_Max_Lag_Endo]++;
+                              tmp_variable_evaluated[i_1] = true;
+                              tmp_endo[incidencematrix.Model_Max_Lag + k]++;
+                              nb_lead_lag_endo++;
+                              OK = true;
                             }
+                          if (-k > Lag)
+                            Lag = -k;
                         }
                     }
                 }
             }
-          ModelBlock->Block_List[*count_Block].nb_other_endo = tmp_nb_other_endo;
-          ModelBlock->Block_List[*count_Block].Other_Endogenous = (int*)malloc(tmp_nb_other_endo * sizeof(int));
-
-
-
-          tmp_exo = (int*)malloc(symbol_table.exo_nbr * sizeof(int));
-          memset(tmp_exo, 0, symbol_table.exo_nbr * sizeof(int));
-          tmp_nb_exo = 0;
+        }
+      (*count_Equ)++;
+    }
+  Lag_Endo = Lag;
+  Lead_Endo = Lead;
 
-          for(k = -incidencematrix.Model_Max_Lag_Exo; k<=incidencematrix.Model_Max_Lead_Exo; k++)
+  tmp_nb_other_endo = 0;
+  for (i = 0;i < size;i++)
+    {
+      for (k = -incidencematrix.Model_Max_Lag_Endo; k<=incidencematrix.Model_Max_Lead_Endo; k++)
+        {
+          Cur_IM = incidencematrix.Get_IM(k, eEndogenous);
+          if (Cur_IM)
             {
-              Cur_IM = incidencematrix.Get_IM(k, eExogenous);
-              if(Cur_IM)
-                {
-                  i_1 = Index_Equ_IM[*count_Equ].index * symbol_table.exo_nbr;
-                  for(j=0;j<symbol_table.exo_nbr;j++)
-                    if(Cur_IM[i_1 + j])
+              i_1 = Index_Equ_IM[first_count_equ+i].index * symbol_table.endo_nbr;
+              for (j = 0;j < symbol_table.endo_nbr;j++)
+                if (Cur_IM[i_1 + j])
+                  {
+                    if (!tmp_variable_evaluated[j])
                       {
-                        if(!tmp_exo[j])
-                          {
-                            tmp_exo[j] = 1;
-                            tmp_nb_exo++;
-                          }
-                        if(k>0 && k>Lead_Exo)
-                          Lead_Exo = k;
-                        else if(k<0 && (-k)>Lag_Exo)
-                          Lag_Exo = -k;
-                        if(k>0 && k>Lead)
-                          Lead = k;
-                        else if(k<0 && (-k)>Lag)
-                          Lag = -k;
-                        tmp_size_exo[k+incidencematrix.Model_Max_Lag_Exo]++;
+                        tmp_other_endo[j] = 1;
+                        tmp_nb_other_endo++;
                       }
-                }
+                    if (k>0 && k>Lead_Other_Endo)
+                      Lead_Other_Endo = k;
+                    else if (k<0 && (-k)>Lag_Other_Endo)
+                      Lag_Other_Endo = -k;
+                    if (k>0 && k>Lead)
+                      Lead = k;
+                    else if (k<0 && (-k)>Lag)
+                      Lag = -k;
+                    tmp_size_other_endo[k+incidencematrix.Model_Max_Lag_Endo]++;
+                  }
             }
+        }
+    }
+  ModelBlock->Block_List[count_Block].nb_other_endo = tmp_nb_other_endo;
+  ModelBlock->Block_List[count_Block].Other_Endogenous = (int*)malloc(tmp_nb_other_endo * sizeof(int));
 
-          ModelBlock->Block_List[*count_Block].nb_exo = tmp_nb_exo;
-          ModelBlock->Block_List[*count_Block].Exogenous = (int*)malloc(tmp_nb_exo * sizeof(int));
-          k = 0;
-          for(j=0;j<symbol_table.exo_nbr;j++)
-            if(tmp_exo[j])
-              {
-                ModelBlock->Block_List[*count_Block].Exogenous[k] = j;
-                k++;
-              }
-
-          ModelBlock->Block_List[*count_Block].nb_exo_det = 0;
-
-          ModelBlock->Block_List[*count_Block].Max_Lag = Lag;
-          ModelBlock->Block_List[*count_Block].Max_Lead = Lead;
-          ModelBlock->Block_List[*count_Block].Max_Lag_Endo = Lag_Endo;
-          ModelBlock->Block_List[*count_Block].Max_Lead_Endo = Lead_Endo;
-          ModelBlock->Block_List[*count_Block].Max_Lag_Exo = Lag_Exo;
-          ModelBlock->Block_List[*count_Block].Max_Lead_Exo = Lead_Exo;
-          ModelBlock->Block_List[*count_Block].Equation = (int*)malloc(sizeof(int));
-          ModelBlock->Block_List[*count_Block].Variable = (int*)malloc(sizeof(int));
-          ModelBlock->Block_List[*count_Block].Own_Derivative = (int*)malloc(sizeof(int));
-          ModelBlock->Block_List[*count_Block].Equation[0] = Index_Equ_IM[*count_Equ].index;
-          ModelBlock->Block_List[*count_Block].Variable[0] = Index_Var_IM[*count_Equ].index;
-
-
-
-          if ((Lead > 0) && (Lag > 0))
-            ModelBlock->Block_List[*count_Block].Simulation_Type = SOLVE_TWO_BOUNDARIES_SIMPLE;
-          else if((Lead > 0) && (Lag == 0))
-            ModelBlock->Block_List[*count_Block].Simulation_Type = SOLVE_BACKWARD_SIMPLE;
-          else
-            ModelBlock->Block_List[*count_Block].Simulation_Type = SOLVE_FORWARD_SIMPLE;
 
-          tmp_exo = (int*)malloc(symbol_table.exo_nbr * sizeof(int));
-          memset(tmp_exo, 0, symbol_table.exo_nbr * sizeof(int));
-          tmp_nb_exo = 0;
-          for(k = -incidencematrix.Model_Max_Lag_Exo; k <=incidencematrix.Model_Max_Lead_Exo; k++)
+  tmp_exo = (int*)malloc(symbol_table.exo_nbr * sizeof(int));
+  memset(tmp_exo, 0, symbol_table.exo_nbr *     sizeof(int));
+  tmp_nb_exo = 0;
+  for (i = 0;i < size;i++)
+    {
+      for (k = -incidencematrix.Model_Max_Lag_Exo; k<=incidencematrix.Model_Max_Lead_Exo; k++)
+        {
+          Cur_IM = incidencematrix.Get_IM(k, eExogenous);
+          if (Cur_IM)
             {
-              Cur_IM = incidencematrix.Get_IM(k, eExogenous);
-              if(Cur_IM)
-                {
-                  i_1 = Index_Equ_IM[*count_Equ].index * symbol_table.exo_nbr;
-                  for(j=0;j<symbol_table.exo_nbr;j++)
-                    if(Cur_IM[i_1 + j] && (!tmp_exo[j]))
+              i_1 = Index_Equ_IM[first_count_equ+i].index * symbol_table.exo_nbr;
+              for (j=0;j<symbol_table.exo_nbr;j++)
+                if (Cur_IM[i_1 + j])
+                  {
+                    if (!tmp_exo[j])
                       {
                         tmp_exo[j] = 1;
                         tmp_nb_exo++;
                       }
-                }
+                    if (k>0 && k>Lead_Exo)
+                      Lead_Exo = k;
+                    else if (k<0 && (-k)>Lag_Exo)
+                      Lag_Exo = -k;
+                    if (k>0 && k>Lead)
+                      Lead = k;
+                    else if (k<0 && (-k)>Lag)
+                      Lag = -k;
+                    tmp_size_exo[k+incidencematrix.Model_Max_Lag_Exo]++;
+                  }
             }
-          ModelBlock->Block_List[*count_Block].nb_exo = tmp_nb_exo;
-          ModelBlock->Block_List[*count_Block].Exogenous = (int*)malloc(tmp_nb_exo * sizeof(int));
-
-          ModelBlock->Block_List[*count_Block].IM_lead_lag = (IM_compact*)malloc((Lead + Lag + 1) * sizeof(IM_compact));
-          ModelBlock->Block_List[*count_Block].Nb_Lead_Lag_Endo = nb_lead_lag_endo;
-
-
-          k = 0;
-          for(j=0;j<symbol_table.exo_nbr;j++)
-            if(tmp_exo[j])
-              {
-                ModelBlock->Block_List[*count_Block].Exogenous[k] = j;
-                k++;
-              }
-          ls = l = 1;
-          i1 = 0;
-          for(int li = 0;li < Lead + Lag + 1;li++)
-            {
-              if(incidencematrix.Model_Max_Lag_Endo - Lag + li>=0)
-                {
-                  ModelBlock->Block_List[*count_Block].IM_lead_lag[li].size = tmp_size[incidencematrix.Model_Max_Lag_Endo - Lag + li];
-                  ModelBlock->Block_List[*count_Block].IM_lead_lag[li].nb_endo = tmp_size[incidencematrix.Model_Max_Lag_Endo - Lag + li];
-                  ModelBlock->Block_List[*count_Block].IM_lead_lag[li].u = (int*)malloc(tmp_size[incidencematrix.Model_Max_Lag_Endo - Lag + li] * sizeof(int));
-                  ModelBlock->Block_List[*count_Block].IM_lead_lag[li].us = (int*)malloc(tmp_size[incidencematrix.Model_Max_Lag_Endo - Lag + li] * sizeof(int));
-                  ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Var = (int*)malloc(tmp_size[incidencematrix.Model_Max_Lag_Endo - Lag + li] * sizeof(int));
-                  ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Equ = (int*)malloc(tmp_size[incidencematrix.Model_Max_Lag_Endo - Lag + li] * sizeof(int));
-                  ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Var_Index = (int*)malloc(tmp_size[incidencematrix.Model_Max_Lag_Endo - Lag + li] * sizeof(int));
-                  ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Equ_Index = (int*)malloc(tmp_size[incidencematrix.Model_Max_Lag_Endo - Lag + li] * sizeof(int));
-
-                  ModelBlock->Block_List[*count_Block].IM_lead_lag[li].size_other_endo = tmp_size_other_endo[incidencematrix.Model_Max_Lag_Endo - Lag + li];
-                  ModelBlock->Block_List[*count_Block].IM_lead_lag[li].nb_other_endo = tmp_other_endo[incidencematrix.Model_Max_Lag_Endo - Lag + li];
-                  ModelBlock->Block_List[*count_Block].IM_lead_lag[li].u_other_endo = (int*)malloc(tmp_size_other_endo[incidencematrix.Model_Max_Lag_Endo - Lag + li] * sizeof(int));
-                  ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Var_other_endo = (int*)malloc(tmp_size_other_endo[incidencematrix.Model_Max_Lag_Endo - Lag + li] * sizeof(int));
-                  ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Equ_other_endo = (int*)malloc(tmp_size_other_endo[incidencematrix.Model_Max_Lag_Endo - Lag + li] * sizeof(int));
-                  ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Var_Index_other_endo = (int*)malloc(tmp_size_other_endo[incidencematrix.Model_Max_Lag_Endo - Lag + li] * sizeof(int));
-                  ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Equ_Index_other_endo = (int*)malloc(tmp_size_other_endo[incidencematrix.Model_Max_Lag_Endo - Lag + li] * sizeof(int));
-
-
-
-                  ModelBlock->Block_List[*count_Block].IM_lead_lag[li].u_init = l;
-                  IM = incidencematrix.Get_IM(li - Lag, eEndogenous);
-                  if(IM)
-                    {
-                      if(IM[Index_Var_IM[*count_Equ].index + Index_Equ_IM[*count_Equ].index*symbol_table.endo_nbr] && nb_lead_lag_endo)
-                        {
-                          tmp_var[0] = i1;
-                          i1++;
-                        }
-                      m = 0;
-                      i_1 = Index_Equ_IM[*count_Equ].index * symbol_table.endo_nbr;
-                      if(IM[Index_Var_IM[*count_Equ].index + i_1])
-                        {
-                          if(li == Lag)
-                            {
-                              ModelBlock->Block_List[*count_Block].IM_lead_lag[li].us[m] = ls;
-                              ls++;
-                            }
-                          ModelBlock->Block_List[*count_Block].IM_lead_lag[li].u[m] = l;
-                          ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Equ[m] = 0;
-                          ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Var[m] = 0;
-                          ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Equ_Index[m] = Index_Equ_IM[*count_Equ].index;
-                          ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Var_Index[m] = Index_Var_IM[*count_Equ].index;
-                          tmp_variable_evaluated[Index_Var_IM[*count_Equ].index] = true;
-                          l++;
-                          m++;
-                        }
-                      ModelBlock->Block_List[*count_Block].IM_lead_lag[li].u_finish = l - 1;
-
-                      m = 0;
-                      for(k = 0;k < symbol_table.endo_nbr;k++)
-                        if((!tmp_variable_evaluated[Index_Var_IM[k].index]) && IM[Index_Var_IM[k].index + i_1])
-                          {
-                            ModelBlock->Block_List[*count_Block].IM_lead_lag[li].u_other_endo[m] = l;
-                            ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Equ_other_endo[m] = 0; //j - first_count_equ;
-                            ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Var_other_endo[m] = k ;
-                            ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Equ_Index_other_endo[m] = Index_Equ_IM[*count_Equ].index;
-                            ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Var_Index_other_endo[m] = Index_Var_IM[k].index;
-                            l++;
-                            m++;
-                          }
-                    }
-                }
-              else
-                ModelBlock->Block_List[*count_Block].IM_lead_lag[li].size = 0;
-              if(incidencematrix.Model_Max_Lag_Exo - Lag + li>=0)
-                {
-                  ModelBlock->Block_List[*count_Block].IM_lead_lag[li].size_exo = tmp_size_exo[incidencematrix.Model_Max_Lag_Exo - Lag + li];
-                  ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Exogenous = (int*)malloc(tmp_size_exo[incidencematrix.Model_Max_Lag_Exo - Lag + li] * sizeof(int));
-                  ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Exogenous_Index = (int*)malloc(tmp_size_exo[incidencematrix.Model_Max_Lag_Exo - Lag + li] * sizeof(int));
-                  ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Equ_X = (int*)malloc(tmp_size_exo[incidencematrix.Model_Max_Lag_Exo - Lag + li] * sizeof(int));
-                  ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Equ_X_Index = (int*)malloc(tmp_size_exo[incidencematrix.Model_Max_Lag_Exo - Lag + li] * sizeof(int));
-                  IM = incidencematrix.Get_IM(li - Lag, eExogenous);
-                  if(IM)
-                    {
-                      m = 0;
-                      i_1 = Index_Equ_IM[*count_Equ].index * symbol_table.exo_nbr;
-                      for(k = 0; k<tmp_nb_exo; k++)
-                        {
-                          if(IM[ModelBlock->Block_List[*count_Block].Exogenous[k]+i_1])
-                            {
-                              ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Exogenous[m] = k;
-                              ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Exogenous_Index[m] = ModelBlock->Block_List[*count_Block].Exogenous[k];
-                              ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Equ_X[m] = 0;
-                              ModelBlock->Block_List[*count_Block].IM_lead_lag[li].Equ_X_Index[m] = Index_Equ_IM[*count_Equ].index;
-                              m++;
-                            }
-                        }
-                    }
-                }
-              else
-                ModelBlock->Block_List[*count_Block].IM_lead_lag[li].size_exo = 0;
-            }
-          (*count_Equ)++;
-          (*count_Block)++;
-          free(tmp_size);
-          free(tmp_size_exo);
-          free(tmp_endo);
-          free(tmp_exo);
-          free(tmp_var);
-          free(tmp_size_other_endo);
-          free(tmp_other_endo);
-          free(tmp_variable_evaluated);
         }
     }
-  else
+
+
+  ModelBlock->Block_List[count_Block].nb_exo = tmp_nb_exo;
+  ModelBlock->Block_List[count_Block].Exogenous = (int*)malloc(tmp_nb_exo * sizeof(int));
+  k = 0;
+  for (j=0;j<symbol_table.exo_nbr;j++)
+    if (tmp_exo[j])
+      {
+        ModelBlock->Block_List[count_Block].Exogenous[k] = j;
+        k++;
+      }
+
+  ModelBlock->Block_List[count_Block].nb_exo_det = 0;
+
+  ModelBlock->Block_List[count_Block].Max_Lag = Lag;
+  ModelBlock->Block_List[count_Block].Max_Lead = Lead;
+  ModelBlock->Block_List[count_Block].Max_Lag_Endo = Lag_Endo;
+  ModelBlock->Block_List[count_Block].Max_Lead_Endo = Lead_Endo;
+  ModelBlock->Block_List[count_Block].Max_Lag_Other_Endo = Lag_Other_Endo;
+  ModelBlock->Block_List[count_Block].Max_Lead_Other_Endo = Lead_Other_Endo;
+  ModelBlock->Block_List[count_Block].Max_Lag_Exo = Lag_Exo;
+  ModelBlock->Block_List[count_Block].Max_Lead_Exo = Lead_Exo;
+  ModelBlock->Block_List[count_Block].IM_lead_lag = (IM_compact*)malloc((Lead + Lag + 1) * sizeof(IM_compact));
+  ls = l = li = size;
+  i1 = 0;
+  ModelBlock->Block_List[count_Block].Nb_Lead_Lag_Endo = nb_lead_lag_endo;
+  for (i = 0;i < Lead + Lag + 1;i++)
     {
-      ModelBlock->Block_List[*count_Block].is_linear=true;
-      ModelBlock->Block_List[*count_Block].Size = size;
-      ModelBlock->Block_List[*count_Block].Type = type;
-      ModelBlock->Block_List[*count_Block].Temporary_terms=new temporary_terms_type ();
-      ModelBlock->Block_List[*count_Block].Temporary_terms->clear();
-      ModelBlock->Block_List[*count_Block].Simulation_Type = UNKNOWN;
-      ModelBlock->Block_List[*count_Block].Equation = (int*)malloc(ModelBlock->Block_List[*count_Block].Size * sizeof(int));
-      ModelBlock->Block_List[*count_Block].Variable = (int*)malloc(ModelBlock->Block_List[*count_Block].Size * sizeof(int));
-      ModelBlock->Block_List[*count_Block].Own_Derivative = (int*)malloc(ModelBlock->Block_List[*count_Block].Size * sizeof(int));
-      Lead = Lag = 0;
-      first_count_equ = *count_Equ;
-      tmp_var = (int*)malloc(size * sizeof(int));
-      tmp_endo = (int*)malloc((incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1) * sizeof(int));
-      tmp_other_endo = (int*)malloc(symbol_table.endo_nbr * sizeof(int));
-      tmp_size = (int*)malloc((incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1) * sizeof(int));
-      tmp_size_other_endo = (int*)malloc((incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1) * sizeof(int));
-      tmp_size_exo = (int*)malloc((incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1) * sizeof(int));
-      memset(tmp_size_exo, 0, (incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1)*sizeof(int));
-      memset(tmp_size_other_endo, 0, (incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1)*sizeof(int));
-      memset(tmp_size, 0, (incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1)*sizeof(int));
-      memset(tmp_endo, 0, (incidencematrix.Model_Max_Lead + incidencematrix.Model_Max_Lag + 1)*sizeof(int));
-      memset(tmp_other_endo, 0, symbol_table.endo_nbr*sizeof(int));
-      nb_lead_lag_endo = 0;
-      Lag_Endo = Lead_Endo = Lag_Other_Endo = Lead_Other_Endo = Lag_Exo = Lead_Exo = 0;
-
-      //Variable by variable looking for all leads and lags its occurence in each equation of the block
-      tmp_variable_evaluated = (bool*)malloc(symbol_table.endo_nbr*sizeof(bool));
-      memset(tmp_variable_evaluated, 0, symbol_table.endo_nbr*sizeof(bool));
-      for(i = 0;i < size;i++)
-        {
-          ModelBlock->Block_List[*count_Block].Equation[i] = Index_Equ_IM[*count_Equ].index;
-          ModelBlock->Block_List[*count_Block].Variable[i] = Index_Var_IM[*count_Equ].index;
-          i_1 = Index_Var_IM[*count_Equ].index;
-          for(k = -incidencematrix.Model_Max_Lag_Endo; k<=incidencematrix.Model_Max_Lead_Endo; k++)
-            {
-              Cur_IM = incidencematrix.Get_IM(k, eEndogenous);
-              if(Cur_IM)
-                {
-                  OK = false;
-                  if(k >= 0)
-                    {
-                      for(j = 0;j < size;j++)
-                        {
-                          if(Cur_IM[i_1 + Index_Equ_IM[first_count_equ + j].index*symbol_table.endo_nbr])
-                            {
-                              tmp_variable_evaluated[i_1] = true;
-                              tmp_size[incidencematrix.Model_Max_Lag_Endo + k]++;
-                              if (!OK)
-                                {
-                                  tmp_endo[incidencematrix.Model_Max_Lag + k]++;
-                                  nb_lead_lag_endo++;
-                                  OK = true;
-                                }
-                              if(k > Lead)
-                                Lead = k;
-                            }
-                        }
-                    }
-                  else
-                    {
-                      for(j = 0;j < size;j++)
-                        {
-                          if(Cur_IM[i_1 + Index_Equ_IM[first_count_equ + j].index*symbol_table.endo_nbr])
-                            {
-                              tmp_size[incidencematrix.Model_Max_Lag_Endo + k]++;
-                              if (!OK)
-                                {
-                                  tmp_variable_evaluated[i_1] = true;
-                                  tmp_endo[incidencematrix.Model_Max_Lag + k]++;
-                                  nb_lead_lag_endo++;
-                                  OK = true;
-                                }
-                              if(-k > Lag)
-                                Lag = -k;
-                            }
-                        }
-                    }
-               }
-            }
-          (*count_Equ)++;
-        }
-      if ((Lag > 0) && (Lead > 0))
-        ModelBlock->Block_List[*count_Block].Simulation_Type = SOLVE_TWO_BOUNDARIES_COMPLETE;
-      else if(size > 1)
+      if (incidencematrix.Model_Max_Lag_Endo-Lag+i>=0)
         {
-          if(Lead > 0)
-            ModelBlock->Block_List[*count_Block].Simulation_Type = SOLVE_BACKWARD_COMPLETE;
-          else
-            ModelBlock->Block_List[*count_Block].Simulation_Type = SOLVE_FORWARD_COMPLETE;
+          ModelBlock->Block_List[count_Block].IM_lead_lag[i].size = tmp_size[incidencematrix.Model_Max_Lag_Endo - Lag + i];
+          ModelBlock->Block_List[count_Block].IM_lead_lag[i].nb_endo = tmp_endo[incidencematrix.Model_Max_Lag_Endo - Lag + i];
+          ModelBlock->Block_List[count_Block].IM_lead_lag[i].u = (int*)malloc(tmp_size[incidencematrix.Model_Max_Lag_Endo - Lag + i] * sizeof(int));
+          ModelBlock->Block_List[count_Block].IM_lead_lag[i].us = (int*)malloc(tmp_size[incidencematrix.Model_Max_Lag_Endo - Lag + i] * sizeof(int));
+          ModelBlock->Block_List[count_Block].IM_lead_lag[i].Var = (int*)malloc(tmp_size[incidencematrix.Model_Max_Lag_Endo - Lag + i] * sizeof(int));
+          ModelBlock->Block_List[count_Block].IM_lead_lag[i].Equ = (int*)malloc(tmp_size[incidencematrix.Model_Max_Lag_Endo - Lag + i] * sizeof(int));
+          ModelBlock->Block_List[count_Block].IM_lead_lag[i].Var_Index = (int*)malloc(tmp_size[incidencematrix.Model_Max_Lag_Endo - Lag + i] * sizeof(int));
+          ModelBlock->Block_List[count_Block].IM_lead_lag[i].Equ_Index = (int*)malloc(tmp_size[incidencematrix.Model_Max_Lag_Endo - Lag + i] * sizeof(int));
+          //cout << "count_Block = " << count_Block << " i = " << i << " size_other_endo = " << tmp_size_other_endo[incidencematrix.Model_Max_Lag_Endo - Lag + i] << "\n";
+          ModelBlock->Block_List[count_Block].IM_lead_lag[i].size_other_endo = tmp_size_other_endo[incidencematrix.Model_Max_Lag_Endo - Lag + i];
+          ModelBlock->Block_List[count_Block].IM_lead_lag[i].nb_other_endo = tmp_other_endo[incidencematrix.Model_Max_Lag_Endo - Lag + i];
+          ModelBlock->Block_List[count_Block].IM_lead_lag[i].u_other_endo = (int*)malloc(tmp_size_other_endo[incidencematrix.Model_Max_Lag_Endo - Lag + i] * sizeof(int));
+          ModelBlock->Block_List[count_Block].IM_lead_lag[i].Var_other_endo = (int*)malloc(tmp_size_other_endo[incidencematrix.Model_Max_Lag_Endo - Lag + i] * sizeof(int));
+          ModelBlock->Block_List[count_Block].IM_lead_lag[i].Equ_other_endo = (int*)malloc(tmp_size_other_endo[incidencematrix.Model_Max_Lag_Endo - Lag + i] * sizeof(int));
+          ModelBlock->Block_List[count_Block].IM_lead_lag[i].Var_Index_other_endo = (int*)malloc(tmp_size_other_endo[incidencematrix.Model_Max_Lag_Endo - Lag + i] * sizeof(int));
+          ModelBlock->Block_List[count_Block].IM_lead_lag[i].Equ_Index_other_endo = (int*)malloc(tmp_size_other_endo[incidencematrix.Model_Max_Lag_Endo - Lag + i] * sizeof(int));
         }
       else
+        ModelBlock->Block_List[count_Block].IM_lead_lag[i].size = 0;
+      if (incidencematrix.Model_Max_Lag_Exo-Lag+i>=0)
         {
-          if(Lead > 0)
-            ModelBlock->Block_List[*count_Block].Simulation_Type = SOLVE_BACKWARD_SIMPLE;
-          else
-            ModelBlock->Block_List[*count_Block].Simulation_Type = SOLVE_FORWARD_SIMPLE;
+          ModelBlock->Block_List[count_Block].IM_lead_lag[i].size_exo = tmp_size_exo[incidencematrix.Model_Max_Lag_Exo - Lag + i];
+          ModelBlock->Block_List[count_Block].IM_lead_lag[i].Exogenous = (int*)malloc(tmp_size_exo[incidencematrix.Model_Max_Lag_Exo - Lag + i] * sizeof(int));
+          ModelBlock->Block_List[count_Block].IM_lead_lag[i].Exogenous_Index = (int*)malloc(tmp_size_exo[incidencematrix.Model_Max_Lag_Exo - Lag + i] * sizeof(int));
+          ModelBlock->Block_List[count_Block].IM_lead_lag[i].Equ_X = (int*)malloc(tmp_size_exo[incidencematrix.Model_Max_Lag_Exo - Lag + i] * sizeof(int));
+          ModelBlock->Block_List[count_Block].IM_lead_lag[i].Equ_X_Index = (int*)malloc(tmp_size_exo[incidencematrix.Model_Max_Lag_Exo - Lag + i] * sizeof(int));
         }
-      Lag_Endo = Lag;
-      Lead_Endo = Lead;
-
-      tmp_nb_other_endo = 0;
-      for(i = 0;i < size;i++)
+      else
+        ModelBlock->Block_List[count_Block].IM_lead_lag[i].size_exo = 0;
+      ModelBlock->Block_List[count_Block].IM_lead_lag[i].u_init = l;
+      memset(tmp_variable_evaluated, 0, symbol_table.endo_nbr*sizeof(bool));
+      IM = incidencematrix.Get_IM(i - Lag, eEndogenous);
+      if (IM)
         {
-          for(k = -incidencematrix.Model_Max_Lag_Endo; k<=incidencematrix.Model_Max_Lead_Endo; k++)
+          for (j = first_count_equ;j < size + first_count_equ;j++)
             {
-              Cur_IM = incidencematrix.Get_IM(k, eEndogenous);
-              if(Cur_IM)
+              i_1 = Index_Var_IM[j].index;
+              m = 0;
+              for (k = first_count_equ;k < size + first_count_equ;k++)
+                if (IM[i_1 + Index_Equ_IM[k].index*symbol_table.endo_nbr])
+                  m++;
+              if (m > 0)
                 {
-                  i_1 = Index_Equ_IM[first_count_equ+i].index * symbol_table.endo_nbr;
-                  for(j = 0;j < symbol_table.endo_nbr;j++)
-                    if(Cur_IM[i_1 + j])
-                      {
-                        if(!tmp_variable_evaluated[j])
-                          {
-                            tmp_other_endo[j] = 1;
-                            tmp_nb_other_endo++;
-                          }
-                        if(k>0 && k>Lead_Other_Endo)
-                          Lead_Other_Endo = k;
-                        else if(k<0 && (-k)>Lag_Other_Endo)
-                          Lag_Other_Endo = -k;
-                        if(k>0 && k>Lead)
-                          Lead = k;
-                        else if(k<0 && (-k)>Lag)
-                          Lag = -k;
-                        tmp_size_other_endo[k+incidencematrix.Model_Max_Lag_Endo]++;
-                      }
+                  tmp_var[j - first_count_equ] = i1;
+                  i1++;
                 }
             }
-        }
-      ModelBlock->Block_List[*count_Block].nb_other_endo = tmp_nb_other_endo;
-      ModelBlock->Block_List[*count_Block].Other_Endogenous = (int*)malloc(tmp_nb_other_endo * sizeof(int));
-
-
-      tmp_exo = (int*)malloc(symbol_table.exo_nbr * sizeof(int));
-      memset(tmp_exo, 0, symbol_table.exo_nbr *     sizeof(int));
-      tmp_nb_exo = 0;
-      for(i = 0;i < size;i++)
-        {
-          for(k = -incidencematrix.Model_Max_Lag_Exo; k<=incidencematrix.Model_Max_Lead_Exo; k++)
+          m = 0;
+          for (j = first_count_equ;j < size + first_count_equ;j++)
             {
-              Cur_IM = incidencematrix.Get_IM(k, eExogenous);
-              if(Cur_IM)
-                {
-                  i_1 = Index_Equ_IM[first_count_equ+i].index * symbol_table.exo_nbr;
-                  for(j=0;j<symbol_table.exo_nbr;j++)
-                    if(Cur_IM[i_1 + j])
+              i_1 = Index_Equ_IM[j].index * symbol_table.endo_nbr;
+              for (k = first_count_equ;k < size + first_count_equ;k++)
+                if (IM[Index_Var_IM[k].index + i_1])
+                  {
+                    if (i == Lag)
                       {
-                        if(!tmp_exo[j])
-                          {
-                            tmp_exo[j] = 1;
-                            tmp_nb_exo++;
-                          }
-                        if(k>0 && k>Lead_Exo)
-                          Lead_Exo = k;
-                        else if(k<0 && (-k)>Lag_Exo)
-                          Lag_Exo = -k;
-                        if(k>0 && k>Lead)
-                          Lead = k;
-                        else if(k<0 && (-k)>Lag)
-                          Lag = -k;
-                        tmp_size_exo[k+incidencematrix.Model_Max_Lag_Exo]++;
+                        ModelBlock->Block_List[count_Block].IM_lead_lag[i].us[m] = ls;
+                        ls++;
                       }
-                }
-            }
-        }
-
-
-      ModelBlock->Block_List[*count_Block].nb_exo = tmp_nb_exo;
-      ModelBlock->Block_List[*count_Block].Exogenous = (int*)malloc(tmp_nb_exo * sizeof(int));
-      k = 0;
-      for(j=0;j<symbol_table.exo_nbr;j++)
-        if(tmp_exo[j])
-          {
-            ModelBlock->Block_List[*count_Block].Exogenous[k] = j;
-            k++;
-          }
-
-      ModelBlock->Block_List[*count_Block].nb_exo_det = 0;
-
-      ModelBlock->Block_List[*count_Block].Max_Lag = Lag;
-      ModelBlock->Block_List[*count_Block].Max_Lead = Lead;
-      ModelBlock->Block_List[*count_Block].Max_Lag_Endo = Lag_Endo;
-      ModelBlock->Block_List[*count_Block].Max_Lead_Endo = Lead_Endo;
-      ModelBlock->Block_List[*count_Block].Max_Lag_Other_Endo = Lag_Other_Endo;
-      ModelBlock->Block_List[*count_Block].Max_Lead_Other_Endo = Lead_Other_Endo;
-      ModelBlock->Block_List[*count_Block].Max_Lag_Exo = Lag_Exo;
-      ModelBlock->Block_List[*count_Block].Max_Lead_Exo = Lead_Exo;
-      ModelBlock->Block_List[*count_Block].IM_lead_lag = (IM_compact*)malloc((Lead + Lag + 1) * sizeof(IM_compact));
-      ls = l = li = size;
-      i1 = 0;
-      ModelBlock->Block_List[*count_Block].Nb_Lead_Lag_Endo = nb_lead_lag_endo;
-      for(i = 0;i < Lead + Lag + 1;i++)
-        {
-          if(incidencematrix.Model_Max_Lag_Endo-Lag+i>=0)
-            {
-              ModelBlock->Block_List[*count_Block].IM_lead_lag[i].size = tmp_size[incidencematrix.Model_Max_Lag_Endo - Lag + i];
-              ModelBlock->Block_List[*count_Block].IM_lead_lag[i].nb_endo = tmp_endo[incidencematrix.Model_Max_Lag_Endo - Lag + i];
-              ModelBlock->Block_List[*count_Block].IM_lead_lag[i].u = (int*)malloc(tmp_size[incidencematrix.Model_Max_Lag_Endo - Lag + i] * sizeof(int));
-              ModelBlock->Block_List[*count_Block].IM_lead_lag[i].us = (int*)malloc(tmp_size[incidencematrix.Model_Max_Lag_Endo - Lag + i] * sizeof(int));
-              ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Var = (int*)malloc(tmp_size[incidencematrix.Model_Max_Lag_Endo - Lag + i] * sizeof(int));
-              ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Equ = (int*)malloc(tmp_size[incidencematrix.Model_Max_Lag_Endo - Lag + i] * sizeof(int));
-              ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Var_Index = (int*)malloc(tmp_size[incidencematrix.Model_Max_Lag_Endo - Lag + i] * sizeof(int));
-              ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Equ_Index = (int*)malloc(tmp_size[incidencematrix.Model_Max_Lag_Endo - Lag + i] * sizeof(int));
-
-              ModelBlock->Block_List[*count_Block].IM_lead_lag[i].size_other_endo = tmp_size_other_endo[incidencematrix.Model_Max_Lag_Endo - Lag + i];
-              ModelBlock->Block_List[*count_Block].IM_lead_lag[i].nb_other_endo = tmp_other_endo[incidencematrix.Model_Max_Lag_Endo - Lag + i];
-              ModelBlock->Block_List[*count_Block].IM_lead_lag[i].u_other_endo = (int*)malloc(tmp_size_other_endo[incidencematrix.Model_Max_Lag_Endo - Lag + i] * sizeof(int));
-              ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Var_other_endo = (int*)malloc(tmp_size_other_endo[incidencematrix.Model_Max_Lag_Endo - Lag + i] * sizeof(int));
-              ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Equ_other_endo = (int*)malloc(tmp_size_other_endo[incidencematrix.Model_Max_Lag_Endo - Lag + i] * sizeof(int));
-              ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Var_Index_other_endo = (int*)malloc(tmp_size_other_endo[incidencematrix.Model_Max_Lag_Endo - Lag + i] * sizeof(int));
-              ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Equ_Index_other_endo = (int*)malloc(tmp_size_other_endo[incidencematrix.Model_Max_Lag_Endo - Lag + i] * sizeof(int));
+                    ModelBlock->Block_List[count_Block].IM_lead_lag[i].u[m] = li;
+                    ModelBlock->Block_List[count_Block].IM_lead_lag[i].Equ[m] = j - first_count_equ;
+                    ModelBlock->Block_List[count_Block].IM_lead_lag[i].Var[m] = k - first_count_equ;
+                    ModelBlock->Block_List[count_Block].IM_lead_lag[i].Equ_Index[m] = Index_Equ_IM[j].index;
+                    ModelBlock->Block_List[count_Block].IM_lead_lag[i].Var_Index[m] = Index_Var_IM[k].index;
+                    tmp_variable_evaluated[Index_Var_IM[k].index] = true;
+                    l++;
+                    m++;
+                    li++;
+                  }
             }
-          else
-            ModelBlock->Block_List[*count_Block].IM_lead_lag[i].size = 0;
-          if(incidencematrix.Model_Max_Lag_Exo-Lag+i>=0)
+          ModelBlock->Block_List[count_Block].IM_lead_lag[i].u_finish = li - 1;
+          m = 0;
+          for (j = first_count_equ;j < size + first_count_equ;j++)
             {
-              ModelBlock->Block_List[*count_Block].IM_lead_lag[i].size_exo = tmp_size_exo[incidencematrix.Model_Max_Lag_Exo - Lag + i];
-              ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Exogenous = (int*)malloc(tmp_size_exo[incidencematrix.Model_Max_Lag_Exo - Lag + i] * sizeof(int));
-              ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Exogenous_Index = (int*)malloc(tmp_size_exo[incidencematrix.Model_Max_Lag_Exo - Lag + i] * sizeof(int));
-              ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Equ_X = (int*)malloc(tmp_size_exo[incidencematrix.Model_Max_Lag_Exo - Lag + i] * sizeof(int));
-              ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Equ_X_Index = (int*)malloc(tmp_size_exo[incidencematrix.Model_Max_Lag_Exo - Lag + i] * sizeof(int));
+              i_1 = Index_Equ_IM[j].index * symbol_table.endo_nbr;
+              for (k = 0;k < symbol_table.endo_nbr;k++)
+                if ((!tmp_variable_evaluated[Index_Var_IM[k].index]) && IM[Index_Var_IM[k].index + i_1])
+                  {
+                    ModelBlock->Block_List[count_Block].IM_lead_lag[i].u_other_endo[m] = l;
+                    ModelBlock->Block_List[count_Block].IM_lead_lag[i].Equ_other_endo[m] = j - first_count_equ;
+                    ModelBlock->Block_List[count_Block].IM_lead_lag[i].Var_other_endo[m] = k;
+                    ModelBlock->Block_List[count_Block].IM_lead_lag[i].Equ_Index_other_endo[m] = Index_Equ_IM[j].index;
+                    ModelBlock->Block_List[count_Block].IM_lead_lag[i].Var_Index_other_endo[m] = Index_Var_IM[k].index;
+                    l++;
+                    m++;
+                  }
             }
-          else
-            ModelBlock->Block_List[*count_Block].IM_lead_lag[i].size_exo = 0;
-          ModelBlock->Block_List[*count_Block].IM_lead_lag[i].u_init = l;
-          memset(tmp_variable_evaluated, 0, symbol_table.endo_nbr*sizeof(bool));
-          IM = incidencematrix.Get_IM(i - Lag, eEndogenous);
-          if(IM)
-            {
-              for(j = first_count_equ;j < size + first_count_equ;j++)
-                {
-                  i_1 = Index_Var_IM[j].index;
-                  m = 0;
-                  for(k = first_count_equ;k < size + first_count_equ;k++)
-                    if(IM[i_1 + Index_Equ_IM[k].index*symbol_table.endo_nbr])
-                      m++;
-                  if(m > 0)
-                    {
-                      tmp_var[j - first_count_equ] = i1;
-                      i1++;
-                    }
-                }
-              m = 0;
-              for(j = first_count_equ;j < size + first_count_equ;j++)
-                {
-                  i_1 = Index_Equ_IM[j].index * symbol_table.endo_nbr;
-                  for(k = first_count_equ;k < size + first_count_equ;k++)
-                    if(IM[Index_Var_IM[k].index + i_1])
-                      {
-                        if(i == Lag)
-                          {
-                            ModelBlock->Block_List[*count_Block].IM_lead_lag[i].us[m] = ls;
-                            ls++;
-                          }
-                        ModelBlock->Block_List[*count_Block].IM_lead_lag[i].u[m] = li;
-                        ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Equ[m] = j - first_count_equ;
-                        ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Var[m] = k - first_count_equ;
-                        ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Equ_Index[m] = Index_Equ_IM[j].index;
-                        ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Var_Index[m] = Index_Var_IM[k].index;
-                        tmp_variable_evaluated[Index_Var_IM[k].index] = true;
-                        l++;
-                        m++;
-                        li++;
-                      }
-                }
-              ModelBlock->Block_List[*count_Block].IM_lead_lag[i].u_finish = li - 1;
-              m = 0;
-              for(j = first_count_equ;j < size + first_count_equ;j++)
-                {
-                  i_1 = Index_Equ_IM[j].index * symbol_table.endo_nbr;
-                  for(k = 0;k < symbol_table.endo_nbr;k++)
-                    if((!tmp_variable_evaluated[Index_Var_IM[k].index]) && IM[Index_Var_IM[k].index + i_1])
-                      {
-                        ModelBlock->Block_List[*count_Block].IM_lead_lag[i].u_other_endo[m] = l;
-                        ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Equ_other_endo[m] = j - first_count_equ;
-                        ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Var_other_endo[m] = k - first_count_equ;
-                        ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Equ_Index_other_endo[m] = Index_Equ_IM[j].index;
-                        ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Var_Index_other_endo[m] = Index_Var_IM[k].index;
-                        l++;
-                        m++;
-                      }
-                }
-            }
-          IM = incidencematrix.Get_IM(i - Lag, eExogenous);
-          if(IM)
+          ModelBlock->Block_List[count_Block].IM_lead_lag[i].size_other_endo = m;
+        }
+      IM = incidencematrix.Get_IM(i - Lag, eExogenous);
+      if (IM)
+        {
+          m = 0;
+          for (j = first_count_equ;j < size + first_count_equ;j++)
             {
-              m = 0;
-              for(j = first_count_equ;j < size + first_count_equ;j++)
+              i_1 = Index_Equ_IM[j].index * symbol_table.exo_nbr;
+              for (k = 0; k<tmp_nb_exo; k++)
                 {
-                  i_1 = Index_Equ_IM[j].index * symbol_table.exo_nbr;
-                  for(k = 0; k<tmp_nb_exo; k++)
+                  if (IM[ModelBlock->Block_List[count_Block].Exogenous[k]+i_1])
                     {
-                      if(IM[ModelBlock->Block_List[*count_Block].Exogenous[k]+i_1])
-                        {
-                          ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Exogenous[m] = k;
-                          ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Exogenous_Index[m] = ModelBlock->Block_List[*count_Block].Exogenous[k];
-                          ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Equ_X[m] = j - first_count_equ;
-                          ModelBlock->Block_List[*count_Block].IM_lead_lag[i].Equ_X_Index[m] = Index_Equ_IM[j].index;
-                          m++;
-                        }
+                      ModelBlock->Block_List[count_Block].IM_lead_lag[i].Exogenous[m] = k;
+                      ModelBlock->Block_List[count_Block].IM_lead_lag[i].Exogenous_Index[m] = ModelBlock->Block_List[count_Block].Exogenous[k];
+                      ModelBlock->Block_List[count_Block].IM_lead_lag[i].Equ_X[m] = j - first_count_equ;
+                      ModelBlock->Block_List[count_Block].IM_lead_lag[i].Equ_X_Index[m] = Index_Equ_IM[j].index;
+                      m++;
                     }
                 }
             }
         }
-      (*count_Block)++;
-      free(tmp_size);
-      free(tmp_size_other_endo);
-      free(tmp_size_exo);
-      free(tmp_endo);
-      free(tmp_other_endo);
-      free(tmp_exo);
-      free(tmp_var);
-      free(tmp_variable_evaluated);
     }
+  free(tmp_size);
+  free(tmp_size_other_endo);
+  free(tmp_size_exo);
+  free(tmp_endo);
+  free(tmp_other_endo);
+  free(tmp_exo);
+  free(tmp_var);
+  free(tmp_variable_evaluated);
 }
 
 
 void
 BlockTriangular::Free_Block(Model_Block* ModelBlock) const
+  {
+    int blk, i;
+    for (blk = 0;blk < ModelBlock->Size;blk++)
+      {
+
+
+        free(ModelBlock->Block_List[blk].Equation);
+        free(ModelBlock->Block_List[blk].Variable);
+        free(ModelBlock->Block_List[blk].Exogenous);
+        free(ModelBlock->Block_List[blk].Own_Derivative);
+        for (i = 0;i < ModelBlock->Block_List[blk].Max_Lag + ModelBlock->Block_List[blk].Max_Lead + 1;i++)
+          {
+            if (incidencematrix.Model_Max_Lag_Endo-ModelBlock->Block_List[blk].Max_Lag+i>=0 && ModelBlock->Block_List[blk].IM_lead_lag[i].size)
+              {
+                free(ModelBlock->Block_List[blk].IM_lead_lag[i].u);
+                free(ModelBlock->Block_List[blk].IM_lead_lag[i].us);
+                free(ModelBlock->Block_List[blk].IM_lead_lag[i].Equ);
+                free(ModelBlock->Block_List[blk].IM_lead_lag[i].Var);
+                free(ModelBlock->Block_List[blk].IM_lead_lag[i].Equ_Index);
+                free(ModelBlock->Block_List[blk].IM_lead_lag[i].Var_Index);
+              }
+            if (incidencematrix.Model_Max_Lag_Exo-ModelBlock->Block_List[blk].Max_Lag+i>=0 && ModelBlock->Block_List[blk].IM_lead_lag[i].size_exo)
+              {
+                free(ModelBlock->Block_List[blk].IM_lead_lag[i].Exogenous);
+                free(ModelBlock->Block_List[blk].IM_lead_lag[i].Exogenous_Index);
+                free(ModelBlock->Block_List[blk].IM_lead_lag[i].Equ_X_Index);
+                free(ModelBlock->Block_List[blk].IM_lead_lag[i].Equ_X);
+              }
+          }
+        free(ModelBlock->Block_List[blk].IM_lead_lag);
+        delete(ModelBlock->Block_List[blk].Temporary_terms);
+        delete(ModelBlock->Block_List[blk].Temporary_InUse);
+      }
+    free(ModelBlock->Block_List);
+    free(ModelBlock);
+    free(Index_Equ_IM);
+    free(Index_Var_IM);
+  }
+
+
+t_type
+BlockTriangular::Reduce_Blocks_and_type_determination(int prologue, int epilogue, block_result_t* res, vector<BinaryOpNode *> equations )
 {
-  int blk, i;
-  for(blk = 0;blk < ModelBlock->Size;blk++)
+  int i=0;
+  NodeID lhs, rhs;
+  ostringstream tmp_output;
+  BinaryOpNode *eq_node;
+  ostringstream tmp_s;
+  temporary_terms_type temporary_terms;
+  int count_equ = 0, blck_count_simult =0;
+  int Blck_Size;
+  int Lead, Lag;
+  t_type Type;
+  bool *Cur_IM;
+  BlockSimulationType Simulation_Type , prev_Type=UNKNOWN;
+  for ( i=0; i<prologue+res->n_sets+epilogue; i++)
     {
+      int first_count_equ = count_equ;
+      if (i < prologue)
+        Blck_Size = 1;
+      else if (i < prologue+res->n_sets)
+        {
+          Blck_Size = res->sets_f[res->ordered[blck_count_simult]] - res->sets_s[res->ordered[blck_count_simult]] + 1;
+          blck_count_simult++;
+        }
+      else if (i < prologue+res->n_sets+epilogue)
+        Blck_Size = 1;
 
-      if ((ModelBlock->Block_List[blk].Type == PROLOGUE) || (ModelBlock->Block_List[blk].Type == EPILOGUE))
+      Lag = Lead = 0;
+      for (count_equ = first_count_equ; count_equ < Blck_Size+first_count_equ; count_equ++)
         {
-          free(ModelBlock->Block_List[blk].Equation);
-          free(ModelBlock->Block_List[blk].Variable);
-          free(ModelBlock->Block_List[blk].Exogenous);
-          free(ModelBlock->Block_List[blk].Own_Derivative);
-          for(i = 0;i < ModelBlock->Block_List[blk].Max_Lag + ModelBlock->Block_List[blk].Max_Lead + 1;i++)
+          int i_1 = Index_Var_IM[count_equ].index;
+          for (int k = -incidencematrix.Model_Max_Lag_Endo; k<=incidencematrix.Model_Max_Lead_Endo; k++)
             {
-              if(ModelBlock->Block_List[blk].IM_lead_lag[i].size)
-                {
-                  free(ModelBlock->Block_List[blk].IM_lead_lag[i].u);
-                  free(ModelBlock->Block_List[blk].IM_lead_lag[i].us);
-                  free(ModelBlock->Block_List[blk].IM_lead_lag[i].Var);
-                  free(ModelBlock->Block_List[blk].IM_lead_lag[i].Equ);
-                  free(ModelBlock->Block_List[blk].IM_lead_lag[i].Var_Index);
-                  free(ModelBlock->Block_List[blk].IM_lead_lag[i].Equ_Index);
-                }
-              if(ModelBlock->Block_List[blk].IM_lead_lag[i].size_exo)
+              Cur_IM = incidencematrix.Get_IM(k, eEndogenous);
+              if (Cur_IM)
                 {
-                  free(ModelBlock->Block_List[blk].IM_lead_lag[i].Exogenous);
-                  free(ModelBlock->Block_List[blk].IM_lead_lag[i].Exogenous_Index);
-                  free(ModelBlock->Block_List[blk].IM_lead_lag[i].Equ_X_Index);
-                  free(ModelBlock->Block_List[blk].IM_lead_lag[i].Equ_X);
+                  for (int j = 0;j < Blck_Size;j++)
+                    {
+                      if (Cur_IM[i_1 + Index_Equ_IM[first_count_equ + j].index*symbol_table.endo_nbr])
+                        {
+                          if (k > Lead)
+                            Lead = k;
+                          else if (-k > Lag)
+                            Lag = -k;
+                        }
+                    }
                 }
             }
-          free(ModelBlock->Block_List[blk].IM_lead_lag);
-          delete(ModelBlock->Block_List[blk].Temporary_terms);
+        }
+      if ((Lag > 0) && (Lead > 0))
+        {
+          if (Blck_Size == 1)
+            Simulation_Type = SOLVE_TWO_BOUNDARIES_SIMPLE;
+          else
+            Simulation_Type = SOLVE_TWO_BOUNDARIES_COMPLETE;
+        }
+      else if (Blck_Size > 1)
+        {
+          if (Lead > 0)
+            Simulation_Type = SOLVE_BACKWARD_COMPLETE;
+          else
+            Simulation_Type = SOLVE_FORWARD_COMPLETE;
         }
       else
         {
-          free(ModelBlock->Block_List[blk].Equation);
-          free(ModelBlock->Block_List[blk].Variable);
-          free(ModelBlock->Block_List[blk].Exogenous);
-          free(ModelBlock->Block_List[blk].Own_Derivative);
-          for(i = 0;i < ModelBlock->Block_List[blk].Max_Lag + ModelBlock->Block_List[blk].Max_Lead + 1;i++)
+          if (Lead > 0)
+            Simulation_Type = SOLVE_BACKWARD_SIMPLE;
+          else
+            Simulation_Type = SOLVE_FORWARD_SIMPLE;
+        }
+      if (Blck_Size == 1)
+        {
+          temporary_terms.clear();
+          eq_node = equations[Index_Equ_IM[first_count_equ].index];
+          lhs = eq_node->get_arg1();
+          rhs = eq_node->get_arg2();
+          tmp_s.str("");
+          tmp_output.str("");
+          lhs->writeOutput(tmp_output, oMatlabDynamicModelSparse, temporary_terms);
+          tmp_s << "y(it_, " << Index_Var_IM[first_count_equ].index+1 << ")";
+          //cout << "tmp_s=" << tmp_s.str() << " tmp_output=" << tmp_output.str() << "  " << bool(tmp_output.str()==tmp_s.str()) << " " << BlockSim(Simulation_Type)
+          //     << " first_count_equ=" << first_count_equ << " equation=" << Index_Equ_IM[first_count_equ].index << "\n";
+          //Determine whether the equation could be evaluated rather than to be solved
+          if (tmp_output.str()==tmp_s.str())
+            {
+              if (Simulation_Type==SOLVE_BACKWARD_SIMPLE)
+                Simulation_Type=EVALUATE_BACKWARD;
+              else if (Simulation_Type==SOLVE_FORWARD_SIMPLE)
+                Simulation_Type=EVALUATE_FORWARD;
+            }
+          else
             {
-              if(incidencematrix.Model_Max_Lag_Endo-ModelBlock->Block_List[blk].Max_Lag+i>=0 && ModelBlock->Block_List[blk].IM_lead_lag[i].size)
+              tmp_output.str("");
+              rhs->writeOutput(tmp_output, oCDynamicModelSparseDLL, temporary_terms);
+              //cout << "sec tmp_s=" << tmp_s.str() << " tmp_output=" << tmp_output.str() << "  " << bool(tmp_output.str()==tmp_s.str()) << " " << BlockSim(Simulation_Type) << "\n";
+              if (tmp_output.str()==tmp_s.str())
                 {
-                  free(ModelBlock->Block_List[blk].IM_lead_lag[i].u);
-                  free(ModelBlock->Block_List[blk].IM_lead_lag[i].us);
-                  free(ModelBlock->Block_List[blk].IM_lead_lag[i].Equ);
-                  free(ModelBlock->Block_List[blk].IM_lead_lag[i].Var);
-                  free(ModelBlock->Block_List[blk].IM_lead_lag[i].Equ_Index);
-                  free(ModelBlock->Block_List[blk].IM_lead_lag[i].Var_Index);
+                  if (Simulation_Type==SOLVE_BACKWARD_SIMPLE)
+                    Simulation_Type=EVALUATE_BACKWARD_R;
+                  else if (Simulation_Type==SOLVE_FORWARD_SIMPLE)
+                    Simulation_Type=EVALUATE_FORWARD_R;
                 }
-              if(incidencematrix.Model_Max_Lag_Exo-ModelBlock->Block_List[blk].Max_Lag+i>=0 && ModelBlock->Block_List[blk].IM_lead_lag[i].size_exo)
+            }
+          if (i > 0)
+            {
+              if ( ((prev_Type ==  EVALUATE_FORWARD_R || prev_Type ==  EVALUATE_FORWARD) && (Simulation_Type == EVALUATE_FORWARD_R || Simulation_Type == EVALUATE_FORWARD))
+                   || ((prev_Type ==  EVALUATE_BACKWARD_R || prev_Type ==  EVALUATE_BACKWARD) && (Simulation_Type == EVALUATE_BACKWARD_R || Simulation_Type == EVALUATE_BACKWARD))
+                 )
                 {
-                  free(ModelBlock->Block_List[blk].IM_lead_lag[i].Exogenous);
-                  free(ModelBlock->Block_List[blk].IM_lead_lag[i].Exogenous_Index);
-                  free(ModelBlock->Block_List[blk].IM_lead_lag[i].Equ_X_Index);
-                  free(ModelBlock->Block_List[blk].IM_lead_lag[i].Equ_X);
+                  //cout << "Type[0].first=" << Type[0].first << " Type[0].second= " << Type[0].second << "\n";
+                  BlockSimulationType c_Type = (Type[Type.size()-1]).first;
+                  int c_Size = (Type[Type.size()-1]).second;
+                  //cout << "i=" << i << " Type.size()=" << Type.size() << " c_Size=" << c_Size << "\n";
+                  Type[Type.size()-1]=make_pair(c_Type, ++c_Size);
                 }
+              else
+                Type.push_back(make_pair(Simulation_Type, Blck_Size));
             }
-          free(ModelBlock->Block_List[blk].IM_lead_lag);
-          delete(ModelBlock->Block_List[blk].Temporary_terms);
+          else
+            Type.push_back(make_pair(Simulation_Type, Blck_Size));
+        }
+      else
+        {
+          /*for (count_equ = first_count_equ; count_equ < Blck_Size+first_count_equ; count_equ++)
+            cout << Index_Equ_IM[count_equ ].index+1 <<  "  " << Index_Var_IM[count_equ ].index+1 << "\n";*/
+          Type.push_back(make_pair(Simulation_Type, Blck_Size));
         }
+      //cout << "Type.size()= " << Type.size() << " BlockSim(Simulation_Type) = " << BlockSim(Simulation_Type) << "\n";
+      prev_Type = Simulation_Type;
     }
-  free(ModelBlock->Block_List);
-  free(ModelBlock);
-  free(Index_Equ_IM);
-  free(Index_Var_IM);
+  return(Type);
 }
 
+
 //------------------------------------------------------------------------------
 // Normalize each equation of the model (endgenous_i = f_i(endogenous_1, ..., endogenous_n) - in order to apply strong connex components search algorithm -
 // and find the optimal blocks triangular decomposition
 bool
-BlockTriangular::Normalize_and_BlockDecompose(bool* IM, Model_Block* ModelBlock, int n, int* prologue, int* epilogue, simple* Index_Var_IM, simple* Index_Equ_IM, bool Do_Normalization, bool mixing, bool* IM_0, jacob_map j_m )
+BlockTriangular::Normalize_and_BlockDecompose(bool* IM, Model_Block* ModelBlock, int n, int* prologue, int* epilogue, simple* Index_Var_IM, simple* Index_Equ_IM, bool Do_Normalization, bool mixing, bool* IM_0, jacob_map j_m, vector<BinaryOpNode *> equations )
 {
-  int i, j, Nb_TotalBlocks, Nb_RecursBlocks;
+  int i, j, Nb_TotalBlocks, Nb_RecursBlocks, Nb_SimulBlocks;
+  BlockType Btype;
   int count_Block, count_Equ;
   block_result_t* res;
   Equation_set* Equation_gr = (Equation_set*) malloc(sizeof(Equation_set));
@@ -821,49 +609,49 @@ BlockTriangular::Normalize_and_BlockDecompose(bool* IM, Model_Block* ModelBlock,
   memcpy(SIM0,IM_0,n*n*sizeof(bool));
   Prologue_Epilogue(IM, prologue, epilogue, n, Index_Var_IM, Index_Equ_IM, SIM0);
   free(SIM0);
-  if(bt_verbose)
+  if (bt_verbose)
     {
       cout << "prologue : " << *prologue << " epilogue : " << *epilogue << "\n";
       cout << "IM_0\n";
       incidencematrix.Print_SIM(IM_0, eEndogenous);
       cout << "IM\n";
       incidencematrix.Print_SIM(IM, eEndogenous);
-      for(i = 0;i < n;i++)
+      for (i = 0;i < n;i++)
         cout << "Index_Var_IM[" << i << "]=" << Index_Var_IM[i].index << " Index_Equ_IM[" << i << "]=" << Index_Equ_IM[i].index << "\n";
     }
-  if(*prologue+*epilogue<n)
+  if (*prologue+*epilogue<n)
     {
-      if(Do_Normalization)
+      if (Do_Normalization)
         {
           cout << "Normalizing the model ...\n";
-          if(mixing)
+          if (mixing)
             {
               double* max_val=(double*)malloc(n*sizeof(double));
               memset(max_val,0,n*sizeof(double));
-              for( map< pair< int, int >, double >::iterator iter = j_m.begin(); iter != j_m.end(); iter++ )
+              for ( map< pair< int, int >, double >::iterator iter = j_m.begin(); iter != j_m.end(); iter++ )
                 {
-                  if(fabs(iter->second)>max_val[iter->first.first])
+                  if (fabs(iter->second)>max_val[iter->first.first])
                     max_val[iter->first.first]=fabs(iter->second);
                 }
-              for( map< pair< int, int >, double >::iterator iter = j_m.begin(); iter != j_m.end(); iter++ )
-                  iter->second/=max_val[iter->first.first];
+              for ( map< pair< int, int >, double >::iterator iter = j_m.begin(); iter != j_m.end(); iter++ )
+                iter->second/=max_val[iter->first.first];
               free(max_val);
               bool OK=false;
               double bi=0.99999999;
               int suppressed=0;
-              while(!OK && bi>1e-14)
+              while (!OK && bi>1e-14)
                 {
                   int suppress=0;
                   SIM0 = (bool*)malloc(n * n * sizeof(bool));
                   memset(SIM0,0,n*n*sizeof(bool));
                   SIM00 = (bool*)malloc(n * n * sizeof(bool));
                   memset(SIM00,0,n*n*sizeof(bool));
-                  for( map< pair< int, int >, double >::iterator iter = j_m.begin(); iter != j_m.end(); iter++ )
+                  for ( map< pair< int, int >, double >::iterator iter = j_m.begin(); iter != j_m.end(); iter++ )
                     {
-                      if(fabs(iter->second)>bi)
+                      if (fabs(iter->second)>bi)
                         {
                           SIM0[iter->first.first*n+iter->first.second]=1;
-                          if(!IM_0[iter->first.first*n+iter->first.second])
+                          if (!IM_0[iter->first.first*n+iter->first.second])
                             {
                               cout << "Error nothing at IM_0[" << iter->first.first << ", " << iter->first.second << "]=" << IM_0[iter->first.first*n+iter->first.second] << "  " << iter->second << "\n";
                             }
@@ -871,25 +659,25 @@ BlockTriangular::Normalize_and_BlockDecompose(bool* IM, Model_Block* ModelBlock,
                       else
                         suppress++;
                     }
-                  for(i = 0;i < n;i++)
-                    for(j = 0;j < n;j++)
+                  for (i = 0;i < n;i++)
+                    for (j = 0;j < n;j++)
                       {
                         SIM00[i*n + j] = SIM0[Index_Equ_IM[i].index * n + Index_Var_IM[j].index];
                       }
                   free(SIM0);
-                  if(suppress!=suppressed)
+                  if (suppress!=suppressed)
                     {
                       OK=normalization.Normalize(n, *prologue, *epilogue, SIM00, Index_Equ_IM, Equation_gr, 1, IM);
-                      if(!OK)
+                      if (!OK)
                         normalization.Free_Equation(n-*prologue-*epilogue,Equation_gr);
                     }
                   suppressed=suppress;
-                  if(!OK)
+                  if (!OK)
                     bi/=1.07;
-                  if(bi>1e-14)
+                  if (bi>1e-14)
                     free(SIM00);
                 }
-              if(!OK)
+              if (!OK)
                 {
                   normalization.Set_fp_verbose(true);
                   OK=normalization.Normalize(n, *prologue, *epilogue, SIM00, Index_Equ_IM, Equation_gr, 1, IM);
@@ -904,13 +692,13 @@ BlockTriangular::Normalize_and_BlockDecompose(bool* IM, Model_Block* ModelBlock,
         normalization.Gr_to_IM_basic(n, *prologue, *epilogue, IM, Equation_gr, false);
     }
   cout << "Finding the optimal block decomposition of the model ...\n";
-  if(*prologue+*epilogue<n)
+  if (*prologue+*epilogue<n)
     {
-      if(bt_verbose)
+      if (bt_verbose)
         blocks.Print_Equation_gr(Equation_gr);
       res = blocks.sc(Equation_gr);
       normalization.Free_Equation(n-*prologue-*epilogue,Equation_gr);
-      if(bt_verbose)
+      if (bt_verbose)
         blocks.block_result_print(res);
     }
   else
@@ -919,40 +707,60 @@ BlockTriangular::Normalize_and_BlockDecompose(bool* IM, Model_Block* ModelBlock,
       res->n_sets=0;
     }
   free(Equation_gr);
-  if ((*prologue) || (*epilogue))
-    j = 1;
-  else
-    j = 0;
-  for(i = 0;i < res->n_sets;i++)
+
+
+  blocks.block_result_to_IM(res, IM, *prologue, symbol_table.endo_nbr, Index_Equ_IM, Index_Var_IM);
+
+
+  t_type  Type = Reduce_Blocks_and_type_determination(*prologue, *epilogue, res, equations);
+
+
+  i = 0;
+  j = 0;
+  Nb_SimulBlocks = 0;
+  for (t_type::const_iterator it = Type.begin(); it!=Type.end(); it++)
     {
-      if ((res->sets_f[i] - res->sets_s[i] + 1) > j)
-        j = res->sets_f[i] - res->sets_s[i] + 1;
+      //cout << "Block " << i++ << " Type=" << BlockSim(it->first) << " Size=" << it->second << "\n";
+      if (it->first==SOLVE_FORWARD_COMPLETE || it->first==SOLVE_BACKWARD_COMPLETE || it->first==SOLVE_TWO_BOUNDARIES_COMPLETE)
+        {
+          Nb_SimulBlocks++;
+          if (it->second>j)
+            j=it->second;
+        }
     }
-  Nb_RecursBlocks = *prologue + *epilogue;
-  Nb_TotalBlocks = res->n_sets + Nb_RecursBlocks;
+
+  Nb_TotalBlocks = Type.size();
+  Nb_RecursBlocks = Nb_TotalBlocks - Nb_SimulBlocks;
   cout << Nb_TotalBlocks << " block(s) found:\n";
   cout << "  " << Nb_RecursBlocks << " recursive block(s) and " << res->n_sets << " simultaneous block(s). \n";
   cout << "  the largest simultaneous block has " << j << " equation(s). \n";
+
   ModelBlock->Size = Nb_TotalBlocks;
   ModelBlock->Periods = periods;
   ModelBlock->Block_List = (Block*)malloc(sizeof(ModelBlock->Block_List[0]) * Nb_TotalBlocks);
-  blocks.block_result_to_IM(res, IM, *prologue, symbol_table.endo_nbr, Index_Equ_IM, Index_Var_IM);
+
   count_Equ = count_Block = 0;
-  if (*prologue)
-    Allocate_Block(*prologue, &count_Equ, &count_Block, PROLOGUE, ModelBlock);
-  for(j = 0;j < res->n_sets;j++)
+  for (t_type::const_iterator it = Type.begin(); it!=Type.end(); it++)
     {
-      if(res->sets_f[res->ordered[j]] == res->sets_s[res->ordered[j]])
-        Allocate_Block(res->sets_f[res->ordered[j]] - res->sets_s[res->ordered[j]] + 1, &count_Equ, &count_Block, PROLOGUE, ModelBlock);
+      if (count_Equ<*prologue)
+        Btype = PROLOGUE;
+      else if (count_Equ<n-*epilogue)
+        if (it->second==1)
+          Btype = PROLOGUE;
+        else
+          Btype = SIMULTANS;
       else
-        Allocate_Block(res->sets_f[res->ordered[j]] - res->sets_s[res->ordered[j]] + 1, &count_Equ, &count_Block, SIMULTANS, ModelBlock);
+        Btype = EPILOGUE;
+      Allocate_Block(it->second, &count_Equ, count_Block++, Btype, it->first, ModelBlock);
     }
-  if (*epilogue)
-    Allocate_Block(*epilogue, &count_Equ, &count_Block, EPILOGUE, ModelBlock);
-  if(res->n_sets)
+  //exit(-1);
+
+  if (res->n_sets)
     blocks.block_result_free(res);
   else
     free(res);
+
+
   return 0;
 }
 
@@ -960,7 +768,7 @@ BlockTriangular::Normalize_and_BlockDecompose(bool* IM, Model_Block* ModelBlock,
 // normalize each equation of the dynamic model
 // and find the optimal block triangular decomposition of the static model
 void
-BlockTriangular::Normalize_and_BlockDecompose_Static_0_Model(const jacob_map &j_m)
+BlockTriangular::Normalize_and_BlockDecompose_Static_0_Model(const jacob_map &j_m, vector<BinaryOpNode *> equations)
 {
   bool* SIM, *SIM_0;
   bool* Cur_IM;
@@ -968,41 +776,41 @@ BlockTriangular::Normalize_and_BlockDecompose_Static_0_Model(const jacob_map &j_
   //First create a static model incidence matrix
   size = symbol_table.endo_nbr * symbol_table.endo_nbr * sizeof(*SIM);
   SIM = (bool*)malloc(size);
-  for(i = 0; i< symbol_table.endo_nbr * symbol_table.endo_nbr; i++) SIM[i] = 0;
-  for(k = -incidencematrix.Model_Max_Lag_Endo; k<=incidencematrix.Model_Max_Lead_Endo; k++)
+  for (i = 0; i< symbol_table.endo_nbr * symbol_table.endo_nbr; i++) SIM[i] = 0;
+  for (k = -incidencematrix.Model_Max_Lag_Endo; k<=incidencematrix.Model_Max_Lead_Endo; k++)
     {
       Cur_IM = incidencematrix.Get_IM(k, eEndogenous);
-      if(Cur_IM)
+      if (Cur_IM)
         {
-          for(i = 0;i < symbol_table.endo_nbr*symbol_table.endo_nbr;i++)
+          for (i = 0;i < symbol_table.endo_nbr*symbol_table.endo_nbr;i++)
             {
               SIM[i] = (SIM[i]) || (Cur_IM[i]);
             }
         }
     }
-  if(bt_verbose)
+  if (bt_verbose)
     {
       cout << "incidence matrix for the static model (unsorted) \n";
       incidencematrix.Print_SIM(SIM, eEndogenous);
     }
   Index_Equ_IM = (simple*)malloc(symbol_table.endo_nbr * sizeof(*Index_Equ_IM));
-  for(i = 0;i < symbol_table.endo_nbr;i++)
+  for (i = 0;i < symbol_table.endo_nbr;i++)
     {
       Index_Equ_IM[i].index = i;
     }
   Index_Var_IM = (simple*)malloc(symbol_table.endo_nbr * sizeof(*Index_Var_IM));
-  for(i = 0;i < symbol_table.endo_nbr;i++)
+  for (i = 0;i < symbol_table.endo_nbr;i++)
     {
       Index_Var_IM[i].index = i;
     }
-  if(ModelBlock != NULL)
+  if (ModelBlock != NULL)
     Free_Block(ModelBlock);
   ModelBlock = (Model_Block*)malloc(sizeof(*ModelBlock));
   Cur_IM = incidencematrix.Get_IM(0, eEndogenous);
   SIM_0 = (bool*)malloc(symbol_table.endo_nbr * symbol_table.endo_nbr * sizeof(*SIM_0));
-  for(i = 0;i < symbol_table.endo_nbr*symbol_table.endo_nbr;i++)
+  for (i = 0;i < symbol_table.endo_nbr*symbol_table.endo_nbr;i++)
     SIM_0[i] = Cur_IM[i];
-  Normalize_and_BlockDecompose(SIM, ModelBlock, symbol_table.endo_nbr, &prologue, &epilogue, Index_Var_IM, Index_Equ_IM, 1, 1, SIM_0, j_m);
+  Normalize_and_BlockDecompose(SIM, ModelBlock, symbol_table.endo_nbr, &prologue, &epilogue, Index_Var_IM, Index_Equ_IM, 1, 1, SIM_0, j_m, equations);
   free(SIM_0);
   free(SIM);
 }
diff --git a/ExprNode.cc b/ExprNode.cc
index d16bba3b8a37ab7efa4ce1c9079ce8616d6dcdad..e9433b37a21c7a36f670fd5e57d186d4bdb8bc98 100644
--- a/ExprNode.cc
+++ b/ExprNode.cc
@@ -114,6 +114,15 @@ NumConstNode::computeDerivative(int varID)
   return datatree.Zero;
 }
 
+
+void
+NumConstNode::collectTemporary_terms(const temporary_terms_type &temporary_terms, Model_Block *ModelBlock, int Curr_Block) const
+{
+  temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<NumConstNode *>(this));
+  if (it != temporary_terms.end())
+    ModelBlock->Block_List[Curr_Block].Temporary_InUse->insert(idx);
+}
+
 void
 NumConstNode::writeOutput(ostream &output, ExprNodeOutputType output_type,
                           const temporary_terms_type &temporary_terms) const
@@ -246,6 +255,14 @@ VariableNode::computeDerivative(int varID)
   exit(EXIT_FAILURE);
 }
 
+void
+VariableNode::collectTemporary_terms(const temporary_terms_type &temporary_terms, Model_Block *ModelBlock, int Curr_Block) const
+{
+  temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<VariableNode *>(this));
+  if (it != temporary_terms.end())
+    ModelBlock->Block_List[Curr_Block].Temporary_InUse->insert(idx);
+}
+
 void
 VariableNode::writeOutput(ostream &output, ExprNodeOutputType output_type,
                           const temporary_terms_type &temporary_terms) const
@@ -279,7 +296,11 @@ VariableNode::writeOutput(ostream &output, ExprNodeOutputType output_type,
     case eModelLocalVariable:
     case eModFileLocalVariable:
       if(output_type==oMatlabDynamicModelSparse || output_type==oMatlabStaticModelSparse)
-        datatree.local_variables_table[symb_id]->writeOutput(output, output_type,temporary_terms);
+        {
+          output << "(";
+          datatree.local_variables_table[symb_id]->writeOutput(output, output_type,temporary_terms);
+          output << ")";
+        }
       else
         output << datatree.symbol_table.getNameByID(type, symb_id);
       break;
@@ -714,6 +735,16 @@ UnaryOpNode::computeTemporaryTerms(map<NodeID, int> &reference_count,
     }
 }
 
+void
+UnaryOpNode::collectTemporary_terms(const temporary_terms_type &temporary_terms, Model_Block *ModelBlock, int Curr_Block) const
+{
+  temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<UnaryOpNode*>(this));
+  if (it != temporary_terms.end())
+    ModelBlock->Block_List[Curr_Block].Temporary_InUse->insert(idx);
+  else
+    arg->collectTemporary_terms(temporary_terms, ModelBlock, Curr_Block);
+}
+
 void
 UnaryOpNode::writeOutput(ostream &output, ExprNodeOutputType output_type,
                          const temporary_terms_type &temporary_terms) const
@@ -1217,6 +1248,20 @@ BinaryOpNode::compile(ofstream &CompileCode, bool lhs_rhs, ExprNodeOutputType ou
   CompileCode.write(reinterpret_cast<char *>(&op_codel),sizeof(op_codel));
 }
 
+void
+BinaryOpNode::collectTemporary_terms(const temporary_terms_type &temporary_terms, Model_Block *ModelBlock, int Curr_Block) const
+{
+  temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<BinaryOpNode *>(this));
+  if (it != temporary_terms.end())
+    ModelBlock->Block_List[Curr_Block].Temporary_InUse->insert(idx);
+  else
+    {
+      arg1->collectTemporary_terms(temporary_terms, ModelBlock, Curr_Block);
+      arg2->collectTemporary_terms(temporary_terms, ModelBlock, Curr_Block);
+    }
+}
+
+
 void
 BinaryOpNode::writeOutput(ostream &output, ExprNodeOutputType output_type,
                           const temporary_terms_type &temporary_terms) const
@@ -1588,6 +1633,21 @@ TrinaryOpNode::compile(ofstream &CompileCode, bool lhs_rhs, ExprNodeOutputType o
   CompileCode.write(reinterpret_cast<char *>(&op_codel),sizeof(op_codel));
 }
 
+void
+TrinaryOpNode::collectTemporary_terms(const temporary_terms_type &temporary_terms, Model_Block *ModelBlock, int Curr_Block) const
+{
+  temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<TrinaryOpNode *>(this));
+  if (it != temporary_terms.end())
+    ModelBlock->Block_List[Curr_Block].Temporary_InUse->insert(idx);
+  else
+    {
+      arg1->collectTemporary_terms(temporary_terms, ModelBlock, Curr_Block);
+      arg2->collectTemporary_terms(temporary_terms, ModelBlock, Curr_Block);
+      arg3->collectTemporary_terms(temporary_terms, ModelBlock, Curr_Block);
+    }
+}
+
+
 void
 TrinaryOpNode::writeOutput(ostream &output, ExprNodeOutputType output_type,
                           const temporary_terms_type &temporary_terms) const
@@ -1708,6 +1768,18 @@ UnknownFunctionNode::collectExogenous(set<pair<int, int> > &result) const
     (*it)->collectExogenous(result);
 }
 
+void
+UnknownFunctionNode::collectTemporary_terms(const temporary_terms_type &temporary_terms, Model_Block *ModelBlock, int Curr_Block) const
+{
+  temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<UnknownFunctionNode *>(this));
+  if (it != temporary_terms.end())
+    ModelBlock->Block_List[Curr_Block].Temporary_InUse->insert(idx);
+  else
+    {
+      //arg->collectTemporary_terms(temporary_terms, result);
+    }
+}
+
 
 double
 UnknownFunctionNode::eval(const eval_context_type &eval_context) const throw (EvalException)
diff --git a/ModFile.cc b/ModFile.cc
index 9bef8e80eb739e7895b5ff3018dba93b0d3598b6..fa5cc04adc24372d6e56dde0364a7d1e9c83db41 100644
--- a/ModFile.cc
+++ b/ModFile.cc
@@ -90,26 +90,35 @@ ModFile::evalAllExpressions()
           cout << "error in evaluation of variable\n";
         }
     }
-  if(init_values.size()!=symbol_table.endo_nbr+symbol_table.exo_nbr+symbol_table.exo_det_nbr)
+  if(init_values.size()<symbol_table.endo_nbr+symbol_table.exo_nbr+symbol_table.exo_det_nbr)
     {
       cout << "\nWarning: Uninitialized variable: \n";
       cout << "Endogenous\n";
       for(j=0;j <symbol_table.endo_nbr; j++)
         {
           if(global_eval_context.find(make_pair(j, eEndogenous))==global_eval_context.end())
-            cout << " " << symbol_table.getNameByID(eEndogenous, j) << "\n";
+            {
+              cout << " " << symbol_table.getNameByID(eEndogenous, j) << "\n";
+              global_eval_context[make_pair(j, eEndogenous)] = 0;
+            }
         }
       cout << "Exogenous\n";
       for(j=0;j <symbol_table.exo_nbr; j++)
         {
           if(global_eval_context.find(make_pair(j, eExogenous))==global_eval_context.end())
-            cout << " " << symbol_table.getNameByID(eExogenous, j) << "\n";
+            {
+              cout << " " << symbol_table.getNameByID(eExogenous, j) << "\n";
+              global_eval_context[make_pair(j, eExogenous)]=0;
+            }
         }
       cout << "Deterministic exogenous\n";
       for(j=0;j <symbol_table.exo_det_nbr; j++)
         {
           if(global_eval_context.find(make_pair(j, eExogenousDet))==global_eval_context.end())
-            cout << " " << symbol_table.getNameByID(eExogenousDet, j) << "\n";
+            {
+              cout << " " << symbol_table.getNameByID(eExogenousDet, j) << "\n";
+              global_eval_context[make_pair(j, eExogenousDet)]=0;
+            }
         }
     }
   //Evaluate Local variables
@@ -307,7 +316,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all) const
         }
     }
 
-  cout << "Processing outputs ..." << endl;
+  cout << "Processing outputs ...";
 
   symbol_table.writeOutput(mOutputFile);
 
diff --git a/ModelTree.cc b/ModelTree.cc
index ecf89de5e82fc5fb9b20faf75cfecf65f8395bad..aa94d128784db762a4ad59dd3777fd7e47e4ff83 100644
--- a/ModelTree.cc
+++ b/ModelTree.cc
@@ -39,48 +39,48 @@
 
 ModelTree::ModelTree(SymbolTable &symbol_table_arg,
                      NumericalConstants &num_constants_arg) :
-  DataTree(symbol_table_arg, num_constants_arg),
-  mode(eStandardMode),
-  cutoff(1e-15),
-  markowitz(0.7),
-  new_SGE(true),
-  computeJacobian(false),
-  computeJacobianExo(false),
-  computeHessian(false),
-  computeStaticHessian(false),
-  computeThirdDerivatives(false),
-  block_triangular(symbol_table_arg)
+    DataTree(symbol_table_arg, num_constants_arg),
+    mode(eStandardMode),
+    cutoff(1e-15),
+    markowitz(0.7),
+    new_SGE(true),
+    computeJacobian(false),
+    computeJacobianExo(false),
+    computeHessian(false),
+    computeStaticHessian(false),
+    computeThirdDerivatives(false),
+    block_triangular(symbol_table_arg)
 {
 }
 
 int
 ModelTree::equation_number() const
-{
-  return(equations.size());
-}
+  {
+    return(equations.size());
+  }
 
 void
 ModelTree::writeDerivative(ostream &output, int eq, int symb_id, int lag,
                            ExprNodeOutputType output_type,
                            const temporary_terms_type &temporary_terms,
                            SymbolType type) const
-{
-  first_derivatives_type::const_iterator it = first_derivatives.find(make_pair(eq, variable_table.getID(type, symb_id, lag)));
-  if (it != first_derivatives.end())
-    (it->second)->writeOutput(output, output_type, temporary_terms);
-  else
-    output << 0;
-}
+  {
+    first_derivatives_type::const_iterator it = first_derivatives.find(make_pair(eq, variable_table.getID(type, symb_id, lag)));
+    if (it != first_derivatives.end())
+      (it->second)->writeOutput(output, output_type, temporary_terms);
+    else
+      output << 0;
+  }
 
 void
 ModelTree::compileDerivative(ofstream &code_file, int eq, int symb_id, int lag, ExprNodeOutputType output_type, map_idx_type map_idx) const
-{
-  first_derivatives_type::const_iterator it = first_derivatives.find(make_pair(eq, variable_table.getID(eEndogenous, symb_id, lag)));
-  if (it != first_derivatives.end())
-    (it->second)->compile(code_file,false, output_type, temporary_terms, map_idx);
-  else
-    code_file.write(&FLDZ, sizeof(FLDZ));
-}
+  {
+    first_derivatives_type::const_iterator it = first_derivatives.find(make_pair(eq, variable_table.getID(eEndogenous, symb_id, lag)));
+    if (it != first_derivatives.end())
+      (it->second)->compile(code_file,false, output_type, temporary_terms, map_idx);
+    else
+      code_file.write(&FLDZ, sizeof(FLDZ));
+  }
 
 
 void
@@ -89,8 +89,8 @@ ModelTree::derive(int order)
   cout << "Processing derivation ..." << endl;
 
   cout << "  Processing Order 1... ";
-  for(int var = 0; var < variable_table.size(); var++)
-    for(int eq = 0; eq < (int) equations.size(); eq++)
+  for (int var = 0; var < variable_table.size(); var++)
+    for (int eq = 0; eq < (int) equations.size(); eq++)
       {
         NodeID d1 = equations[eq]->getDerivative(var);
         if (d1 == Zero)
@@ -102,15 +102,15 @@ ModelTree::derive(int order)
   if (order >= 2)
     {
       cout << "  Processing Order 2... ";
-      for(first_derivatives_type::const_iterator it = first_derivatives.begin();
-          it != first_derivatives.end(); it++)
+      for (first_derivatives_type::const_iterator it = first_derivatives.begin();
+           it != first_derivatives.end(); it++)
         {
           int eq = it->first.first;
           int var1 = it->first.second;
           NodeID d1 = it->second;
 
           // Store only second derivatives with var2 <= var1
-          for(int var2 = 0; var2 <= var1; var2++)
+          for (int var2 = 0; var2 <= var1; var2++)
             {
               NodeID d2 = d1->getDerivative(var2);
               if (d2 == Zero)
@@ -124,8 +124,8 @@ ModelTree::derive(int order)
   if (order >= 3)
     {
       cout << "  Processing Order 3... ";
-      for(second_derivatives_type::const_iterator it = second_derivatives.begin();
-          it != second_derivatives.end(); it++)
+      for (second_derivatives_type::const_iterator it = second_derivatives.begin();
+           it != second_derivatives.end(); it++)
         {
           int eq = it->first.first;
 
@@ -136,7 +136,7 @@ ModelTree::derive(int order)
           NodeID d2 = it->second;
 
           // Store only third derivatives such that var3 <= var2 <= var1
-          for(int var3 = 0; var3 <= var2; var3++)
+          for (int var3 = 0; var3 <= var2; var3++)
             {
               NodeID d3 = d2->getDerivative(var3);
               if (d3 == Zero)
@@ -156,80 +156,80 @@ ModelTree::computeTemporaryTerms(int order)
 
   bool is_matlab = (mode != eDLLMode);
 
-  for(vector<BinaryOpNode *>::iterator it = equations.begin();
-      it != equations.end(); it++)
+  for (vector<BinaryOpNode *>::iterator it = equations.begin();
+       it != equations.end(); it++)
     (*it)->computeTemporaryTerms(reference_count, temporary_terms, is_matlab);
 
-  for(first_derivatives_type::iterator it = first_derivatives.begin();
-      it != first_derivatives.end(); it++)
+  for (first_derivatives_type::iterator it = first_derivatives.begin();
+       it != first_derivatives.end(); it++)
     it->second->computeTemporaryTerms(reference_count, temporary_terms, is_matlab);
 
   if (order >= 2)
-    for(second_derivatives_type::iterator it = second_derivatives.begin();
-        it != second_derivatives.end(); it++)
+    for (second_derivatives_type::iterator it = second_derivatives.begin();
+         it != second_derivatives.end(); it++)
       it->second->computeTemporaryTerms(reference_count, temporary_terms, is_matlab);
 
   if (order >= 3)
-    for(third_derivatives_type::iterator it = third_derivatives.begin();
-        it != third_derivatives.end(); it++)
+    for (third_derivatives_type::iterator it = third_derivatives.begin();
+         it != third_derivatives.end(); it++)
       it->second->computeTemporaryTerms(reference_count, temporary_terms, is_matlab);
 }
 
 void
 ModelTree::writeTemporaryTerms(ostream &output, ExprNodeOutputType output_type) const
-{
-  // A copy of temporary terms
-  temporary_terms_type tt2;
+  {
+    // A copy of temporary terms
+    temporary_terms_type tt2;
 
-  if (temporary_terms.size() > 0 && (!OFFSET(output_type)))
-    output << "double\n";
+    if (temporary_terms.size() > 0 && (!OFFSET(output_type)))
+      output << "double\n";
 
-  for(temporary_terms_type::const_iterator it = temporary_terms.begin();
-      it != temporary_terms.end(); it++)
-    {
-      if (!OFFSET(output_type) && it != temporary_terms.begin())
-        output << "," << endl;
+    for (temporary_terms_type::const_iterator it = temporary_terms.begin();
+         it != temporary_terms.end(); it++)
+      {
+        if (!OFFSET(output_type) && it != temporary_terms.begin())
+          output << "," << endl;
 
-      (*it)->writeOutput(output, output_type, temporary_terms);
-      output << " = ";
+        (*it)->writeOutput(output, output_type, temporary_terms);
+        output << " = ";
 
-      (*it)->writeOutput(output, output_type, tt2);
+        (*it)->writeOutput(output, output_type, tt2);
 
-      // Insert current node into tt2
-      tt2.insert(*it);
+        // Insert current node into tt2
+        tt2.insert(*it);
 
-      if (OFFSET(output_type))
-        output << ";" << endl;
-    }
-  if (!OFFSET(output_type))
-    output << ";" << endl;
-}
+        if (OFFSET(output_type))
+          output << ";" << endl;
+      }
+    if (!OFFSET(output_type))
+      output << ";" << endl;
+  }
 
 void
 ModelTree::writeModelLocalVariables(ostream &output, ExprNodeOutputType output_type) const
-{
-  for(map<int, NodeID>::const_iterator it = local_variables_table.begin();
-      it != local_variables_table.end(); it++)
-    {
-      int id = it->first;
-      NodeID value = it->second;
+  {
+    for (map<int, NodeID>::const_iterator it = local_variables_table.begin();
+         it != local_variables_table.end(); it++)
+      {
+        int id = it->first;
+        NodeID value = it->second;
 
-      if (!OFFSET(output_type))
-        output << "double ";
+        if (!OFFSET(output_type))
+          output << "double ";
 
-      output << symbol_table.getNameByID(eModelLocalVariable, id) << " = ";
-      // Use an empty set for the temporary terms
-      value->writeOutput(output, output_type, temporary_terms_type());
-      output << ";" << endl;
-    }
-}
+        output << symbol_table.getNameByID(eModelLocalVariable, id) << " = ";
+        // Use an empty set for the temporary terms
+        value->writeOutput(output, output_type, temporary_terms_type());
+        output << ";" << endl;
+      }
+  }
 
 
 void
 ModelTree::BuildIncidenceMatrix()
 {
   set<pair<int, int> > endogenous, exogenous;
-  for(int eq = 0; eq < (int) equations.size(); eq++)
+  for (int eq = 0; eq < (int) equations.size(); eq++)
     {
       BinaryOpNode *eq_node = equations[eq];
       endogenous.clear();
@@ -237,7 +237,7 @@ ModelTree::BuildIncidenceMatrix()
       Id->collectEndogenous(endogenous);
       Id = eq_node->arg2;
       Id->collectEndogenous(endogenous);
-      for(set<pair<int, int> >::iterator it_endogenous=endogenous.begin();it_endogenous!=endogenous.end();it_endogenous++)
+      for (set<pair<int, int> >::iterator it_endogenous=endogenous.begin();it_endogenous!=endogenous.end();it_endogenous++)
         {
           block_triangular.incidencematrix.fill_IM(eq, it_endogenous->first, it_endogenous->second, eEndogenous);
         }
@@ -246,7 +246,7 @@ ModelTree::BuildIncidenceMatrix()
       Id->collectExogenous(exogenous);
       Id = eq_node->arg2;
       Id->collectExogenous(exogenous);
-      for(set<pair<int, int> >::iterator it_exogenous=exogenous.begin();it_exogenous!=exogenous.end();it_exogenous++)
+      for (set<pair<int, int> >::iterator it_exogenous=exogenous.begin();it_exogenous!=exogenous.end();it_exogenous++)
         {
           block_triangular.incidencematrix.fill_IM(eq, it_exogenous->first, it_exogenous->second, eExogenous);
         }
@@ -255,24 +255,24 @@ ModelTree::BuildIncidenceMatrix()
 
 void
 ModelTree::writeModelEquations(ostream &output, ExprNodeOutputType output_type) const
-{
-  for(int eq = 0; eq < (int) equations.size(); eq++)
-    {
-      BinaryOpNode *eq_node = equations[eq];
+  {
+    for (int eq = 0; eq < (int) equations.size(); eq++)
+      {
+        BinaryOpNode *eq_node = equations[eq];
 
-      NodeID lhs = eq_node->arg1;
-      output << "lhs =";
-      lhs->writeOutput(output, output_type, temporary_terms);
-      output << ";" << endl;
+        NodeID lhs = eq_node->arg1;
+        output << "lhs =";
+        lhs->writeOutput(output, output_type, temporary_terms);
+        output << ";" << endl;
 
-      NodeID rhs = eq_node->arg2;
-      output << "rhs =";
-      rhs->writeOutput(output, output_type, temporary_terms);
-      output << ";" << endl;
+        NodeID rhs = eq_node->arg2;
+        output << "rhs =";
+        rhs->writeOutput(output, output_type, temporary_terms);
+        output << ";" << endl;
 
-      output << "residual" << LPAR(output_type) << eq + OFFSET(output_type) << RPAR(output_type) << "= lhs-rhs;" << endl;
-    }
-}
+        output << "residual" << LPAR(output_type) << eq + OFFSET(output_type) << RPAR(output_type) << "= lhs-rhs;" << endl;
+      }
+  }
 
 void
 ModelTree::computeTemporaryTermsOrdered(int order, Model_Block *ModelBlock)
@@ -282,878 +282,855 @@ ModelTree::computeTemporaryTermsOrdered(int order, Model_Block *ModelBlock)
   temporary_terms_type vect;
   ostringstream tmp_output;
   BinaryOpNode *eq_node;
-  NodeID lhs, rhs;
   first_derivatives_type::const_iterator it;
   ostringstream tmp_s;
 
   temporary_terms.clear();
   map_idx.clear();
-  for(j = 0;j < ModelBlock->Size;j++)
+  for (j = 0;j < ModelBlock->Size;j++)
     {
-      if (ModelBlock->Block_List[j].Size==1)
-        {
-          eq_node = equations[ModelBlock->Block_List[j].Equation[0]];
-          lhs = eq_node->arg1;
-          rhs = eq_node->arg2;
-          tmp_s.str("");
-          tmp_output.str("");
-          lhs->writeOutput(tmp_output, oCDynamicModelSparseDLL, temporary_terms);
-          tmp_s << "y[Per_y_+" << ModelBlock->Block_List[j].Variable[0] << "]";
-          //Determine whether the equation could be evaluated rather than to be solved
-          if (tmp_output.str()==tmp_s.str())
-            {
-              if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_BACKWARD_SIMPLE)
-                ModelBlock->Block_List[j].Simulation_Type=EVALUATE_BACKWARD;
-              else if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_FORWARD_SIMPLE)
-                ModelBlock->Block_List[j].Simulation_Type=EVALUATE_FORWARD;
-            }
-          else
-            {
-              tmp_output.str("");
-              rhs->writeOutput(tmp_output, oCDynamicModelSparseDLL, temporary_terms);
-              if (tmp_output.str()==tmp_s.str())
-                {
-                  if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_BACKWARD_SIMPLE)
-                    ModelBlock->Block_List[j].Simulation_Type=EVALUATE_BACKWARD_R;
-                  else if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_FORWARD_SIMPLE)
-                    ModelBlock->Block_List[j].Simulation_Type=EVALUATE_FORWARD_R;
-                }
-            }
-        }
       // Compute the temporary terms reordered
-      for(i = 0;i < ModelBlock->Block_List[j].Size;i++)
+      for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
         {
           eq_node = equations[ModelBlock->Block_List[j].Equation[i]];
           eq_node->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, j, ModelBlock, map_idx);
         }
-      if (ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_BACKWARD
-          && ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_FORWARD
-          &&ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_BACKWARD_R
-          && ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_FORWARD_R)
+      for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
         {
-          if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_COMPLETE ||
-              ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_SIMPLE)
-            {
-              for(m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
-                {
-                  lag=m-ModelBlock->Block_List[j].Max_Lag;
-                  for(i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
-                    {
-                      eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
-                      var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
-                      it=first_derivatives.find(make_pair(eq,variable_table.getID(eEndogenous, var,lag)));
-                      it->second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, j, ModelBlock, map_idx);
-                    }
-                }
-            }
-          else if (ModelBlock->Block_List[j].Simulation_Type!=SOLVE_BACKWARD_SIMPLE
-                   && ModelBlock->Block_List[j].Simulation_Type!=SOLVE_FORWARD_SIMPLE)
-            {
-              m=ModelBlock->Block_List[j].Max_Lag;
-              for(i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
-                {
-                  eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
-                  var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
-                  it=first_derivatives.find(make_pair(eq,variable_table.getID(eEndogenous,var,0)));
-                  it->second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, j, ModelBlock, map_idx);
-                }
-            }
-          else
+          lag=m-ModelBlock->Block_List[j].Max_Lag;
+          for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
             {
-              eq=ModelBlock->Block_List[j].Equation[0];
-              var=ModelBlock->Block_List[j].Variable[0];
-              it=first_derivatives.find(make_pair(eq,variable_table.getID(eEndogenous,var,0)));
+              eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
+              var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
+              it=first_derivatives.find(make_pair(eq,variable_table.getID(eEndogenous, var,lag)));
               it->second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, j, ModelBlock, map_idx);
             }
         }
-    }
-  if (order == 2)
-    for(second_derivatives_type::iterator it = second_derivatives.begin();
-        it != second_derivatives.end(); it++)
-      it->second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, 0, ModelBlock, map_idx);
-  // Add a mapping form node ID to temporary terms order
-  j=0;
-  for(temporary_terms_type::const_iterator it = temporary_terms.begin();
-       it != temporary_terms.end(); it++)
-    map_idx[(*it)->idx]=j++;
-}
-
-void
-ModelTree::writeModelEquationsOrdered_M( Model_Block *ModelBlock, const string &dynamic_basename) const
-{
-  int i,j,k,m;
-  string tmp_s, sps;
-  ostringstream tmp_output, tmp1_output, global_output;
-  NodeID lhs=NULL, rhs=NULL;
-  BinaryOpNode *eq_node;
-  bool OK, lhs_rhs_done, skip_the_head;
-  ostringstream Uf[symbol_table.endo_nbr];
-  map<NodeID, int> reference_count;
-  int prev_Simulation_Type=-1, count_derivates=0;
-  int jacobian_max_endo_col, jacobian_max_exo_col;
-  ofstream  output;
-  temporary_terms_type::const_iterator it_temp=temporary_terms.begin();
-  //----------------------------------------------------------------------
-  //Temporary variables declaration
-  OK=true;
-  for(temporary_terms_type::const_iterator it = temporary_terms.begin();
-      it != temporary_terms.end(); it++)
-    {
-      if (OK)
-        OK=false;
-      else
-        tmp_output << " ";
-
-      (*it)->writeOutput(tmp_output, oMatlabStaticModelSparse, temporary_terms);
-
-    }
-  if(tmp_output.str().length())
-    global_output << "  global " << tmp_output.str() << /*" M_ ;\n"�*/";\n";
-  //For each block
-  int gen_blocks=0;
-  for(j = 0;j < ModelBlock->Size;j++)
-    {
-      //For a block composed of a single equation determines wether we have to evaluate or to solve the equation
-      if (ModelBlock->Block_List[j].Size==1)
-        {
-          lhs_rhs_done=true;
-          eq_node = equations[ModelBlock->Block_List[j].Equation[0]];
-          lhs = eq_node->arg1;
-          rhs = eq_node->arg2;
-          tmp_output.str("");
-          lhs->writeOutput(tmp_output, oMatlabDynamicModelSparse, temporary_terms);
-        }
-      else
-        lhs_rhs_done=false;
-      if (BlockTriangular::BlockSim(prev_Simulation_Type)==BlockTriangular::BlockSim(ModelBlock->Block_List[j].Simulation_Type)
-          && (ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD
-              ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD
-              ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD_R
-              ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD_R ))
-        skip_the_head=true;
-      else
-        skip_the_head=false;
-      if (!skip_the_head)
-        {
-          count_derivates=0;
-          gen_blocks++;
-          if (j>0)
-            {
-              if(prev_Simulation_Type==EVALUATE_BACKWARD || prev_Simulation_Type==EVALUATE_BACKWARD_R ||
-                 prev_Simulation_Type==EVALUATE_FORWARD || prev_Simulation_Type==EVALUATE_FORWARD_R)
-                 output << "  end;\n";
-              output << "return;\n";
-              output.close();
-            }
-          tmp1_output.str("");
-          tmp1_output << dynamic_basename << "_" << j+1 << ".m";
-          output.open(tmp1_output.str().c_str(), ios::out | ios::binary);
-          output << "%\n";
-          output << "% " << tmp1_output.str() << " : Computes dynamic model for Dynare\n";
-          output << "%\n";
-          output << "% Warning : this file is generated automatically by Dynare\n";
-          output << "%           from model file (.mod)\n\n";
-          output << "%/\n";
-          /*else
-            output << "\n\n";*/
-          if (ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD
-              ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD
-              ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD_R
-              ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD_R)
-            output << "function [y, g1, g2, g3] = " << dynamic_basename << "_" << j+1 << "(y, x, params, jacobian_eval, g1, g2, g3, y_kmin, periods)\n";
-          else if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_FORWARD_COMPLETE
-              ||   ModelBlock->Block_List[j].Simulation_Type==SOLVE_BACKWARD_COMPLETE)
-            output << "function [residual, g1, g2, g3, b] = " << dynamic_basename << "_" << j+1 << "(y, x, params, it_, jacobian_eval, g1, g2, g3)\n";
-          else if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_BACKWARD_SIMPLE
-              ||   ModelBlock->Block_List[j].Simulation_Type==SOLVE_FORWARD_SIMPLE)
-            output << "function [residual, g1, g2, g3, b] = " << dynamic_basename << "_" << j+1 << "(y, x, params, it_, jacobian_eval, g1, g2, g3)\n";
-          else
-            output << "function [residual, g1, g2, g3, b] = " << dynamic_basename << "_" << j+1 << "(y, x, params, periods, jacobian_eval, g1, g2, g3, y_kmin, y_size)\n";
-          output << "  % ////////////////////////////////////////////////////////////////////////" << endl
-                 << "  % //" << string("                     Block ").substr(int(log10(j + 1))) << j + 1 << " " << BlockTriangular::BlockType0(ModelBlock->Block_List[j].Type)
-                 << "          //" << endl
-                 << "  % //                     Simulation type "
-                 << BlockTriangular::BlockSim(ModelBlock->Block_List[j].Simulation_Type) << "  //" << endl
-                 << "  % ////////////////////////////////////////////////////////////////////////" << endl;
-          //The Temporary terms
-          output << global_output.str();
-          output << "  residual=zeros(" << ModelBlock->Block_List[j].Size << ",1);\n";
-          if (ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD
-              ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD
-              ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD_R
-              ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD_R)
-            output << "  for it_ = y_kmin+1:(y_kmin+periods)\n";
-          /*output << "  if M_.param_nbr > 0\n";
-          output << "    params =  M_.params;\n";
-          output << "  end\n";*/
-        }
-
-
-      temporary_terms_type tt2;
-      if(ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_COMPLETE || ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_SIMPLE)
-        {
-          int nze;
-          for(nze=0,m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
-            nze+=ModelBlock->Block_List[j].IM_lead_lag[m].size;
-          output << "  g2=0;g3=0;\n";
-          output << "  b = [];\n";
-          output << "  for it_ = y_kmin+1:(periods+y_kmin)\n";
-          output << "    Per_y_=it_*y_size;\n";
-          output << "    Per_J_=(it_-y_kmin-1)*y_size;\n";
-          output << "    Per_K_=(it_-1)*y_size;\n";
-          sps="  ";
-        }
-      else
-        sps="";
-      if (ModelBlock->Block_List[j].Temporary_terms->size())
-        output << "  " << sps << "% //Temporary variables" << endl;
-      i=0;
-      for(temporary_terms_type::const_iterator it = ModelBlock->Block_List[j].Temporary_terms->begin();
-          it != ModelBlock->Block_List[j].Temporary_terms->end(); it++)
-        {
-          output << "  " <<  sps;
-          (*it)->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
-          output << " = ";
-          (*it)->writeOutput(output, oMatlabDynamicModelSparse, tt2);
-          // Insert current node into tt2
-          tt2.insert(*it);
-          output << ";" << endl;
-          i++;
-        }
-      // The equations
-      for(i = 0;i < ModelBlock->Block_List[j].Size;i++)
+      for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
         {
-          string sModel = symbol_table.getNameByID(eEndogenous, ModelBlock->Block_List[j].Variable[i]) ;
-          output << sps << "  % equation " << ModelBlock->Block_List[j].Equation[i]+1 << " variable : " << sModel
-                 << " (" << ModelBlock->Block_List[j].Variable[i]+1 << ")" << endl;
-          if (!lhs_rhs_done)
-            {
-              eq_node = equations[ModelBlock->Block_List[j].Equation[i]];
-              lhs = eq_node->arg1;
-              rhs = eq_node->arg2;
-              tmp_output.str("");
-              lhs->writeOutput(tmp_output, oMatlabDynamicModelSparse, temporary_terms);
-            }
-          output << "  ";
-          switch(ModelBlock->Block_List[j].Simulation_Type)
+          lag=m-ModelBlock->Block_List[j].Max_Lag;
+          for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_exo;i++)
             {
-            case EVALUATE_BACKWARD:
-            case EVALUATE_FORWARD:
-              output << tmp_output.str();
-              output << " = ";
-              rhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
-              output << ";\n";
-              break;
-            case EVALUATE_BACKWARD_R:
-            case EVALUATE_FORWARD_R:
-              rhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
-              output << " = ";
-              lhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
-              output << ";\n";
-              break;
-            case SOLVE_BACKWARD_SIMPLE:
-            case SOLVE_FORWARD_SIMPLE:
-              /*output << sps << "residual(" << i+1 << ") = (";
-              goto end;*/
-            case SOLVE_BACKWARD_COMPLETE:
-            case SOLVE_FORWARD_COMPLETE:
-              Uf[ModelBlock->Block_List[j].Equation[i]] << "    b(" << i+1 << ") = residual(" << i+1 << ")";
-              output << sps << "residual(" << i+1 << ") = (";
-              goto end;
-            case SOLVE_TWO_BOUNDARIES_COMPLETE:
-            case SOLVE_TWO_BOUNDARIES_SIMPLE:
-              Uf[ModelBlock->Block_List[j].Equation[i]] << "    b(" << i+1 << "+Per_J_) = -residual(" << i+1 << ", it_)";
-              output << sps << "residual(" << i+1 << ", it_) = (";
-              goto end;
-            default:
-            end:
-              output << tmp_output.str();
-              output << ") - (";
-              rhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
-              output << ");\n";
-#ifdef CONDITION
-              if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_COMPLETE || ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_SIMPLE)
-                output << "  condition(" << i+1 << ")=0;\n";
-#endif
+              eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_X_Index[i];
+              var=ModelBlock->Block_List[j].IM_lead_lag[m].Exogenous_Index[i];
+              it=first_derivatives.find(make_pair(eq,variable_table.getID(eExogenous, var,lag)));
+              it->second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, j, ModelBlock, map_idx);
             }
         }
-      // The Jacobian if we have to solve the block
-      if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_SIMPLE
-          ||  ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_COMPLETE)
-          output << "  " << sps << "% Jacobian  " << endl;
-      else
-          output << "  " << sps << "% Jacobian  " << endl << "  if jacobian_eval" << endl;
-      switch(ModelBlock->Block_List[j].Simulation_Type)
+      //jacobian_max_exo_col=(variable_table.max_exo_lag+variable_table.max_exo_lead+1)*symbol_table.exo_nbr;
+      for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
         {
-        case EVALUATE_BACKWARD:
-        case EVALUATE_FORWARD:
-        case EVALUATE_BACKWARD_R:
-        case EVALUATE_FORWARD_R:
-          count_derivates++;
-          for(m=0;m<ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag+1;m++)
-            {
-              k=m-ModelBlock->Block_List[j].Max_Lag;
-              for(i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
-                {
-                  if(ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i]==ModelBlock->Block_List[j].Variable[0])
-                    {
-                      output << "    g1(" << ModelBlock->Block_List[j].Equation[0]+1 << ", "
-                                          << ModelBlock->Block_List[j].Variable[0]+1
-                                          + (m+variable_table.max_endo_lag-ModelBlock->Block_List[j].Max_Lag)*symbol_table.endo_nbr
-                                          << ")=";
-                      writeDerivative(output, ModelBlock->Block_List[j].Equation[0], ModelBlock->Block_List[j].Variable[0], k, oMatlabDynamicModelSparse, temporary_terms, eEndogenous);
-                      output << "; % variable=" << symbol_table.getNameByID(eEndogenous, ModelBlock->Block_List[j].Variable[0])
-                             << "(" << k//variable_table.getLag(variable_table.getSymbolID(ModelBlock->Block_List[j].Variable[0]))
-                             << ") " << ModelBlock->Block_List[j].Variable[0]+1
-                             << ", equation=" << ModelBlock->Block_List[j].Equation[0]+1 << endl;
-                    }
-                }
-            }
-          jacobian_max_endo_col=(variable_table.max_endo_lag+variable_table.max_endo_lead+1)*symbol_table.endo_nbr;
-          for(m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
-            {
-              k=m-ModelBlock->Block_List[j].Max_Lag;
-              for(i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_exo;i++)
-                {
-                  int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_X_Index[i];
-                  int var=ModelBlock->Block_List[j].IM_lead_lag[m].Exogenous_Index[i];
-                  output << "    g1(" << eq+1 << ", "
-                                      << jacobian_max_endo_col+var+1+(m+variable_table.max_exo_lag-ModelBlock->Block_List[j].Max_Lag)*symbol_table.exo_nbr << ") = ";
-                  writeDerivative(output, eq, var, k, oMatlabDynamicModelSparse, temporary_terms, eExogenous);
-                  output << "; % variable=" << symbol_table.getNameByID(eExogenous, var)
-                         << "(" << k << ") " << var+1
-                         << ", equation=" << eq+1 << endl;
-                }
-            }
-          jacobian_max_exo_col=(variable_table.max_exo_lag+variable_table.max_exo_lead+1)*symbol_table.exo_nbr;
-          for(m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
-            {
-              k=m-ModelBlock->Block_List[j].Max_Lag;
-              if(block_triangular.incidencematrix.Model_Max_Lag_Endo - ModelBlock->Block_List[j].Max_Lag +m >=0)
-                {
-                  for(i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_other_endo;i++)
-                    {
-                      int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index_other_endo[i];
-                      int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index_other_endo[i];
-                      output << "    g1(" << eq+1 << ", "
-                                          << jacobian_max_endo_col+jacobian_max_exo_col+var+1+(m+variable_table.max_endo_lag-ModelBlock->Block_List[j].Max_Lag)*symbol_table.endo_nbr << ") = ";
-                      writeDerivative(output, eq, var, k, oMatlabDynamicModelSparse, temporary_terms, eEndogenous);
-                      output << "; % variable=" << symbol_table.getNameByID(eEndogenous, var)
-                             << "(" << k << ") " << var+1
-                             << ", equation=" << eq+1 << endl;
-                    }
-                }
-            }
-          if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_BACKWARD_SIMPLE
-          || ModelBlock->Block_List[j].Simulation_Type==SOLVE_FORWARD_SIMPLE)
-            {
-              output << "  else\n";
-              output << "    g1=";
-              writeDerivative(output, ModelBlock->Block_List[j].Equation[0], ModelBlock->Block_List[j].Variable[0], 0, oMatlabDynamicModelSparse, temporary_terms, eEndogenous);
-              output << "; % variable=" << symbol_table.getNameByID(eEndogenous, ModelBlock->Block_List[j].Variable[0])
-                     << "(" << variable_table.getLag(variable_table.getSymbolID(ModelBlock->Block_List[j].Variable[0]))
-                     << ") " << ModelBlock->Block_List[j].Variable[0]+1
-                     << ", equation=" << ModelBlock->Block_List[j].Equation[0]+1 << endl;
-            }
-          if (ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD
-          || ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD
-          || ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD_R
-          || ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD_R
-          || ModelBlock->Block_List[j].Simulation_Type==SOLVE_BACKWARD_SIMPLE
-          || ModelBlock->Block_List[j].Simulation_Type==SOLVE_FORWARD_SIMPLE)
-            output << "  end;" << endl;
-          break;
-        case SOLVE_BACKWARD_SIMPLE:
-        case SOLVE_FORWARD_SIMPLE:
-        case SOLVE_BACKWARD_COMPLETE:
-        case SOLVE_FORWARD_COMPLETE:
-          count_derivates++;
-          output << "    b = [];\n";
-          for(m=0;m<ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag+1;m++)
-            {
-              k=m-ModelBlock->Block_List[j].Max_Lag;
-              for(i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
-                {
-                  int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
-                  int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
-                  output << "    g1(" << eq+1 << ", " << var+1+(m+variable_table.max_lag-ModelBlock->Block_List[j].Max_Lag)*symbol_table.endo_nbr << ") = ";
-                  writeDerivative(output, eq, var, k, oMatlabDynamicModelSparse, temporary_terms, eEndogenous);
-                  output << "; % variable=" << symbol_table.getNameByID(eEndogenous, var)
-                         << "(" << k
-                         << ") " << var+1
-                         << ", equation=" << eq+1 << endl;
-                }
-            }
-          jacobian_max_endo_col=(variable_table.max_endo_lag+variable_table.max_endo_lead+1)*symbol_table.endo_nbr;
-          for(m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
-            {
-              k=m-ModelBlock->Block_List[j].Max_Lag;
-              for(i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_exo;i++)
-                {
-                  int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_X_Index[i];
-                  int var=ModelBlock->Block_List[j].IM_lead_lag[m].Exogenous_Index[i];
-                  output << "    g1(" << eq+1 << ", " << jacobian_max_endo_col+var+1+(m+variable_table.max_exo_lag-ModelBlock->Block_List[j].Max_Lag)*ModelBlock->Block_List[j].nb_exo << ") = ";
-                  writeDerivative(output, eq, var, k, oMatlabDynamicModelSparse, temporary_terms, eExogenous);
-                  output << "; % variable=" << symbol_table.getNameByID(eExogenous, var)
-                         << "(" << k << ") " << var+1
-                         << ", equation=" << eq+1 << endl;
-                }
-            }
-          output << "  else" << endl;
-
-          m=ModelBlock->Block_List[j].Max_Lag;
-          for(i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
-            {
-              int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
-              int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
-              int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
-              int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Var[i];
-              Uf[ModelBlock->Block_List[j].Equation[eqr]] << "+g1(" << eqr+1 << ", " << varr+1 << ")*y(it_, " << var+1 << ")";
-              output << "    g1(" << eqr+1 << ", " << varr+1 << ") = ";
-              writeDerivative(output, eq, var, 0, oMatlabDynamicModelSparse, temporary_terms, eEndogenous);
-              output << "; % variable=" << symbol_table.getNameByID(eEndogenous, var)
-                     << "(" << variable_table.getLag(variable_table.getSymbolID(var)) << ") " << var+1
-                     << ", equation=" << eq+1 << endl;
-            }
-          for(i = 0;i < ModelBlock->Block_List[j].Size;i++)
-            output << Uf[ModelBlock->Block_List[j].Equation[i]].str() << ";\n";
-          output << "  end;\n";
-          break;
-        case SOLVE_TWO_BOUNDARIES_SIMPLE:
-        case SOLVE_TWO_BOUNDARIES_COMPLETE:
-          output << "    if ~jacobian_eval" << endl;
-          for(m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
-            {
-              k=m-ModelBlock->Block_List[j].Max_Lag;
-              for(i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
-                {
-                  int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
-                  int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
-                  int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
-                  int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Var[i];
-                  if (k==0)
-                    Uf[ModelBlock->Block_List[j].Equation[eqr]] << "+g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+Per_K_)*y(it_, " << var+1 << ")";
-                  else if (k==1)
-                    Uf[ModelBlock->Block_List[j].Equation[eqr]] << "+g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+Per_y_)*y(it_+1, " << var+1 << ")";
-                  else if (k>0)
-                    Uf[ModelBlock->Block_List[j].Equation[eqr]] << "+g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+y_size*(it_+" << k-1 << "))*y(it_+" << k << ", " << var+1 << ")";
-                  else if (k<0)
-                    Uf[ModelBlock->Block_List[j].Equation[eqr]] << "+g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+y_size*(it_" << k-1 << "))*y(it_" << k << ", " << var+1 << ")";
-                  if(k==0)
-                    output << "      g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+Per_K_) = ";
-                  else if(k==1)
-                    output << "      g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+Per_y_) = ";
-                  else if(k>0)
-                    output << "      g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+y_size*(it_+" << k-1 << ")) = ";
-                  else if(k<0)
-                    output << "      g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+y_size*(it_" << k-1 << ")) = ";
-                  writeDerivative(output, eq, var, k, oMatlabDynamicModelSparse, temporary_terms, eEndogenous);
-                  output << "; % variable=" << symbol_table.getNameByID(eEndogenous, var)
-                         << "(" << k << ") " << var+1
-                         << ", equation=" << eq+1 << endl;
-#ifdef CONDITION
-                  output << "  if (fabs(condition[" << eqr << "])<fabs(u[" << u << "+Per_u_]))\n";
-                  output << "    condition(" << eqr << ")=u(" << u << "+Per_u_);\n";
-#endif
-                }
-            }
-          for(i = 0;i < ModelBlock->Block_List[j].Size;i++)
-            {
-              output << "  " << Uf[ModelBlock->Block_List[j].Equation[i]].str() << ";\n";
-#ifdef CONDITION
-              output << "  if (fabs(condition(" << i+1 << "))<fabs(u(" << i << "+Per_u_)))\n";
-              output << "    condition(" << i+1 << ")=u(" << i+1 << "+Per_u_);\n";
-#endif
-            }
-#ifdef CONDITION
-          for(m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
-            {
-              k=m-ModelBlock->Block_List[j].Max_Lag;
-              for(i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
-                {
-                  int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
-                  int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
-                  int u=ModelBlock->Block_List[j].IM_lead_lag[m].u[i];
-                  int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
-                  output << "  u(" << u+1 << "+Per_u_) = u(" << u+1 << "+Per_u_) / condition(" << eqr+1 << ");\n";
-                }
-            }
-          for(i = 0;i < ModelBlock->Block_List[j].Size;i++)
-            output << "  u(" << i+1 << "+Per_u_) = u(" << i+1 << "+Per_u_) / condition(" << i+1 << ");\n";
-#endif
-
-          output << "    else" << endl;
-          for(m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
-            {
-              k=m-ModelBlock->Block_List[j].Max_Lag;
-              for(i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
-                {
-                  int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
-                  int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
-                  int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
-                  int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Var[i];
-                  output << "      g1(" << eqr+1 << ", " << varr+1+(m-ModelBlock->Block_List[j].Max_Lag+ModelBlock->Block_List[j].Max_Lag_Endo)*ModelBlock->Block_List[j].Size << ") = ";
-                  writeDerivative(output, eq, var, k, oMatlabDynamicModelSparse, temporary_terms, eEndogenous);
-                  output << "; % variable=" << symbol_table.getNameByID(eEndogenous, var)
-                         << "(" << k << ") " << var+1
-                         << ", equation=" << eq+1 << endl;
-                }
-            }
-          jacobian_max_endo_col=(ModelBlock->Block_List[j].Max_Lead_Endo+ModelBlock->Block_List[j].Max_Lag_Endo+1)*ModelBlock->Block_List[j].Size;
-          for(m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
+          lag=m-ModelBlock->Block_List[j].Max_Lag;
+          if (block_triangular.incidencematrix.Model_Max_Lag_Endo - ModelBlock->Block_List[j].Max_Lag +m >=0)
             {
-              k=m-ModelBlock->Block_List[j].Max_Lag;
-              for(i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_exo;i++)
+              for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_other_endo;i++)
                 {
-                  int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_X_Index[i];
-                  int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_X[i];
-                  int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Exogenous[i];
-                  int var=ModelBlock->Block_List[j].IM_lead_lag[m].Exogenous_Index[i];
-                  output << "      g1(" << eqr+1 << ", "
-                  << jacobian_max_endo_col+(m-(ModelBlock->Block_List[j].Max_Lag-ModelBlock->Block_List[j].Max_Lag_Exo))*ModelBlock->Block_List[j].nb_exo+varr+1 << ") = ";
-                  writeDerivative(output, eq, var, k, oMatlabDynamicModelSparse, temporary_terms, eExogenous);
-                  output << "; % variable (exogenous)=" << symbol_table.getNameByID(eExogenous, var)
-                         << "(" << k << ") " << var+1 << " " << varr+1
-                         << ", equation=" << eq+1 << endl;
+                  eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index_other_endo[i];
+                  var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index_other_endo[i];
+                  it=first_derivatives.find(make_pair(eq,variable_table.getID(eEndogenous, var,lag)));
+                  it->second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, j, ModelBlock, map_idx);
                 }
             }
-          output << "    end;\n";
-          output << "  end;\n";
-          break;
-        default:
-          break;
         }
-      prev_Simulation_Type=ModelBlock->Block_List[j].Simulation_Type;
-    }
-  if(prev_Simulation_Type==EVALUATE_BACKWARD || prev_Simulation_Type==EVALUATE_BACKWARD_R ||
-     prev_Simulation_Type==EVALUATE_FORWARD || prev_Simulation_Type==EVALUATE_FORWARD_R)
-     output << "  end;\n";
-  output << "return;\n";
-  output.close();
-}
-
-void
-ModelTree::writeModelStaticEquationsOrdered_M(Model_Block *ModelBlock, const string &static_basename) const
-{
-  int i,j,k,m, var, eq, g1_index = 1;
-  string tmp_s, sps;
-  ostringstream tmp_output, tmp1_output, global_output;
-  NodeID lhs=NULL, rhs=NULL;
-  BinaryOpNode *eq_node;
-  bool OK, lhs_rhs_done, skip_the_head;
-  ostringstream Uf[symbol_table.endo_nbr];
-  map<NodeID, int> reference_count;
-  int prev_Simulation_Type=-1;
-  int nze=0;
-  bool *IM, *IMl;
-  ofstream  output;
-  temporary_terms_type::const_iterator it_temp=temporary_terms.begin();
-  //----------------------------------------------------------------------
-  //Temporary variables declaration
-  OK=true;
-  for(temporary_terms_type::const_iterator it = temporary_terms.begin();
-      it != temporary_terms.end(); it++)
-    {
-      if (OK)
-        OK=false;
-      else
-        tmp_output << " ";
-      (*it)->writeOutput(tmp_output, oMatlabStaticModelSparse, temporary_terms);
     }
-  if(tmp_output.str().length())
-    global_output << "  global " << tmp_output.str() << /*" M_ ;\n"*/ ";\n";
-  //For each block
-  for(j = 0;j < ModelBlock->Size;j++)
+  for (j = 0;j < ModelBlock->Size;j++)
     {
-      //For a block composed of a single equation determines wether we have to evaluate or to solve the equation
-      if (ModelBlock->Block_List[j].Size==1)
-        {
-          lhs_rhs_done=true;
-          eq_node = equations[ModelBlock->Block_List[j].Equation[0]];
-          lhs = eq_node->arg1;
-          rhs = eq_node->arg2;
-          tmp_output.str("");
-          lhs->writeOutput(tmp_output, oMatlabStaticModelSparse, temporary_terms);
-        }
-      else
-        lhs_rhs_done=false;
-      if (BlockTriangular::BlockSim(prev_Simulation_Type)==BlockTriangular::BlockSim(ModelBlock->Block_List[j].Simulation_Type)
-          && (ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD
-              ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD
-              ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD_R
-              ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD_R ))
-        {
-          skip_the_head=true;
-          g1_index++;
-        }
-      else
-        {
-          skip_the_head=false;
-          g1_index = 1;
-        }
-      if (!skip_the_head)
+      // Compute the temporary terms reordered
+      for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
         {
-
-          if (j>0)
-            {
-              output << "return;\n";
-              output.close();
-            }
-          tmp1_output.str("");
-          tmp1_output << static_basename << "_" << j+1 << ".m";
-          output.open(tmp1_output.str().c_str(), ios::out | ios::binary);
-          output << "%\n";
-          output << "% " << tmp1_output.str() << " : Computes static model for Dynare\n";
-          output << "%\n";
-          output << "% Warning : this file is generated automatically by Dynare\n";
-          output << "%           from model file (.mod)\n\n";
-          output << "%/\n";
-
-          /*if (j>0)
-            {
-              output << "return;\n\n\n";
-            }
-          else
-            output << "\n\n";*/
-          if(ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD
-           ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD
-           ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD_R
-           ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD_R )
-            output << "function [y, g1] = " << static_basename << "_" << j+1 << "(y, x, params, jacobian_eval)\n";
-          else
-            output << "function [residual, g1, g2, g3, b] = " << static_basename << "_" << j+1 << "(y, x, params, jacobian_eval)\n";
-          output << "  % ////////////////////////////////////////////////////////////////////////" << endl
-                 << "  % //" << string("                     Block ").substr(int(log10(j + 1))) << j + 1 << " "
-                 << BlockTriangular::BlockType0(ModelBlock->Block_List[j].Type) << "          //" << endl
-                 << "  % //                     Simulation type ";
-          output << BlockTriangular::BlockSim(ModelBlock->Block_List[j].Simulation_Type) << "  //" << endl
-                 << "  % ////////////////////////////////////////////////////////////////////////" << endl;
-          //The Temporary terms
-          output << global_output.str();
-          /*output << "  if M_.param_nbr > 0\n";
-          output << "    params =  M_.params;\n";
-          output << "  end\n";*/
+          eq_node = equations[ModelBlock->Block_List[j].Equation[i]];
+          eq_node->collectTemporary_terms(temporary_terms, ModelBlock, j);
         }
-
-      temporary_terms_type tt2;
-
-      int n=ModelBlock->Block_List[j].Size;
-      int n1=symbol_table.endo_nbr;
-      IM=(bool*)malloc(n*n*sizeof(bool));
-      memset(IM, 0, n*n*sizeof(bool));
-      for(m=-ModelBlock->Block_List[j].Max_Lag;m<=ModelBlock->Block_List[j].Max_Lead;m++)
+      for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
         {
-          IMl=block_triangular.incidencematrix.Get_IM(m, eEndogenous);
-          if(IMl)
+          lag=m-ModelBlock->Block_List[j].Max_Lag;
+          for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
             {
-              for(i=0;i<n;i++)
-                {
-                  eq=ModelBlock->Block_List[j].Equation[i];
-                  for(k=0;k<n;k++)
-                    {
-                      var=ModelBlock->Block_List[j].Variable[k];
-                      IM[i*n+k]=IM[i*n+k] || IMl[eq*n1+var];
-                    }
-                }
+              eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
+              var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
+              it=first_derivatives.find(make_pair(eq,variable_table.getID(eEndogenous, var,lag)));
+              it->second->collectTemporary_terms(temporary_terms, ModelBlock, j);
             }
         }
-      for(nze=0, i=0;i<n*n;i++)
-        {
-          nze+=IM[i];
-        }
-      memset(IM, 0, n*n*sizeof(bool));
-      if( ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_BACKWARD && ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_FORWARD
-       && ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_BACKWARD_R && ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_FORWARD_R)
-         {
-          output << "  g1=spalloc(" << ModelBlock->Block_List[j].Size << ", " << ModelBlock->Block_List[j].Size << ", " << nze << ");\n";
-          output << "  residual=zeros(" << ModelBlock->Block_List[j].Size << ",1);\n";
-         }
-      sps="";
-      if (ModelBlock->Block_List[j].Temporary_terms->size())
-        output << "  " << sps << "% //Temporary variables" << endl;
-      i=0;
-      for(temporary_terms_type::const_iterator it = ModelBlock->Block_List[j].Temporary_terms->begin();
-          it != ModelBlock->Block_List[j].Temporary_terms->end(); it++)
-        {
-          output << "  " <<  sps;
-          (*it)->writeOutput(output, oMatlabStaticModelSparse, temporary_terms);
-          output << " = ";
-          (*it)->writeOutput(output, oMatlabStaticModelSparse, tt2);
-          // Insert current node into tt2
-          tt2.insert(*it);
-          output << ";" << endl;
-          i++;
-        }
-      // The equations
-      for(i = 0;i < ModelBlock->Block_List[j].Size;i++)
+      for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
         {
-          //ModelBlock->Block_List[j].Variable_Sorted[i] = variable_table.getID(eEndogenous, ModelBlock->Block_List[j].Variable[i], 0);
-          string sModel = symbol_table.getNameByID(eEndogenous, ModelBlock->Block_List[j].Variable[i]) ;
-          output << sps << "  % equation " << ModelBlock->Block_List[j].Equation[i]+1 << " variable : "
-                 << sModel << " (" << ModelBlock->Block_List[j].Variable[i]+1 << ")" << endl;
-          if (!lhs_rhs_done)
+          lag=m-ModelBlock->Block_List[j].Max_Lag;
+          for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_exo;i++)
             {
-              eq_node = equations[ModelBlock->Block_List[j].Equation[i]];
-              lhs = eq_node->arg1;
-              rhs = eq_node->arg2;
-              tmp_output.str("");
-              lhs->writeOutput(tmp_output, oMatlabStaticModelSparse, temporary_terms);
-            }
-          output << "  ";
-          switch(ModelBlock->Block_List[j].Simulation_Type)
-            {
-            case EVALUATE_BACKWARD:
-            case EVALUATE_FORWARD:
-              output << tmp_output.str();
-              output << " = ";
-              rhs->writeOutput(output, oMatlabStaticModelSparse, temporary_terms);
-              output << ";\n";
-              break;
-            case EVALUATE_BACKWARD_R:
-            case EVALUATE_FORWARD_R:
-              rhs->writeOutput(output, oMatlabStaticModelSparse, temporary_terms);
-              output << " = ";
-              lhs->writeOutput(output, oMatlabStaticModelSparse, temporary_terms);
-              output << ";\n";
-              break;
-            case SOLVE_BACKWARD_SIMPLE:
-            case SOLVE_FORWARD_SIMPLE:
-            case SOLVE_BACKWARD_COMPLETE:
-            case SOLVE_FORWARD_COMPLETE:
-            case SOLVE_TWO_BOUNDARIES_COMPLETE:
-            case SOLVE_TWO_BOUNDARIES_SIMPLE:
-              Uf[ModelBlock->Block_List[j].Equation[i]] << "b(" << i+1 << ") =  residual(" << i+1 << ")";
-              goto end;
-            default:
-            end:
-              output << sps << "residual(" << i+1 << ") = (";
-              output << tmp_output.str();
-              output << ") - (";
-              rhs->writeOutput(output, oMatlabStaticModelSparse, temporary_terms);
-              output << ");\n";
-#ifdef CONDITION
-              if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_COMPLETE || ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_SIMPLE)
-                output << "  condition(" << i+1 << ")=0;\n";
-#endif
+              eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_X_Index[i];
+              var=ModelBlock->Block_List[j].IM_lead_lag[m].Exogenous_Index[i];
+              it=first_derivatives.find(make_pair(eq,variable_table.getID(eExogenous, var,lag)));
+              it->second->collectTemporary_terms(temporary_terms, ModelBlock, j);
             }
         }
-      // The Jacobian if we have to solve the block
-      output << "  " << sps << "% Jacobian  " << endl;
-      switch(ModelBlock->Block_List[j].Simulation_Type)
+      //jacobian_max_exo_col=(variable_table.max_exo_lag+variable_table.max_exo_lead+1)*symbol_table.exo_nbr;
+      for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
         {
-        case EVALUATE_BACKWARD:
-        case EVALUATE_FORWARD:
-        case EVALUATE_BACKWARD_R:
-        case EVALUATE_FORWARD_R:
-          output << "  if(jacobian_eval)\n";
-          output << "    g1( " << g1_index << ", " << g1_index << ")=";
-          writeDerivative(output, ModelBlock->Block_List[j].Equation[0], ModelBlock->Block_List[j].Variable[0], 0, oMatlabStaticModelSparse, temporary_terms, eEndogenous);
-          output << "; % variable=" << symbol_table.getNameByID(eEndogenous, ModelBlock->Block_List[j].Variable[0])
-                 << "(" << variable_table.getLag(variable_table.getSymbolID(ModelBlock->Block_List[j].Variable[0]))
-                 << ") " << ModelBlock->Block_List[j].Variable[0]+1
-                 << ", equation=" << ModelBlock->Block_List[j].Equation[0]+1 << endl;
-          output << "  end\n";
-          break;
-        case SOLVE_BACKWARD_SIMPLE:
-        case SOLVE_FORWARD_SIMPLE:
-        case SOLVE_BACKWARD_COMPLETE:
-        case SOLVE_FORWARD_COMPLETE:
-        case SOLVE_TWO_BOUNDARIES_COMPLETE:
-        case SOLVE_TWO_BOUNDARIES_SIMPLE:
-          output << "  g2=0;g3=0;\n";
-          for(m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
+          lag=m-ModelBlock->Block_List[j].Max_Lag;
+          if (block_triangular.incidencematrix.Model_Max_Lag_Endo - ModelBlock->Block_List[j].Max_Lag +m >=0)
             {
-              k=m-ModelBlock->Block_List[j].Max_Lag;
-              for(i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
+              for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_other_endo;i++)
                 {
-                  int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
-                  int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
-                  int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
-                  int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Var[i];
-                  if(!IM[eqr*ModelBlock->Block_List[j].Size+varr])
-                    {
-                      Uf[ModelBlock->Block_List[j].Equation[eqr]] << "-g1(" << eqr+1
-                                                                  << ", " << varr+1 << ")*y( " << var+1 << ")";
-                      IM[eqr*ModelBlock->Block_List[j].Size+varr]=true;
-                    }
-                  output << "  g1(" << eqr+1 << ", " << varr+1 << ") = g1(" << eqr+1 << ", " << varr+1 << ") + ";
-                  writeDerivative(output, eq, var, k, oMatlabStaticModelSparse, temporary_terms, eEndogenous);
-                  output << "; % variable=" << symbol_table.getNameByID(eEndogenous, var)
-                         << "(" << k << ") " << var+1
-                         << ", equation=" << eq+1 << endl;
-#ifdef CONDITION
-                  output << "  if (fabs(condition[" << eqr << "])<fabs(u[" << u << "+Per_u_]))\n";
-                  output << "    condition(" << eqr << ")=u(" << u << "+Per_u_);\n";
-#endif
-                }
-            }
-          for(i = 0;i < ModelBlock->Block_List[j].Size;i++)
-            {
-              output << "  " << Uf[ModelBlock->Block_List[j].Equation[i]].str() << ";\n";
-#ifdef CONDITION
-              output << "  if (fabs(condition(" << i+1 << "))<fabs(u(" << i << "+Per_u_)))\n";
-              output << "    condition(" << i+1 << ")=u(" << i+1 << "+Per_u_);\n";
-#endif
-            }
-          //output << "  end\n";
-#ifdef CONDITION
-          for(m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
-            {
-              k=m-ModelBlock->Block_List[j].Max_Lag;
-              for(i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
-                {
-                  int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
-                  int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
-                  int u=ModelBlock->Block_List[j].IM_lead_lag[m].u[i];
-                  int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
-                  output << "  u(" << u+1 << "+Per_u_) = u(" << u+1 << "+Per_u_) / condition(" << eqr+1 << ");\n";
+                  eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index_other_endo[i];
+                  var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index_other_endo[i];
+                  it=first_derivatives.find(make_pair(eq,variable_table.getID(eEndogenous, var,lag)));
+                  it->second->collectTemporary_terms(temporary_terms, ModelBlock, j);
                 }
             }
-          for(i = 0;i < ModelBlock->Block_List[j].Size;i++)
-            output << "  u(" << i+1 << "+Per_u_) = u(" << i+1 << "+Per_u_) / condition(" << i+1 << ");\n";
-#endif
-          break;
-        default:
-          break;
         }
-      prev_Simulation_Type=ModelBlock->Block_List[j].Simulation_Type;
-      free(IM);
     }
-  output << "return;\n\n\n";
+  // Add a mapping form node ID to temporary terms order
+  j=0;
+  for (temporary_terms_type::const_iterator it = temporary_terms.begin();
+       it != temporary_terms.end(); it++)
+    map_idx[(*it)->idx]=j++;
 }
 
-
 void
-ModelTree::writeModelEquationsCodeOrdered(const string file_name, const Model_Block *ModelBlock, const string bin_basename, ExprNodeOutputType output_type) const
+ModelTree::writeModelEquationsOrdered_M( Model_Block *ModelBlock, const string &dynamic_basename) const
   {
-    struct Uff_l
-      {
-        int u, var, lag;
-        Uff_l *pNext;
-      };
-
-    struct Uff
-      {
-        Uff_l *Ufl, *Ufl_First;
-        int eqr;
-      };
-
-    int i,j,k,m, v, ModelBlock_Aggregated_Count, k0, k1;
-    string tmp_s;
-    ostringstream tmp_output;
-    ofstream code_file;
+    int i,j,k,m;
+    string tmp_s, sps;
+    ostringstream tmp_output, tmp1_output, global_output;
     NodeID lhs=NULL, rhs=NULL;
     BinaryOpNode *eq_node;
-    bool lhs_rhs_done;
-    Uff Uf[symbol_table.endo_nbr];
+    ostringstream Uf[symbol_table.endo_nbr];
     map<NodeID, int> reference_count;
-    map<int,int> ModelBlock_Aggregated_Size, ModelBlock_Aggregated_Number;
-    int prev_Simulation_Type=-1;
-    SymbolicGaussElimination SGE;
+    int prev_Simulation_Type=-1, count_derivates=0;
+    int jacobian_max_endo_col;
+    ofstream  output;
     temporary_terms_type::const_iterator it_temp=temporary_terms.begin();
+    int nze, nze_exo, nze_other_endo;
     //----------------------------------------------------------------------
-    string main_name=file_name;
-    main_name+=".cod";
+    //For each block
+    for (j = 0;j < ModelBlock->Size;j++)
+      {
+        //For a block composed of a single equation determines wether we have to evaluate or to solve the equation
+        nze = nze_exo = nze_other_endo =0;
+        for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
+          nze+=ModelBlock->Block_List[j].IM_lead_lag[m].size;
+        for (m=0;m<=ModelBlock->Block_List[j].Max_Lead_Exo+ModelBlock->Block_List[j].Max_Lag_Exo;m++)
+          nze_exo+=ModelBlock->Block_List[j].IM_lead_lag[m].size_exo;
+        for (m=0;m<=ModelBlock->Block_List[j].Max_Lead_Other_Endo+ModelBlock->Block_List[j].Max_Lag_Other_Endo;m++)
+          nze_other_endo+=ModelBlock->Block_List[j].IM_lead_lag[m].size_other_endo;
+        tmp1_output.str("");
+        tmp1_output << dynamic_basename << "_" << j+1 << ".m";
+        output.open(tmp1_output.str().c_str(), ios::out | ios::binary);
+        output << "%\n";
+        output << "% " << tmp1_output.str() << " : Computes dynamic model for Dynare\n";
+        output << "%\n";
+        output << "% Warning : this file is generated automatically by Dynare\n";
+        output << "%           from model file (.mod)\n\n";
+        output << "%/\n";
+        if (ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD
+            ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD
+            ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD_R
+            ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD_R)
+          {
+            output << "function [y, g1, g2, g3, varargout] = " << dynamic_basename << "_" << j+1 << "(y, x, params, jacobian_eval, y_kmin, periods)\n";
+          }
+        else if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_FORWARD_COMPLETE
+                 ||   ModelBlock->Block_List[j].Simulation_Type==SOLVE_BACKWARD_COMPLETE)
+          output << "function [residual, g1, g2, g3, varargout] = " << dynamic_basename << "_" << j+1 << "(y, x, params, it_, jacobian_eval)\n";
+        else if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_BACKWARD_SIMPLE
+                 ||   ModelBlock->Block_List[j].Simulation_Type==SOLVE_FORWARD_SIMPLE)
+          output << "function [residual, g1, g2, g3, varargout] = " << dynamic_basename << "_" << j+1 << "(y, x, params, it_, jacobian_eval)\n";
+        else
+          output << "function [residual, g1, g2, g3, b, varargout] = " << dynamic_basename << "_" << j+1 << "(y, x, params, periods, jacobian_eval, y_kmin, y_size)\n";
+        output << "  % ////////////////////////////////////////////////////////////////////////" << endl
+        << "  % //" << string("                     Block ").substr(int(log10(j + 1))) << j + 1 << " " << BlockTriangular::BlockType0(ModelBlock->Block_List[j].Type)
+        << "          //" << endl
+        << "  % //                     Simulation type "
+        << BlockTriangular::BlockSim(ModelBlock->Block_List[j].Simulation_Type) << "  //" << endl
+        << "  % ////////////////////////////////////////////////////////////////////////" << endl;
+        //The Temporary terms
+        if (ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD
+            ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD
+            ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD_R
+            ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD_R)
+          {
+            output << "  if(jacobian_eval)\n";
+            output << "    g1 = spalloc(" << ModelBlock->Block_List[j].Size << ", " << ModelBlock->Block_List[j].Size*(1+ModelBlock->Block_List[j].Max_Lag_Endo+ModelBlock->Block_List[j].Max_Lead_Endo) << ", " << nze << ");\n";
+            output << "    g1_x=spalloc(" << ModelBlock->Block_List[j].Size << ", " << (ModelBlock->Block_List[j].nb_exo + ModelBlock->Block_List[j].nb_exo_det)*(1+ModelBlock->Block_List[j].Max_Lag_Exo+ModelBlock->Block_List[j].Max_Lead_Exo) << ", " << nze_exo << ");\n";
+            output << "    g1_o=spalloc(" << ModelBlock->Block_List[j].Size << ", " << ModelBlock->Block_List[j].nb_other_endo*(1+ModelBlock->Block_List[j].Max_Lag_Other_Endo+ModelBlock->Block_List[j].Max_Lead_Other_Endo) << ", " << nze_other_endo << ");\n";
+            output << "  end;\n";
+          }
+        else
+          {
+            output << "  if(jacobian_eval)\n";
+            output << "    g1 = spalloc(" << ModelBlock->Block_List[j].Size << ", " << ModelBlock->Block_List[j].Size*(1+ModelBlock->Block_List[j].Max_Lag_Endo+ModelBlock->Block_List[j].Max_Lead_Endo) << ", " << nze << ");\n";
+            output << "    g1_x=spalloc(" << ModelBlock->Block_List[j].Size << ", " << (ModelBlock->Block_List[j].nb_exo + ModelBlock->Block_List[j].nb_exo_det)*(1+ModelBlock->Block_List[j].Max_Lag_Exo+ModelBlock->Block_List[j].Max_Lead_Exo) << ", " << nze_exo << ");\n";
+            output << "    g1_o=spalloc(" << ModelBlock->Block_List[j].Size << ", " << ModelBlock->Block_List[j].nb_other_endo*(1+ModelBlock->Block_List[j].Max_Lag_Other_Endo+ModelBlock->Block_List[j].Max_Lead_Other_Endo) << ", " << nze_other_endo << ");\n";
+            output << "  else\n";
+            if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_COMPLETE || ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_SIMPLE)
+              output << "    g1 = spalloc(" << ModelBlock->Block_List[j].Size*ModelBlock->Periods << ", " << ModelBlock->Block_List[j].Size*(ModelBlock->Periods+ModelBlock->Block_List[j].Max_Lag+ModelBlock->Block_List[j].Max_Lead) << ", " << nze*ModelBlock->Periods << ");\n";
+            else
+              output << "    g1 = spalloc(" << ModelBlock->Block_List[j].Size << ", " << ModelBlock->Block_List[j].Size << ", " << nze << ");\n";
+            output << "  end;\n";
+          }
+
+        output << "  g2=0;g3=0;\n";
+        temporary_terms_type tt2;
+        if(ModelBlock->Block_List[j].Temporary_InUse->size())
+          {
+            tmp_output.str("");
+            for (temporary_terms_inuse_type::const_iterator it = ModelBlock->Block_List[j].Temporary_InUse->begin();
+                 it != ModelBlock->Block_List[j].Temporary_InUse->end(); it++)
+              tmp_output << " T" << *it;
+            output << "  global" << tmp_output.str() << ";\n";
+          }
+        output << "  residual=zeros(" << ModelBlock->Block_List[j].Size << ",1);\n";
+        if (ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD
+            ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD
+            ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD_R
+            ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD_R)
+          output << "  for it_ = y_kmin+1:(y_kmin+periods)\n";
+
+
+        if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_COMPLETE || ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_SIMPLE)
+          {
+            output << "  b = [];\n";
+            output << "  for it_ = y_kmin+1:(periods+y_kmin)\n";
+            output << "    Per_y_=it_*y_size;\n";
+            output << "    Per_J_=(it_-y_kmin-1)*y_size;\n";
+            output << "    Per_K_=(it_-1)*y_size;\n";
+            sps="  ";
+          }
+        else
+          if(ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD || ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD ||
+             ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD_R || ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD_R)
+            sps = "  ";
+          else
+            sps="";
+        if (ModelBlock->Block_List[j].Temporary_terms->size())
+          output << "  " << sps << "% //Temporary variables" << endl;
+        i=0;
+        for (temporary_terms_type::const_iterator it = ModelBlock->Block_List[j].Temporary_terms->begin();
+             it != ModelBlock->Block_List[j].Temporary_terms->end(); it++)
+          {
+            output << "  " <<  sps;
+            (*it)->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
+            output << " = ";
+            (*it)->writeOutput(output, oMatlabDynamicModelSparse, tt2);
+            // Insert current node into tt2
+            tt2.insert(*it);
+            output << ";" << endl;
+            i++;
+          }
+        // The equations
+        for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
+          {
+            string sModel = symbol_table.getNameByID(eEndogenous, ModelBlock->Block_List[j].Variable[i]) ;
+            eq_node = equations[ModelBlock->Block_List[j].Equation[i]];
+            lhs = eq_node->arg1;
+            rhs = eq_node->arg2;
+            tmp_output.str("");
+            lhs->writeOutput(tmp_output, oMatlabDynamicModelSparse, temporary_terms);
+            switch (ModelBlock->Block_List[j].Simulation_Type)
+              {
+              case EVALUATE_BACKWARD:
+              case EVALUATE_FORWARD:
+                output << "    % equation " << ModelBlock->Block_List[j].Equation[i]+1 << " variable : " << sModel
+                << " (" << ModelBlock->Block_List[j].Variable[i]+1 << ")" << endl;
+                output << "    ";
+                output << tmp_output.str();
+                output << " = ";
+                rhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
+                output << ";\n";
+                break;
+              case EVALUATE_BACKWARD_R:
+              case EVALUATE_FORWARD_R:
+                output << "    % equation " << ModelBlock->Block_List[j].Equation[i]+1 << " variable : " << sModel
+                << " (" << ModelBlock->Block_List[j].Variable[i]+1 << ")" << endl;
+                output << "  ";
+                rhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
+                output << " = ";
+                lhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
+                output << ";\n";
+                break;
+              case SOLVE_BACKWARD_SIMPLE:
+              case SOLVE_FORWARD_SIMPLE:
+              case SOLVE_BACKWARD_COMPLETE:
+              case SOLVE_FORWARD_COMPLETE:
+                output << "  % equation " << ModelBlock->Block_List[j].Equation[i]+1 << " variable : " << sModel
+                << " (" << ModelBlock->Block_List[j].Variable[i]+1 << ")" << endl;
+                output << "  " << "residual(" << i+1 << ") = (";
+                goto end;
+              case SOLVE_TWO_BOUNDARIES_COMPLETE:
+              case SOLVE_TWO_BOUNDARIES_SIMPLE:
+                output << "    % equation " << ModelBlock->Block_List[j].Equation[i]+1 << " variable : " << sModel
+                << " (" << ModelBlock->Block_List[j].Variable[i]+1 << ")" << endl;
+                Uf[ModelBlock->Block_List[j].Equation[i]] << "    b(" << i+1 << "+Per_J_) = -residual(" << i+1 << ", it_)";
+                output << "    residual(" << i+1 << ", it_) = (";
+                goto end;
+              default:
+end:
+                output << tmp_output.str();
+                output << ") - (";
+                rhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
+                output << ");\n";
+#ifdef CONDITION
+                if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_COMPLETE || ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_SIMPLE)
+                  output << "  condition(" << i+1 << ")=0;\n";
+#endif
+              }
+          }
+        // The Jacobian if we have to solve the block
+        if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_SIMPLE
+            ||  ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_COMPLETE)
+          output << "  " << sps << "% Jacobian  " << endl;
+        else
+          if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_BACKWARD_SIMPLE || ModelBlock->Block_List[j].Simulation_Type==SOLVE_FORWARD_SIMPLE ||
+              ModelBlock->Block_List[j].Simulation_Type==SOLVE_BACKWARD_COMPLETE || ModelBlock->Block_List[j].Simulation_Type==SOLVE_FORWARD_COMPLETE)
+            output << "  % Jacobian  " << endl << "  if jacobian_eval" << endl;
+          else
+            output << "    % Jacobian  " << endl << "    if jacobian_eval" << endl;
+        switch (ModelBlock->Block_List[j].Simulation_Type)
+          {
+          case EVALUATE_BACKWARD:
+          case EVALUATE_FORWARD:
+          case EVALUATE_BACKWARD_R:
+          case EVALUATE_FORWARD_R:
+            count_derivates++;
+            for (m=0;m<ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag+1;m++)
+              {
+                k=m-ModelBlock->Block_List[j].Max_Lag;
+                for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
+                  {
+                    int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
+                    int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
+                    int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
+                    int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Var[i];
+                    output << "      g1(" << eqr+1 << ", " << /*varr+1+(m+variable_table.max_lag-ModelBlock->Block_List[j].Max_Lag)*symbol_table.endo_nbr*/
+                    varr+1+m*ModelBlock->Block_List[j].Size << ") = ";
+                    writeDerivative(output, eq, var, k, oMatlabDynamicModelSparse, temporary_terms, eEndogenous);
+                    output << "; % variable=" << symbol_table.getNameByID(eEndogenous, var)
+                    << "(" << k//variable_table.getLag(variable_table.getSymbolID(ModelBlock->Block_List[j].Variable[0]))
+                    << ") " << var+1
+                    << ", equation=" << eq+1 << endl;
+                  }
+              }
+            //jacobian_max_endo_col=(variable_table.max_endo_lag+variable_table.max_endo_lead+1)*symbol_table.endo_nbr;
+            for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
+              {
+                k=m-ModelBlock->Block_List[j].Max_Lag;
+                for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_exo;i++)
+                  {
+                    int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_X_Index[i];
+                    int var=ModelBlock->Block_List[j].IM_lead_lag[m].Exogenous_Index[i];
+                    int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_X[i];
+                    int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Exogenous[i];
+                    output << "      g1_x(" << eqr+1 << ", "
+                    << varr+1+(m+variable_table.max_exo_lag-ModelBlock->Block_List[j].Max_Lag)*symbol_table.exo_nbr << ") = ";
+                    writeDerivative(output, eq, var, k, oMatlabDynamicModelSparse, temporary_terms, eExogenous);
+                    output << "; % variable=" << symbol_table.getNameByID(eExogenous, var)
+                    << "(" << k << ") " << var+1
+                    << ", equation=" << eq+1 << endl;
+                  }
+              }
+            //jacobian_max_exo_col=(variable_table.max_exo_lag+variable_table.max_exo_lead+1)*symbol_table.exo_nbr;
+            for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
+              {
+                k=m-ModelBlock->Block_List[j].Max_Lag;
+                if (block_triangular.incidencematrix.Model_Max_Lag_Endo - ModelBlock->Block_List[j].Max_Lag +m >=0)
+                  {
+                    for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_other_endo;i++)
+                      {
+                        int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index_other_endo[i];
+                        int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index_other_endo[i];
+                        int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_other_endo[i];
+                        int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Var_other_endo[i];
+                        output << "      g1_o(" << eqr+1 << ", "
+                        << varr+1+(m+variable_table.max_endo_lag-ModelBlock->Block_List[j].Max_Lag)*symbol_table.endo_nbr << ") = ";
+                        writeDerivative(output, eq, var, k, oMatlabDynamicModelSparse, temporary_terms, eEndogenous);
+                        output << "; % variable=" << symbol_table.getNameByID(eEndogenous, var)
+                        << "(" << k << ") " << var+1
+                        << ", equation=" << eq+1 << endl;
+                      }
+                  }
+              }
+            output << "      varargout{1}=g1_x;\n";
+            output << "      varargout{2}=g1_o;\n";
+            output << "    end;" << endl;
+            output << "  end;" << endl;
+            break;
+          case SOLVE_BACKWARD_SIMPLE:
+          case SOLVE_FORWARD_SIMPLE:
+          case SOLVE_BACKWARD_COMPLETE:
+          case SOLVE_FORWARD_COMPLETE:
+            count_derivates++;
+            for (m=0;m<ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag+1;m++)
+              {
+                k=m-ModelBlock->Block_List[j].Max_Lag;
+                for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
+                  {
+                    int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
+                    int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
+                    int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
+                    int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Var[i];
+                    output << "    g1(" << eqr+1 << ", " << /*varr+1+(m+variable_table.max_lag-ModelBlock->Block_List[j].Max_Lag)*symbol_table.endo_nbr*/
+                    varr+1+m*ModelBlock->Block_List[j].Size << ") = ";
+                    writeDerivative(output, eq, var, k, oMatlabDynamicModelSparse, temporary_terms, eEndogenous);
+                    output << "; % variable=" << symbol_table.getNameByID(eEndogenous, var)
+                    << "(" << k
+                    << ") " << var+1
+                    << ", equation=" << eq+1 << endl;
+                  }
+              }
+            /*jacobian_max_endo_col=(variable_table.max_endo_lag+variable_table.max_endo_lead+1)*symbol_table.endo_nbr;*/
+            for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
+              {
+                k=m-ModelBlock->Block_List[j].Max_Lag;
+                for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_exo;i++)
+                  {
+                    int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_X_Index[i];
+                    int var=ModelBlock->Block_List[j].IM_lead_lag[m].Exogenous_Index[i];
+                    int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_X[i];
+                    int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Exogenous[i];
+                    output << "    g1_x(" << eqr+1 << ", " << varr+1+(m+variable_table.max_exo_lag-ModelBlock->Block_List[j].Max_Lag)*ModelBlock->Block_List[j].nb_exo << ") = ";
+                    writeDerivative(output, eq, var, k, oMatlabDynamicModelSparse, temporary_terms, eExogenous);
+                    output << "; % variable=" << symbol_table.getNameByID(eExogenous, var)
+                    << "(" << k << ") " << var+1
+                    << ", equation=" << eq+1 << endl;
+                  }
+              }
+            //jacobian_max_exo_col=(variable_table.max_exo_lag+variable_table.max_exo_lead+1)*symbol_table.exo_nbr;
+            for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
+              {
+                k=m-ModelBlock->Block_List[j].Max_Lag;
+                if (block_triangular.incidencematrix.Model_Max_Lag_Endo - ModelBlock->Block_List[j].Max_Lag +m >=0)
+                  {
+                    for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_other_endo;i++)
+                      {
+                        int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index_other_endo[i];
+                        int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index_other_endo[i];
+                        int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_other_endo[i];
+                        int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Var_other_endo[i];
+                        output << "    g1_o(" << eqr+1 << ", "
+                        << varr+1+(m+variable_table.max_endo_lag-ModelBlock->Block_List[j].Max_Lag)*symbol_table.endo_nbr << ") = ";
+                        writeDerivative(output, eq, var, k, oMatlabDynamicModelSparse, temporary_terms, eEndogenous);
+                        output << "; % variable=" << symbol_table.getNameByID(eEndogenous, var)
+                        << "(" << k << ") " << var+1
+                        << ", equation=" << eq+1 << endl;
+                      }
+                  }
+              }
+            output << "    varargout{1}=g1_x;\n";
+            output << "    varargout{2}=g1_o;\n";
+            output << "  else" << endl;
+
+            m=ModelBlock->Block_List[j].Max_Lag;
+            for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
+              {
+                int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
+                int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
+                int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
+                int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Var[i];
+                //Uf[ModelBlock->Block_List[j].Equation[eqr]] << "+g1(" << eqr+1 << ", " << varr+1 << ")*y(it_, " << var+1 << ")";
+                output << "    g1(" << eqr+1 << ", " << varr+1 << ") = ";
+                writeDerivative(output, eq, var, 0, oMatlabDynamicModelSparse, temporary_terms, eEndogenous);
+                output << "; % variable=" << symbol_table.getNameByID(eEndogenous, var)
+                << "(" << variable_table.getLag(variable_table.getSymbolID(var)) << ") " << var+1
+                << ", equation=" << eq+1 << endl;
+              }
+            output << "  end;\n";
+            break;
+          case SOLVE_TWO_BOUNDARIES_SIMPLE:
+          case SOLVE_TWO_BOUNDARIES_COMPLETE:
+            output << "    if ~jacobian_eval" << endl;
+            for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
+              {
+                k=m-ModelBlock->Block_List[j].Max_Lag;
+                for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
+                  {
+                    int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
+                    int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
+                    int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
+                    int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Var[i];
+                    if (k==0)
+                      Uf[ModelBlock->Block_List[j].Equation[eqr]] << "+g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+Per_K_)*y(it_, " << var+1 << ")";
+                    else if (k==1)
+                      Uf[ModelBlock->Block_List[j].Equation[eqr]] << "+g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+Per_y_)*y(it_+1, " << var+1 << ")";
+                    else if (k>0)
+                      Uf[ModelBlock->Block_List[j].Equation[eqr]] << "+g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+y_size*(it_+" << k-1 << "))*y(it_+" << k << ", " << var+1 << ")";
+                    else if (k<0)
+                      Uf[ModelBlock->Block_List[j].Equation[eqr]] << "+g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+y_size*(it_" << k-1 << "))*y(it_" << k << ", " << var+1 << ")";
+                    if (k==0)
+                      output << "      g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+Per_K_) = ";
+                    else if (k==1)
+                      output << "      g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+Per_y_) = ";
+                    else if (k>0)
+                      output << "      g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+y_size*(it_+" << k-1 << ")) = ";
+                    else if (k<0)
+                      output << "      g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+y_size*(it_" << k-1 << ")) = ";
+                    writeDerivative(output, eq, var, k, oMatlabDynamicModelSparse, temporary_terms, eEndogenous);
+                    output << "; % variable=" << symbol_table.getNameByID(eEndogenous, var)
+                    << "(" << k << ") " << var+1
+                    << ", equation=" << eq+1 << endl;
+#ifdef CONDITION
+                    output << "  if (fabs(condition[" << eqr << "])<fabs(u[" << u << "+Per_u_]))\n";
+                    output << "    condition(" << eqr << ")=u(" << u << "+Per_u_);\n";
+#endif
+                  }
+              }
+            for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
+              {
+                output << "  " << Uf[ModelBlock->Block_List[j].Equation[i]].str() << ";\n";
+#ifdef CONDITION
+                output << "  if (fabs(condition(" << i+1 << "))<fabs(u(" << i << "+Per_u_)))\n";
+                output << "    condition(" << i+1 << ")=u(" << i+1 << "+Per_u_);\n";
+#endif
+              }
+#ifdef CONDITION
+            for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
+              {
+                k=m-ModelBlock->Block_List[j].Max_Lag;
+                for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
+                  {
+                    int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
+                    int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
+                    int u=ModelBlock->Block_List[j].IM_lead_lag[m].u[i];
+                    int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
+                    output << "  u(" << u+1 << "+Per_u_) = u(" << u+1 << "+Per_u_) / condition(" << eqr+1 << ");\n";
+                  }
+              }
+            for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
+              output << "  u(" << i+1 << "+Per_u_) = u(" << i+1 << "+Per_u_) / condition(" << i+1 << ");\n";
+#endif
+
+            output << "    else" << endl;
+            for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
+              {
+                k=m-ModelBlock->Block_List[j].Max_Lag;
+                for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
+                  {
+                    int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
+                    int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
+                    int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
+                    int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Var[i];
+                    output << "      g1(" << eqr+1 << ", " << varr+1+(m-ModelBlock->Block_List[j].Max_Lag+ModelBlock->Block_List[j].Max_Lag_Endo)*ModelBlock->Block_List[j].Size << ") = ";
+                    writeDerivative(output, eq, var, k, oMatlabDynamicModelSparse, temporary_terms, eEndogenous);
+                    output << "; % variable=" << symbol_table.getNameByID(eEndogenous, var)
+                    << "(" << k << ") " << var+1
+                    << ", equation=" << eq+1 << endl;
+                  }
+              }
+            jacobian_max_endo_col=(ModelBlock->Block_List[j].Max_Lead_Endo+ModelBlock->Block_List[j].Max_Lag_Endo+1)*ModelBlock->Block_List[j].Size;
+            for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
+              {
+                k=m-ModelBlock->Block_List[j].Max_Lag;
+                for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_exo;i++)
+                  {
+                    int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_X_Index[i];
+                    int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_X[i];
+                    int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Exogenous[i];
+                    int var=ModelBlock->Block_List[j].IM_lead_lag[m].Exogenous_Index[i];
+                    output << "      g1_x(" << eqr+1 << ", "
+                    << jacobian_max_endo_col+(m-(ModelBlock->Block_List[j].Max_Lag-ModelBlock->Block_List[j].Max_Lag_Exo))*ModelBlock->Block_List[j].nb_exo+varr+1 << ") = ";
+                    writeDerivative(output, eq, var, k, oMatlabDynamicModelSparse, temporary_terms, eExogenous);
+                    output << "; % variable (exogenous)=" << symbol_table.getNameByID(eExogenous, var)
+                    << "(" << k << ") " << var+1 << " " << varr+1
+                    << ", equation=" << eq+1 << endl;
+                  }
+              }
+            //jacobian_max_exo_col=(variable_table.max_exo_lag+variable_table.max_exo_lead+1)*symbol_table.exo_nbr;
+            for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
+              {
+                k=m-ModelBlock->Block_List[j].Max_Lag;
+                if (block_triangular.incidencematrix.Model_Max_Lag_Endo - ModelBlock->Block_List[j].Max_Lag +m >=0)
+                  {
+                    for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_other_endo;i++)
+                      {
+                        int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index_other_endo[i];
+                        int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index_other_endo[i];
+                        int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_other_endo[i];
+                        int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Var_other_endo[i];
+                        output << "      g1_o(" << eqr+1 << ", "
+                        << varr+1+(m+variable_table.max_endo_lag-ModelBlock->Block_List[j].Max_Lag)*symbol_table.endo_nbr << ") = ";
+                        writeDerivative(output, eq, var, k, oMatlabDynamicModelSparse, temporary_terms, eEndogenous);
+                        output << "; % variable=" << symbol_table.getNameByID(eEndogenous, var)
+                        << "(" << k << ") " << var+1
+                        << ", equation=" << eq+1 << endl;
+                      }
+                  }
+              }
+            //output << "  else" << endl;
+            output << "      varargout{1}=g1_x;\n";
+            output << "      varargout{2}=g1_o;\n";
+            output << "    end;\n";
+            output << "  end;\n";
+            break;
+          default:
+            break;
+          }
+        prev_Simulation_Type=ModelBlock->Block_List[j].Simulation_Type;
+        output.close();
+      }
+  }
+
+void
+ModelTree::writeModelStaticEquationsOrdered_M(Model_Block *ModelBlock, const string &static_basename) const
+  {
+    int i,j,k,m, var, eq, g1_index = 1;
+    string tmp_s, sps;
+    ostringstream tmp_output, tmp1_output, global_output;
+    NodeID lhs=NULL, rhs=NULL;
+    BinaryOpNode *eq_node;
+    map<NodeID, int> reference_count;
+    int prev_Simulation_Type=-1;
+    int nze=0;
+    bool *IM, *IMl;
+    ofstream  output;
+    temporary_terms_type::const_iterator it_temp=temporary_terms.begin();
+    //----------------------------------------------------------------------
+    for (j = 0;j < ModelBlock->Size;j++)
+      {
+        //For a block composed of a single equation determines wether we have to evaluate or to solve the equation
+        tmp1_output.str("");
+        tmp1_output << static_basename << "_" << j+1 << ".m";
+        output.open(tmp1_output.str().c_str(), ios::out | ios::binary);
+        output << "%\n";
+        output << "% " << tmp1_output.str() << " : Computes static model for Dynare\n";
+        output << "%\n";
+        output << "% Warning : this file is generated automatically by Dynare\n";
+        output << "%           from model file (.mod)\n\n";
+        output << "%/\n";
+        if (ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD
+            ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD
+            ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD_R
+            ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD_R )
+          output << "function [y, g1] = " << static_basename << "_" << j+1 << "(y, x, params, jacobian_eval)\n";
+        else
+          output << "function [residual, g1, g2, g3] = " << static_basename << "_" << j+1 << "(y, x, params, jacobian_eval)\n";
+        output << "  % ////////////////////////////////////////////////////////////////////////" << endl
+        << "  % //" << string("                     Block ").substr(int(log10(j + 1))) << j + 1 << " "
+        << BlockTriangular::BlockType0(ModelBlock->Block_List[j].Type) << "          //" << endl
+        << "  % //                     Simulation type ";
+        output << BlockTriangular::BlockSim(ModelBlock->Block_List[j].Simulation_Type) << "  //" << endl
+        << "  % ////////////////////////////////////////////////////////////////////////" << endl;
+        //The Temporary terms
+        //output << global_output.str();
+        temporary_terms_type tt2;
+        if(ModelBlock->Block_List[j].Temporary_InUse->size())
+          {
+            tmp_output.str("");
+            for (temporary_terms_inuse_type::const_iterator it = ModelBlock->Block_List[j].Temporary_InUse->begin();
+                 it != ModelBlock->Block_List[j].Temporary_InUse->end(); it++)
+              tmp_output << " T" << *it;
+            output << "  global" << tmp_output.str() << ";\n";
+          }
+
+        int n=ModelBlock->Block_List[j].Size;
+        int n1=symbol_table.endo_nbr;
+        IM=(bool*)malloc(n*n*sizeof(bool));
+        memset(IM, 0, n*n*sizeof(bool));
+        for (m=-ModelBlock->Block_List[j].Max_Lag;m<=ModelBlock->Block_List[j].Max_Lead;m++)
+          {
+            IMl=block_triangular.incidencematrix.Get_IM(m, eEndogenous);
+            if (IMl)
+              {
+                for (i=0;i<n;i++)
+                  {
+                    eq=ModelBlock->Block_List[j].Equation[i];
+                    for (k=0;k<n;k++)
+                      {
+                        var=ModelBlock->Block_List[j].Variable[k];
+                        IM[i*n+k]=IM[i*n+k] || IMl[eq*n1+var];
+                      }
+                  }
+              }
+          }
+        for (nze=0, i=0;i<n*n;i++)
+          {
+            nze+=IM[i];
+          }
+        memset(IM, 0, n*n*sizeof(bool));
+        if ( ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_BACKWARD && ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_FORWARD
+             && ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_BACKWARD_R && ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_FORWARD_R)
+          {
+            output << "  g1=spalloc(" << ModelBlock->Block_List[j].Size << ", " << ModelBlock->Block_List[j].Size << ", " << nze << ");\n";
+            output << "  residual=zeros(" << ModelBlock->Block_List[j].Size << ",1);\n";
+          }
+        sps="";
+        if (ModelBlock->Block_List[j].Temporary_terms->size())
+          output << "  " << sps << "% //Temporary variables" << endl;
+        i=0;
+        //temporary_terms_type tt2;
+        for (temporary_terms_type::const_iterator it = ModelBlock->Block_List[j].Temporary_terms->begin();
+             it != ModelBlock->Block_List[j].Temporary_terms->end(); it++)
+          {
+            output << "  " <<  sps;
+            (*it)->writeOutput(output, oMatlabStaticModelSparse, temporary_terms);
+            output << " = ";
+            (*it)->writeOutput(output, oMatlabStaticModelSparse, tt2);
+            // Insert current node into tt2
+            tt2.insert(*it);
+            output << ";" << endl;
+            i++;
+          }
+        // The equations
+        for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
+          {
+            //ModelBlock->Block_List[j].Variable_Sorted[i] = variable_table.getID(eEndogenous, ModelBlock->Block_List[j].Variable[i], 0);
+            string sModel = symbol_table.getNameByID(eEndogenous, ModelBlock->Block_List[j].Variable[i]) ;
+            output << sps << "  % equation " << ModelBlock->Block_List[j].Equation[i]+1 << " variable : "
+            << sModel << " (" << ModelBlock->Block_List[j].Variable[i]+1 << ")" << endl;
+            /*if (!lhs_rhs_done)
+              {*/
+                eq_node = equations[ModelBlock->Block_List[j].Equation[i]];
+                lhs = eq_node->arg1;
+                rhs = eq_node->arg2;
+                tmp_output.str("");
+                lhs->writeOutput(tmp_output, oMatlabStaticModelSparse, temporary_terms);
+              /*}*/
+            output << "  ";
+            switch (ModelBlock->Block_List[j].Simulation_Type)
+              {
+              case EVALUATE_BACKWARD:
+              case EVALUATE_FORWARD:
+                output << tmp_output.str();
+                output << " = ";
+                rhs->writeOutput(output, oMatlabStaticModelSparse, temporary_terms);
+                output << ";\n";
+                break;
+              case EVALUATE_BACKWARD_R:
+              case EVALUATE_FORWARD_R:
+                rhs->writeOutput(output, oMatlabStaticModelSparse, temporary_terms);
+                output << " = ";
+                lhs->writeOutput(output, oMatlabStaticModelSparse, temporary_terms);
+                output << ";\n";
+                break;
+              case SOLVE_BACKWARD_SIMPLE:
+              case SOLVE_FORWARD_SIMPLE:
+              case SOLVE_BACKWARD_COMPLETE:
+              case SOLVE_FORWARD_COMPLETE:
+              case SOLVE_TWO_BOUNDARIES_COMPLETE:
+              case SOLVE_TWO_BOUNDARIES_SIMPLE:
+                //Uf[ModelBlock->Block_List[j].Equation[i]] << "b(" << i+1 << ") =  residual(" << i+1 << ")";
+                goto end;
+              default:
+end:
+                output << sps << "residual(" << i+1 << ") = (";
+                output << tmp_output.str();
+                output << ") - (";
+                rhs->writeOutput(output, oMatlabStaticModelSparse, temporary_terms);
+                output << ");\n";
+#ifdef CONDITION
+                if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_COMPLETE || ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_SIMPLE)
+                  output << "  condition(" << i+1 << ")=0;\n";
+#endif
+              }
+          }
+        // The Jacobian if we have to solve the block
+        output << "  " << sps << "% Jacobian  " << endl;
+        switch (ModelBlock->Block_List[j].Simulation_Type)
+          {
+          case EVALUATE_BACKWARD:
+          case EVALUATE_FORWARD:
+          case EVALUATE_BACKWARD_R:
+          case EVALUATE_FORWARD_R:
+            output << "  if(jacobian_eval)\n";
+            output << "    g1( " << g1_index << ", " << g1_index << ")=";
+            writeDerivative(output, ModelBlock->Block_List[j].Equation[0], ModelBlock->Block_List[j].Variable[0], 0, oMatlabStaticModelSparse, temporary_terms, eEndogenous);
+            output << "; % variable=" << symbol_table.getNameByID(eEndogenous, ModelBlock->Block_List[j].Variable[0])
+            << "(" << variable_table.getLag(variable_table.getSymbolID(ModelBlock->Block_List[j].Variable[0]))
+            << ") " << ModelBlock->Block_List[j].Variable[0]+1
+            << ", equation=" << ModelBlock->Block_List[j].Equation[0]+1 << endl;
+            output << "  end\n";
+            break;
+          case SOLVE_BACKWARD_SIMPLE:
+          case SOLVE_FORWARD_SIMPLE:
+          case SOLVE_BACKWARD_COMPLETE:
+          case SOLVE_FORWARD_COMPLETE:
+          case SOLVE_TWO_BOUNDARIES_COMPLETE:
+          case SOLVE_TWO_BOUNDARIES_SIMPLE:
+            output << "  g2=0;g3=0;\n";
+            for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
+              {
+                k=m-ModelBlock->Block_List[j].Max_Lag;
+                for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
+                  {
+                    int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
+                    int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
+                    int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
+                    int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Var[i];
+                    /*if(!IM[eqr*ModelBlock->Block_List[j].Size+varr])
+                      {
+                        Uf[ModelBlock->Block_List[j].Equation[eqr]] << "-g1(" << eqr+1
+                                                                    << ", " << varr+1 << ")*y( " << var+1 << ")";
+                        IM[eqr*ModelBlock->Block_List[j].Size+varr]=true;
+                      }*/
+                    output << "  g1(" << eqr+1 << ", " << varr+1 << ") = g1(" << eqr+1 << ", " << varr+1 << ") + ";
+                    writeDerivative(output, eq, var, k, oMatlabStaticModelSparse, temporary_terms, eEndogenous);
+                    output << "; % variable=" << symbol_table.getNameByID(eEndogenous, var)
+                    << "(" << k << ") " << var+1
+                    << ", equation=" << eq+1 << endl;
+#ifdef CONDITION
+                    output << "  if (fabs(condition[" << eqr << "])<fabs(u[" << u << "+Per_u_]))\n";
+                    output << "    condition(" << eqr << ")=u(" << u << "+Per_u_);\n";
+#endif
+                  }
+              }
+#ifdef CONDITION
+            for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
+              {
+                k=m-ModelBlock->Block_List[j].Max_Lag;
+                for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
+                  {
+                    int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
+                    int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
+                    int u=ModelBlock->Block_List[j].IM_lead_lag[m].u[i];
+                    int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
+                    output << "  u(" << u+1 << "+Per_u_) = u(" << u+1 << "+Per_u_) / condition(" << eqr+1 << ");\n";
+                  }
+              }
+            for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
+              output << "  u(" << i+1 << "+Per_u_) = u(" << i+1 << "+Per_u_) / condition(" << i+1 << ");\n";
+#endif
+            break;
+          default:
+            break;
+          }
+        prev_Simulation_Type=ModelBlock->Block_List[j].Simulation_Type;
+        free(IM);
+        output << "return;\n";
+        output.close();
+      }
+    //output << "return;\n\n\n";
+  }
+
+
+void
+ModelTree::writeModelEquationsCodeOrdered(const string file_name, const Model_Block *ModelBlock, const string bin_basename, ExprNodeOutputType output_type) const
+  {
+    struct Uff_l
+      {
+        int u, var, lag;
+        Uff_l *pNext;
+      };
+
+    struct Uff
+      {
+        Uff_l *Ufl, *Ufl_First;
+        int eqr;
+      };
+
+    int i,j,k,m, v, ModelBlock_Aggregated_Count, k0, k1;
+    string tmp_s;
+    ostringstream tmp_output;
+    ofstream code_file;
+    NodeID lhs=NULL, rhs=NULL;
+    BinaryOpNode *eq_node;
+    bool lhs_rhs_done;
+    Uff Uf[symbol_table.endo_nbr];
+    map<NodeID, int> reference_count;
+    map<int,int> ModelBlock_Aggregated_Size, ModelBlock_Aggregated_Number;
+    int prev_Simulation_Type=-1;
+    SymbolicGaussElimination SGE;
+    temporary_terms_type::const_iterator it_temp=temporary_terms.begin();
+    //----------------------------------------------------------------------
+    string main_name=file_name;
+    main_name+=".cod";
     code_file.open(main_name.c_str(), ios::out | ios::binary | ios::ate );
     if (!code_file.is_open())
       {
@@ -1167,13 +1144,13 @@ ModelTree::writeModelEquationsCodeOrdered(const string file_name, const Model_Bl
     //search for successive and identical blocks
     i=k=k0=0;
     ModelBlock_Aggregated_Count=-1;
-    for(j = 0;j < ModelBlock->Size;j++)
+    for (j = 0;j < ModelBlock->Size;j++)
       {
         if (BlockTriangular::BlockSim(prev_Simulation_Type)==BlockTriangular::BlockSim(ModelBlock->Block_List[j].Simulation_Type)
-              && (ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD
-                  ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD
-                  ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD_R
-                  ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD_R ))
+            && (ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD
+                ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD
+                ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD_R
+                ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD_R ))
           {
           }
         else
@@ -1189,7 +1166,7 @@ ModelTree::writeModelEquationsCodeOrdered(const string file_name, const Model_Bl
     ModelBlock_Aggregated_Count++;
     //For each block
     j=0;
-    for(k0 = 0;k0 < ModelBlock_Aggregated_Count;k0++)
+    for (k0 = 0;k0 < ModelBlock_Aggregated_Count;k0++)
       {
         k1=j;
         if (k0>0)
@@ -1199,9 +1176,9 @@ ModelTree::writeModelEquationsCodeOrdered(const string file_name, const Model_Bl
         code_file.write(reinterpret_cast<char *>(&v),sizeof(v));
         v=ModelBlock->Block_List[j].Simulation_Type;
         code_file.write(reinterpret_cast<char *>(&v),sizeof(v));
-        for(k=0; k<ModelBlock_Aggregated_Size[k0]; k++)
+        for (k=0; k<ModelBlock_Aggregated_Size[k0]; k++)
           {
-            for(i=0; i < ModelBlock->Block_List[j].Size;i++)
+            for (i=0; i < ModelBlock->Block_List[j].Size;i++)
               {
                 code_file.write(reinterpret_cast<char *>(&ModelBlock->Block_List[j].Variable[i]),sizeof(ModelBlock->Block_List[j].Variable[i]));
                 code_file.write(reinterpret_cast<char *>(&ModelBlock->Block_List[j].Equation[i]),sizeof(ModelBlock->Block_List[j].Equation[i]));
@@ -1231,7 +1208,7 @@ ModelTree::writeModelEquationsCodeOrdered(const string file_name, const Model_Bl
                 SGE.file_is_open();
               }
           }
-        for(k1 = 0; k1 < ModelBlock_Aggregated_Size[k0]; k1++)
+        for (k1 = 0; k1 < ModelBlock_Aggregated_Size[k0]; k1++)
           {
             //For a block composed of a single equation determines whether we have to evaluate or to solve the equation
             if (ModelBlock->Block_List[j].Size==1)
@@ -1246,7 +1223,7 @@ ModelTree::writeModelEquationsCodeOrdered(const string file_name, const Model_Bl
             //The Temporary terms
             temporary_terms_type tt2;
             i=0;
-            for(temporary_terms_type::const_iterator it = ModelBlock->Block_List[j].Temporary_terms->begin();
+            for (temporary_terms_type::const_iterator it = ModelBlock->Block_List[j].Temporary_terms->begin();
                  it != ModelBlock->Block_List[j].Temporary_terms->end(); it++)
               {
                 (*it)->compile(code_file,false, output_type, tt2, map_idx);
@@ -1263,7 +1240,7 @@ ModelTree::writeModelEquationsCodeOrdered(const string file_name, const Model_Bl
 #endif
                 i++;
               }
-            for(temporary_terms_type::const_iterator it = ModelBlock->Block_List[j].Temporary_terms->begin();
+            for (temporary_terms_type::const_iterator it = ModelBlock->Block_List[j].Temporary_terms->begin();
                  it != ModelBlock->Block_List[j].Temporary_terms->end(); it++)
               {
                 map_idx_type::const_iterator ii=map_idx.find((*it)->idx);
@@ -1272,7 +1249,7 @@ ModelTree::writeModelEquationsCodeOrdered(const string file_name, const Model_Bl
 #endif
               }
             // The equations
-            for(i = 0;i < ModelBlock->Block_List[j].Size;i++)
+            for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
               {
                 //ModelBlock->Block_List[j].Variable_Sorted[i] = variable_table.getID(eEndogenous, ModelBlock->Block_List[j].Variable[i], 0);
                 if (!lhs_rhs_done)
@@ -1283,45 +1260,45 @@ ModelTree::writeModelEquationsCodeOrdered(const string file_name, const Model_Bl
                   }
                 switch (ModelBlock->Block_List[j].Simulation_Type)
                   {
-                    case EVALUATE_BACKWARD:
-                    case EVALUATE_FORWARD:
-                      rhs->compile(code_file,false, output_type, temporary_terms, map_idx);
-                      lhs->compile(code_file,true, output_type, temporary_terms, map_idx);
-                      break;
-                    case EVALUATE_BACKWARD_R:
-                    case EVALUATE_FORWARD_R:
-                      lhs->compile(code_file,false, output_type, temporary_terms, map_idx);
-                      rhs->compile(code_file,true, output_type, temporary_terms, map_idx);
-                      break;
+                  case EVALUATE_BACKWARD:
+                  case EVALUATE_FORWARD:
+                    rhs->compile(code_file,false, output_type, temporary_terms, map_idx);
+                    lhs->compile(code_file,true, output_type, temporary_terms, map_idx);
+                    break;
+                  case EVALUATE_BACKWARD_R:
+                  case EVALUATE_FORWARD_R:
+                    lhs->compile(code_file,false, output_type, temporary_terms, map_idx);
+                    rhs->compile(code_file,true, output_type, temporary_terms, map_idx);
+                    break;
                     /*case SOLVE_TWO_BOUNDARIES_SIMPLE:
                       v=ModelBlock->Block_List[j].Equation[i];
                       Uf[v].eqr=i;
                       Uf[v].Ufl=NULL;
                       goto end;*/
-                    case SOLVE_BACKWARD_COMPLETE:
-                    case SOLVE_FORWARD_COMPLETE:
-                      v=ModelBlock->Block_List[j].Equation[i];
-                      Uf[v].eqr=i;
-                      Uf[v].Ufl=NULL;
-                      goto end;
-                    case SOLVE_TWO_BOUNDARIES_COMPLETE:
-                    case SOLVE_TWO_BOUNDARIES_SIMPLE:
-                      v=ModelBlock->Block_List[j].Equation[i];
-                      Uf[v].eqr=i;
-                      Uf[v].Ufl=NULL;
-                      goto end;
-                    default:
-                      end:
-                      lhs->compile(code_file,false, output_type, temporary_terms, map_idx);
-                      rhs->compile(code_file,false, output_type, temporary_terms, map_idx);
-                      code_file.write(&FBINARY, sizeof(FBINARY));
-                      int v=oMinus;
-                      code_file.write(reinterpret_cast<char *>(&v),sizeof(v));
-                      code_file.write(&FSTPR, sizeof(FSTPR));
-                      code_file.write(reinterpret_cast<char *>(&i), sizeof(i));
+                  case SOLVE_BACKWARD_COMPLETE:
+                  case SOLVE_FORWARD_COMPLETE:
+                    v=ModelBlock->Block_List[j].Equation[i];
+                    Uf[v].eqr=i;
+                    Uf[v].Ufl=NULL;
+                    goto end;
+                  case SOLVE_TWO_BOUNDARIES_COMPLETE:
+                  case SOLVE_TWO_BOUNDARIES_SIMPLE:
+                    v=ModelBlock->Block_List[j].Equation[i];
+                    Uf[v].eqr=i;
+                    Uf[v].Ufl=NULL;
+                    goto end;
+                  default:
+end:
+                    lhs->compile(code_file,false, output_type, temporary_terms, map_idx);
+                    rhs->compile(code_file,false, output_type, temporary_terms, map_idx);
+                    code_file.write(&FBINARY, sizeof(FBINARY));
+                    int v=oMinus;
+                    code_file.write(reinterpret_cast<char *>(&v),sizeof(v));
+                    code_file.write(&FSTPR, sizeof(FSTPR));
+                    code_file.write(reinterpret_cast<char *>(&i), sizeof(i));
 #ifdef CONDITION
-                      if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_COMPLETE)
-                        output << "  condition[" << i << "]=0;\n";
+                    if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_COMPLETE)
+                      output << "  condition[" << i << "]=0;\n";
 #endif
                   }
               }
@@ -1334,168 +1311,168 @@ ModelTree::writeModelEquationsCodeOrdered(const string file_name, const Model_Bl
               {
                 switch (ModelBlock->Block_List[j].Simulation_Type)
                   {
-                    case SOLVE_BACKWARD_SIMPLE:
-                    case SOLVE_FORWARD_SIMPLE:
-                      compileDerivative(code_file, ModelBlock->Block_List[j].Equation[0], ModelBlock->Block_List[j].Variable[0], 0, output_type, map_idx);
-                      code_file.write(&FSTPG, sizeof(FSTPG));
-                      v=0;
-                      code_file.write(reinterpret_cast<char *>(&v), sizeof(v));
-                      break;
-                    case SOLVE_BACKWARD_COMPLETE:
-                    case SOLVE_FORWARD_COMPLETE:
-                      m=ModelBlock->Block_List[j].Max_Lag;
-                      for(i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
-                        {
-                          int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
-                          int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
-                          int u=ModelBlock->Block_List[j].IM_lead_lag[m].us[i];
-                          int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
-                          int v=ModelBlock->Block_List[j].Equation[eqr];
-                          if (!Uf[v].Ufl)
-                            {
-                              Uf[v].Ufl=(Uff_l*)malloc(sizeof(Uff_l));
-                              Uf[v].Ufl_First=Uf[v].Ufl;
-                            }
-                          else
-                            {
-                              Uf[v].Ufl->pNext=(Uff_l*)malloc(sizeof(Uff_l));
-                              Uf[v].Ufl=Uf[v].Ufl->pNext;
-                            }
-                          Uf[v].Ufl->pNext=NULL;
-                          Uf[v].Ufl->u=u;
-                          Uf[v].Ufl->var=var;
-                          compileDerivative(code_file, eq, var, 0, output_type, map_idx);
-                          code_file.write(&FSTPU, sizeof(FSTPU));
-                          code_file.write(reinterpret_cast<char *>(&u), sizeof(u));
-                        }
-                      for(i = 0;i < ModelBlock->Block_List[j].Size;i++)
-                        {
-                          code_file.write(&FLDR, sizeof(FLDR));
-                          code_file.write(reinterpret_cast<char *>(&i), sizeof(i));
-                          code_file.write(&FLDZ, sizeof(FLDZ));
-                          int v=ModelBlock->Block_List[j].Equation[i];
-                          for(Uf[v].Ufl=Uf[v].Ufl_First;Uf[v].Ufl;Uf[v].Ufl=Uf[v].Ufl->pNext)
-                            {
-                              code_file.write(&FLDU, sizeof(FLDU));
-                              code_file.write(reinterpret_cast<char *>(&Uf[v].Ufl->u), sizeof(Uf[v].Ufl->u));
-                              code_file.write(&FLDV, sizeof(FLDV));
-                              char vc=eEndogenous;
-                              code_file.write(reinterpret_cast<char *>(&vc), sizeof(vc));
-                              code_file.write(reinterpret_cast<char *>(&Uf[v].Ufl->var), sizeof(Uf[v].Ufl->var));
-                              int v1=0;
-                              code_file.write(reinterpret_cast<char *>(&v1), sizeof(v1));
-                              code_file.write(&FBINARY, sizeof(FBINARY));
-                              v1=oTimes;
-                              code_file.write(reinterpret_cast<char *>(&v1), sizeof(v1));
-                              code_file.write(&FCUML, sizeof(FCUML));
-                            }
-                          Uf[v].Ufl=Uf[v].Ufl_First;
-                          while(Uf[v].Ufl)
-                            {
-                              Uf[v].Ufl_First=Uf[v].Ufl->pNext;
-                              free(Uf[v].Ufl);
-                              Uf[v].Ufl=Uf[v].Ufl_First;
-                            }
-                          code_file.write(&FBINARY, sizeof(FBINARY));
-                          v=oMinus;
-                          code_file.write(reinterpret_cast<char *>(&v), sizeof(v));
-                          code_file.write(&FSTPU, sizeof(FSTPU));
-                          code_file.write(reinterpret_cast<char *>(&i), sizeof(i));
-                        }
-                      break;
-                    case SOLVE_TWO_BOUNDARIES_COMPLETE:
-                    case SOLVE_TWO_BOUNDARIES_SIMPLE:
-                      for(m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
-                        {
-                          k=m-ModelBlock->Block_List[j].Max_Lag;
-                          for(i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
-                            {
-                              int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
-                              int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
-                              int u=ModelBlock->Block_List[j].IM_lead_lag[m].u[i];
-                              int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
-                              int v=ModelBlock->Block_List[j].Equation[eqr];
-                              if (!Uf[v].Ufl)
-                                {
-                                  Uf[v].Ufl=(Uff_l*)malloc(sizeof(Uff_l));
-                                  Uf[v].Ufl_First=Uf[v].Ufl;
-                                }
-                              else
-                                {
-                                  Uf[v].Ufl->pNext=(Uff_l*)malloc(sizeof(Uff_l));
-                                  Uf[v].Ufl=Uf[v].Ufl->pNext;
-                                }
-                              Uf[v].Ufl->pNext=NULL;
-                              Uf[v].Ufl->u=u;
-                              Uf[v].Ufl->var=var;
-                              Uf[v].Ufl->lag=k;
-                              compileDerivative(code_file, eq, var, k, output_type, map_idx);
-                              code_file.write(&FSTPU, sizeof(FSTPU));
-                              code_file.write(reinterpret_cast<char *>(&u), sizeof(u));
+                  case SOLVE_BACKWARD_SIMPLE:
+                  case SOLVE_FORWARD_SIMPLE:
+                    compileDerivative(code_file, ModelBlock->Block_List[j].Equation[0], ModelBlock->Block_List[j].Variable[0], 0, output_type, map_idx);
+                    code_file.write(&FSTPG, sizeof(FSTPG));
+                    v=0;
+                    code_file.write(reinterpret_cast<char *>(&v), sizeof(v));
+                    break;
+                  case SOLVE_BACKWARD_COMPLETE:
+                  case SOLVE_FORWARD_COMPLETE:
+                    m=ModelBlock->Block_List[j].Max_Lag;
+                    for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
+                      {
+                        int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
+                        int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
+                        int u=ModelBlock->Block_List[j].IM_lead_lag[m].us[i];
+                        int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
+                        int v=ModelBlock->Block_List[j].Equation[eqr];
+                        if (!Uf[v].Ufl)
+                          {
+                            Uf[v].Ufl=(Uff_l*)malloc(sizeof(Uff_l));
+                            Uf[v].Ufl_First=Uf[v].Ufl;
+                          }
+                        else
+                          {
+                            Uf[v].Ufl->pNext=(Uff_l*)malloc(sizeof(Uff_l));
+                            Uf[v].Ufl=Uf[v].Ufl->pNext;
+                          }
+                        Uf[v].Ufl->pNext=NULL;
+                        Uf[v].Ufl->u=u;
+                        Uf[v].Ufl->var=var;
+                        compileDerivative(code_file, eq, var, 0, output_type, map_idx);
+                        code_file.write(&FSTPU, sizeof(FSTPU));
+                        code_file.write(reinterpret_cast<char *>(&u), sizeof(u));
+                      }
+                    for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
+                      {
+                        code_file.write(&FLDR, sizeof(FLDR));
+                        code_file.write(reinterpret_cast<char *>(&i), sizeof(i));
+                        code_file.write(&FLDZ, sizeof(FLDZ));
+                        int v=ModelBlock->Block_List[j].Equation[i];
+                        for (Uf[v].Ufl=Uf[v].Ufl_First;Uf[v].Ufl;Uf[v].Ufl=Uf[v].Ufl->pNext)
+                          {
+                            code_file.write(&FLDU, sizeof(FLDU));
+                            code_file.write(reinterpret_cast<char *>(&Uf[v].Ufl->u), sizeof(Uf[v].Ufl->u));
+                            code_file.write(&FLDV, sizeof(FLDV));
+                            char vc=eEndogenous;
+                            code_file.write(reinterpret_cast<char *>(&vc), sizeof(vc));
+                            code_file.write(reinterpret_cast<char *>(&Uf[v].Ufl->var), sizeof(Uf[v].Ufl->var));
+                            int v1=0;
+                            code_file.write(reinterpret_cast<char *>(&v1), sizeof(v1));
+                            code_file.write(&FBINARY, sizeof(FBINARY));
+                            v1=oTimes;
+                            code_file.write(reinterpret_cast<char *>(&v1), sizeof(v1));
+                            code_file.write(&FCUML, sizeof(FCUML));
+                          }
+                        Uf[v].Ufl=Uf[v].Ufl_First;
+                        while (Uf[v].Ufl)
+                          {
+                            Uf[v].Ufl_First=Uf[v].Ufl->pNext;
+                            free(Uf[v].Ufl);
+                            Uf[v].Ufl=Uf[v].Ufl_First;
+                          }
+                        code_file.write(&FBINARY, sizeof(FBINARY));
+                        v=oMinus;
+                        code_file.write(reinterpret_cast<char *>(&v), sizeof(v));
+                        code_file.write(&FSTPU, sizeof(FSTPU));
+                        code_file.write(reinterpret_cast<char *>(&i), sizeof(i));
+                      }
+                    break;
+                  case SOLVE_TWO_BOUNDARIES_COMPLETE:
+                  case SOLVE_TWO_BOUNDARIES_SIMPLE:
+                    for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
+                      {
+                        k=m-ModelBlock->Block_List[j].Max_Lag;
+                        for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
+                          {
+                            int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
+                            int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
+                            int u=ModelBlock->Block_List[j].IM_lead_lag[m].u[i];
+                            int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
+                            int v=ModelBlock->Block_List[j].Equation[eqr];
+                            if (!Uf[v].Ufl)
+                              {
+                                Uf[v].Ufl=(Uff_l*)malloc(sizeof(Uff_l));
+                                Uf[v].Ufl_First=Uf[v].Ufl;
+                              }
+                            else
+                              {
+                                Uf[v].Ufl->pNext=(Uff_l*)malloc(sizeof(Uff_l));
+                                Uf[v].Ufl=Uf[v].Ufl->pNext;
+                              }
+                            Uf[v].Ufl->pNext=NULL;
+                            Uf[v].Ufl->u=u;
+                            Uf[v].Ufl->var=var;
+                            Uf[v].Ufl->lag=k;
+                            compileDerivative(code_file, eq, var, k, output_type, map_idx);
+                            code_file.write(&FSTPU, sizeof(FSTPU));
+                            code_file.write(reinterpret_cast<char *>(&u), sizeof(u));
 #ifdef CONDITION
-                              output << "  if (fabs(condition[" << eqr << "])<fabs(u[" << u << "+Per_u_]))\n";
-                              output << "    condition[" << eqr << "]=u[" << u << "+Per_u_];\n";
+                            output << "  if (fabs(condition[" << eqr << "])<fabs(u[" << u << "+Per_u_]))\n";
+                            output << "    condition[" << eqr << "]=u[" << u << "+Per_u_];\n";
 #endif
-                            }
-                        }
-                      for(i = 0;i < ModelBlock->Block_List[j].Size;i++)
-                        {
-                          code_file.write(&FLDR, sizeof(FLDR));
-                          code_file.write(reinterpret_cast<char *>(&i), sizeof(i));
-                          code_file.write(&FLDZ, sizeof(FLDZ));
-                          int v=ModelBlock->Block_List[j].Equation[i];
-                          for(Uf[v].Ufl=Uf[v].Ufl_First;Uf[v].Ufl;Uf[v].Ufl=Uf[v].Ufl->pNext)
-                            {
-                              code_file.write(&FLDU, sizeof(FLDU));
-                              code_file.write(reinterpret_cast<char *>(&Uf[v].Ufl->u), sizeof(Uf[v].Ufl->u));
-                              code_file.write(&FLDV, sizeof(FLDV));
-                              char vc=eEndogenous;
-                              code_file.write(reinterpret_cast<char *>(&vc), sizeof(vc));
-                              int v1=Uf[v].Ufl->var;
-                              code_file.write(reinterpret_cast<char *>(&v1), sizeof(v1));
-                              v1=Uf[v].Ufl->lag;
-                              code_file.write(reinterpret_cast<char *>(&v1), sizeof(v1));
-                              code_file.write(&FBINARY, sizeof(FBINARY));
-                              v1=oTimes;
-                              code_file.write(reinterpret_cast<char *>(&v1), sizeof(v1));
-                              code_file.write(&FCUML, sizeof(FCUML));
-                            }
-                          Uf[v].Ufl=Uf[v].Ufl_First;
-                          while(Uf[v].Ufl)
-                            {
-                              Uf[v].Ufl_First=Uf[v].Ufl->pNext;
-                              free(Uf[v].Ufl);
-                              Uf[v].Ufl=Uf[v].Ufl_First;
-                            }
-                          code_file.write(&FBINARY, sizeof(FBINARY));
-                          v=oMinus;
-                          code_file.write(reinterpret_cast<char *>(&v), sizeof(v));
-                          code_file.write(&FSTPU, sizeof(FSTPU));
-                          code_file.write(reinterpret_cast<char *>(&i), sizeof(i));
+                          }
+                      }
+                    for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
+                      {
+                        code_file.write(&FLDR, sizeof(FLDR));
+                        code_file.write(reinterpret_cast<char *>(&i), sizeof(i));
+                        code_file.write(&FLDZ, sizeof(FLDZ));
+                        int v=ModelBlock->Block_List[j].Equation[i];
+                        for (Uf[v].Ufl=Uf[v].Ufl_First;Uf[v].Ufl;Uf[v].Ufl=Uf[v].Ufl->pNext)
+                          {
+                            code_file.write(&FLDU, sizeof(FLDU));
+                            code_file.write(reinterpret_cast<char *>(&Uf[v].Ufl->u), sizeof(Uf[v].Ufl->u));
+                            code_file.write(&FLDV, sizeof(FLDV));
+                            char vc=eEndogenous;
+                            code_file.write(reinterpret_cast<char *>(&vc), sizeof(vc));
+                            int v1=Uf[v].Ufl->var;
+                            code_file.write(reinterpret_cast<char *>(&v1), sizeof(v1));
+                            v1=Uf[v].Ufl->lag;
+                            code_file.write(reinterpret_cast<char *>(&v1), sizeof(v1));
+                            code_file.write(&FBINARY, sizeof(FBINARY));
+                            v1=oTimes;
+                            code_file.write(reinterpret_cast<char *>(&v1), sizeof(v1));
+                            code_file.write(&FCUML, sizeof(FCUML));
+                          }
+                        Uf[v].Ufl=Uf[v].Ufl_First;
+                        while (Uf[v].Ufl)
+                          {
+                            Uf[v].Ufl_First=Uf[v].Ufl->pNext;
+                            free(Uf[v].Ufl);
+                            Uf[v].Ufl=Uf[v].Ufl_First;
+                          }
+                        code_file.write(&FBINARY, sizeof(FBINARY));
+                        v=oMinus;
+                        code_file.write(reinterpret_cast<char *>(&v), sizeof(v));
+                        code_file.write(&FSTPU, sizeof(FSTPU));
+                        code_file.write(reinterpret_cast<char *>(&i), sizeof(i));
 #ifdef CONDITION
-                          output << "  if (fabs(condition[" << i << "])<fabs(u[" << i << "+Per_u_]))\n";
-                          output << "    condition[" << i << "]=u[" << i << "+Per_u_];\n";
+                        output << "  if (fabs(condition[" << i << "])<fabs(u[" << i << "+Per_u_]))\n";
+                        output << "    condition[" << i << "]=u[" << i << "+Per_u_];\n";
 #endif
-                        }
+                      }
 #ifdef CONDITION
-                      for(m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
-                        {
-                          k=m-ModelBlock->Block_List[j].Max_Lag;
-                          for(i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
-                            {
-                              int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
-                              int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
-                              int u=ModelBlock->Block_List[j].IM_lead_lag[m].u[i];
-                              int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
-                              output << "  u[" << u << "+Per_u_] /= condition[" << eqr << "];\n";
-                            }
-                        }
-                      for(i = 0;i < ModelBlock->Block_List[j].Size;i++)
-                        output << "  u[" << i << "+Per_u_] /= condition[" << i << "];\n";
+                    for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
+                      {
+                        k=m-ModelBlock->Block_List[j].Max_Lag;
+                        for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
+                          {
+                            int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
+                            int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
+                            int u=ModelBlock->Block_List[j].IM_lead_lag[m].u[i];
+                            int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
+                            output << "  u[" << u << "+Per_u_] /= condition[" << eqr << "];\n";
+                          }
+                      }
+                    for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
+                      output << "  u[" << i << "+Per_u_] /= condition[" << i << "];\n";
 #endif
-                      break;
-                    default:
-                      break;
+                    break;
+                  default:
+                    break;
                   }
 
                 prev_Simulation_Type=ModelBlock->Block_List[j].Simulation_Type;
@@ -1511,1483 +1488,1473 @@ ModelTree::writeModelEquationsCodeOrdered(const string file_name, const Model_Bl
 
 void
 ModelTree::writeStaticMFile(const string &static_basename) const
-{
-  string filename = static_basename + ".m";
+  {
+    string filename = static_basename + ".m";
 
-  ofstream mStaticModelFile;
-  mStaticModelFile.open(filename.c_str(), ios::out | ios::binary);
-  if (!mStaticModelFile.is_open())
-    {
-      cerr << "Error: Can't open file " << filename << " for writing" << endl;
-      exit(EXIT_FAILURE);
-    }
-  // Writing comments and function definition command
-  mStaticModelFile << "function [residual, g1, g2] = " << static_basename << "(y, x, params)" << endl
-                   << "%" << endl
-                   << "% Status : Computes static model for Dynare" << endl
-                   << "%" << endl
-                   << "% Warning : this file is generated automatically by Dynare" << endl
-                   << "%           from model file (.mod)" << endl << endl;
+    ofstream mStaticModelFile;
+    mStaticModelFile.open(filename.c_str(), ios::out | ios::binary);
+    if (!mStaticModelFile.is_open())
+      {
+        cerr << "Error: Can't open file " << filename << " for writing" << endl;
+        exit(EXIT_FAILURE);
+      }
+    // Writing comments and function definition command
+    mStaticModelFile << "function [residual, g1, g2] = " << static_basename << "(y, x, params)" << endl
+    << "%" << endl
+    << "% Status : Computes static model for Dynare" << endl
+    << "%" << endl
+    << "% Warning : this file is generated automatically by Dynare" << endl
+    << "%           from model file (.mod)" << endl << endl;
 
-  writeStaticModel(mStaticModelFile);
+    writeStaticModel(mStaticModelFile);
 
-  mStaticModelFile.close();
-}
+    mStaticModelFile.close();
+  }
 
 
 void
 ModelTree::writeDynamicMFile(const string &dynamic_basename) const
-{
-  string filename = dynamic_basename + ".m";
+  {
+    string filename = dynamic_basename + ".m";
 
-  ofstream mDynamicModelFile;
-  mDynamicModelFile.open(filename.c_str(), ios::out | ios::binary);
-  if (!mDynamicModelFile.is_open())
-    {
-      cerr << "Error: Can't open file " << filename << " for writing" << endl;
-      exit(EXIT_FAILURE);
-    }
-  mDynamicModelFile << "function [residual, g1, g2, g3] = " << dynamic_basename << "(y, x, params, it_)" << endl
-                    << "%" << endl
-                    << "% Status : Computes dynamic model for Dynare" << endl
-                    << "%" << endl
-                    << "% Warning : this file is generated automatically by Dynare" << endl
-                    << "%           from model file (.mod)" << endl << endl;
+    ofstream mDynamicModelFile;
+    mDynamicModelFile.open(filename.c_str(), ios::out | ios::binary);
+    if (!mDynamicModelFile.is_open())
+      {
+        cerr << "Error: Can't open file " << filename << " for writing" << endl;
+        exit(EXIT_FAILURE);
+      }
+    mDynamicModelFile << "function [residual, g1, g2, g3] = " << dynamic_basename << "(y, x, params, it_)" << endl
+    << "%" << endl
+    << "% Status : Computes dynamic model for Dynare" << endl
+    << "%" << endl
+    << "% Warning : this file is generated automatically by Dynare" << endl
+    << "%           from model file (.mod)" << endl << endl;
 
-  writeDynamicModel(mDynamicModelFile);
+    writeDynamicModel(mDynamicModelFile);
 
-  mDynamicModelFile.close();
-}
+    mDynamicModelFile.close();
+  }
 
 void
 ModelTree::writeStaticCFile(const string &static_basename) const
-{
-  string filename = static_basename + ".c";
+  {
+    string filename = static_basename + ".c";
 
-  ofstream mStaticModelFile;
-  mStaticModelFile.open(filename.c_str(), ios::out | ios::binary);
-  if (!mStaticModelFile.is_open())
-    {
-      cerr << "Error: Can't open file " << filename << " for writing" << endl;
-      exit(EXIT_FAILURE);
-    }
-  mStaticModelFile << "/*" << endl
-                   << " * " << filename << " : Computes static model for Dynare" << endl
-                   << " * Warning : this file is generated automatically by Dynare" << endl
-                   << " *           from model file (.mod)" << endl
-                   << endl
-                   << " */" << endl
-                   << "#include <math.h>" << endl
-                   << "#include \"mex.h\"" << endl;
-
-  // Writing the function Static
-  writeStaticModel(mStaticModelFile);
-
-  // Writing the gateway routine
-  mStaticModelFile << "/* The gateway routine */" << endl
-                   << "void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])" << endl
-                   << "{" << endl
-                   << "  double *y, *x, *params;" << endl
-                   << "  double *residual, *g1;" << endl
-                   << endl
-                   << "  /* Create a pointer to the input matrix y. */" << endl
-                   << "  y = mxGetPr(prhs[0]);" << endl
-                   << endl
-                   << "  /* Create a pointer to the input matrix x. */" << endl
-                   << "  x = mxGetPr(prhs[1]);" << endl
-                   << endl
-                   << "  /* Create a pointer to the input matrix params. */" << endl
-                   << "  params = mxGetPr(prhs[2]);" << endl
-                   << endl
-                   << "  residual = NULL;" << endl
-                   << "  if (nlhs >= 1)" << endl
-                   << "  {" << endl
-                   << "      /* Set the output pointer to the output matrix residual. */" << endl
-                   << "      plhs[0] = mxCreateDoubleMatrix(" << equations.size() << ",1, mxREAL);" << endl
-                   << "     /* Create a C pointer to a copy of the output matrix residual. */" << endl
-                   << "     residual = mxGetPr(plhs[0]);" << endl
-                   << "  }" << endl
-                   << endl
-                   << "  g1 = NULL;" << endl
-                   << "  if (nlhs >= 2)" << endl
-                   << "  {" << endl
-                   << "      /* Set the output pointer to the output matrix g1. */" << endl
-                   << "      plhs[1] = mxCreateDoubleMatrix(" << equations.size() << ", " << symbol_table.endo_nbr << ", mxREAL);" << endl
-                   << "      /* Create a C pointer to a copy of the output matrix g1. */" << endl
-                   << "      g1 = mxGetPr(plhs[1]);" << endl
-                   << "  }" << endl
-                   << endl
-                   << "  /* Call the C Static. */" << endl
-                   << "  Static(y, x, params, residual, g1);" << endl
-                   << "}" << endl;
-
-  mStaticModelFile.close();
-}
+    ofstream mStaticModelFile;
+    mStaticModelFile.open(filename.c_str(), ios::out | ios::binary);
+    if (!mStaticModelFile.is_open())
+      {
+        cerr << "Error: Can't open file " << filename << " for writing" << endl;
+        exit(EXIT_FAILURE);
+      }
+    mStaticModelFile << "/*" << endl
+    << " * " << filename << " : Computes static model for Dynare" << endl
+    << " * Warning : this file is generated automatically by Dynare" << endl
+    << " *           from model file (.mod)" << endl
+    << endl
+    << " */" << endl
+    << "#include <math.h>" << endl
+    << "#include \"mex.h\"" << endl;
+
+    // Writing the function Static
+    writeStaticModel(mStaticModelFile);
+
+    // Writing the gateway routine
+    mStaticModelFile << "/* The gateway routine */" << endl
+    << "void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])" << endl
+    << "{" << endl
+    << "  double *y, *x, *params;" << endl
+    << "  double *residual, *g1;" << endl
+    << endl
+    << "  /* Create a pointer to the input matrix y. */" << endl
+    << "  y = mxGetPr(prhs[0]);" << endl
+    << endl
+    << "  /* Create a pointer to the input matrix x. */" << endl
+    << "  x = mxGetPr(prhs[1]);" << endl
+    << endl
+    << "  /* Create a pointer to the input matrix params. */" << endl
+    << "  params = mxGetPr(prhs[2]);" << endl
+    << endl
+    << "  residual = NULL;" << endl
+    << "  if (nlhs >= 1)" << endl
+    << "  {" << endl
+    << "      /* Set the output pointer to the output matrix residual. */" << endl
+    << "      plhs[0] = mxCreateDoubleMatrix(" << equations.size() << ",1, mxREAL);" << endl
+    << "     /* Create a C pointer to a copy of the output matrix residual. */" << endl
+    << "     residual = mxGetPr(plhs[0]);" << endl
+    << "  }" << endl
+    << endl
+    << "  g1 = NULL;" << endl
+    << "  if (nlhs >= 2)" << endl
+    << "  {" << endl
+    << "      /* Set the output pointer to the output matrix g1. */" << endl
+    << "      plhs[1] = mxCreateDoubleMatrix(" << equations.size() << ", " << symbol_table.endo_nbr << ", mxREAL);" << endl
+    << "      /* Create a C pointer to a copy of the output matrix g1. */" << endl
+    << "      g1 = mxGetPr(plhs[1]);" << endl
+    << "  }" << endl
+    << endl
+    << "  /* Call the C Static. */" << endl
+    << "  Static(y, x, params, residual, g1);" << endl
+    << "}" << endl;
+
+    mStaticModelFile.close();
+  }
 
 void
 ModelTree::writeDynamicCFile(const string &dynamic_basename) const
-{
-  string filename = dynamic_basename + ".c";
-  ofstream mDynamicModelFile;
+  {
+    string filename = dynamic_basename + ".c";
+    ofstream mDynamicModelFile;
 
-  mDynamicModelFile.open(filename.c_str(), ios::out | ios::binary);
-  if (!mDynamicModelFile.is_open())
-    {
-      cerr << "Error: Can't open file " << filename << " for writing" << endl;
-      exit(EXIT_FAILURE);
-    }
-  mDynamicModelFile << "/*" << endl
-                    << " * " << filename << " : Computes dynamic model for Dynare" << endl
-                    << " *" << endl
-                    << " * Warning : this file is generated automatically by Dynare" << endl
-                    << " *           from model file (.mod)" << endl
-                    << endl
-                    << " */" << endl
-                    << "#include <math.h>" << endl
-                    << "#include \"mex.h\"" << endl;
-
-  // Writing the function body
-  writeDynamicModel(mDynamicModelFile);
-
-  // Writing the gateway routine
-  mDynamicModelFile << "/* The gateway routine */" << endl
-                    << "void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])" << endl
-                    << "{" << endl
-                    << "  double *y, *x, *params;" << endl
-                    << "  double *residual, *g1, *g2;" << endl
-                    << "  int nb_row_x, it_;" << endl
-                    << endl
-                    << "  /* Create a pointer to the input matrix y. */" << endl
-                    << "  y = mxGetPr(prhs[0]);" << endl
-                    << endl
-                    << "  /* Create a pointer to the input matrix x. */" << endl
-                    << "  x = mxGetPr(prhs[1]);" << endl
-                    << endl
-                    << "  /* Create a pointer to the input matrix params. */" << endl
-                    << "  params = mxGetPr(prhs[2]);" << endl
-                    << endl
-                    << "  /* Fetch time index */" << endl
-                    << "  it_ = (int) mxGetScalar(prhs[3]) - 1;" << endl
-                    << endl
-                    << "  /* Gets number of rows of matrix x. */" << endl
-                    << "  nb_row_x = mxGetM(prhs[1]);" << endl
-                    << endl
-                    << "  residual = NULL;" << endl
-                    << "  if (nlhs >= 1)" << endl
-                    << "  {" << endl
-                    << "     /* Set the output pointer to the output matrix residual. */" << endl
-                    << "     plhs[0] = mxCreateDoubleMatrix(" << equations.size() << ",1, mxREAL);" << endl
-                    << "     /* Create a C pointer to a copy of the output matrix residual. */" << endl
-                    << "     residual = mxGetPr(plhs[0]);" << endl
-                    << "  }" << endl
-                    << endl
-                    << "  g1 = NULL;" << endl
-                    << "  if (nlhs >= 2)" << endl
-                    << "  {" << endl
-                    << "     /* Set the output pointer to the output matrix g1. */" << endl
-
-                    << "     plhs[1] = mxCreateDoubleMatrix(" << equations.size() << ", " << variable_table.getDynJacobianColsNbr(computeJacobianExo) << ", mxREAL);" << endl
-                    << "     /* Create a C pointer to a copy of the output matrix g1. */" << endl
-                    << "     g1 = mxGetPr(plhs[1]);" << endl
-                    << "  }" << endl
-                    << endl
-                    << "  g2 = NULL;" << endl
-                    << " if (nlhs >= 3)" << endl
-                    << "  {" << endl
-                    << "     /* Set the output pointer to the output matrix g2. */" << endl
-                    << "     plhs[2] = mxCreateDoubleMatrix(" << equations.size() << ", " << variable_table.getDynJacobianColsNbr(computeJacobianExo)*variable_table.getDynJacobianColsNbr(computeJacobianExo) << ", mxREAL);" << endl
-                    << "     /* Create a C pointer to a copy of the output matrix g1. */" << endl
-                    << "     g2 = mxGetPr(plhs[2]);" << endl
-                    << "  }" << endl
-                    << endl
-                    << "  /* Call the C subroutines. */" << endl
-                    << "  Dynamic(y, x, nb_row_x, params, it_, residual, g1, g2);" << endl
-                    << "}" << endl;
-  mDynamicModelFile.close();
-}
+    mDynamicModelFile.open(filename.c_str(), ios::out | ios::binary);
+    if (!mDynamicModelFile.is_open())
+      {
+        cerr << "Error: Can't open file " << filename << " for writing" << endl;
+        exit(EXIT_FAILURE);
+      }
+    mDynamicModelFile << "/*" << endl
+    << " * " << filename << " : Computes dynamic model for Dynare" << endl
+    << " *" << endl
+    << " * Warning : this file is generated automatically by Dynare" << endl
+    << " *           from model file (.mod)" << endl
+    << endl
+    << " */" << endl
+    << "#include <math.h>" << endl
+    << "#include \"mex.h\"" << endl;
+
+    // Writing the function body
+    writeDynamicModel(mDynamicModelFile);
+
+    // Writing the gateway routine
+    mDynamicModelFile << "/* The gateway routine */" << endl
+    << "void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])" << endl
+    << "{" << endl
+    << "  double *y, *x, *params;" << endl
+    << "  double *residual, *g1, *g2;" << endl
+    << "  int nb_row_x, it_;" << endl
+    << endl
+    << "  /* Create a pointer to the input matrix y. */" << endl
+    << "  y = mxGetPr(prhs[0]);" << endl
+    << endl
+    << "  /* Create a pointer to the input matrix x. */" << endl
+    << "  x = mxGetPr(prhs[1]);" << endl
+    << endl
+    << "  /* Create a pointer to the input matrix params. */" << endl
+    << "  params = mxGetPr(prhs[2]);" << endl
+    << endl
+    << "  /* Fetch time index */" << endl
+    << "  it_ = (int) mxGetScalar(prhs[3]) - 1;" << endl
+    << endl
+    << "  /* Gets number of rows of matrix x. */" << endl
+    << "  nb_row_x = mxGetM(prhs[1]);" << endl
+    << endl
+    << "  residual = NULL;" << endl
+    << "  if (nlhs >= 1)" << endl
+    << "  {" << endl
+    << "     /* Set the output pointer to the output matrix residual. */" << endl
+    << "     plhs[0] = mxCreateDoubleMatrix(" << equations.size() << ",1, mxREAL);" << endl
+    << "     /* Create a C pointer to a copy of the output matrix residual. */" << endl
+    << "     residual = mxGetPr(plhs[0]);" << endl
+    << "  }" << endl
+    << endl
+    << "  g1 = NULL;" << endl
+    << "  if (nlhs >= 2)" << endl
+    << "  {" << endl
+    << "     /* Set the output pointer to the output matrix g1. */" << endl
+
+    << "     plhs[1] = mxCreateDoubleMatrix(" << equations.size() << ", " << variable_table.getDynJacobianColsNbr(computeJacobianExo) << ", mxREAL);" << endl
+    << "     /* Create a C pointer to a copy of the output matrix g1. */" << endl
+    << "     g1 = mxGetPr(plhs[1]);" << endl
+    << "  }" << endl
+    << endl
+    << "  g2 = NULL;" << endl
+    << " if (nlhs >= 3)" << endl
+    << "  {" << endl
+    << "     /* Set the output pointer to the output matrix g2. */" << endl
+    << "     plhs[2] = mxCreateDoubleMatrix(" << equations.size() << ", " << variable_table.getDynJacobianColsNbr(computeJacobianExo)*variable_table.getDynJacobianColsNbr(computeJacobianExo) << ", mxREAL);" << endl
+    << "     /* Create a C pointer to a copy of the output matrix g1. */" << endl
+    << "     g2 = mxGetPr(plhs[2]);" << endl
+    << "  }" << endl
+    << endl
+    << "  /* Call the C subroutines. */" << endl
+    << "  Dynamic(y, x, nb_row_x, params, it_, residual, g1, g2);" << endl
+    << "}" << endl;
+    mDynamicModelFile.close();
+  }
 
 void
 ModelTree::writeStaticModel(ostream &StaticOutput) const
-{
-  ostringstream model_output;    // Used for storing model equations
-  ostringstream jacobian_output; // Used for storing jacobian equations
-  ostringstream hessian_output;
-  ostringstream lsymetric;       // For symmetric elements in hessian
-
-  ExprNodeOutputType output_type = (mode == eDLLMode ? oCStaticModel : oMatlabStaticModel);
-
-  writeModelLocalVariables(model_output, output_type);
+  {
+    ostringstream model_output;    // Used for storing model equations
+    ostringstream jacobian_output; // Used for storing jacobian equations
+    ostringstream hessian_output;
+    ostringstream lsymetric;       // For symmetric elements in hessian
 
-  writeTemporaryTerms(model_output, output_type);
+    ExprNodeOutputType output_type = (mode == eDLLMode ? oCStaticModel : oMatlabStaticModel);
 
-  writeModelEquations(model_output, output_type);
+    writeModelLocalVariables(model_output, output_type);
 
-  // Write Jacobian w.r. to endogenous only
-  for(first_derivatives_type::const_iterator it = first_derivatives.begin();
-      it != first_derivatives.end(); it++)
-    {
-      int eq = it->first.first;
-      int var = it->first.second;
-      NodeID d1 = it->second;
+    writeTemporaryTerms(model_output, output_type);
 
-      if (variable_table.getType(var) == eEndogenous)
-        {
-          ostringstream g1;
-          g1 << "  g1";
-          matrixHelper(g1, eq, variable_table.getSymbolID(var), output_type);
+    writeModelEquations(model_output, output_type);
 
-          jacobian_output << g1.str() << "=" << g1.str() << "+";
-          d1->writeOutput(jacobian_output, output_type, temporary_terms);
-          jacobian_output << ";" << endl;
-        }
-    }
-
-  // Write Hessian w.r. to endogenous only
-  if (computeStaticHessian)
-    for(second_derivatives_type::const_iterator it = second_derivatives.begin();
-        it != second_derivatives.end(); it++)
+    // Write Jacobian w.r. to endogenous only
+    for (first_derivatives_type::const_iterator it = first_derivatives.begin();
+         it != first_derivatives.end(); it++)
       {
         int eq = it->first.first;
-        int var1 = it->first.second.first;
-        int var2 = it->first.second.second;
-        NodeID d2 = it->second;
+        int var = it->first.second;
+        NodeID d1 = it->second;
 
-        // Keep only derivatives w.r. to endogenous variables
-        if (variable_table.getType(var1) == eEndogenous
-            && variable_table.getType(var2) == eEndogenous)
+        if (variable_table.getType(var) == eEndogenous)
           {
-            int id1 = variable_table.getSymbolID(var1);
-            int id2 = variable_table.getSymbolID(var2);
-
-            int col_nb = id1*symbol_table.endo_nbr+id2;
-            int col_nb_sym = id2*symbol_table.endo_nbr+id1;
-
-            hessian_output << "  g2";
-            matrixHelper(hessian_output, eq, col_nb, output_type);
-            hessian_output << " = ";
-            d2->writeOutput(hessian_output, output_type, temporary_terms);
-            hessian_output << ";" << endl;
+            ostringstream g1;
+            g1 << "  g1";
+            matrixHelper(g1, eq, variable_table.getSymbolID(var), output_type);
 
-            // Treating symetric elements
-            if (var1 != var2)
-              {
-                lsymetric <<  "  g2";
-                matrixHelper(lsymetric, eq, col_nb_sym, output_type);
-                lsymetric << " = " <<  "g2";
-                matrixHelper(lsymetric, eq, col_nb, output_type);
-                lsymetric << ";" << endl;
-              }
+            jacobian_output << g1.str() << "=" << g1.str() << "+";
+            d1->writeOutput(jacobian_output, output_type, temporary_terms);
+            jacobian_output << ";" << endl;
           }
       }
 
-  // Writing ouputs
-  if (mode != eDLLMode)
-    {
-      StaticOutput << "residual = zeros( " << equations.size() << ", 1);" << endl << endl
-                   << "%" << endl
-                   << "% Model equations" << endl
-                   << "%" << endl
-                   << endl
-                   << model_output.str()
-                   << "if ~isreal(residual)" << endl
-                   << "  residual = real(residual)+imag(residual).^2;" << endl
-                   << "end" << endl
-                   << "if nargout >= 2," << endl
-                   << "  g1 = zeros(" << equations.size() << ", " << symbol_table.endo_nbr << ");" << endl
-                   << endl
-                   << "%" << endl
-                   << "% Jacobian matrix" << endl
-                   << "%" << endl
-                   << endl
-                   << jacobian_output.str()
-                   << "  if ~isreal(g1)" << endl
-                   << "    g1 = real(g1)+2*imag(g1);" << endl
-                   << "  end" << endl
-                   << "end" << endl;
-      if (computeStaticHessian)
+    // Write Hessian w.r. to endogenous only
+    if (computeStaticHessian)
+      for (second_derivatives_type::const_iterator it = second_derivatives.begin();
+           it != second_derivatives.end(); it++)
         {
-          StaticOutput << "if nargout >= 3,\n";
-          // Writing initialization instruction for matrix g2
-          int ncols = symbol_table.endo_nbr * symbol_table.endo_nbr;
-          StaticOutput << "  g2 = sparse([],[],[], " << equations.size() << ", " << ncols << ", " << 5*ncols << ");" << endl
-                       << endl
-                       << "%" << endl
-                       << "% Hessian matrix" << endl
-                       << "%" << endl
-                       << endl
-                       << hessian_output.str()
-                       << lsymetric.str()
-                       << "end;" << endl;
+          int eq = it->first.first;
+          int var1 = it->first.second.first;
+          int var2 = it->first.second.second;
+          NodeID d2 = it->second;
+
+          // Keep only derivatives w.r. to endogenous variables
+          if (variable_table.getType(var1) == eEndogenous
+              && variable_table.getType(var2) == eEndogenous)
+            {
+              int id1 = variable_table.getSymbolID(var1);
+              int id2 = variable_table.getSymbolID(var2);
+
+              int col_nb = id1*symbol_table.endo_nbr+id2;
+              int col_nb_sym = id2*symbol_table.endo_nbr+id1;
+
+              hessian_output << "  g2";
+              matrixHelper(hessian_output, eq, col_nb, output_type);
+              hessian_output << " = ";
+              d2->writeOutput(hessian_output, output_type, temporary_terms);
+              hessian_output << ";" << endl;
+
+              // Treating symetric elements
+              if (var1 != var2)
+                {
+                  lsymetric <<  "  g2";
+                  matrixHelper(lsymetric, eq, col_nb_sym, output_type);
+                  lsymetric << " = " <<  "g2";
+                  matrixHelper(lsymetric, eq, col_nb, output_type);
+                  lsymetric << ";" << endl;
+                }
+            }
         }
-    }
-  else
-    {
-      StaticOutput << "void Static(double *y, double *x, double *params, double *residual, double *g1)" << endl
-                   << "{" << endl
-                   << "  double lhs, rhs;" << endl
+
+    // Writing ouputs
+    if (mode != eDLLMode)
+      {
+        StaticOutput << "residual = zeros( " << equations.size() << ", 1);" << endl << endl
+        << "%" << endl
+        << "% Model equations" << endl
+        << "%" << endl
+        << endl
+        << model_output.str()
+        << "if ~isreal(residual)" << endl
+        << "  residual = real(residual)+imag(residual).^2;" << endl
+        << "end" << endl
+        << "if nargout >= 2," << endl
+        << "  g1 = zeros(" << equations.size() << ", " << symbol_table.endo_nbr << ");" << endl
+        << endl
+        << "%" << endl
+        << "% Jacobian matrix" << endl
+        << "%" << endl
+        << endl
+        << jacobian_output.str()
+        << "  if ~isreal(g1)" << endl
+        << "    g1 = real(g1)+2*imag(g1);" << endl
+        << "  end" << endl
+        << "end" << endl;
+        if (computeStaticHessian)
+          {
+            StaticOutput << "if nargout >= 3,\n";
+            // Writing initialization instruction for matrix g2
+            int ncols = symbol_table.endo_nbr * symbol_table.endo_nbr;
+            StaticOutput << "  g2 = sparse([],[],[], " << equations.size() << ", " << ncols << ", " << 5*ncols << ");" << endl
+            << endl
+            << "%" << endl
+            << "% Hessian matrix" << endl
+            << "%" << endl
+            << endl
+            << hessian_output.str()
+            << lsymetric.str()
+            << "end;" << endl;
+          }
+      }
+    else
+      {
+        StaticOutput << "void Static(double *y, double *x, double *params, double *residual, double *g1)" << endl
+        << "{" << endl
+        << "  double lhs, rhs;" << endl
         // Writing residual equations
-                   << "  /* Residual equations */" << endl
-                   << "  if (residual == NULL)" << endl
-                   << "    return;" << endl
-                   << "  else" << endl
-                   << "    {" << endl
-                   << model_output.str()
+        << "  /* Residual equations */" << endl
+        << "  if (residual == NULL)" << endl
+        << "    return;" << endl
+        << "  else" << endl
+        << "    {" << endl
+        << model_output.str()
         // Writing Jacobian
-                   << "     /* Jacobian for endogenous variables without lag */" << endl
-                   << "     if (g1 == NULL)" << endl
-                   << "       return;" << endl
-                   << "     else" << endl
-                   << "       {" << endl
-                   << jacobian_output.str()
-                   << "       }" << endl
-                   << "    }" << endl
-                   << "}" << endl << endl;
-    }
-}
+        << "     /* Jacobian for endogenous variables without lag */" << endl
+        << "     if (g1 == NULL)" << endl
+        << "       return;" << endl
+        << "     else" << endl
+        << "       {" << endl
+        << jacobian_output.str()
+        << "       }" << endl
+        << "    }" << endl
+        << "}" << endl << endl;
+      }
+  }
 
 string
 ModelTree::reform(const string name1) const
-{
-  string name=name1;
-  int pos = name.find("\\", 0);
-  while(pos >= 0)
-    {
-      if (name.substr(pos + 1, 1) != "\\")
-        {
-          name = name.insert(pos, "\\");
-          pos++;
-        }
-      pos++;
-      pos = name.find("\\", pos);
-    }
-  return (name);
-}
+  {
+    string name=name1;
+    int pos = name.find("\\", 0);
+    while (pos >= 0)
+      {
+        if (name.substr(pos + 1, 1) != "\\")
+          {
+            name = name.insert(pos, "\\");
+            pos++;
+          }
+        pos++;
+        pos = name.find("\\", pos);
+      }
+    return (name);
+  }
 
 void
 ModelTree::Write_Inf_To_Bin_File(const string &dynamic_basename, const string &bin_basename, const int &num,
                                  int &u_count_int, bool &file_open) const
-{
-  int j;
-  std::ofstream SaveCode;
-  if (file_open)
-    SaveCode.open((bin_basename + ".bin").c_str(), ios::out | ios::in | ios::binary | ios ::ate );
-  else
-    SaveCode.open((bin_basename + ".bin").c_str(), ios::out | ios::binary);
-  if (!SaveCode.is_open())
-    {
-      cout << "Error : Can't open file \"" << bin_basename << ".bin\" for writing\n";
-      exit(EXIT_FAILURE);
-    }
-  u_count_int=0;
-  for(int m=0;m<=block_triangular.ModelBlock->Block_List[num].Max_Lead+block_triangular.ModelBlock->Block_List[num].Max_Lag;m++)
-    {
-      int k1=m-block_triangular.ModelBlock->Block_List[num].Max_Lag;
-      for(j=0;j<block_triangular.ModelBlock->Block_List[num].IM_lead_lag[m].size;j++)
-        {
-          int varr=block_triangular.ModelBlock->Block_List[num].IM_lead_lag[m].Var[j]+k1*block_triangular.ModelBlock->Block_List[num].Size;
-          int u=block_triangular.ModelBlock->Block_List[num].IM_lead_lag[m].u[j];
-          int eqr1=block_triangular.ModelBlock->Block_List[num].IM_lead_lag[m].Equ[j];
-          SaveCode.write(reinterpret_cast<char *>(&eqr1), sizeof(eqr1));
-          SaveCode.write(reinterpret_cast<char *>(&varr), sizeof(varr));
-          SaveCode.write(reinterpret_cast<char *>(&k1), sizeof(k1));
-          SaveCode.write(reinterpret_cast<char *>(&u), sizeof(u));
-          u_count_int++;
-        }
-    }
-  for(j=0;j<block_triangular.ModelBlock->Block_List[num].Size;j++)
-    {
-       int eqr1=j;
-       int varr=block_triangular.ModelBlock->Block_List[num].Size*(block_triangular.periods
-                                                                   +block_triangular.incidencematrix.Model_Max_Lead_Endo);
-       int k1=0;
-       SaveCode.write(reinterpret_cast<char *>(&eqr1), sizeof(eqr1));
-       SaveCode.write(reinterpret_cast<char *>(&varr), sizeof(varr));
-       SaveCode.write(reinterpret_cast<char *>(&k1), sizeof(k1));
-       SaveCode.write(reinterpret_cast<char *>(&eqr1), sizeof(eqr1));
-       u_count_int++;
-    }
+  {
+    int j;
+    std::ofstream SaveCode;
+    if (file_open)
+      SaveCode.open((bin_basename + ".bin").c_str(), ios::out | ios::in | ios::binary | ios ::ate );
+    else
+      SaveCode.open((bin_basename + ".bin").c_str(), ios::out | ios::binary);
+    if (!SaveCode.is_open())
+      {
+        cout << "Error : Can't open file \"" << bin_basename << ".bin\" for writing\n";
+        exit(EXIT_FAILURE);
+      }
+    u_count_int=0;
+    for (int m=0;m<=block_triangular.ModelBlock->Block_List[num].Max_Lead+block_triangular.ModelBlock->Block_List[num].Max_Lag;m++)
+      {
+        int k1=m-block_triangular.ModelBlock->Block_List[num].Max_Lag;
+        for (j=0;j<block_triangular.ModelBlock->Block_List[num].IM_lead_lag[m].size;j++)
+          {
+            int varr=block_triangular.ModelBlock->Block_List[num].IM_lead_lag[m].Var[j]+k1*block_triangular.ModelBlock->Block_List[num].Size;
+            int u=block_triangular.ModelBlock->Block_List[num].IM_lead_lag[m].u[j];
+            int eqr1=block_triangular.ModelBlock->Block_List[num].IM_lead_lag[m].Equ[j];
+            SaveCode.write(reinterpret_cast<char *>(&eqr1), sizeof(eqr1));
+            SaveCode.write(reinterpret_cast<char *>(&varr), sizeof(varr));
+            SaveCode.write(reinterpret_cast<char *>(&k1), sizeof(k1));
+            SaveCode.write(reinterpret_cast<char *>(&u), sizeof(u));
+            u_count_int++;
+          }
+      }
+    for (j=0;j<block_triangular.ModelBlock->Block_List[num].Size;j++)
+      {
+        int eqr1=j;
+        int varr=block_triangular.ModelBlock->Block_List[num].Size*(block_triangular.periods
+                 +block_triangular.incidencematrix.Model_Max_Lead_Endo);
+        int k1=0;
+        SaveCode.write(reinterpret_cast<char *>(&eqr1), sizeof(eqr1));
+        SaveCode.write(reinterpret_cast<char *>(&varr), sizeof(varr));
+        SaveCode.write(reinterpret_cast<char *>(&k1), sizeof(k1));
+        SaveCode.write(reinterpret_cast<char *>(&eqr1), sizeof(eqr1));
+        u_count_int++;
+      }
 
-  for(j=0;j<block_triangular.ModelBlock->Block_List[num].Size;j++)
-    {
-      int varr=block_triangular.ModelBlock->Block_List[num].Variable[j];
-      SaveCode.write(reinterpret_cast<char *>(&varr), sizeof(varr));
-    }
-  for(j=0;j<block_triangular.ModelBlock->Block_List[num].Size;j++)
-    {
-      int eqr1=block_triangular.ModelBlock->Block_List[num].Equation[j];
-      SaveCode.write(reinterpret_cast<char *>(&eqr1), sizeof(eqr1));
-    }
-  SaveCode.close();
-}
+    for (j=0;j<block_triangular.ModelBlock->Block_List[num].Size;j++)
+      {
+        int varr=block_triangular.ModelBlock->Block_List[num].Variable[j];
+        SaveCode.write(reinterpret_cast<char *>(&varr), sizeof(varr));
+      }
+    for (j=0;j<block_triangular.ModelBlock->Block_List[num].Size;j++)
+      {
+        int eqr1=block_triangular.ModelBlock->Block_List[num].Equation[j];
+        SaveCode.write(reinterpret_cast<char *>(&eqr1), sizeof(eqr1));
+      }
+    SaveCode.close();
+  }
 
 void
 ModelTree::writeSparseStaticMFile(const string &static_basename, const string &basename, const int mode) const
-{
-  string filename;
-  ofstream mStaticModelFile;
-  ostringstream tmp, tmp1, tmp_eq;
-  int i, k, prev_Simulation_Type, ga_index = 1;
-  bool skip_head, open_par=false;
-
-  chdir(basename.c_str());
-  filename = static_basename + ".m";
-  mStaticModelFile.open(filename.c_str(), ios::out | ios::binary);
-  if (!mStaticModelFile.is_open())
-    {
-      cerr << "Error: Can't open file " << filename << " for writing" << endl;
-      exit(EXIT_FAILURE);
-    }
-  mStaticModelFile << "%\n";
-  mStaticModelFile << "% " << filename << " : Computes static model for Dynare\n";
-  mStaticModelFile << "%\n";
-  mStaticModelFile << "% Warning : this file is generated automatically by Dynare\n";
-  mStaticModelFile << "%           from model file (.mod)\n\n";
-  mStaticModelFile << "%/\n";
-  mStaticModelFile << "function [varargout] = " << static_basename << "(varargin)\n";
-  mStaticModelFile << "  global oo_ M_ options_ ys0_ ;\n";
-  bool OK=true;
-  ostringstream tmp_output;
-  for(temporary_terms_type::const_iterator it = temporary_terms.begin();
-      it != temporary_terms.end(); it++)
-    {
-      if (OK)
-        OK=false;
-      else
-        tmp_output << " ";
-      (*it)->writeOutput(tmp_output, oMatlabDynamicModel, temporary_terms);
-    }
-  if (tmp_output.str().length()>0)
-    mStaticModelFile << "  global " << tmp_output.str() << " M_ ;\n";
-  mStaticModelFile << "  T_init=0;\n";
-  tmp_output.str("");
-  for(temporary_terms_type::const_iterator it = temporary_terms.begin();
-      it != temporary_terms.end(); it++)
-    {
-      tmp_output << "  ";
-      (*it)->writeOutput(tmp_output, oMatlabDynamicModel, temporary_terms);
-      tmp_output << "=T_init;\n";
-    }
-  if (tmp_output.str().length()>0)
-    mStaticModelFile << tmp_output.str();
-
-  mStaticModelFile << "  y_kmin=M_.maximum_lag;\n";
-  mStaticModelFile << "  y_kmax=M_.maximum_lead;\n";
-  mStaticModelFile << "  y_size=M_.endo_nbr;\n";
-
-  /*tmp_output.str("");
-  writeModelLocalVariables(tmp_output, oMatlabDynamicModel);
-  if (tmp_output.str().length()>0)
-    mStaticModelFile << tmp_output.str() << "\n";*/
-
-
-  mStaticModelFile << "  if(length(varargin)>0)\n";
-  mStaticModelFile << "    %A simple evaluation of the static model\n";
-  //mStaticModelFile << "    global it_;\n";
-  mStaticModelFile << "    y=varargin{1}(:);\n";
-  mStaticModelFile << "    ys=y;\n";
-  mStaticModelFile << "    g1=[];\n";
-  mStaticModelFile << "    x=varargin{2}(:);\n";
-  mStaticModelFile << "    params=varargin{3}(:);\n";
-  mStaticModelFile << "    residual=zeros(1, " << symbol_table.endo_nbr << ");\n";
-  prev_Simulation_Type=-1;
-  tmp.str("");
-  tmp_eq.str("");
-  for(i=0;i<block_triangular.ModelBlock->Size;i++)
-    {
-      k=block_triangular.ModelBlock->Block_List[i].Simulation_Type;
-      if ((BlockTriangular::BlockSim(prev_Simulation_Type)!=BlockTriangular::BlockSim(k))  &&
-         ((prev_Simulation_Type==EVALUATE_FORWARD || prev_Simulation_Type==EVALUATE_BACKWARD || prev_Simulation_Type==EVALUATE_FORWARD_R || prev_Simulation_Type==EVALUATE_BACKWARD_R)
-      || (k==EVALUATE_FORWARD || k==EVALUATE_BACKWARD || k==EVALUATE_FORWARD_R || k==EVALUATE_BACKWARD_R)))
-        {
-          mStaticModelFile << "    y_index_eq=[" << tmp_eq.str() << "];\n";
-          tmp_eq.str("");
-          mStaticModelFile << "    y_index=[" << tmp.str() << "];\n";
-          tmp.str("");
-          mStaticModelFile << tmp1.str();
-          tmp1.str("");
-        }
-      for(int ik=0;ik<block_triangular.ModelBlock->Block_List[i].Size;ik++)
-        {
-          tmp << " " << block_triangular.ModelBlock->Block_List[i].Variable[ik]+1;
-          tmp_eq << " " << block_triangular.ModelBlock->Block_List[i].Equation[ik]+1;
-        }
-      if(k==EVALUATE_FORWARD || k==EVALUATE_BACKWARD || k==EVALUATE_FORWARD_R || k==EVALUATE_BACKWARD_R)
-        {
-          if(i==block_triangular.ModelBlock->Size-1)
-            {
-              mStaticModelFile << "    y_index_eq=[" << tmp_eq.str() << "];\n";
-              tmp_eq.str("");
-              mStaticModelFile << "    y_index=[" << tmp.str() << "];\n";
-              tmp.str("");
-              mStaticModelFile << tmp1.str();
-              tmp1.str("");
-            }
-         }
-
-      if (BlockTriangular::BlockSim(prev_Simulation_Type)==BlockTriangular::BlockSim(k) &&
-              (k==EVALUATE_FORWARD || k==EVALUATE_BACKWARD || k==EVALUATE_FORWARD_R || k==EVALUATE_BACKWARD_R))
-            skip_head=true;
-          else
-            skip_head=false;
+  {
+    string filename;
+    ofstream mStaticModelFile;
+    ostringstream tmp, tmp1, tmp_eq;
+    int i, k, prev_Simulation_Type, ga_index = 1;
+    bool skip_head, open_par=false;
+
+    chdir(basename.c_str());
+    filename = static_basename + ".m";
+    mStaticModelFile.open(filename.c_str(), ios::out | ios::binary);
+    if (!mStaticModelFile.is_open())
+      {
+        cerr << "Error: Can't open file " << filename << " for writing" << endl;
+        exit(EXIT_FAILURE);
+      }
+    mStaticModelFile << "%\n";
+    mStaticModelFile << "% " << filename << " : Computes static model for Dynare\n";
+    mStaticModelFile << "%\n";
+    mStaticModelFile << "% Warning : this file is generated automatically by Dynare\n";
+    mStaticModelFile << "%           from model file (.mod)\n\n";
+    mStaticModelFile << "%/\n";
+    mStaticModelFile << "function [varargout] = " << static_basename << "(varargin)\n";
+    mStaticModelFile << "  global oo_ M_ options_ ys0_ ;\n";
+    bool OK=true;
+    ostringstream tmp_output;
+    for (temporary_terms_type::const_iterator it = temporary_terms.begin();
+         it != temporary_terms.end(); it++)
+      {
+        if (OK)
+          OK=false;
+        else
+          tmp_output << " ";
+        (*it)->writeOutput(tmp_output, oMatlabDynamicModel, temporary_terms);
+      }
+    if (tmp_output.str().length()>0)
+      mStaticModelFile << "  global " << tmp_output.str() << " M_ ;\n";
+    mStaticModelFile << "  T_init=0;\n";
+    tmp_output.str("");
+    for (temporary_terms_type::const_iterator it = temporary_terms.begin();
+         it != temporary_terms.end(); it++)
+      {
+        tmp_output << "  ";
+        (*it)->writeOutput(tmp_output, oMatlabDynamicModel, temporary_terms);
+        tmp_output << "=T_init;\n";
+      }
+    if (tmp_output.str().length()>0)
+      mStaticModelFile << tmp_output.str();
+
+    mStaticModelFile << "  y_kmin=M_.maximum_lag;\n";
+    mStaticModelFile << "  y_kmax=M_.maximum_lead;\n";
+    mStaticModelFile << "  y_size=M_.endo_nbr;\n";
+
+    /*tmp_output.str("");
+    writeModelLocalVariables(tmp_output, oMatlabDynamicModel);
+    if (tmp_output.str().length()>0)
+      mStaticModelFile << tmp_output.str() << "\n";*/
+
+
+    mStaticModelFile << "  if(length(varargin)>0)\n";
+    mStaticModelFile << "    %A simple evaluation of the static model\n";
+    //mStaticModelFile << "    global it_;\n";
+    mStaticModelFile << "    y=varargin{1}(:);\n";
+    mStaticModelFile << "    ys=y;\n";
+    mStaticModelFile << "    g1=[];\n";
+    mStaticModelFile << "    x=varargin{2}(:);\n";
+    mStaticModelFile << "    params=varargin{3}(:);\n";
+    mStaticModelFile << "    residual=zeros(1, " << symbol_table.endo_nbr << ");\n";
+    prev_Simulation_Type=-1;
+    tmp.str("");
+    tmp_eq.str("");
+    for (i=0;i<block_triangular.ModelBlock->Size;i++)
+      {
+        k=block_triangular.ModelBlock->Block_List[i].Simulation_Type;
+        if ((BlockTriangular::BlockSim(prev_Simulation_Type)!=BlockTriangular::BlockSim(k))  &&
+            ((prev_Simulation_Type==EVALUATE_FORWARD || prev_Simulation_Type==EVALUATE_BACKWARD || prev_Simulation_Type==EVALUATE_FORWARD_R || prev_Simulation_Type==EVALUATE_BACKWARD_R)
+             || (k==EVALUATE_FORWARD || k==EVALUATE_BACKWARD || k==EVALUATE_FORWARD_R || k==EVALUATE_BACKWARD_R)))
+          {
+            mStaticModelFile << "    y_index_eq=[" << tmp_eq.str() << "];\n";
+            tmp_eq.str("");
+            mStaticModelFile << "    y_index=[" << tmp.str() << "];\n";
+            tmp.str("");
+            mStaticModelFile << tmp1.str();
+            tmp1.str("");
+          }
+        for (int ik=0;ik<block_triangular.ModelBlock->Block_List[i].Size;ik++)
+          {
+            tmp << " " << block_triangular.ModelBlock->Block_List[i].Variable[ik]+1;
+            tmp_eq << " " << block_triangular.ModelBlock->Block_List[i].Equation[ik]+1;
+          }
+        if (k==EVALUATE_FORWARD || k==EVALUATE_BACKWARD || k==EVALUATE_FORWARD_R || k==EVALUATE_BACKWARD_R)
+          {
+            if (i==block_triangular.ModelBlock->Size-1)
+              {
+                mStaticModelFile << "    y_index_eq=[" << tmp_eq.str() << "];\n";
+                tmp_eq.str("");
+                mStaticModelFile << "    y_index=[" << tmp.str() << "];\n";
+                tmp.str("");
+                mStaticModelFile << tmp1.str();
+                tmp1.str("");
+              }
+          }
 
-      switch(k)
-        {
-           case EVALUATE_FORWARD:
-           case EVALUATE_BACKWARD:
-           case EVALUATE_FORWARD_R:
-           case EVALUATE_BACKWARD_R:
-             if(!skip_head)
-               {
-                 ga_index = 1;
-                 tmp1 << "    [y, ga]=" << static_basename << "_" << i + 1 << "(y, x, params, 1);\n";
-                 tmp1 << "    residual(y_index)=ys(y_index)-y(y_index);\n";
-                 tmp1 << "    g1(y_index_eq, y_index) = ga;\n";
-               }
-             else
-               ga_index++;
-             break;
-           case SOLVE_FORWARD_COMPLETE:
-           case SOLVE_BACKWARD_COMPLETE:
-           case SOLVE_FORWARD_SIMPLE:
-           case SOLVE_BACKWARD_SIMPLE:
-           case SOLVE_TWO_BOUNDARIES_COMPLETE:
-           case SOLVE_TWO_BOUNDARIES_SIMPLE:
-             mStaticModelFile << "    y_index_eq = [" << tmp_eq.str() << "];\n";
-             mStaticModelFile << "    y_index = [";
-             mStaticModelFile << tmp.str();
-             mStaticModelFile << " ];\n";
-             tmp.str("");
-             tmp_eq.str("");
-             mStaticModelFile << "    [r, ga]=" << static_basename << "_" <<  i + 1 << "(y, x, params, 1);\n";
-             mStaticModelFile << "    g1(y_index_eq, y_index) = ga;\n";
-             mStaticModelFile << "    residual(y_index)=r;\n";
-             break;
-        }
-      prev_Simulation_Type=k;
-    }
-  mStaticModelFile << "    varargout{1}=residual';\n";
-  mStaticModelFile << "    varargout{2}=g1;\n";
-  mStaticModelFile << "    return;\n";
-  mStaticModelFile << "  end;\n";
-  mStaticModelFile << "  %The deterministic simulation of the block decomposed static model\n";
-  mStaticModelFile << "  periods=options_.periods;\n";
-  mStaticModelFile << "  maxit_=options_.maxit_;\n";
-  mStaticModelFile << "  solve_tolf=options_.solve_tolf;\n";
-  mStaticModelFile << "  y=oo_.steady_state;\n";
-  mStaticModelFile << "  x=oo_.exo_steady_state;\n";
-  mStaticModelFile << "  params=M_.params;\n";
-  mStaticModelFile << "  varargout{2}=1;\n";
-  prev_Simulation_Type=-1;
-  int Blck_Num = 0;
-  for(i = 0;i < block_triangular.ModelBlock->Size;i++)
-    {
-      k = block_triangular.ModelBlock->Block_List[i].Simulation_Type;
-      if (BlockTriangular::BlockSim(prev_Simulation_Type)==BlockTriangular::BlockSim(k) &&
-         (k==EVALUATE_FORWARD || k==EVALUATE_BACKWARD || k==EVALUATE_FORWARD_R || k==EVALUATE_BACKWARD_R))
-        skip_head=true;
-      else
-        {
+        if (BlockTriangular::BlockSim(prev_Simulation_Type)==BlockTriangular::BlockSim(k) &&
+            (k==EVALUATE_FORWARD || k==EVALUATE_BACKWARD || k==EVALUATE_FORWARD_R || k==EVALUATE_BACKWARD_R))
+          skip_head=true;
+        else
           skip_head=false;
-          Blck_Num++;
-        }
-      if ((k == EVALUATE_FORWARD || k == EVALUATE_FORWARD_R || k == EVALUATE_BACKWARD || k == EVALUATE_BACKWARD_R) && (block_triangular.ModelBlock->Block_List[i].Size))
-        {
-          if (!skip_head)
-            {
-              if (open_par)
-                {
-                  mStaticModelFile << "  end\n";
-                }
-             mStaticModelFile << "  y=" << static_basename << "_" << i + 1 << "(y, x, params, 0);\n";
-            }
-          open_par=false;
-        }
-      else if ((k == SOLVE_FORWARD_SIMPLE || k == SOLVE_BACKWARD_SIMPLE) || (k == SOLVE_FORWARD_COMPLETE || k == SOLVE_BACKWARD_COMPLETE || k == SOLVE_TWO_BOUNDARIES_COMPLETE || k == SOLVE_TWO_BOUNDARIES_SIMPLE) && (block_triangular.ModelBlock->Block_List[i].Size))
-        {
-          if (open_par)
-            {
-              mStaticModelFile << "end\n";
-            }
-          open_par=false;
-          mStaticModelFile << "  y_index=[";
-          for(int ik=0;ik<block_triangular.ModelBlock->Block_List[i].Size;ik++)
-            {
-              mStaticModelFile << " " << block_triangular.ModelBlock->Block_List[i].Variable[ik]+1;
-            }
-          mStaticModelFile << " ];\n";
 
+        switch (k)
+          {
+          case EVALUATE_FORWARD:
+          case EVALUATE_BACKWARD:
+          case EVALUATE_FORWARD_R:
+          case EVALUATE_BACKWARD_R:
+            if (!skip_head)
+              {
+                ga_index = 1;
+                tmp1 << "    [y, ga]=" << static_basename << "_" << i + 1 << "(y, x, params, 1);\n";
+                tmp1 << "    residual(y_index)=ys(y_index)-y(y_index);\n";
+                tmp1 << "    g1(y_index_eq, y_index) = ga;\n";
+              }
+            else
+              ga_index++;
+            break;
+          case SOLVE_FORWARD_COMPLETE:
+          case SOLVE_BACKWARD_COMPLETE:
+          case SOLVE_FORWARD_SIMPLE:
+          case SOLVE_BACKWARD_SIMPLE:
+          case SOLVE_TWO_BOUNDARIES_COMPLETE:
+          case SOLVE_TWO_BOUNDARIES_SIMPLE:
+            mStaticModelFile << "    y_index_eq = [" << tmp_eq.str() << "];\n";
+            mStaticModelFile << "    y_index = [";
+            mStaticModelFile << tmp.str();
+            mStaticModelFile << " ];\n";
+            tmp.str("");
+            tmp_eq.str("");
+            mStaticModelFile << "    [r, ga]=" << static_basename << "_" <<  i + 1 << "(y, x, params, 1);\n";
+            mStaticModelFile << "    g1(y_index_eq, y_index) = ga;\n";
+            mStaticModelFile << "    residual(y_index)=r;\n";
+            break;
+          }
+        prev_Simulation_Type=k;
+      }
+    mStaticModelFile << "    varargout{1}=residual';\n";
+    mStaticModelFile << "    varargout{2}=g1;\n";
+    mStaticModelFile << "    return;\n";
+    mStaticModelFile << "  end;\n";
+    mStaticModelFile << "  %The deterministic simulation of the block decomposed static model\n";
+    mStaticModelFile << "  periods=options_.periods;\n";
+    mStaticModelFile << "  maxit_=options_.maxit_;\n";
+    mStaticModelFile << "  solve_tolf=options_.solve_tolf;\n";
+    mStaticModelFile << "  y=oo_.steady_state;\n";
+    mStaticModelFile << "  x=oo_.exo_steady_state;\n";
+    mStaticModelFile << "  params=M_.params;\n";
+    mStaticModelFile << "  varargout{2}=1;\n";
+    prev_Simulation_Type=-1;
+    int Blck_Num = 0;
+    for (i = 0;i < block_triangular.ModelBlock->Size;i++)
+      {
+        k = block_triangular.ModelBlock->Block_List[i].Simulation_Type;
+        if (BlockTriangular::BlockSim(prev_Simulation_Type)==BlockTriangular::BlockSim(k) &&
+            (k==EVALUATE_FORWARD || k==EVALUATE_BACKWARD || k==EVALUATE_FORWARD_R || k==EVALUATE_BACKWARD_R))
+          skip_head=true;
+        else
+          {
+            skip_head=false;
+            Blck_Num++;
+          }
+        if ((k == EVALUATE_FORWARD || k == EVALUATE_FORWARD_R || k == EVALUATE_BACKWARD || k == EVALUATE_BACKWARD_R) && (block_triangular.ModelBlock->Block_List[i].Size))
+          {
+            if (!skip_head)
+              {
+                if (open_par)
+                  {
+                    mStaticModelFile << "  end\n";
+                  }
+                mStaticModelFile << "  y=" << static_basename << "_" << i + 1 << "(y, x, params, 0);\n";
+              }
+            open_par=false;
+          }
+        else if ((k == SOLVE_FORWARD_SIMPLE || k == SOLVE_BACKWARD_SIMPLE || k == SOLVE_FORWARD_COMPLETE || k == SOLVE_BACKWARD_COMPLETE || k == SOLVE_TWO_BOUNDARIES_COMPLETE || k == SOLVE_TWO_BOUNDARIES_SIMPLE) && (block_triangular.ModelBlock->Block_List[i].Size))
+          {
+            if (open_par)
+              {
+                mStaticModelFile << "end\n";
+              }
+            open_par=false;
+            mStaticModelFile << "  y_index=[";
+            for (int ik=0;ik<block_triangular.ModelBlock->Block_List[i].Size;ik++)
+              {
+                mStaticModelFile << " " << block_triangular.ModelBlock->Block_List[i].Variable[ik]+1;
+              }
+            mStaticModelFile << " ];\n";
 
-          mStaticModelFile << "  g1=0;g2=0;g3=0;\n";
 
-          int nze, m;
-          for(nze=0,m=0;m<=block_triangular.ModelBlock->Block_List[i].Max_Lead+block_triangular.ModelBlock->Block_List[i].Max_Lag;m++)
-            nze+=block_triangular.ModelBlock->Block_List[i].IM_lead_lag[m].size;
-          mStaticModelFile << "  y = solve_one_boundary('"  << static_basename << "_" <<  i + 1 << "'" <<
-                                                         ", y, x, params, y_index, " << nze <<
-                                                         ", 1, " << block_triangular.ModelBlock->Block_List[i].is_linear <<
-                                                         ", "  << Blck_Num << ", y_kmin, options_.maxit_, options_.solve_tolf, options_.slowc, options_.cutoff, options_.simulation_method, 1, 0, 0);\n";
+            mStaticModelFile << "  g1=0;g2=0;g3=0;\n";
 
-        }
-      prev_Simulation_Type=k;
-    }
-  if(open_par)
+            int nze, m;
+            for (nze=0,m=0;m<=block_triangular.ModelBlock->Block_List[i].Max_Lead+block_triangular.ModelBlock->Block_List[i].Max_Lag;m++)
+              nze+=block_triangular.ModelBlock->Block_List[i].IM_lead_lag[m].size;
+            mStaticModelFile << "  y = solve_one_boundary('"  << static_basename << "_" <<  i + 1 << "'" <<
+            ", y, x, params, y_index, " << nze <<
+            ", 1, " << block_triangular.ModelBlock->Block_List[i].is_linear <<
+            ", "  << Blck_Num << ", y_kmin, options_.maxit_, options_.solve_tolf, options_.slowc, options_.cutoff, options_.simulation_method, 1, 0, 0);\n";
+
+          }
+        prev_Simulation_Type=k;
+      }
+    if (open_par)
+      mStaticModelFile << "  end;\n";
+    mStaticModelFile << "  oo_.steady_state = y;\n";
+    mStaticModelFile << "  if isempty(ys0_)\n";
+    mStaticModelFile << "    oo_.endo_simul(:,1:M_.maximum_lag) = oo_.steady_state * ones(1,M_.maximum_lag);\n";
     mStaticModelFile << "  end;\n";
-  mStaticModelFile << "  oo_.steady_state = y;\n";
-  mStaticModelFile << "  if isempty(ys0_)\n";
-  mStaticModelFile << "    oo_.endo_simul(:,1:M_.maximum_lag) = oo_.steady_state * ones(1,M_.maximum_lag);\n";
-  mStaticModelFile << "  end;\n";
-  mStaticModelFile << "  disp('Steady State value');\n";
-  mStaticModelFile << "  disp([strcat(M_.endo_names,' : ') num2str(oo_.steady_state,'%f')]);\n";
-  mStaticModelFile << "  varargout{2}=0;\n";
-  mStaticModelFile << "  varargout{1}=oo_.steady_state;\n";
-  mStaticModelFile << "return;\n";
-  writeModelStaticEquationsOrdered_M(block_triangular.ModelBlock, static_basename);
-  mStaticModelFile.close();
-  chdir("..");
-}
+    mStaticModelFile << "  disp('Steady State value');\n";
+    mStaticModelFile << "  disp([strcat(M_.endo_names,' : ') num2str(oo_.steady_state,'%f')]);\n";
+    mStaticModelFile << "  varargout{2}=0;\n";
+    mStaticModelFile << "  varargout{1}=oo_.steady_state;\n";
+    mStaticModelFile << "return;\n";
+    writeModelStaticEquationsOrdered_M(block_triangular.ModelBlock, static_basename);
+    mStaticModelFile.close();
+    chdir("..");
+  }
 
 void
 ModelTree::writeSparseDynamicMFile(const string &dynamic_basename, const string &basename, const int mode) const
-{
-  string sp;
-  ofstream mDynamicModelFile;
-  ostringstream tmp, tmp1, tmp_eq;
-  int prev_Simulation_Type, tmp_i;
-  SymbolicGaussElimination SGE;
-  bool OK;
-  chdir(basename.c_str());
-  string filename = dynamic_basename + ".m";
-  mDynamicModelFile.open(filename.c_str(), ios::out | ios::binary);
-  if (!mDynamicModelFile.is_open())
-    {
-      cerr << "Error: Can't open file " << filename << " for writing" << endl;
-      exit(EXIT_FAILURE);
-    }
-  mDynamicModelFile << "%\n";
-  mDynamicModelFile << "% " << filename << " : Computes dynamic model for Dynare\n";
-  mDynamicModelFile << "%\n";
-  mDynamicModelFile << "% Warning : this file is generated automatically by Dynare\n";
-  mDynamicModelFile << "%           from model file (.mod)\n\n";
-  mDynamicModelFile << "%/\n";
-
-  int i, k, Nb_SGE=0;
-  bool printed = false, skip_head, open_par=false;
-  if (computeJacobian || computeJacobianExo || computeHessian)
-    {
-      mDynamicModelFile << "function [varargout] = " << dynamic_basename << "(varargin)\n";
-      mDynamicModelFile << "  global oo_ options_ M_ ;\n";
-      mDynamicModelFile << "  g2=[];g3=[];\n";
-      //Temporary variables declaration
-      OK=true;
-      ostringstream tmp_output;
-      for(temporary_terms_type::const_iterator it = temporary_terms.begin();
-          it != temporary_terms.end(); it++)
-        {
-          if (OK)
-            OK=false;
-          else
-            tmp_output << " ";
-          (*it)->writeOutput(tmp_output, oMatlabStaticModelSparse, temporary_terms);
-        }
-      if (tmp_output.str().length()>0)
-        mDynamicModelFile << "  global " << tmp_output.str() << " M_ ;\n";
+  {
+    string sp;
+    ofstream mDynamicModelFile;
+    ostringstream tmp, tmp1, tmp_eq;
+    int prev_Simulation_Type, tmp_i;
+    SymbolicGaussElimination SGE;
+    bool OK;
+    chdir(basename.c_str());
+    string filename = dynamic_basename + ".m";
+    mDynamicModelFile.open(filename.c_str(), ios::out | ios::binary);
+    if (!mDynamicModelFile.is_open())
+      {
+        cerr << "Error: Can't open file " << filename << " for writing" << endl;
+        exit(EXIT_FAILURE);
+      }
+    mDynamicModelFile << "%\n";
+    mDynamicModelFile << "% " << filename << " : Computes dynamic model for Dynare\n";
+    mDynamicModelFile << "%\n";
+    mDynamicModelFile << "% Warning : this file is generated automatically by Dynare\n";
+    mDynamicModelFile << "%           from model file (.mod)\n\n";
+    mDynamicModelFile << "%/\n";
+
+    int i, k, Nb_SGE=0;
+    bool printed = false, skip_head, open_par=false;
+    if (computeJacobian || computeJacobianExo || computeHessian)
+      {
+        mDynamicModelFile << "function [varargout] = " << dynamic_basename << "(varargin)\n";
+        mDynamicModelFile << "  global oo_ options_ M_ ;\n";
+        mDynamicModelFile << "  g2=[];g3=[];\n";
+        //Temporary variables declaration
+        OK=true;
+        ostringstream tmp_output;
+        for (temporary_terms_type::const_iterator it = temporary_terms.begin();
+             it != temporary_terms.end(); it++)
+          {
+            if (OK)
+              OK=false;
+            else
+              tmp_output << " ";
+            (*it)->writeOutput(tmp_output, oMatlabStaticModelSparse, temporary_terms);
+          }
+        if (tmp_output.str().length()>0)
+          mDynamicModelFile << "  global " << tmp_output.str() << " M_ ;\n";
 
-      mDynamicModelFile << "  T_init=zeros(1,options_.periods+M_.maximum_lag+M_.maximum_lead);\n";
-      tmp_output.str("");
-      for(temporary_terms_type::const_iterator it = temporary_terms.begin();
-          it != temporary_terms.end(); it++)
-        {
-          tmp_output << "  ";
-          (*it)->writeOutput(tmp_output, oMatlabDynamicModel, temporary_terms);
-          tmp_output << "=T_init;\n";
-        }
-      if (tmp_output.str().length()>0)
-        mDynamicModelFile << tmp_output.str();
-
-      mDynamicModelFile << "  y_kmin=M_.maximum_lag;\n";
-      mDynamicModelFile << "  y_kmax=M_.maximum_lead;\n";
-      mDynamicModelFile << "  y_size=M_.endo_nbr;\n";
-      mDynamicModelFile << "  if(length(varargin)>0)\n";
-      mDynamicModelFile << "    %it is a simple evaluation of the dynamic model for time _it\n";
-      mDynamicModelFile << "    params=varargin{3};\n";
-      mDynamicModelFile << "    it_=varargin{4};\n";
-      i = symbol_table.endo_nbr*(variable_table.max_endo_lag+variable_table.max_endo_lead+1)+
-          symbol_table.exo_nbr*(variable_table.max_exo_lag+variable_table.max_exo_lead+1);
-      mDynamicModelFile << "    g1=spalloc(" << symbol_table.endo_nbr << ", " << i << ", " << i*symbol_table.endo_nbr << ");\n";
-      mDynamicModelFile << "    Per_u_=0;\n";
-      mDynamicModelFile << "    Per_y_=it_*y_size;\n";
-      mDynamicModelFile << "    y=varargin{1};\n";
-      mDynamicModelFile << "    ys=y(it_,:);\n";
-      mDynamicModelFile << "    x=varargin{2};\n";
-      prev_Simulation_Type=-1;
-      tmp.str("");
-      tmp_eq.str("");
-      for(i = 0;i < block_triangular.ModelBlock->Size;i++)
-        {
-          k=block_triangular.ModelBlock->Block_List[i].Simulation_Type;
-          if ((BlockTriangular::BlockSim(prev_Simulation_Type)!=BlockTriangular::BlockSim(k))  &&
-              ((prev_Simulation_Type==EVALUATE_FORWARD || prev_Simulation_Type==EVALUATE_BACKWARD || prev_Simulation_Type==EVALUATE_FORWARD_R || prev_Simulation_Type==EVALUATE_BACKWARD_R)
-               || (k==EVALUATE_FORWARD || k==EVALUATE_BACKWARD || k==EVALUATE_FORWARD_R || k==EVALUATE_BACKWARD_R)))
-            {
-              mDynamicModelFile << "    y_index_eq=[" << tmp_eq.str() << "];\n";
-              tmp_eq.str("");
-              mDynamicModelFile << "    y_index=[" << tmp.str() << "];\n";
-              tmp.str("");
-              mDynamicModelFile << tmp1.str();
-              tmp1.str("");
-            }
-          for(int ik=0;ik<block_triangular.ModelBlock->Block_List[i].Size;ik++)
-            {
-              tmp << " " << block_triangular.ModelBlock->Block_List[i].Variable[ik]+1;
-              tmp_eq << " " << block_triangular.ModelBlock->Block_List[i].Equation[ik]+1;
-            }
-          if(k==EVALUATE_FORWARD || k==EVALUATE_BACKWARD || k==EVALUATE_FORWARD_R || k==EVALUATE_BACKWARD_R)
-            {
-              if(i==block_triangular.ModelBlock->Size-1)
-                {
-                  mDynamicModelFile << "    y_index_eq=[" << tmp_eq.str() << "];\n";
-                  tmp_eq.str("");
-                  mDynamicModelFile << "    y_index=[" << tmp.str() << "];\n";
-                  tmp.str("");
-                  mDynamicModelFile << tmp1.str();
-                  tmp1.str("");
-                }
-            }
-          if (BlockTriangular::BlockSim(prev_Simulation_Type)==BlockTriangular::BlockSim(k) &&
-              (k==EVALUATE_FORWARD || k==EVALUATE_BACKWARD || k==EVALUATE_FORWARD_R || k==EVALUATE_BACKWARD_R))
-            skip_head=true;
-          else
-            skip_head=false;
-          switch(k)
-            {
-            case EVALUATE_FORWARD:
-            case EVALUATE_BACKWARD:
-            case EVALUATE_FORWARD_R:
-            case EVALUATE_BACKWARD_R:
-              if(!skip_head)
-                {
-                  tmp1 << "    [y, g1, g2, g3]=" << dynamic_basename << "_" << i + 1 << "(y, x, params, 1, g1, g2, g3, it_-1, 1);\n";
-                  tmp1 << "    residual(y_index_eq)=ys(y_index)-y(it_, y_index);\n";
-                }
-              break;
-            case SOLVE_FORWARD_SIMPLE:
-            case SOLVE_BACKWARD_SIMPLE:
-              mDynamicModelFile << "    y_index_eq = " << block_triangular.ModelBlock->Block_List[i].Equation[0]+1 << ";\n";
-              mDynamicModelFile << "    [r, g1, g2, g3]=" << dynamic_basename << "_" << i + 1 << "(y, x, params, it_, 1, g1, g2, g3);\n";
-              mDynamicModelFile << "    residual(y_index_eq)=r;\n";
-              tmp_eq.str("");
-              tmp.str("");
-              break;
-            case SOLVE_FORWARD_COMPLETE:
-            case SOLVE_BACKWARD_COMPLETE:
-              mDynamicModelFile << "    y_index_eq = [" << tmp_eq.str() << "];\n";
-              mDynamicModelFile << "    [r, g1, g2, g3, b]=" << dynamic_basename << "_" << i + 1 << "(y, x, params, it_, 1, g1, g2, g3);\n";
-              mDynamicModelFile << "    residual(y_index_eq)=r;\n";
-              break;
-            case SOLVE_TWO_BOUNDARIES_COMPLETE:
-            case SOLVE_TWO_BOUNDARIES_SIMPLE:
-              int j;
-              mDynamicModelFile << "    y_index_eq = [" << tmp_eq.str() << "];\n";
-              tmp_i=block_triangular.ModelBlock->Block_List[i].Max_Lag_Endo+block_triangular.ModelBlock->Block_List[i].Max_Lead_Endo+1;
-              mDynamicModelFile << "    y_index = [";
-              for(j=0;j<tmp_i;j++)
-                for(int ik=0;ik<block_triangular.ModelBlock->Block_List[i].Size;ik++)
+        mDynamicModelFile << "  T_init=zeros(1,options_.periods+M_.maximum_lag+M_.maximum_lead);\n";
+        tmp_output.str("");
+        for (temporary_terms_type::const_iterator it = temporary_terms.begin();
+             it != temporary_terms.end(); it++)
+          {
+            tmp_output << "  ";
+            (*it)->writeOutput(tmp_output, oMatlabDynamicModel, temporary_terms);
+            tmp_output << "=T_init;\n";
+          }
+        if (tmp_output.str().length()>0)
+          mDynamicModelFile << tmp_output.str();
+
+        mDynamicModelFile << "  y_kmin=M_.maximum_lag;\n";
+        mDynamicModelFile << "  y_kmax=M_.maximum_lead;\n";
+        mDynamicModelFile << "  y_size=M_.endo_nbr;\n";
+        mDynamicModelFile << "  if(length(varargin)>0)\n";
+        mDynamicModelFile << "    %it is a simple evaluation of the dynamic model for time _it\n";
+        mDynamicModelFile << "    params=varargin{3};\n";
+        mDynamicModelFile << "    it_=varargin{4};\n";
+        /*i = symbol_table.endo_nbr*(variable_table.max_endo_lag+variable_table.max_endo_lead+1)+
+            symbol_table.exo_nbr*(variable_table.max_exo_lag+variable_table.max_exo_lead+1);
+        mDynamicModelFile << "    g1=spalloc(" << symbol_table.endo_nbr << ", " << i << ", " << i*symbol_table.endo_nbr << ");\n";*/
+        mDynamicModelFile << "    Per_u_=0;\n";
+        mDynamicModelFile << "    Per_y_=it_*y_size;\n";
+        mDynamicModelFile << "    y=varargin{1};\n";
+        mDynamicModelFile << "    ys=y(it_,:);\n";
+        mDynamicModelFile << "    x=varargin{2};\n";
+        prev_Simulation_Type=-1;
+        tmp.str("");
+        tmp_eq.str("");
+        for (int count_call=1, i = 0;i < block_triangular.ModelBlock->Size;i++, count_call++)
+          {
+            k=block_triangular.ModelBlock->Block_List[i].Simulation_Type;
+            if ((BlockTriangular::BlockSim(prev_Simulation_Type)!=BlockTriangular::BlockSim(k))  &&
+                ((prev_Simulation_Type==EVALUATE_FORWARD || prev_Simulation_Type==EVALUATE_BACKWARD || prev_Simulation_Type==EVALUATE_FORWARD_R || prev_Simulation_Type==EVALUATE_BACKWARD_R)
+                 || (k==EVALUATE_FORWARD || k==EVALUATE_BACKWARD || k==EVALUATE_FORWARD_R || k==EVALUATE_BACKWARD_R)))
+              {
+                mDynamicModelFile << "    y_index_eq=[" << tmp_eq.str() << "];\n";
+                tmp_eq.str("");
+                mDynamicModelFile << "    y_index=[" << tmp.str() << "];\n";
+                tmp.str("");
+                mDynamicModelFile << tmp1.str();
+                tmp1.str("");
+              }
+            for (int ik=0;ik<block_triangular.ModelBlock->Block_List[i].Size;ik++)
+              {
+                tmp << " " << block_triangular.ModelBlock->Block_List[i].Variable[ik]+1;
+                tmp_eq << " " << block_triangular.ModelBlock->Block_List[i].Equation[ik]+1;
+              }
+            if (k==EVALUATE_FORWARD || k==EVALUATE_BACKWARD || k==EVALUATE_FORWARD_R || k==EVALUATE_BACKWARD_R)
+              {
+                if (i==block_triangular.ModelBlock->Size-1)
+                  {
+                    mDynamicModelFile << "    y_index_eq=[" << tmp_eq.str() << "];\n";
+                    tmp_eq.str("");
+                    mDynamicModelFile << "    y_index=[" << tmp.str() << "];\n";
+                    tmp.str("");
+                    mDynamicModelFile << tmp1.str();
+                    tmp1.str("");
+                  }
+              }
+            if (BlockTriangular::BlockSim(prev_Simulation_Type)==BlockTriangular::BlockSim(k) &&
+                (k==EVALUATE_FORWARD || k==EVALUATE_BACKWARD || k==EVALUATE_FORWARD_R || k==EVALUATE_BACKWARD_R))
+              skip_head=true;
+            else
+              skip_head=false;
+            switch (k)
+              {
+              case EVALUATE_FORWARD:
+              case EVALUATE_BACKWARD:
+              case EVALUATE_FORWARD_R:
+              case EVALUATE_BACKWARD_R:
+                if (!skip_head)
+                  {
+                    tmp1 << "    [y, dr(" << count_call << ").g1, dr(" << count_call << ").g2, dr(" << count_call << ").g3, dr(" << count_call << ").g1_x, dr(" << count_call << ").g1_o]=" << dynamic_basename << "_" << i + 1 << "(y, x, params, 1, it_-1, 1);\n";
+                    tmp1 << "    residual(y_index_eq)=ys(y_index)-y(it_, y_index);\n";
+                  }
+                break;
+              case SOLVE_FORWARD_SIMPLE:
+              case SOLVE_BACKWARD_SIMPLE:
+                mDynamicModelFile << "    y_index_eq = " << block_triangular.ModelBlock->Block_List[i].Equation[0]+1 << ";\n";
+                mDynamicModelFile << "    [r, dr(" << count_call << ").g1, dr(" << count_call << ").g2, dr(" << count_call << ").g3, dr(" << count_call << ").g1_x, dr(" << count_call << ").g1_o]=" << dynamic_basename << "_" << i + 1 << "(y, x, params, it_, 1);\n";
+                mDynamicModelFile << "    residual(y_index_eq)=r;\n";
+                tmp_eq.str("");
+                tmp.str("");
+                break;
+              case SOLVE_FORWARD_COMPLETE:
+              case SOLVE_BACKWARD_COMPLETE:
+                mDynamicModelFile << "    y_index_eq = [" << tmp_eq.str() << "];\n";
+                mDynamicModelFile << "    [r, dr(" << count_call << ").g1, dr(" << count_call << ").g2, dr(" << count_call << ").g3, dr(" << count_call << ").g1_x, dr(" << count_call << ").g1_o]=" << dynamic_basename << "_" << i + 1 << "(y, x, params, it_, 1);\n";
+                mDynamicModelFile << "    residual(y_index_eq)=r;\n";
+                break;
+              case SOLVE_TWO_BOUNDARIES_COMPLETE:
+              case SOLVE_TWO_BOUNDARIES_SIMPLE:
+                int j;
+                mDynamicModelFile << "    y_index_eq = [" << tmp_eq.str() << "];\n";
+                tmp_i=block_triangular.ModelBlock->Block_List[i].Max_Lag_Endo+block_triangular.ModelBlock->Block_List[i].Max_Lead_Endo+1;
+                mDynamicModelFile << "    y_index = [";
+                for (j=0;j<tmp_i;j++)
+                  for (int ik=0;ik<block_triangular.ModelBlock->Block_List[i].Size;ik++)
+                    {
+                      mDynamicModelFile << " " << block_triangular.ModelBlock->Block_List[i].Variable[ik]+1+j*symbol_table.endo_nbr;
+                    }
+                int tmp_ix=block_triangular.ModelBlock->Block_List[i].Max_Lag_Exo+block_triangular.ModelBlock->Block_List[i].Max_Lead_Exo+1;
+                for (j=0;j<tmp_ix;j++)
+                  for (int ik=0;ik<block_triangular.ModelBlock->Block_List[i].nb_exo;ik++)
+                    mDynamicModelFile << " " << block_triangular.ModelBlock->Block_List[i].Exogenous[ik]+1+j*symbol_table.exo_nbr+symbol_table.endo_nbr*tmp_i;
+                mDynamicModelFile << " ];\n";
+                tmp.str("");
+                tmp_eq.str("");
+                //mDynamicModelFile << "    ga = [];\n";
+                j = block_triangular.ModelBlock->Block_List[i].Size*(block_triangular.ModelBlock->Block_List[i].Max_Lag_Endo+block_triangular.ModelBlock->Block_List[i].Max_Lead_Endo+1)
+                    + block_triangular.ModelBlock->Block_List[i].nb_exo*(block_triangular.ModelBlock->Block_List[i].Max_Lag_Exo+block_triangular.ModelBlock->Block_List[i].Max_Lead_Exo+1);
+                /*mDynamicModelFile << "    ga=spalloc(" << block_triangular.ModelBlock->Block_List[i].Size << ", " << j << ", " <<
+                block_triangular.ModelBlock->Block_List[i].Size*j << ");\n";*/
+                tmp_i=block_triangular.ModelBlock->Block_List[i].Max_Lag_Endo+block_triangular.ModelBlock->Block_List[i].Max_Lead_Endo+1;
+                mDynamicModelFile << "    [r, dr(" << count_call << ").g1, dr(" << count_call << ").g2, dr(" << count_call << ").g3, b, dr(" << count_call << ").g1_x, dr(" << count_call << ").g1_o]=" << dynamic_basename << "_" <<  i + 1 << "(y, x, params, it_-" << variable_table.max_lag << ", 1, " << variable_table.max_lag << ", " << block_triangular.ModelBlock->Block_List[i].Size << ");\n";
+                /*if(block_triangular.ModelBlock->Block_List[i].Max_Lag==variable_table.max_lag && block_triangular.ModelBlock->Block_List[i].Max_Lead==variable_table.max_lead)
+                  mDynamicModelFile << "    g1(y_index_eq,y_index) = ga;\n";
+                else
+                  mDynamicModelFile << "    g1(y_index_eq,y_index) = ga(:," << 1+(variable_table.max_lag-block_triangular.ModelBlock->Block_List[i].Max_Lag)*block_triangular.ModelBlock->Block_List[i].Size << ":" << (variable_table.max_lag+1+block_triangular.ModelBlock->Block_List[i].Max_Lead)*block_triangular.ModelBlock->Block_List[i].Size << ");\n";*/
+                mDynamicModelFile << "    residual(y_index_eq)=r(:,M_.maximum_lag+1);\n";
+                break;
+              }
+            prev_Simulation_Type=k;
+          }
+        if (tmp1.str().length())
+          {
+            mDynamicModelFile << tmp1.str();
+            tmp1.str("");
+          }
+        mDynamicModelFile << "    varargout{1}=residual;\n";
+        mDynamicModelFile << "    varargout{2}=dr;\n";
+        mDynamicModelFile << "    return;\n";
+        mDynamicModelFile << "  end;\n";
+        mDynamicModelFile << "  %it is the deterministic simulation of the block decomposed dynamic model\n";
+        mDynamicModelFile << "  if(options_.simulation_method==0)\n";
+        mDynamicModelFile << "    mthd='Sparse LU';\n";
+        mDynamicModelFile << "  elseif(options_.simulation_method==2)\n";
+        mDynamicModelFile << "    mthd='GMRES';\n";
+        mDynamicModelFile << "  elseif(options_.simulation_method==3)\n";
+        mDynamicModelFile << "    mthd='BICGSTAB';\n";
+        mDynamicModelFile << "  else\n";
+        mDynamicModelFile << "    mthd='UNKNOWN';\n";
+        mDynamicModelFile << "  end;\n";
+        mDynamicModelFile << "  disp (['-----------------------------------------------------']) ;\n";
+        mDynamicModelFile << "  disp (['MODEL SIMULATION: (method=' mthd ')']) ;\n";
+        mDynamicModelFile << "  fprintf('\\n') ;\n";
+        mDynamicModelFile << "  periods=options_.periods;\n";
+        mDynamicModelFile << "  maxit_=options_.maxit_;\n";
+        mDynamicModelFile << "  solve_tolf=options_.solve_tolf;\n";
+        mDynamicModelFile << "  y=oo_.endo_simul';\n";
+        mDynamicModelFile << "  x=oo_.exo_simul;\n";
+      }
+    prev_Simulation_Type=-1;
+    mDynamicModelFile << "  params=M_.params;\n";
+    mDynamicModelFile << "  oo_.deterministic_simulation.status = 0;\n";
+    for (i = 0;i < block_triangular.ModelBlock->Size;i++)
+      {
+        k = block_triangular.ModelBlock->Block_List[i].Simulation_Type;
+        if (BlockTriangular::BlockSim(prev_Simulation_Type)==BlockTriangular::BlockSim(k) &&
+            (k==EVALUATE_FORWARD || k==EVALUATE_BACKWARD || k==EVALUATE_FORWARD_R || k==EVALUATE_BACKWARD_R))
+          skip_head=true;
+        else
+          skip_head=false;
+        if ((k == EVALUATE_FORWARD || k == EVALUATE_FORWARD_R) && (block_triangular.ModelBlock->Block_List[i].Size))
+          {
+            if (!skip_head)
+              {
+                if (open_par)
+                  {
+                    mDynamicModelFile << "  end\n";
+                  }
+                mDynamicModelFile << "  oo_.deterministic_simulation.status = 1;\n";
+                mDynamicModelFile << "  oo_.deterministic_simulation.error = 0;\n";
+                mDynamicModelFile << "  oo_.deterministic_simulation.iterations = 0;\n";
+                mDynamicModelFile << "  if(isfield(oo_.deterministic_simulation,'block'))\n";
+                mDynamicModelFile << "    blck_num = length(oo_.deterministic_simulation.block)+1;\n";
+                mDynamicModelFile << "  else\n";
+                mDynamicModelFile << "    blck_num = 1;\n";
+                mDynamicModelFile << "  end;\n";
+                mDynamicModelFile << "  oo_.deterministic_simulation.block(blck_num).status = 1;\n";
+                mDynamicModelFile << "  oo_.deterministic_simulation.block(blck_num).error = 0;\n";
+                mDynamicModelFile << "  oo_.deterministic_simulation.block(blck_num).iterations = 0;\n";
+                mDynamicModelFile << "  g1=[];g2=[];g3=[];\n";
+                //mDynamicModelFile << "  for it_ = y_kmin+1:(periods+y_kmin)\n";
+                mDynamicModelFile << "    y=" << dynamic_basename << "_" << i + 1 << "(y, x, params, 0, y_kmin, periods);\n";
+              }
+            //open_par=true;
+          }
+        else if ((k == EVALUATE_BACKWARD || k == EVALUATE_BACKWARD_R) && (block_triangular.ModelBlock->Block_List[i].Size))
+          {
+            if (!skip_head)
+              {
+                if (open_par)
                   {
-                    mDynamicModelFile << " " << block_triangular.ModelBlock->Block_List[i].Variable[ik]+1+j*symbol_table.endo_nbr;
-                 }
-              int tmp_ix=block_triangular.ModelBlock->Block_List[i].Max_Lag_Exo+block_triangular.ModelBlock->Block_List[i].Max_Lead_Exo+1;
-              for(j=0;j<tmp_ix;j++)
-                for(int ik=0;ik<block_triangular.ModelBlock->Block_List[i].nb_exo;ik++)
-                  mDynamicModelFile << " " << block_triangular.ModelBlock->Block_List[i].Exogenous[ik]+1+j*symbol_table.exo_nbr+symbol_table.endo_nbr*tmp_i;
-              mDynamicModelFile << " ];\n";
-              tmp.str("");
-              tmp_eq.str("");
-              mDynamicModelFile << "    ga = [];\n";
-              j = block_triangular.ModelBlock->Block_List[i].Size*(block_triangular.ModelBlock->Block_List[i].Max_Lag_Endo+block_triangular.ModelBlock->Block_List[i].Max_Lead_Endo+1)
-                + block_triangular.ModelBlock->Block_List[i].nb_exo*(block_triangular.ModelBlock->Block_List[i].Max_Lag_Exo+block_triangular.ModelBlock->Block_List[i].Max_Lead_Exo+1);
-              mDynamicModelFile << "    ga=spalloc(" << block_triangular.ModelBlock->Block_List[i].Size << ", " << j << ", " <<
-              block_triangular.ModelBlock->Block_List[i].Size*j << ");\n";
-              tmp_i=block_triangular.ModelBlock->Block_List[i].Max_Lag_Endo+block_triangular.ModelBlock->Block_List[i].Max_Lead_Endo+1;
-              mDynamicModelFile << "    [r, ga, g2, g3, b]=" << dynamic_basename << "_" <<  i + 1 << "(y, x, params, it_-" << variable_table.max_lag << ", 1, ga, g2, g3, " << variable_table.max_lag << ", " << block_triangular.ModelBlock->Block_List[i].Size << ");\n";
-              if(block_triangular.ModelBlock->Block_List[i].Max_Lag==variable_table.max_lag && block_triangular.ModelBlock->Block_List[i].Max_Lead==variable_table.max_lead)
-                mDynamicModelFile << "    g1(y_index_eq,y_index) = ga;\n";
-              else
-                mDynamicModelFile << "    g1(y_index_eq,y_index) = ga(:," << 1+(variable_table.max_lag-block_triangular.ModelBlock->Block_List[i].Max_Lag)*block_triangular.ModelBlock->Block_List[i].Size << ":" << (variable_table.max_lag+1+block_triangular.ModelBlock->Block_List[i].Max_Lead)*block_triangular.ModelBlock->Block_List[i].Size << ");\n";
-              mDynamicModelFile << "    residual(y_index_eq)=r(:,M_.maximum_lag+1);\n";
-              break;
-            }
-          prev_Simulation_Type=k;
-        }
-      if(tmp1.str().length())
-        {
-          mDynamicModelFile << tmp1.str();
-          tmp1.str("");
-        }
-      mDynamicModelFile << "    varargout{1}=residual;\n";
-      mDynamicModelFile << "    varargout{2}=g1;\n";
-      mDynamicModelFile << "    return;\n";
-      mDynamicModelFile << "  end;\n";
-      mDynamicModelFile << "  %it is the deterministic simulation of the block decomposed dynamic model\n";
-      mDynamicModelFile << "  if(options_.simulation_method==0)\n";
-      mDynamicModelFile << "    mthd='Sparse LU';\n";
-      mDynamicModelFile << "  elseif(options_.simulation_method==2)\n";
-      mDynamicModelFile << "    mthd='GMRES';\n";
-      mDynamicModelFile << "  elseif(options_.simulation_method==3)\n";
-      mDynamicModelFile << "    mthd='BICGSTAB';\n";
-      mDynamicModelFile << "  else\n";
-      mDynamicModelFile << "    mthd='UNKNOWN';\n";
-      mDynamicModelFile << "  end;\n";
-      mDynamicModelFile << "  disp (['-----------------------------------------------------']) ;\n";
-      mDynamicModelFile << "  disp (['MODEL SIMULATION: (method=' mthd ')']) ;\n";
-      mDynamicModelFile << "  fprintf('\\n') ;\n";
-      mDynamicModelFile << "  periods=options_.periods;\n";
-      mDynamicModelFile << "  maxit_=options_.maxit_;\n";
-      mDynamicModelFile << "  solve_tolf=options_.solve_tolf;\n";
-      mDynamicModelFile << "  y=oo_.endo_simul';\n";
-      mDynamicModelFile << "  x=oo_.exo_simul;\n";
-    }
-  prev_Simulation_Type=-1;
-  mDynamicModelFile << "  params=M_.params;\n";
-  mDynamicModelFile << "  oo_.deterministic_simulation.status = 0;\n";
-  for(i = 0;i < block_triangular.ModelBlock->Size;i++)
-    {
-      k = block_triangular.ModelBlock->Block_List[i].Simulation_Type;
-      if (BlockTriangular::BlockSim(prev_Simulation_Type)==BlockTriangular::BlockSim(k) &&
-          (k==EVALUATE_FORWARD || k==EVALUATE_BACKWARD || k==EVALUATE_FORWARD_R || k==EVALUATE_BACKWARD_R))
-        skip_head=true;
-      else
-        skip_head=false;
-      if ((k == EVALUATE_FORWARD || k == EVALUATE_FORWARD_R) && (block_triangular.ModelBlock->Block_List[i].Size))
-        {
-          if (!skip_head)
-            {
-              if (open_par)
-                {
-                  mDynamicModelFile << "  end\n";
-                }
-              mDynamicModelFile << "  oo_.deterministic_simulation.status = 1;\n";
-              mDynamicModelFile << "  oo_.deterministic_simulation.error = 0;\n";
-              mDynamicModelFile << "  oo_.deterministic_simulation.iterations = 0;\n";
-              mDynamicModelFile << "  if(isfield(oo_.deterministic_simulation,'block'))\n";
-              mDynamicModelFile << "    blck_num = length(oo_.deterministic_simulation.block)+1;\n";
-              mDynamicModelFile << "  else\n";
-              mDynamicModelFile << "    blck_num = 1;\n";
-              mDynamicModelFile << "  end;\n";
-              mDynamicModelFile << "  oo_.deterministic_simulation.block(blck_num).status = 1;\n";
-              mDynamicModelFile << "  oo_.deterministic_simulation.block(blck_num).error = 0;\n";
-              mDynamicModelFile << "  oo_.deterministic_simulation.block(blck_num).iterations = 0;\n";
-              mDynamicModelFile << "  g1=[];g2=[];g3=[];\n";
-              //mDynamicModelFile << "  for it_ = y_kmin+1:(periods+y_kmin)\n";
-              mDynamicModelFile << "    y=" << dynamic_basename << "_" << i + 1 << "(y, x, params, 0, g1, g2, g3, y_kmin, periods);\n";
-            }
-          //open_par=true;
-        }
-      else if ((k == EVALUATE_BACKWARD || k == EVALUATE_BACKWARD_R) && (block_triangular.ModelBlock->Block_List[i].Size))
-        {
-          if (!skip_head)
-            {
-              if (open_par)
-                {
-                  mDynamicModelFile << "  end\n";
-                }
-              mDynamicModelFile << "  oo_.deterministic_simulation.status = 1;\n";
-              mDynamicModelFile << "  oo_.deterministic_simulation.error = 0;\n";
-              mDynamicModelFile << "  oo_.deterministic_simulation.iterations = 0;\n";
-              mDynamicModelFile << "  if(isfield(oo_.deterministic_simulation,'block'))\n";
-              mDynamicModelFile << "    blck_num = length(oo_.deterministic_simulation.block)+1;\n";
-              mDynamicModelFile << "  else\n";
-              mDynamicModelFile << "    blck_num = 1;\n";
-              mDynamicModelFile << "  end;\n";
-              mDynamicModelFile << "  oo_.deterministic_simulation.block(blck_num).status = 1;\n";
-              mDynamicModelFile << "  oo_.deterministic_simulation.block(blck_num).error = 0;\n";
-              mDynamicModelFile << "  oo_.deterministic_simulation.block(blck_num).iterations = 0;\n";
-              mDynamicModelFile << "  g1=[];g2=[];g3=[];\n";
-              mDynamicModelFile << "    " << dynamic_basename << "_" << i + 1 << "(y, x, params, 0, g1, g2, g3, y_kmin, periods);\n";
-            }
-        }
-      else if ((k == SOLVE_FORWARD_COMPLETE || k == SOLVE_FORWARD_SIMPLE) && (block_triangular.ModelBlock->Block_List[i].Size))
-        {
-          if (open_par)
-            mDynamicModelFile << "  end\n";
-          open_par=false;
-          mDynamicModelFile << "  g1=0;\n";
-          mDynamicModelFile << "  r=0;\n";
-          tmp.str("");
-          for(int ik=0;ik<block_triangular.ModelBlock->Block_List[i].Size;ik++)
-            {
-              tmp << " " << block_triangular.ModelBlock->Block_List[i].Variable[ik]+1;
-            }
-          mDynamicModelFile << "  y_index = [" << tmp.str() << "];\n";
-          int nze, m;
-          for(nze=0,m=0;m<=block_triangular.ModelBlock->Block_List[i].Max_Lead+block_triangular.ModelBlock->Block_List[i].Max_Lag;m++)
-            nze+=block_triangular.ModelBlock->Block_List[i].IM_lead_lag[m].size;
-          mDynamicModelFile << "  if(isfield(oo_.deterministic_simulation,'block'))\n";
-          mDynamicModelFile << "    blck_num = length(oo_.deterministic_simulation.block)+1;\n";
-          mDynamicModelFile << "  else\n";
-          mDynamicModelFile << "    blck_num = 1;\n";
-          mDynamicModelFile << "  end;\n";
-          mDynamicModelFile << "  y = solve_one_boundary('"  << dynamic_basename << "_" <<  i + 1 << "'" <<
-                                                         ", y, x, params, y_index, " << nze <<
-                                                         ", options_.periods, " << block_triangular.ModelBlock->Block_List[i].is_linear <<
-                                                         ", blck_num, y_kmin, options_.maxit_, options_.solve_tolf, options_.slowc, options_.cutoff, options_.simulation_method, 1, 1, 0);\n";
+                    mDynamicModelFile << "  end\n";
+                  }
+                mDynamicModelFile << "  oo_.deterministic_simulation.status = 1;\n";
+                mDynamicModelFile << "  oo_.deterministic_simulation.error = 0;\n";
+                mDynamicModelFile << "  oo_.deterministic_simulation.iterations = 0;\n";
+                mDynamicModelFile << "  if(isfield(oo_.deterministic_simulation,'block'))\n";
+                mDynamicModelFile << "    blck_num = length(oo_.deterministic_simulation.block)+1;\n";
+                mDynamicModelFile << "  else\n";
+                mDynamicModelFile << "    blck_num = 1;\n";
+                mDynamicModelFile << "  end;\n";
+                mDynamicModelFile << "  oo_.deterministic_simulation.block(blck_num).status = 1;\n";
+                mDynamicModelFile << "  oo_.deterministic_simulation.block(blck_num).error = 0;\n";
+                mDynamicModelFile << "  oo_.deterministic_simulation.block(blck_num).iterations = 0;\n";
+                mDynamicModelFile << "  g1=[];g2=[];g3=[];\n";
+                mDynamicModelFile << "    " << dynamic_basename << "_" << i + 1 << "(y, x, params, 0, y_kmin, periods);\n";
+              }
+          }
+        else if ((k == SOLVE_FORWARD_COMPLETE || k == SOLVE_FORWARD_SIMPLE) && (block_triangular.ModelBlock->Block_List[i].Size))
+          {
+            if (open_par)
+              mDynamicModelFile << "  end\n";
+            open_par=false;
+            mDynamicModelFile << "  g1=0;\n";
+            mDynamicModelFile << "  r=0;\n";
+            tmp.str("");
+            for (int ik=0;ik<block_triangular.ModelBlock->Block_List[i].Size;ik++)
+              {
+                tmp << " " << block_triangular.ModelBlock->Block_List[i].Variable[ik]+1;
+              }
+            mDynamicModelFile << "  y_index = [" << tmp.str() << "];\n";
+            int nze, m;
+            for (nze=0,m=0;m<=block_triangular.ModelBlock->Block_List[i].Max_Lead+block_triangular.ModelBlock->Block_List[i].Max_Lag;m++)
+              nze+=block_triangular.ModelBlock->Block_List[i].IM_lead_lag[m].size;
+            mDynamicModelFile << "  if(isfield(oo_.deterministic_simulation,'block'))\n";
+            mDynamicModelFile << "    blck_num = length(oo_.deterministic_simulation.block)+1;\n";
+            mDynamicModelFile << "  else\n";
+            mDynamicModelFile << "    blck_num = 1;\n";
+            mDynamicModelFile << "  end;\n";
+            mDynamicModelFile << "  y = solve_one_boundary('"  << dynamic_basename << "_" <<  i + 1 << "'" <<
+            ", y, x, params, y_index, " << nze <<
+            ", options_.periods, " << block_triangular.ModelBlock->Block_List[i].is_linear <<
+            ", blck_num, y_kmin, options_.maxit_, options_.solve_tolf, options_.slowc, options_.cutoff, options_.simulation_method, 1, 1, 0);\n";
 
-        }
-      else if ((k == SOLVE_BACKWARD_COMPLETE || k == SOLVE_BACKWARD_SIMPLE) && (block_triangular.ModelBlock->Block_List[i].Size))
-        {
-          if (open_par)
-            mDynamicModelFile << "  end\n";
-          open_par=false;
-          mDynamicModelFile << "  g1=0;\n";
-          mDynamicModelFile << "  r=0;\n";
-          tmp.str("");
-          for(int ik=0;ik<block_triangular.ModelBlock->Block_List[i].Size;ik++)
-            {
-              tmp << " " << block_triangular.ModelBlock->Block_List[i].Variable[ik]+1;
-            }
-          mDynamicModelFile << "  y_index = [" << tmp.str() << "];\n";
-          int nze, m;
-          for(nze=0,m=0;m<=block_triangular.ModelBlock->Block_List[i].Max_Lead+block_triangular.ModelBlock->Block_List[i].Max_Lag;m++)
-            nze+=block_triangular.ModelBlock->Block_List[i].IM_lead_lag[m].size;
-          mDynamicModelFile << "  if(isfield(oo_.deterministic_simulation,'block'))\n";
-          mDynamicModelFile << "    blck_num = length(oo_.deterministic_simulation.block)+1;\n";
-          mDynamicModelFile << "  else\n";
-          mDynamicModelFile << "    blck_num = 1;\n";
-          mDynamicModelFile << "  end;\n";
-          mDynamicModelFile << "  y = solve_one_boundary('"  << dynamic_basename << "_" <<  i + 1 << "'" <<
-                                                         ", y, x, params, y_index, " << nze <<
-                                                         ", options_.periods, " << block_triangular.ModelBlock->Block_List[i].is_linear <<
-                                                         ", blck_num, y_kmin, options_.maxit_, options_.solve_tolf, options_.slowc, options_.cutoff, options_.simulation_method, 1, 1, 0);\n";
-        }
-      else if ((k == SOLVE_TWO_BOUNDARIES_COMPLETE || k == SOLVE_TWO_BOUNDARIES_SIMPLE) && (block_triangular.ModelBlock->Block_List[i].Size))
-        {
-          if (open_par)
-            mDynamicModelFile << "  end\n";
-          open_par=false;
-          if (!printed)
-            {
-              printed = true;
-            }
-          Nb_SGE++;
-          int nze, m;
-          for(nze=0,m=0;m<=block_triangular.ModelBlock->Block_List[i].Max_Lead+block_triangular.ModelBlock->Block_List[i].Max_Lag;m++)
-            nze+=block_triangular.ModelBlock->Block_List[i].IM_lead_lag[m].size;
-          mDynamicModelFile << "  y_index=[";
-          for(int ik=0;ik<block_triangular.ModelBlock->Block_List[i].Size;ik++)
-            {
-              mDynamicModelFile << " " << block_triangular.ModelBlock->Block_List[i].Variable[ik]+1;
-            }
-          mDynamicModelFile << "  ];\n";
-          mDynamicModelFile << "  if(isfield(oo_.deterministic_simulation,'block'))\n";
-          mDynamicModelFile << "    blck_num = length(oo_.deterministic_simulation.block)+1;\n";
-          mDynamicModelFile << "  else\n";
-          mDynamicModelFile << "    blck_num = 1;\n";
-          mDynamicModelFile << "  end;\n";
-          mDynamicModelFile << "  y = solve_two_boundaries('" << dynamic_basename << "_" <<  i + 1 << "'" <<
-                                                         ", y, x, params, y_index, " << nze <<
-                                                         ", options_.periods, " << block_triangular.ModelBlock->Block_List[i].Max_Lag <<
-                                                         ", " << block_triangular.ModelBlock->Block_List[i].Max_Lead <<
-                                                         ", " << block_triangular.ModelBlock->Block_List[i].is_linear <<
-                                                         ", blck_num, y_kmin, options_.maxit_, options_.solve_tolf, options_.slowc, options_.cutoff, options_.simulation_method);\n";
+          }
+        else if ((k == SOLVE_BACKWARD_COMPLETE || k == SOLVE_BACKWARD_SIMPLE) && (block_triangular.ModelBlock->Block_List[i].Size))
+          {
+            if (open_par)
+              mDynamicModelFile << "  end\n";
+            open_par=false;
+            mDynamicModelFile << "  g1=0;\n";
+            mDynamicModelFile << "  r=0;\n";
+            tmp.str("");
+            for (int ik=0;ik<block_triangular.ModelBlock->Block_List[i].Size;ik++)
+              {
+                tmp << " " << block_triangular.ModelBlock->Block_List[i].Variable[ik]+1;
+              }
+            mDynamicModelFile << "  y_index = [" << tmp.str() << "];\n";
+            int nze, m;
+            for (nze=0,m=0;m<=block_triangular.ModelBlock->Block_List[i].Max_Lead+block_triangular.ModelBlock->Block_List[i].Max_Lag;m++)
+              nze+=block_triangular.ModelBlock->Block_List[i].IM_lead_lag[m].size;
+            mDynamicModelFile << "  if(isfield(oo_.deterministic_simulation,'block'))\n";
+            mDynamicModelFile << "    blck_num = length(oo_.deterministic_simulation.block)+1;\n";
+            mDynamicModelFile << "  else\n";
+            mDynamicModelFile << "    blck_num = 1;\n";
+            mDynamicModelFile << "  end;\n";
+            mDynamicModelFile << "  y = solve_one_boundary('"  << dynamic_basename << "_" <<  i + 1 << "'" <<
+            ", y, x, params, y_index, " << nze <<
+            ", options_.periods, " << block_triangular.ModelBlock->Block_List[i].is_linear <<
+            ", blck_num, y_kmin, options_.maxit_, options_.solve_tolf, options_.slowc, options_.cutoff, options_.simulation_method, 1, 1, 0);\n";
+          }
+        else if ((k == SOLVE_TWO_BOUNDARIES_COMPLETE || k == SOLVE_TWO_BOUNDARIES_SIMPLE) && (block_triangular.ModelBlock->Block_List[i].Size))
+          {
+            if (open_par)
+              mDynamicModelFile << "  end\n";
+            open_par=false;
+            if (!printed)
+              {
+                printed = true;
+              }
+            Nb_SGE++;
+            int nze, m;
+            for (nze=0,m=0;m<=block_triangular.ModelBlock->Block_List[i].Max_Lead+block_triangular.ModelBlock->Block_List[i].Max_Lag;m++)
+              nze+=block_triangular.ModelBlock->Block_List[i].IM_lead_lag[m].size;
+            mDynamicModelFile << "  y_index=[";
+            for (int ik=0;ik<block_triangular.ModelBlock->Block_List[i].Size;ik++)
+              {
+                mDynamicModelFile << " " << block_triangular.ModelBlock->Block_List[i].Variable[ik]+1;
+              }
+            mDynamicModelFile << "  ];\n";
+            mDynamicModelFile << "  if(isfield(oo_.deterministic_simulation,'block'))\n";
+            mDynamicModelFile << "    blck_num = length(oo_.deterministic_simulation.block)+1;\n";
+            mDynamicModelFile << "  else\n";
+            mDynamicModelFile << "    blck_num = 1;\n";
+            mDynamicModelFile << "  end;\n";
+            mDynamicModelFile << "  y = solve_two_boundaries('" << dynamic_basename << "_" <<  i + 1 << "'" <<
+            ", y, x, params, y_index, " << nze <<
+            ", options_.periods, " << block_triangular.ModelBlock->Block_List[i].Max_Lag <<
+            ", " << block_triangular.ModelBlock->Block_List[i].Max_Lead <<
+            ", " << block_triangular.ModelBlock->Block_List[i].is_linear <<
+            ", blck_num, y_kmin, options_.maxit_, options_.solve_tolf, options_.slowc, options_.cutoff, options_.simulation_method);\n";
 
-        }
-      prev_Simulation_Type=k;
-    }
-  if(open_par)
-    mDynamicModelFile << "  end;\n";
-  open_par=false;
-  mDynamicModelFile << "  oo_.endo_simul = y';\n";
-  mDynamicModelFile << "return;\n";
+          }
+        prev_Simulation_Type=k;
+      }
+    if (open_par)
+      mDynamicModelFile << "  end;\n";
+    open_par=false;
+    mDynamicModelFile << "  oo_.endo_simul = y';\n";
+    mDynamicModelFile << "return;\n";
 
-  mDynamicModelFile.close();
+    mDynamicModelFile.close();
 
-  writeModelEquationsOrdered_M( block_triangular.ModelBlock, dynamic_basename);
+    writeModelEquationsOrdered_M( block_triangular.ModelBlock, dynamic_basename);
 
-  chdir("..");
-  if (printed)
-    cout << "done\n";
-}
+    chdir("..");
+    if (printed)
+      cout << "done\n";
+  }
 
 void
 ModelTree::writeDynamicModel(ostream &DynamicOutput) const
-{
-  ostringstream lsymetric;       // Used when writing symetric elements in Hessian
-  ostringstream model_output;    // Used for storing model equations
-  ostringstream jacobian_output; // Used for storing jacobian equations
-  ostringstream hessian_output;  // Used for storing Hessian equations
-  ostringstream third_derivatives_output;
-
-  ExprNodeOutputType output_type = (mode == eStandardMode || mode==eSparseMode ? oMatlabDynamicModel : oCDynamicModel);
+  {
+    ostringstream lsymetric;       // Used when writing symetric elements in Hessian
+    ostringstream model_output;    // Used for storing model equations
+    ostringstream jacobian_output; // Used for storing jacobian equations
+    ostringstream hessian_output;  // Used for storing Hessian equations
+    ostringstream third_derivatives_output;
 
-  writeModelLocalVariables(model_output, output_type);
+    ExprNodeOutputType output_type = (mode == eStandardMode || mode==eSparseMode ? oMatlabDynamicModel : oCDynamicModel);
 
-  writeTemporaryTerms(model_output, output_type);
+    writeModelLocalVariables(model_output, output_type);
 
-  writeModelEquations(model_output, output_type);
+    writeTemporaryTerms(model_output, output_type);
 
-  int nrows = equations.size();
-  int nvars = variable_table.getDynJacobianColsNbr(computeJacobianExo);
-  int nvars_sq = nvars * nvars;
+    writeModelEquations(model_output, output_type);
 
-  // Writing Jacobian
-  if (computeJacobian || computeJacobianExo)
-    for(first_derivatives_type::const_iterator it = first_derivatives.begin();
-        it != first_derivatives.end(); it++)
-      {
-        int eq = it->first.first;
-        int var = it->first.second;
-        NodeID d1 = it->second;
+    int nrows = equations.size();
+    int nvars = variable_table.getDynJacobianColsNbr(computeJacobianExo);
+    int nvars_sq = nvars * nvars;
 
-        if (computeJacobianExo || variable_table.getType(var) == eEndogenous)
-          {
-            ostringstream g1;
-            g1 << "  g1";
-            matrixHelper(g1, eq, variable_table.getDynJacobianCol(var), output_type);
+    // Writing Jacobian
+    if (computeJacobian || computeJacobianExo)
+      for (first_derivatives_type::const_iterator it = first_derivatives.begin();
+           it != first_derivatives.end(); it++)
+        {
+          int eq = it->first.first;
+          int var = it->first.second;
+          NodeID d1 = it->second;
 
-            jacobian_output << g1.str() << "=" << g1.str() << "+";
-            d1->writeOutput(jacobian_output, output_type, temporary_terms);
-            jacobian_output << ";" << endl;
-          }
-      }
+          if (computeJacobianExo || variable_table.getType(var) == eEndogenous)
+            {
+              ostringstream g1;
+              g1 << "  g1";
+              matrixHelper(g1, eq, variable_table.getDynJacobianCol(var), output_type);
 
-  // Writing Hessian
-  if (computeHessian)
-    for(second_derivatives_type::const_iterator it = second_derivatives.begin();
-        it != second_derivatives.end(); it++)
-      {
-        int eq = it->first.first;
-        int var1 = it->first.second.first;
-        int var2 = it->first.second.second;
-        NodeID d2 = it->second;
+              jacobian_output << g1.str() << "=" << g1.str() << "+";
+              d1->writeOutput(jacobian_output, output_type, temporary_terms);
+              jacobian_output << ";" << endl;
+            }
+        }
 
-        int id1 = variable_table.getDynJacobianCol(var1);
-        int id2 = variable_table.getDynJacobianCol(var2);
+    // Writing Hessian
+    if (computeHessian)
+      for (second_derivatives_type::const_iterator it = second_derivatives.begin();
+           it != second_derivatives.end(); it++)
+        {
+          int eq = it->first.first;
+          int var1 = it->first.second.first;
+          int var2 = it->first.second.second;
+          NodeID d2 = it->second;
 
-        int col_nb = id1*nvars+id2;
-        int col_nb_sym = id2*nvars+id1;
+          int id1 = variable_table.getDynJacobianCol(var1);
+          int id2 = variable_table.getDynJacobianCol(var2);
 
-        hessian_output << "  g2";
-        matrixHelper(hessian_output, eq, col_nb, output_type);
-        hessian_output << " = ";
-        d2->writeOutput(hessian_output, output_type, temporary_terms);
-        hessian_output << ";" << endl;
+          int col_nb = id1*nvars+id2;
+          int col_nb_sym = id2*nvars+id1;
 
-        // Treating symetric elements
-        if (id1 != id2)
-          {
-            lsymetric <<  "  g2";
-            matrixHelper(lsymetric, eq, col_nb_sym, output_type);
-            lsymetric << " = " <<  "g2";
-            matrixHelper(lsymetric, eq, col_nb, output_type);
-            lsymetric << ";" << endl;
-          }
-      }
+          hessian_output << "  g2";
+          matrixHelper(hessian_output, eq, col_nb, output_type);
+          hessian_output << " = ";
+          d2->writeOutput(hessian_output, output_type, temporary_terms);
+          hessian_output << ";" << endl;
 
-  // Writing third derivatives
-  if (computeThirdDerivatives)
-    for(third_derivatives_type::const_iterator it = third_derivatives.begin();
-        it != third_derivatives.end(); it++)
-      {
-        int eq = it->first.first;
-        int var1 = it->first.second.first;
-        int var2 = it->first.second.second.first;
-        int var3 = it->first.second.second.second;
-        NodeID d3 = it->second;
-
-        int id1 = variable_table.getDynJacobianCol(var1);
-        int id2 = variable_table.getDynJacobianCol(var2);
-        int id3 = variable_table.getDynJacobianCol(var3);
-
-        // Reference column number for the g3 matrix
-        int ref_col = id1 * nvars_sq + id2 * nvars + id3;
-
-        third_derivatives_output << "  g3";
-        matrixHelper(third_derivatives_output, eq, ref_col, output_type);
-        third_derivatives_output << " = ";
-        d3->writeOutput(third_derivatives_output, output_type, temporary_terms);
-        third_derivatives_output << ";" << endl;
-
-        // Compute the column numbers for the 5 other permutations of (id1,id2,id3) and store them in a set (to avoid duplicates if two indexes are equal)
-        set<int> cols;
-        cols.insert(id1 * nvars_sq + id3 * nvars + id2);
-        cols.insert(id2 * nvars_sq + id1 * nvars + id3);
-        cols.insert(id2 * nvars_sq + id3 * nvars + id1);
-        cols.insert(id3 * nvars_sq + id1 * nvars + id2);
-        cols.insert(id3 * nvars_sq + id2 * nvars + id1);
-
-        for(set<int>::iterator it2 = cols.begin(); it2 != cols.end(); it2++)
-          if (*it2 != ref_col)
+          // Treating symetric elements
+          if (id1 != id2)
             {
-              third_derivatives_output << "  g3";
-              matrixHelper(third_derivatives_output, eq, *it2, output_type);
-              third_derivatives_output << " = " << "g3";
-              matrixHelper(third_derivatives_output, eq, ref_col, output_type);
-              third_derivatives_output << ";" << endl;
+              lsymetric <<  "  g2";
+              matrixHelper(lsymetric, eq, col_nb_sym, output_type);
+              lsymetric << " = " <<  "g2";
+              matrixHelper(lsymetric, eq, col_nb, output_type);
+              lsymetric << ";" << endl;
             }
-      }
-
-  if (mode == eStandardMode)
-    {
-      DynamicOutput << "%" << endl
-                    << "% Model equations" << endl
-                    << "%" << endl
-                    << endl
-                    << "residual = zeros(" << nrows << ", 1);" << endl
-                    << model_output.str();
-
-      if (computeJacobian || computeJacobianExo)
-        {
-          // Writing initialization instruction for matrix g1
-          DynamicOutput << "if nargout >= 2," << endl
-                        << "  g1 = zeros(" << nrows << ", " << nvars << ");" << endl
-                        << endl
-                        << "%" << endl
-                        << "% Jacobian matrix" << endl
-                        << "%" << endl
-                        << endl
-                        << jacobian_output.str()
-                        << "end" << endl;
-        }
-      if (computeHessian)
-        {
-          // Writing initialization instruction for matrix g2
-          int ncols = nvars_sq;
-          DynamicOutput << "if nargout >= 3," << endl
-                        << "  g2 = sparse([],[],[], " << nrows << ", " << ncols << ", " << 5*ncols << ");" << endl
-                        << endl
-                        << "%" << endl
-                        << "% Hessian matrix" << endl
-                        << "%" << endl
-                        << endl
-                        << hessian_output.str()
-                        << lsymetric.str()
-                        << "end;" << endl;
-        }
-      if (computeThirdDerivatives)
-        {
-          int ncols = nvars_sq * nvars;
-          DynamicOutput << "if nargout >= 4," << endl
-                        << "  g3 = sparse([],[],[], " << nrows << ", " << ncols << ", " << 5*ncols << ");" << endl
-                        << endl
-                        << "%" << endl
-                        << "% Third order derivatives" << endl
-                        << "%" << endl
-                        << endl
-                        << third_derivatives_output.str()
-                        << "end;" << endl;
-        }
-    }
-  else
-    {
-      DynamicOutput << "void Dynamic(double *y, double *x, int nb_row_x, double *params, int it_, double *residual, double *g1, double *g2)" << endl
-                    << "{" << endl
-                    << "  double lhs, rhs;" << endl
-                    << endl
-                    << "  /* Residual equations */" << endl
-                    << model_output.str();
-
-      if (computeJacobian || computeJacobianExo)
-        {
-          DynamicOutput << "  /* Jacobian  */" << endl
-                        << "  if (g1 == NULL)" << endl
-                        << "    return;" << endl
-                        << "  else" << endl
-                        << "    {" << endl
-                        << jacobian_output.str()
-                        << "    }" << endl;
         }
-      if (computeHessian)
+
+    // Writing third derivatives
+    if (computeThirdDerivatives)
+      for (third_derivatives_type::const_iterator it = third_derivatives.begin();
+           it != third_derivatives.end(); it++)
         {
-          DynamicOutput << "  /* Hessian for endogenous and exogenous variables */" << endl
-                        << "  if (g2 == NULL)" << endl
-                        << "    return;" << endl
-                        << "  else" << endl
-                        << "    {" << endl
-                        << hessian_output.str()
-                        << lsymetric.str()
-                        << "    }" << endl;
+          int eq = it->first.first;
+          int var1 = it->first.second.first;
+          int var2 = it->first.second.second.first;
+          int var3 = it->first.second.second.second;
+          NodeID d3 = it->second;
+
+          int id1 = variable_table.getDynJacobianCol(var1);
+          int id2 = variable_table.getDynJacobianCol(var2);
+          int id3 = variable_table.getDynJacobianCol(var3);
+
+          // Reference column number for the g3 matrix
+          int ref_col = id1 * nvars_sq + id2 * nvars + id3;
+
+          third_derivatives_output << "  g3";
+          matrixHelper(third_derivatives_output, eq, ref_col, output_type);
+          third_derivatives_output << " = ";
+          d3->writeOutput(third_derivatives_output, output_type, temporary_terms);
+          third_derivatives_output << ";" << endl;
+
+          // Compute the column numbers for the 5 other permutations of (id1,id2,id3) and store them in a set (to avoid duplicates if two indexes are equal)
+          set<int> cols;
+          cols.insert(id1 * nvars_sq + id3 * nvars + id2);
+          cols.insert(id2 * nvars_sq + id1 * nvars + id3);
+          cols.insert(id2 * nvars_sq + id3 * nvars + id1);
+          cols.insert(id3 * nvars_sq + id1 * nvars + id2);
+          cols.insert(id3 * nvars_sq + id2 * nvars + id1);
+
+          for (set<int>::iterator it2 = cols.begin(); it2 != cols.end(); it2++)
+            if (*it2 != ref_col)
+              {
+                third_derivatives_output << "  g3";
+                matrixHelper(third_derivatives_output, eq, *it2, output_type);
+                third_derivatives_output << " = " << "g3";
+                matrixHelper(third_derivatives_output, eq, ref_col, output_type);
+                third_derivatives_output << ";" << endl;
+              }
         }
-      DynamicOutput << "}" << endl << endl;
-    }
-}
+
+    if (mode == eStandardMode)
+      {
+        DynamicOutput << "%" << endl
+        << "% Model equations" << endl
+        << "%" << endl
+        << endl
+        << "residual = zeros(" << nrows << ", 1);" << endl
+        << model_output.str();
+
+        if (computeJacobian || computeJacobianExo)
+          {
+            // Writing initialization instruction for matrix g1
+            DynamicOutput << "if nargout >= 2," << endl
+            << "  g1 = zeros(" << nrows << ", " << nvars << ");" << endl
+            << endl
+            << "%" << endl
+            << "% Jacobian matrix" << endl
+            << "%" << endl
+            << endl
+            << jacobian_output.str()
+            << "end" << endl;
+          }
+        if (computeHessian)
+          {
+            // Writing initialization instruction for matrix g2
+            int ncols = nvars_sq;
+            DynamicOutput << "if nargout >= 3," << endl
+            << "  g2 = sparse([],[],[], " << nrows << ", " << ncols << ", " << 5*ncols << ");" << endl
+            << endl
+            << "%" << endl
+            << "% Hessian matrix" << endl
+            << "%" << endl
+            << endl
+            << hessian_output.str()
+            << lsymetric.str()
+            << "end;" << endl;
+          }
+        if (computeThirdDerivatives)
+          {
+            int ncols = nvars_sq * nvars;
+            DynamicOutput << "if nargout >= 4," << endl
+            << "  g3 = sparse([],[],[], " << nrows << ", " << ncols << ", " << 5*ncols << ");" << endl
+            << endl
+            << "%" << endl
+            << "% Third order derivatives" << endl
+            << "%" << endl
+            << endl
+            << third_derivatives_output.str()
+            << "end;" << endl;
+          }
+      }
+    else
+      {
+        DynamicOutput << "void Dynamic(double *y, double *x, int nb_row_x, double *params, int it_, double *residual, double *g1, double *g2)" << endl
+        << "{" << endl
+        << "  double lhs, rhs;" << endl
+        << endl
+        << "  /* Residual equations */" << endl
+        << model_output.str();
+
+        if (computeJacobian || computeJacobianExo)
+          {
+            DynamicOutput << "  /* Jacobian  */" << endl
+            << "  if (g1 == NULL)" << endl
+            << "    return;" << endl
+            << "  else" << endl
+            << "    {" << endl
+            << jacobian_output.str()
+            << "    }" << endl;
+          }
+        if (computeHessian)
+          {
+            DynamicOutput << "  /* Hessian for endogenous and exogenous variables */" << endl
+            << "  if (g2 == NULL)" << endl
+            << "    return;" << endl
+            << "  else" << endl
+            << "    {" << endl
+            << hessian_output.str()
+            << lsymetric.str()
+            << "    }" << endl;
+          }
+        DynamicOutput << "}" << endl << endl;
+      }
+  }
 
 void
 ModelTree::writeOutput(ostream &output) const
-{
-  /* Writing initialisation for M_.lead_lag_incidence matrix
-     M_.lead_lag_incidence is a matrix with as many columns as there are
-     endogenous variables and as many rows as there are periods in the
-     models (nbr of rows = M_.max_lag+M_.max_lead+1)
-
-     The matrix elements are equal to zero if a variable isn't present in the
-     model at a given period.
-  */
-  output << "M_.lead_lag_incidence = [";
-  // Loop on endogenous variables
-  int lag = 0;
-  for(int endoID = 0; endoID < symbol_table.endo_nbr; endoID++)
-    {
-      output << "\n\t";
-      // Loop on periods
-      for(lag = -variable_table.max_endo_lag; lag <= variable_table.max_endo_lead; lag++)
-        {
-          // Print variableID if exists with current period, otherwise print 0
-          try
-            {
-              int varID = variable_table.getID(eEndogenous, endoID, lag);
-              output << " " << variable_table.getDynJacobianCol(varID) + 1;
-            }
-          catch(VariableTable::UnknownVariableKeyException &e)
-            {
-              output << " 0";
-            }
-        }
-      output << ";";
-    }
-  output << "]';\n";
-  //In case of sparse model, writes the block structure of the model
+  {
+    /* Writing initialisation for M_.lead_lag_incidence matrix
+       M_.lead_lag_incidence is a matrix with as many columns as there are
+       endogenous variables and as many rows as there are periods in the
+       models (nbr of rows = M_.max_lag+M_.max_lead+1)
+
+       The matrix elements are equal to zero if a variable isn't present in the
+       model at a given period.
+    */
+    output << "M_.lead_lag_incidence = [";
+    // Loop on endogenous variables
+    int lag = 0;
+    for (int endoID = 0; endoID < symbol_table.endo_nbr; endoID++)
+      {
+        output << "\n\t";
+        // Loop on periods
+        for (lag = -variable_table.max_endo_lag; lag <= variable_table.max_endo_lead; lag++)
+          {
+            // Print variableID if exists with current period, otherwise print 0
+            try
+              {
+                int varID = variable_table.getID(eEndogenous, endoID, lag);
+                output << " " << variable_table.getDynJacobianCol(varID) + 1;
+              }
+            catch (VariableTable::UnknownVariableKeyException &e)
+              {
+                output << " 0";
+              }
+          }
+        output << ";";
+      }
+    output << "]';\n";
+    //In case of sparse model, writes the block structure of the model
 
-  if(mode==eSparseMode || mode==eSparseDLLMode)
-    {
-      int prev_Simulation_Type=-1;
-      bool skip_the_head;
-      int k=0;
-      int count_lead_lag_incidence = 0;
-      int max_lead, max_lag, max_lag_endo, max_lead_endo, max_lag_exo, max_lead_exo;
-      for(int j = 0;j < block_triangular.ModelBlock->Size;j++)
-        {
-          //For a block composed of a single equation determines wether we have to evaluate or to solve the equation
-          if (BlockTriangular::BlockSim(prev_Simulation_Type)==BlockTriangular::BlockSim(block_triangular.ModelBlock->Block_List[j].Simulation_Type)
-              && (block_triangular.ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD
+    if (mode==eSparseMode || mode==eSparseDLLMode)
+      {
+        //int prev_Simulation_Type=-1;
+        //bool skip_the_head;
+        int k=0;
+        int count_lead_lag_incidence = 0;
+        int max_lead, max_lag, max_lag_endo, max_lead_endo, max_lag_exo, max_lead_exo;
+        for (int j = 0;j < block_triangular.ModelBlock->Size;j++)
+          {
+            //For a block composed of a single equation determines wether we have to evaluate or to solve the equation
+            //skip_the_head=false;
+            k++;
+            count_lead_lag_incidence = 0;
+            int Block_size=block_triangular.ModelBlock->Block_List[j].Size;
+            max_lag =block_triangular.ModelBlock->Block_List[j].Max_Lag ;
+            max_lead=block_triangular.ModelBlock->Block_List[j].Max_Lead;
+            max_lag_endo =block_triangular.ModelBlock->Block_List[j].Max_Lag_Endo ;
+            max_lead_endo=block_triangular.ModelBlock->Block_List[j].Max_Lead_Endo;
+            max_lag_exo =block_triangular.ModelBlock->Block_List[j].Max_Lag_Exo ;
+            max_lead_exo=block_triangular.ModelBlock->Block_List[j].Max_Lead_Exo;
+            bool evaluate=false;
+            vector<int> exogenous;
+            vector<int>::iterator it_exogenous;
+            exogenous.clear();
+            ostringstream tmp_s, tmp_s_eq;
+            tmp_s.str("");
+            tmp_s_eq.str("");
+            for (int i=0;i<block_triangular.ModelBlock->Block_List[j].Size;i++)
+              {
+                tmp_s << " " << block_triangular.ModelBlock->Block_List[j].Variable[i]+1;
+                tmp_s_eq << " " << block_triangular.ModelBlock->Block_List[j].Equation[i]+1;
+              }
+            for (int i=0;i<block_triangular.ModelBlock->Block_List[j].nb_exo;i++)
+              {
+                int ii=block_triangular.ModelBlock->Block_List[j].Exogenous[i];
+                for (it_exogenous=exogenous.begin();it_exogenous!=exogenous.end() && *it_exogenous!=ii;it_exogenous++) /*cout << "*it_exogenous=" << *it_exogenous << "\n"*/;
+                if (it_exogenous==exogenous.end() || exogenous.begin()==exogenous.end())
+                  exogenous.push_back(ii);
+              }
+            /*if ((block_triangular.ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD
               ||block_triangular.ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD
               ||block_triangular.ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD_R
-              ||block_triangular.ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD_R ))
-             skip_the_head=true;
-          else
-            {
-              skip_the_head=false;
-              k++;
-              count_lead_lag_incidence = 0;
-              int Block_size=block_triangular.ModelBlock->Block_List[j].Size;
-              max_lag =block_triangular.ModelBlock->Block_List[j].Max_Lag ;
-              max_lead=block_triangular.ModelBlock->Block_List[j].Max_Lead;
-              max_lag_endo =block_triangular.ModelBlock->Block_List[j].Max_Lag_Endo ;
-              max_lead_endo=block_triangular.ModelBlock->Block_List[j].Max_Lead_Endo;
-              max_lag_exo =block_triangular.ModelBlock->Block_List[j].Max_Lag_Exo ;
-              max_lead_exo=block_triangular.ModelBlock->Block_List[j].Max_Lead_Exo;
-              bool evaluate=false;
-              vector<int> exogenous;
-              vector<int>::iterator it_exogenous;
-              exogenous.clear();
-              ostringstream tmp_s, tmp_s_eq;
-              tmp_s.str("");
-              tmp_s_eq.str("");
-              for(int i=0;i<block_triangular.ModelBlock->Block_List[j].Size;i++)
-                {
-                  tmp_s << " " << block_triangular.ModelBlock->Block_List[j].Variable[i]+1;
-                  tmp_s_eq << " " << block_triangular.ModelBlock->Block_List[j].Equation[i]+1;
-                }
-              for(int i=0;i<block_triangular.ModelBlock->Block_List[j].nb_exo;i++)
-                {
-                  int ii=block_triangular.ModelBlock->Block_List[j].Exogenous[i];
-                  for(it_exogenous=exogenous.begin();it_exogenous!=exogenous.end() && *it_exogenous!=ii;it_exogenous++) /*cout << "*it_exogenous=" << *it_exogenous << "\n"*/;
-                  if(it_exogenous==exogenous.end() || exogenous.begin()==exogenous.end())
-                    exogenous.push_back(ii);
-                }
-              if (block_triangular.ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD
-                ||block_triangular.ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD
-                ||block_triangular.ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD_R
-                ||block_triangular.ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD_R
-                && j+Block_size<(block_triangular.ModelBlock->Size))
-                {
-                  bool OK=true;
-                  evaluate=true;
-                  while(j+Block_size<(block_triangular.ModelBlock->Size) && OK)
-                    {
-                      if(BlockTriangular::BlockSim(block_triangular.ModelBlock->Block_List[j].Simulation_Type)!=BlockTriangular::BlockSim(block_triangular.ModelBlock->Block_List[j+Block_size].Simulation_Type))
-                        OK=false;
-                      else
-                        {
-                          if(max_lag <block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lag )
-                            max_lag =block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lag ;
-                          if(max_lead<block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lead)
-                            max_lead=block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lead;
-                          if(max_lag_endo <block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lag_Endo )
-                            max_lag_endo =block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lag_Endo ;
-                          if(max_lead_endo<block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lead_Endo)
-                            max_lead_endo=block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lead_Endo;
-                          if(max_lag_exo <block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lag_Exo )
-                            max_lag_exo =block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lag_Exo ;
-                          if(max_lead_exo<block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lead_Exo)
-                            max_lead_exo=block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lead_Exo;
-                          for(int i=0;i<block_triangular.ModelBlock->Block_List[j+Block_size].Size;i++)
-                            {
-                              tmp_s << " " << block_triangular.ModelBlock->Block_List[j+Block_size].Variable[i]+1;
-                              tmp_s_eq << " " << block_triangular.ModelBlock->Block_List[j+Block_size].Equation[i]+1;
-                            }
-                          for(int i=0;i<block_triangular.ModelBlock->Block_List[j+Block_size].nb_exo;i++)
-                            {
-                              int ii=block_triangular.ModelBlock->Block_List[j+Block_size].Exogenous[i];
-                              if(it_exogenous==exogenous.end())
-                                exogenous.push_back(ii);
-                            }
-                          Block_size+=block_triangular.ModelBlock->Block_List[j+Block_size].Size;
-                        }
-                    }
-                }
-              output << "M_.block_structure.block(" << k << ").num = " << j+1 << ";\n";
-              output << "M_.block_structure.block(" << k << ").Simulation_Type = " << block_triangular.ModelBlock->Block_List[j].Simulation_Type << ";\n";
-              output << "M_.block_structure.block(" << k << ").maximum_lag = " << max_lag << ";\n";
-              output << "M_.block_structure.block(" << k << ").maximum_lead = " << max_lead << ";\n";
-              output << "M_.block_structure.block(" << k << ").maximum_endo_lag = " << max_lag_endo << ";\n";
-              output << "M_.block_structure.block(" << k << ").maximum_endo_lead = " << max_lead_endo << ";\n";
-              output << "M_.block_structure.block(" << k << ").maximum_exo_lag = " << max_lag_exo << ";\n";
-              output << "M_.block_structure.block(" << k << ").maximum_exo_lead = " << max_lead_exo << ";\n";
-              output << "M_.block_structure.block(" << k << ").endo_nbr = " << Block_size << ";\n";
-              output << "M_.block_structure.block(" << k << ").equation = [" << tmp_s_eq.str() << "];\n";
-              output << "M_.block_structure.block(" << k << ").variable = [" << tmp_s.str() << "];\n";
-              output << "M_.block_structure.block(" << k << ").exogenous = [";
-              int i=0;
-              for(it_exogenous=exogenous.begin();it_exogenous!=exogenous.end();it_exogenous++)
-                if(*it_exogenous>=0)
+              ||block_triangular.ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD_R)
+              && j+Block_size<(block_triangular.ModelBlock->Size))
+              {
+                bool OK=true;
+                evaluate=true;
+                while(j+Block_size<(block_triangular.ModelBlock->Size) && OK)
                   {
-                    output << " " << *it_exogenous+1;
-                    i++;
+                    if(BlockTriangular::BlockSim(block_triangular.ModelBlock->Block_List[j].Simulation_Type)!=BlockTriangular::BlockSim(block_triangular.ModelBlock->Block_List[j+Block_size].Simulation_Type))
+                      OK=false;
+                    else
+                      {
+                        if(max_lag <block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lag )
+                          max_lag =block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lag ;
+                        if(max_lead<block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lead)
+                          max_lead=block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lead;
+                        if(max_lag_endo <block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lag_Endo )
+                          max_lag_endo =block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lag_Endo ;
+                        if(max_lead_endo<block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lead_Endo)
+                          max_lead_endo=block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lead_Endo;
+                        if(max_lag_exo <block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lag_Exo )
+                          max_lag_exo =block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lag_Exo ;
+                        if(max_lead_exo<block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lead_Exo)
+                          max_lead_exo=block_triangular.ModelBlock->Block_List[j+Block_size].Max_Lead_Exo;
+                        for(int i=0;i<block_triangular.ModelBlock->Block_List[j+Block_size].Size;i++)
+                          {
+                            tmp_s << " " << block_triangular.ModelBlock->Block_List[j+Block_size].Variable[i]+1;
+                            tmp_s_eq << " " << block_triangular.ModelBlock->Block_List[j+Block_size].Equation[i]+1;
+                          }
+                        for(int i=0;i<block_triangular.ModelBlock->Block_List[j+Block_size].nb_exo;i++)
+                          {
+                            int ii=block_triangular.ModelBlock->Block_List[j+Block_size].Exogenous[i];
+                            if(it_exogenous==exogenous.end())
+                              exogenous.push_back(ii);
+                          }
+                        Block_size+=block_triangular.ModelBlock->Block_List[j+Block_size].Size;
+                      }
                   }
-              output << "];\n";
-              output << "M_.block_structure.block(" << k << ").exo_nbr = " << i << ";\n";
+              }*/
+            output << "M_.block_structure.block(" << k << ").num = " << j+1 << ";\n";
+            output << "M_.block_structure.block(" << k << ").Simulation_Type = " << block_triangular.ModelBlock->Block_List[j].Simulation_Type << ";\n";
+            output << "M_.block_structure.block(" << k << ").maximum_lag = " << max_lag << ";\n";
+            output << "M_.block_structure.block(" << k << ").maximum_lead = " << max_lead << ";\n";
+            output << "M_.block_structure.block(" << k << ").maximum_endo_lag = " << max_lag_endo << ";\n";
+            output << "M_.block_structure.block(" << k << ").maximum_endo_lead = " << max_lead_endo << ";\n";
+            output << "M_.block_structure.block(" << k << ").maximum_exo_lag = " << max_lag_exo << ";\n";
+            output << "M_.block_structure.block(" << k << ").maximum_exo_lead = " << max_lead_exo << ";\n";
+            output << "M_.block_structure.block(" << k << ").endo_nbr = " << Block_size << ";\n";
+            output << "M_.block_structure.block(" << k << ").equation = [" << tmp_s_eq.str() << "];\n";
+            output << "M_.block_structure.block(" << k << ").variable = [" << tmp_s.str() << "];\n";
+            output << "M_.block_structure.block(" << k << ").exogenous = [";
+            int i=0;
+            for (it_exogenous=exogenous.begin();it_exogenous!=exogenous.end();it_exogenous++)
+              if (*it_exogenous>=0)
+                {
+                  output << " " << *it_exogenous+1;
+                  i++;
+                }
+            output << "];\n";
+            output << "M_.block_structure.block(" << k << ").exo_nbr = " << i << ";\n";
 
-              output << "M_.block_structure.block(" << k << ").exo_det_nbr = " << block_triangular.ModelBlock->Block_List[j].nb_exo_det << ";\n";
+            output << "M_.block_structure.block(" << k << ").exo_det_nbr = " << block_triangular.ModelBlock->Block_List[j].nb_exo_det << ";\n";
 
-              tmp_s.str("");
+            tmp_s.str("");
 
-              bool done_IM=false;
-              if(!evaluate)
-                {
-                  output << "M_.block_structure.block(" << k << ").lead_lag_incidence = [];\n";
-                  for(int l=-max_lag_endo;l<max_lead_endo+1;l++)
-                    {
-                      bool *tmp_IM;
-                      tmp_IM=block_triangular.incidencematrix.Get_IM(l, eEndogenous);
-                      if(tmp_IM)
-                        {
-                          for(int l_var=0;l_var<block_triangular.ModelBlock->Block_List[j].Size;l_var++)
-                            {
-                              for(int l_equ=0;l_equ<block_triangular.ModelBlock->Block_List[j].Size;l_equ++)
-                                if(tmp_IM[block_triangular.ModelBlock->Block_List[j].Equation[l_equ]*symbol_table.endo_nbr+block_triangular.ModelBlock->Block_List[j].Variable[l_var]])
-                                  {
-                                    count_lead_lag_incidence++;
-                                    if(tmp_s.str().length())
-                                      tmp_s << " ";
-                                    tmp_s << count_lead_lag_incidence;
-                                    done_IM=true;
-                                    break;
-                                  }
-                              if(!done_IM)
-                                tmp_s << " 0";
-                              done_IM=false;
-                            }
-                           output << "M_.block_structure.block(" << k << ").lead_lag_incidence = [ M_.block_structure.block(" << k << ").lead_lag_incidence; " << tmp_s.str() << "];\n";
-                           tmp_s.str("");
-                        }
-                    }
-                }
-              else
-                {
-                  bool done_some_where;
-                  output << "M_.block_structure.block(" << k << ").lead_lag_incidence = [\n";
-                  for(int l=-max_lag_endo;l<max_lead_endo+1;l++)
-                    {
-                      bool not_increm=true;
-                      bool *tmp_IM;
-                      tmp_IM=block_triangular.incidencematrix.Get_IM(l, eEndogenous);
-                      int ii=j;
-                      if(tmp_IM)
-                        {
-                          done_some_where = false;
-                          while(ii-j<Block_size)
-                            {
-                              for(int l_var=0;l_var<block_triangular.ModelBlock->Block_List[ii].Size;l_var++)
+            bool done_IM=false;
+            if (!evaluate)
+              {
+                output << "M_.block_structure.block(" << k << ").lead_lag_incidence = [];\n";
+                for (int l=-max_lag_endo;l<max_lead_endo+1;l++)
+                  {
+                    bool *tmp_IM;
+                    tmp_IM=block_triangular.incidencematrix.Get_IM(l, eEndogenous);
+                    if (tmp_IM)
+                      {
+                        for (int l_var=0;l_var<block_triangular.ModelBlock->Block_List[j].Size;l_var++)
+                          {
+                            for (int l_equ=0;l_equ<block_triangular.ModelBlock->Block_List[j].Size;l_equ++)
+                              if (tmp_IM[block_triangular.ModelBlock->Block_List[j].Equation[l_equ]*symbol_table.endo_nbr+block_triangular.ModelBlock->Block_List[j].Variable[l_var]])
                                 {
-                                  for(int l_equ=0;l_equ<block_triangular.ModelBlock->Block_List[ii].Size;l_equ++)
-                                    if(tmp_IM[block_triangular.ModelBlock->Block_List[ii].Equation[l_equ]*symbol_table.endo_nbr+block_triangular.ModelBlock->Block_List[ii].Variable[l_var]])
-                                      {
-                                        //if(not_increm && l==-max_lag)
-                                          count_lead_lag_incidence++;
-                                        not_increm=false;
-                                        if(tmp_s.str().length())
-                                          tmp_s << " ";
-                                        //tmp_s << count_lead_lag_incidence+(l+max_lag)*Block_size;
-                                        tmp_s << count_lead_lag_incidence;
-                                        done_IM=true;
-                                        break;
-                                      }
-                                  if(!done_IM)
-                                    tmp_s << " 0";
-                                  else
-                                    done_some_where = true;
-                                  done_IM=false;
+                                  count_lead_lag_incidence++;
+                                  if (tmp_s.str().length())
+                                    tmp_s << " ";
+                                  tmp_s << count_lead_lag_incidence;
+                                  done_IM=true;
+                                  break;
                                 }
-                              ii++;
-                            }
-                          output << tmp_s.str() << "\n";
-                          tmp_s.str("");
-                        }
-                    }
-                  output << "];\n";
-                }
-            }
-          prev_Simulation_Type=block_triangular.ModelBlock->Block_List[j].Simulation_Type;
+                            if (!done_IM)
+                              tmp_s << " 0";
+                            done_IM=false;
+                          }
+                        output << "M_.block_structure.block(" << k << ").lead_lag_incidence = [ M_.block_structure.block(" << k << ").lead_lag_incidence; " << tmp_s.str() << "];\n";
+                        tmp_s.str("");
+                      }
+                  }
+              }
+            else
+              {
+                bool done_some_where;
+                output << "M_.block_structure.block(" << k << ").lead_lag_incidence = [\n";
+                for (int l=-max_lag_endo;l<max_lead_endo+1;l++)
+                  {
+                    bool not_increm=true;
+                    bool *tmp_IM;
+                    tmp_IM=block_triangular.incidencematrix.Get_IM(l, eEndogenous);
+                    int ii=j;
+                    if (tmp_IM)
+                      {
+                        done_some_where = false;
+                        while (ii-j<Block_size)
+                          {
+                            for (int l_var=0;l_var<block_triangular.ModelBlock->Block_List[ii].Size;l_var++)
+                              {
+                                for (int l_equ=0;l_equ<block_triangular.ModelBlock->Block_List[ii].Size;l_equ++)
+                                  if (tmp_IM[block_triangular.ModelBlock->Block_List[ii].Equation[l_equ]*symbol_table.endo_nbr+block_triangular.ModelBlock->Block_List[ii].Variable[l_var]])
+                                    {
+                                      //if(not_increm && l==-max_lag)
+                                      count_lead_lag_incidence++;
+                                      not_increm=false;
+                                      if (tmp_s.str().length())
+                                        tmp_s << " ";
+                                      //tmp_s << count_lead_lag_incidence+(l+max_lag)*Block_size;
+                                      tmp_s << count_lead_lag_incidence;
+                                      done_IM=true;
+                                      break;
+                                    }
+                                if (!done_IM)
+                                  tmp_s << " 0";
+                                else
+                                  done_some_where = true;
+                                done_IM=false;
+                              }
+                            ii++;
+                          }
+                        output << tmp_s.str() << "\n";
+                        tmp_s.str("");
+                      }
+                  }
+                output << "];\n";
+              }
 
-        }
-      for(int j=-block_triangular.incidencematrix.Model_Max_Lag_Endo;j<=block_triangular.incidencematrix.Model_Max_Lead_Endo;j++)
-        {
-          bool* IM = block_triangular.incidencematrix.Get_IM(j, eEndogenous);
-          if(IM)
-            {
-              bool new_entry=true;
-              output << "M_.block_structure.incidence(" << block_triangular.incidencematrix.Model_Max_Lag_Endo+j+1 << ").lead_lag = " << j << ";\n";
-              output << "M_.block_structure.incidence(" << block_triangular.incidencematrix.Model_Max_Lag_Endo+j+1 << ").sparse_IM = [";
-              for(int i=0;i<symbol_table.endo_nbr*symbol_table.endo_nbr;i++)
-                {
-                  if(IM[i])
-                    {
-                      if(!new_entry)
-                        output << " ; ";
-                      else
-                        output << " ";
-                      output << i/symbol_table.endo_nbr+1 << " " << i % symbol_table.endo_nbr+1;
-                      new_entry=false;
-                    }
-                }
-              output << "];\n";
-            }
-        }
-    }
-  // Writing initialization for some other variables
-  output << "M_.exo_names_orig_ord = [1:" << symbol_table.exo_nbr << "];\n";
-  output << "M_.maximum_lag = " << variable_table.max_lag << ";\n";
-  output << "M_.maximum_lead = " << variable_table.max_lead << ";\n";
-  if (symbol_table.endo_nbr)
-    {
-      output << "M_.maximum_endo_lag = " << variable_table.max_endo_lag << ";\n";
-      output << "M_.maximum_endo_lead = " << variable_table.max_endo_lead << ";\n";
-      output << "oo_.steady_state = zeros(" << symbol_table.endo_nbr << ", 1);\n";
-    }
-  if (symbol_table.exo_nbr)
-    {
-      output << "M_.maximum_exo_lag = " << variable_table.max_exo_lag << ";\n";
-      output << "M_.maximum_exo_lead = " << variable_table.max_exo_lead << ";\n";
-      output << "oo_.exo_steady_state = zeros(" << symbol_table.exo_nbr << ", 1);\n";
-    }
-  if (symbol_table.exo_det_nbr)
-    {
-      output << "M_.maximum_exo_det_lag = " << variable_table.max_exo_det_lag << ";\n";
-      output << "M_.maximum_exo_det_lead = " << variable_table.max_exo_det_lead << ";\n";
-      output << "oo_.exo_det_steady_state = zeros(" << symbol_table.exo_det_nbr << ", 1);\n";
-    }
-  if (symbol_table.parameter_nbr)
-    output << "M_.params = repmat(NaN," << symbol_table.parameter_nbr << ", 1);\n";
-}
+          }
+        for (int j=-block_triangular.incidencematrix.Model_Max_Lag_Endo;j<=block_triangular.incidencematrix.Model_Max_Lead_Endo;j++)
+          {
+            bool* IM = block_triangular.incidencematrix.Get_IM(j, eEndogenous);
+            if (IM)
+              {
+                bool new_entry=true;
+                output << "M_.block_structure.incidence(" << block_triangular.incidencematrix.Model_Max_Lag_Endo+j+1 << ").lead_lag = " << j << ";\n";
+                output << "M_.block_structure.incidence(" << block_triangular.incidencematrix.Model_Max_Lag_Endo+j+1 << ").sparse_IM = [";
+                for (int i=0;i<symbol_table.endo_nbr*symbol_table.endo_nbr;i++)
+                  {
+                    if (IM[i])
+                      {
+                        if (!new_entry)
+                          output << " ; ";
+                        else
+                          output << " ";
+                        output << i/symbol_table.endo_nbr+1 << " " << i % symbol_table.endo_nbr+1;
+                        new_entry=false;
+                      }
+                  }
+                output << "];\n";
+              }
+          }
+      }
+    // Writing initialization for some other variables
+    output << "M_.exo_names_orig_ord = [1:" << symbol_table.exo_nbr << "];\n";
+    output << "M_.maximum_lag = " << variable_table.max_lag << ";\n";
+    output << "M_.maximum_lead = " << variable_table.max_lead << ";\n";
+    if (symbol_table.endo_nbr)
+      {
+        output << "M_.maximum_endo_lag = " << variable_table.max_endo_lag << ";\n";
+        output << "M_.maximum_endo_lead = " << variable_table.max_endo_lead << ";\n";
+        output << "oo_.steady_state = zeros(" << symbol_table.endo_nbr << ", 1);\n";
+      }
+    if (symbol_table.exo_nbr)
+      {
+        output << "M_.maximum_exo_lag = " << variable_table.max_exo_lag << ";\n";
+        output << "M_.maximum_exo_lead = " << variable_table.max_exo_lead << ";\n";
+        output << "oo_.exo_steady_state = zeros(" << symbol_table.exo_nbr << ", 1);\n";
+      }
+    if (symbol_table.exo_det_nbr)
+      {
+        output << "M_.maximum_exo_det_lag = " << variable_table.max_exo_det_lag << ";\n";
+        output << "M_.maximum_exo_det_lead = " << variable_table.max_exo_det_lead << ";\n";
+        output << "oo_.exo_det_steady_state = zeros(" << symbol_table.exo_det_nbr << ", 1);\n";
+      }
+    if (symbol_table.parameter_nbr)
+      output << "M_.params = repmat(NaN," << symbol_table.parameter_nbr << ", 1);\n";
+  }
 
 void
 ModelTree::addEquation(NodeID eq)
@@ -3010,8 +2977,8 @@ ModelTree::evaluateJacobian(const eval_context_type &eval_context, jacob_map *j_
   int j=0;
   bool *IM=NULL;
   int a_variable_lag=-9999;
-  for(first_derivatives_type::iterator it = first_derivatives.begin();
-      it != first_derivatives.end(); it++)
+  for (first_derivatives_type::iterator it = first_derivatives.begin();
+       it != first_derivatives.end(); it++)
     {
       if (variable_table.getType(it->first.second) == eEndogenous)
         {
@@ -3021,10 +2988,11 @@ ModelTree::evaluateJacobian(const eval_context_type &eval_context, jacob_map *j_
             {
               val = Id->eval(eval_context);
             }
-          catch(ExprNode::EvalException &e)
+          catch (ExprNode::EvalException &e)
             {
               cout << "evaluation of Jacobian failed for equation " << it->first.first+1 << " and variable " << symbol_table.getNameByID(eEndogenous, variable_table.getSymbolID(it->first.second)) << "(" << variable_table.getLag(it->first.second) << ") [" << variable_table.getSymbolID(it->first.second) << "] !" << endl;
-              Id->writeOutput(cout, oMatlabDynamicModelSparse, temporary_terms);cout << "\n";
+              Id->writeOutput(cout, oMatlabDynamicModelSparse, temporary_terms);
+              cout << "\n";
               cerr << "ModelTree::evaluateJacobian: evaluation of Jacobian failed for equation " << it->first.first+1 << " and variable " << symbol_table.getNameByID(eEndogenous, variable_table.getSymbolID(it->first.second)) << "(" << variable_table.getLag(it->first.second) << ")!" << endl;
             }
           int eq=it->first.first;
@@ -3042,7 +3010,7 @@ ModelTree::evaluateJacobian(const eval_context_type &eval_context, jacob_map *j_
             }
           if (IM[eq*symbol_table.endo_nbr+var] && (fabs(val) < cutoff))
             {
-              if(block_triangular.bt_verbose)
+              if (block_triangular.bt_verbose)
                 cout << "the coefficient related to variable " << var << " with lag " << k1 << " in equation " << eq << " is equal to " << val << " and is set to 0 in the incidence matrix (size=" << symbol_table.endo_nbr << ")\n";
               block_triangular.incidencematrix.unfill_IM(eq, var, k1, eEndogenous);
               i++;
@@ -3060,13 +3028,13 @@ void
 ModelTree::BlockLinear(Model_Block *ModelBlock)
 {
   int i,j,l,m,ll;
-  for(j = 0;j < ModelBlock->Size;j++)
+  for (j = 0;j < ModelBlock->Size;j++)
     {
       if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_BACKWARD_COMPLETE ||
           ModelBlock->Block_List[j].Simulation_Type==SOLVE_FORWARD_COMPLETE)
         {
           ll=ModelBlock->Block_List[j].Max_Lag;
-          for(i=0;i<ModelBlock->Block_List[j].IM_lead_lag[ll].size;i++)
+          for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[ll].size;i++)
             {
               int eq=ModelBlock->Block_List[j].IM_lead_lag[ll].Equ_Index[i];
               int var=ModelBlock->Block_List[j].IM_lead_lag[ll].Var_Index[i];
@@ -3078,7 +3046,7 @@ ModelTree::BlockLinear(Model_Block *ModelBlock)
                   Id->collectEndogenous(endogenous);
                   if (endogenous.size() > 0)
                     {
-                      for(l=0;l<ModelBlock->Block_List[j].Size;l++)
+                      for (l=0;l<ModelBlock->Block_List[j].Size;l++)
                         {
                           if (endogenous.find(make_pair(ModelBlock->Block_List[j].Variable[l], 0)) != endogenous.end())
                             {
@@ -3092,10 +3060,10 @@ ModelTree::BlockLinear(Model_Block *ModelBlock)
         }
       else if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_COMPLETE || ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_SIMPLE)
         {
-          for(m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
+          for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
             {
               int k1=m-ModelBlock->Block_List[j].Max_Lag;
-              for(i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
+              for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
                 {
                   int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
                   int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
@@ -3107,7 +3075,7 @@ ModelTree::BlockLinear(Model_Block *ModelBlock)
                       Id->collectEndogenous(endogenous);
                       if (endogenous.size() > 0)
                         {
-                          for(l=0;l<ModelBlock->Block_List[j].Size;l++)
+                          for (l=0;l<ModelBlock->Block_List[j].Size;l++)
                             {
                               if (endogenous.find(make_pair(ModelBlock->Block_List[j].Variable[l], k1)) != endogenous.end())
                                 {
@@ -3120,7 +3088,7 @@ ModelTree::BlockLinear(Model_Block *ModelBlock)
                 }
             }
         }
-    follow:
+follow:
       i=0;
     }
 }
@@ -3157,7 +3125,7 @@ ModelTree::computingPass(const eval_context_type &eval_context, bool no_tmp_term
           cout << "The gross incidence matrix \n";
           block_triangular.incidencematrix.Print_IM(eEndogenous);
         }
-      block_triangular.Normalize_and_BlockDecompose_Static_0_Model(j_m);
+      block_triangular.Normalize_and_BlockDecompose_Static_0_Model(j_m, equations);
       BlockLinear(block_triangular.ModelBlock);
 
       if (!no_tmp_terms)
@@ -3170,68 +3138,68 @@ ModelTree::computingPass(const eval_context_type &eval_context, bool no_tmp_term
 
 void
 ModelTree::writeStaticFile(const string &basename) const
-{
-  switch(mode)
-    {
-    case eStandardMode:
-    case eSparseDLLMode:
-      writeStaticMFile(basename + "_static");
-      break;
-    case eSparseMode:
-      // create a directory to store all files
+  {
+    switch (mode)
+      {
+      case eStandardMode:
+      case eSparseDLLMode:
+        writeStaticMFile(basename + "_static");
+        break;
+      case eSparseMode:
+        // create a directory to store all files
 #ifdef _WIN32
-      mkdir(basename.c_str());
+        mkdir(basename.c_str());
 #else
-      mkdir(basename.c_str(), 0777);
+        mkdir(basename.c_str(), 0777);
 #endif
 
-      writeSparseStaticMFile(basename + "_static", basename, mode);
-      break;
-    case eDLLMode:
-      writeStaticCFile(basename + "_static");
-      break;
-    }
-}
+        writeSparseStaticMFile(basename + "_static", basename, mode);
+        break;
+      case eDLLMode:
+        writeStaticCFile(basename + "_static");
+        break;
+      }
+  }
 
 void
 ModelTree::writeDynamicFile(const string &basename) const
-{
-  switch(mode)
-    {
-    case eStandardMode:
-      writeDynamicMFile(basename + "_dynamic");
-      break;
-    case eSparseMode:
-      writeSparseDynamicMFile(basename + "_dynamic", basename, mode);
-      block_triangular.Free_Block(block_triangular.ModelBlock);
-      block_triangular.incidencematrix.Free_IM();
-      //block_triangular.Free_IM_X(block_triangular.First_IM_X);
-      break;
-    case eDLLMode:
-      writeDynamicCFile(basename + "_dynamic");
-      break;
-    case eSparseDLLMode:
-      // create a directory to store all the files
+  {
+    switch (mode)
+      {
+      case eStandardMode:
+        writeDynamicMFile(basename + "_dynamic");
+        break;
+      case eSparseMode:
+        writeSparseDynamicMFile(basename + "_dynamic", basename, mode);
+        block_triangular.Free_Block(block_triangular.ModelBlock);
+        block_triangular.incidencematrix.Free_IM();
+        //block_triangular.Free_IM_X(block_triangular.First_IM_X);
+        break;
+      case eDLLMode:
+        writeDynamicCFile(basename + "_dynamic");
+        break;
+      case eSparseDLLMode:
+        // create a directory to store all the files
 #ifdef _WIN32
-      mkdir(basename.c_str());
+        mkdir(basename.c_str());
 #else
-      mkdir(basename.c_str(), 0777);
+        mkdir(basename.c_str(), 0777);
 #endif
-      writeModelEquationsCodeOrdered(basename + "_dynamic", block_triangular.ModelBlock, basename, oCDynamicModelSparseDLL);
-      block_triangular.Free_Block(block_triangular.ModelBlock);
-      block_triangular.incidencematrix.Free_IM();
-      //block_triangular.Free_IM_X(block_triangular.First_IM_X);
-      break;
-    }
-}
+        writeModelEquationsCodeOrdered(basename + "_dynamic", block_triangular.ModelBlock, basename, oCDynamicModelSparseDLL);
+        block_triangular.Free_Block(block_triangular.ModelBlock);
+        block_triangular.incidencematrix.Free_IM();
+        //block_triangular.Free_IM_X(block_triangular.First_IM_X);
+        break;
+      }
+  }
 
 void
 ModelTree::matrixHelper(ostream &output, int eq_nb, int col_nb, ExprNodeOutputType output_type) const
-{
-  output << LPAR(output_type);
-  if (OFFSET(output_type))
-    output << eq_nb + 1 << ", " << col_nb + 1;
-  else
-    output << eq_nb + col_nb * equations.size();
-  output << RPAR(output_type);
-}
+  {
+    output << LPAR(output_type);
+    if (OFFSET(output_type))
+      output << eq_nb + 1 << ", " << col_nb + 1;
+    else
+      output << eq_nb + col_nb * equations.size();
+    output << RPAR(output_type);
+  }
diff --git a/include/BlockTriangular.hh b/include/BlockTriangular.hh
index 8762856548b89207046c4f29b8fd9a090b8e4351..2434a1a81478b5eb1ab28ad2462a6114ca187c82 100644
--- a/include/BlockTriangular.hh
+++ b/include/BlockTriangular.hh
@@ -21,6 +21,7 @@
 #define _BLOCKTRIANGULAR_HH
 
 #include <string>
+#include "CodeInterpreter.hh"
 #include "ExprNode.hh"
 #include "SymbolTable.hh"
 #include "ModelNormalization.hh"
@@ -36,6 +37,8 @@
 //! Matrix of doubles for representing jacobian
 typedef map<pair<int ,int >,double> jacob_map;
 
+typedef vector<pair<BlockSimulationType, int> > t_type;
+
 //! Create the incidence matrix, computes prologue & epilogue, normalizes the model and computes the block decomposition
 class BlockTriangular
 {
@@ -48,11 +51,12 @@ public:
   Blocks blocks;
   Normalization normalization;
   IncidenceMatrix incidencematrix;
-  void Normalize_and_BlockDecompose_Static_0_Model(const jacob_map &j_m);
-  bool Normalize_and_BlockDecompose(bool* IM, Model_Block* ModelBlock, int n, int* prologue, int* epilogue, simple* Index_Var_IM, simple* Index_Equ_IM, bool Do_Normalization, bool mixing, bool* IM_0 , jacob_map j_m);
+  void Normalize_and_BlockDecompose_Static_0_Model(const jacob_map &j_m, vector<BinaryOpNode *> equations);
+  bool Normalize_and_BlockDecompose(bool* IM, Model_Block* ModelBlock, int n, int* prologue, int* epilogue, simple* Index_Var_IM, simple* Index_Equ_IM, bool Do_Normalization, bool mixing, bool* IM_0 , jacob_map j_m, vector<BinaryOpNode *> equations);
   void Prologue_Epilogue(bool* IM, int* prologue, int* epilogue, int n, simple* Index_Var_IM, simple* Index_Equ_IM, bool* IM0);
-  void Allocate_Block(int size, int *count_Equ, int *count_Block, BlockType type, Model_Block * ModelBlock);
+  void Allocate_Block(int size, int *count_Equ, int count_Block, BlockType type, BlockSimulationType SimType, Model_Block * ModelBlock);
   void Free_Block(Model_Block* ModelBlock) const;
+  t_type Reduce_Blocks_and_type_determination(int prologue, int epilogue, block_result_t* res, vector<BinaryOpNode *> equations );
   simple *Index_Equ_IM;
   simple *Index_Var_IM;
   int prologue, epilogue;
diff --git a/include/CodeInterpreter.hh b/include/CodeInterpreter.hh
index f5cfebaeee2f8eb55cc8b8266f8e67d0ebf18c6c..2786ca411c1e1c0255227af32af2a6dce92c2571 100644
--- a/include/CodeInterpreter.hh
+++ b/include/CodeInterpreter.hh
@@ -49,7 +49,7 @@ enum BlockType
     SIMULTAN = 3   //<! Simultaneous time unseparable block
   };
 
-enum BlockSimulationType
+/*enum BlockSimulationType
   {
     UNKNOWN = -1,                      //!< Unknown simulation type
     EVALUATE_FORWARD = 0,             //!< Simple evaluation, normalized variable on left-hand side, forward
@@ -63,6 +63,21 @@ enum BlockSimulationType
     EVALUATE_FORWARD_R = 8,           //!< Simple evaluation, normalized variable on right-hand side, forward
     EVALUATE_BACKWARD_R = 9            //!< Simple evaluation, normalized variable on right-hand side, backward
   };
+*/
+enum BlockSimulationType
+  {
+    UNKNOWN,                      //!< Unknown simulation type
+    EVALUATE_FORWARD,             //!< Simple evaluation, normalized variable on left-hand side, forward
+    EVALUATE_BACKWARD,             //!< Simple evaluation, normalized variable on left-hand side, backward
+    SOLVE_FORWARD_SIMPLE,         //!< Block of one equation, newton solver needed, forward
+    SOLVE_BACKWARD_SIMPLE,         //!< Block of one equation, newton solver needed, backward
+    SOLVE_TWO_BOUNDARIES_SIMPLE,   //!< Block of one equation, newton solver needed, forward & ackward
+    SOLVE_FORWARD_COMPLETE,       //!< Block of several equations, newton solver needed, forward
+    SOLVE_BACKWARD_COMPLETE,       //!< Block of several equations, newton solver needed, backward
+    SOLVE_TWO_BOUNDARIES_COMPLETE, //!< Block of several equations, newton solver needed, forward and backwar
+    EVALUATE_FORWARD_R,           //!< Simple evaluation, normalized variable on right-hand side, forward
+    EVALUATE_BACKWARD_R            //!< Simple evaluation, normalized variable on right-hand side, backward
+  };
 
 //! Enumeration of possible symbol types
 /*! Warning: do not to change existing values: the order matters for VariableTable (at least for endogenous and exogenous types), and the values matter for homotopy_setup command */
diff --git a/include/ExprNode.hh b/include/ExprNode.hh
index 7dab877183cf529704e9ba331acd83266ee8e274..06d9228e019d7b00174f82e7a04709a8bf594374 100644
--- a/include/ExprNode.hh
+++ b/include/ExprNode.hh
@@ -44,6 +44,7 @@ struct ExprNodeLess;
 /*! They are ordered by index number thanks to ExprNodeLess */
 typedef set<NodeID, ExprNodeLess> temporary_terms_type;
 typedef map<int,int> map_idx_type;
+typedef set<int> temporary_terms_inuse_type;
 
 //! Possible types of output when writing ExprNode(s)
 enum ExprNodeOutputType
@@ -144,6 +145,7 @@ public:
       They are added to the set given in argument */
   virtual void collectEndogenous(set<pair<int, int> > &result) const = 0;
   virtual void collectExogenous(set<pair<int, int> > &result) const = 0;
+  virtual void collectTemporary_terms(const temporary_terms_type &temporary_terms, Model_Block *ModelBlock, int Curr_Block) const = 0;
   virtual void computeTemporaryTerms(map<NodeID, int> &reference_count,
                                      temporary_terms_type &temporary_terms,
                                      map<NodeID, int> &first_occurence,
@@ -181,6 +183,7 @@ public:
   virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms) const;
   virtual void collectEndogenous(set<pair<int, int> > &result) const;
   virtual void collectExogenous(set<pair<int, int> > &result) const;
+  virtual void collectTemporary_terms(const temporary_terms_type &temporary_terms, Model_Block *ModelBlock, int Curr_Block) const;
   virtual double eval(const eval_context_type &eval_context) const throw (EvalException);
   virtual void compile(ofstream &CompileCode, bool lhs_rhs, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms, map_idx_type map_idx) const;
 };
@@ -201,6 +204,7 @@ public:
   virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms = temporary_terms_type()) const;
   virtual void collectEndogenous(set<pair<int, int> > &result) const;
   virtual void collectExogenous(set<pair<int, int> > &result) const;
+  virtual void collectTemporary_terms(const temporary_terms_type &temporary_terms, Model_Block *ModelBlock, int Curr_Block) const;
   virtual double eval(const eval_context_type &eval_context) const throw (EvalException);
   virtual void compile(ofstream &CompileCode, bool lhs_rhs, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms, map_idx_type map_idx) const;
 };
@@ -227,6 +231,7 @@ public:
                                      map_idx_type &map_idx) const;
   virtual void collectEndogenous(set<pair<int, int> > &result) const;
   virtual void collectExogenous(set<pair<int, int> > &result) const;
+  virtual void collectTemporary_terms(const temporary_terms_type &temporary_terms, Model_Block *ModelBlock, int Curr_Block) const;
   static double eval_opcode(UnaryOpcode op_code, double v) throw (EvalException);
   virtual double eval(const eval_context_type &eval_context) const throw (EvalException);
   virtual void compile(ofstream &CompileCode, bool lhs_rhs, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms, map_idx_type map_idx) const;
@@ -255,9 +260,12 @@ public:
                                      map_idx_type &map_idx) const;
   virtual void collectEndogenous(set<pair<int, int> > &result) const;
   virtual void collectExogenous(set<pair<int, int> > &result) const;
+  virtual void collectTemporary_terms(const temporary_terms_type &temporary_terms, Model_Block *ModelBlock, int Curr_Block) const;
   static double eval_opcode(double v1, BinaryOpcode op_code, double v2) throw (EvalException);
   virtual double eval(const eval_context_type &eval_context) const throw (EvalException);
   virtual void compile(ofstream &CompileCode, bool lhs_rhs, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms, map_idx_type map_idx) const;
+  virtual NodeID get_arg1() { return(arg1);};
+  virtual NodeID get_arg2() { return(arg2);};
 };
 
 enum TrinaryOpcode
@@ -288,6 +296,7 @@ public:
                                      map_idx_type &map_idx) const;
   virtual void collectEndogenous(set<pair<int, int> > &result) const;
   virtual void collectExogenous(set<pair<int, int> > &result) const;
+  virtual void collectTemporary_terms(const temporary_terms_type &temporary_terms, Model_Block *ModelBlock, int Curr_Block) const;
   static double eval_opcode(double v1, TrinaryOpcode op_code, double v2, double v3) throw (EvalException);
   virtual double eval(const eval_context_type &eval_context) const throw (EvalException);
   virtual void compile(ofstream &CompileCode, bool lhs_rhs, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms, map_idx_type map_idx) const;
@@ -314,6 +323,7 @@ public:
                                      map_idx_type &map_idx) const;
   virtual void collectEndogenous(set<pair<int, int> > &result) const;
   virtual void collectExogenous(set<pair<int, int> > &result) const;
+  virtual void collectTemporary_terms(const temporary_terms_type &temporary_terms, Model_Block *ModelBlock, int Curr_Block) const;
   virtual double eval(const eval_context_type &eval_context) const throw (EvalException);
   virtual void compile(ofstream &CompileCode, bool lhs_rhs, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms, map_idx_type map_idx) const;
 };
@@ -340,6 +350,7 @@ struct Block
   int *Equation, *Own_Derivative;
   int *Variable, *Other_Endogenous, *Exogenous;
   temporary_terms_type *Temporary_terms;
+  temporary_terms_inuse_type *Temporary_InUse;
   IM_compact *IM_lead_lag;
   int Code_Start, Code_Length;
 };