Refactoring and optimizations