improve the merge function