refactored to be more testable

Now the functions are broken up more. While they are still mutative, they are simpler