Added tests

I re-arranged the code so that it could be tested more easily and added a few tests.