Greatly cleaned up merging logic