Various refactoring and cleanup