WIP, experiments.
Tweak the algorithm. Add debug print-outs.
Fix the algorithm. Break out code into processSegment().
Remove debug print-outs.