optimized contour algorithm