Various simplifications and refactoring of the algorithm so far.