Refactoring and other small fixes