The algorithm used is still quite inefficient, but at least the code is easier to read and a little bit simpler now.