memory leak fix and updated algorithm for picking ordering of segments
added to reference