improved the algorithm