Functions to efficiently merge segments.