Major refactoring to make code testable