Some refactoring to remove duplicate code.