Various refactoring and clean-up