Add some tests and fix a bunch of bugs found writing them