Some refactoring to reduce code complexity.