Add tests, fix some bugs