Make all the unit tests pass and in the process fix a few bugs