Minor refactoring and optimizations