Some refactoring to reduce code duplication.