improved merge code