More refactoring and optimizations