Refactor code to remove some duplication