Rewrote merging functions to speeden up merging