Refine logic and add some tests.