Improve merging function