Some small optimizations and refactorings