Significant optimization of the algorithm