Translation of http://bost.ocks.org/mike/algorithms/