More unit test work + some bugfixes exposed by unit tests