Refactoring and performance improvments