Fixed a special case in the end of the algorithm.