refine logic and add unit test