Overall refactoring and cleanup