FIxed bug with freezing algorithm due to end condition.