Refactored to make things testable, then added tests