added segment merging algorithm