Some improvements to allow easier mocking. Added a few tests.