Code cleanup and refactoring