fixed the algorithm