Some more refactoring and cleanup