Refactoring and code cleanup