working version of merge with buffer