More code cleanup and refactoring