Large refactoring and cleanup