Rearrange the logic for clarity and add a new unit test.