add tests, refine logic