Better algorithm from 2nd ed of PiL.