refactor the algorithm, now it fast enough.