Refactor code and add tests

This resolves #13, and is a good place to start adding further tests.