Completed the three way merge function