Major refactoring and code cleanup