Fixed numSegments calculation, removed old foreach