I’ve looked at a dozen version of this algorithm, and this is the most readable by far.