Refactored a lot of code for better testability