Refactoring and minor performance improvements