Improve logic and add tests.