BS-2663, refactor flow merge algorithm