Massive cleanup and refactoring