Refactoring and small performance tweaks.