Tests

Adds a bunch of tests and fixes a couple of bugs the tests revealed.