code: def order_derived_variables(regime):
      ordering = []
      dvs = []
      dvsnoexp = []
      maxcount = 5
      for dv in regime.derived_variables:
          if dv.expression_tree == None:
              dvsnoexp.append(dv.name)
          else:
              dvs.append(dv.name)
      for dv in regime.conditional_derived_variables:
          if len(dv.cases) == 0:
              dvsnoexp.append(dv.name)
          else:
              dvs.append(dv.name)
      count = maxcount
      while count > 0 and dvs != []:
          count = count - 1
          for dv1 in dvs:
              if dv1 in regime.derived_variables:
                  dv = regime.derived_variables[dv1]
              else:
                  dv = regime.conditional_derived_variables[dv1]
              found = False
              if isinstance(dv, DerivedVariable):
                  exp_tree = dv.expression_tree
                  for dv2 in dvs:
                      if dv1 != dv2 and is_var_in_exp_tree(dv2, exp_tree):
                          found = True
              else:
                  for case in dv.cases:
                      for dv2 in dvs:
                          if dv1 != dv2 and (is_var_in_exp_tree(dv2, case.condition_expression_tree) or
                                             is_var_in_exp_tree(dv2, case.value_expression_tree)):
                              found = True
              if not found:
                  ordering.append(dv1)
                  del dvs[dvs.index(dv1)]
                  count = maxcount
                  break
      if count == 0:
          raise SimBuildError(("Unable to find ordering for derived "
                               "variables in regime '{0}'").format(regime.name))
      return dvsnoexp + ordering