Giant refactoring and cleanup