refined the algorithm