Refactoring and cleanup