Refactor the main functions to reduce repetition.