Refactored the SegmentBySegment/run4mad function