Split some code out for easier testing
Add tests of the logic