Major code cleanup and refactoring