Refactors merge code

These changes:

(a) refactor the long merge code into functions to assist with profiling
(b) makes the most obvious change based on profiling for performance improvement (although it is still pretty terrible when merging large numbers of files, it is slightly better this way)