Greatly sped up the algorithm