Rewrite segmentutil to be simpler and more correct

Also include some timing code that I found useful when debugging and probably doesn't hurt to have included.

@jebeck Can you give this a once over?  For `segmentutil.js` it might be easier to just look at the file, 'cause even though github is trying to show you a diff, it's a complete rewrite with nothing but the top couple of lines maintained.