Code refactoring and cleanup