Add unit tests, fix some errors