More unit tests and a bunch of bug fixes