Minor optimizations and refactoring