Abstracted out state for recursive flattening

The state management for flattening the recursive structure for
factoring is now abstracted out into some other classes (and maintained
in class variables). This makes the nodes method much easier to read
and no longer needs to pass around state.