Fix tests and a couple of bugs