Refactoring and performance improvements