Clean up by the extracting commonly used code as a function.