Refactors a bit to be more testable. Add tests.