Fixed the algorithm