Refactor out the merging logic