Refactoring and minor improvements