Finally getting around to implementing some unit tests. 

Some refactoring involved to enable easier testing.