Major refactoring for testability