massive refactoring and cleanup