Major refactoring to help maintainability