debugged merge function