Fix a serious bug in the expand_rules function.

While doing a code review with Bryan, noticed that the accumulator to the helper function `loop` within `expand_rules` was being discarded, which was wrong. We rewrote the code to thread the accumulator all the way through. Also replaced several `List.fold_left`s (with a fragile invariant) with `List.fold_right` instead.

Added some comments on the purpose of internal helper functions in `expand_rules`.