Finished refactoring.

Should have feature parity with the old code.