public static Cons optimizeOrderOfApplicableRules(Cons rules, boolean tailP) {
    { Cons cursor = rules;
      Cons result = Stella.NIL;
      Description antecedent = null;
      int antecedentindex = (tailP ? 0 : 1);

      if (rules.rest == Stella.NIL) {
        return (rules);
      }
      { int i = Stella.NULL_INTEGER;
        int iter000 = 0;

        loop000 : for (;true; iter000 = iter000 + 1) {
          i = iter000;
          while (!(cursor == Stella.NIL)) {
            antecedent = ((Description)((((Proposition)(cursor.value)).arguments.theArray)[antecedentindex]));
            if (antecedent.internalVariables.length() == i) {
              result = Cons.cons(((Proposition)(cursor.value)), result);
              cursor.value = null;
            }
            cursor = cursor.rest;
          }
          cursor = rules.remove(null);
          if (cursor == Stella.NIL) {
            break loop000;
          }
        }
      }
      return (result.reverse());
    }
  }