Some performance optimizations and refactorings.