Improve segments logic and algorithm