Refactoring and testing improvements