Rewriting helper functions and reorganizing, in part to speed it up.