Moving some of the functionality out of the merge() function so it's reusable elsewhere.