General code cleanup and refactoring