forloop merge function to recursive merge function refactor