Big refactoring and cleanup