A bit of refactoring to make testing easier. And tests.

Signed-off-by: Geoff Lane <geoff@zorched.net>