fixing the algorithm