Drastical improvement of the algorithm