Refactoring and minor optimizations.