Updated segmentation method

Improved performance of segmentation method, added protection from stack
overflow.