Some refactoring and optimizations