Add tests and fix some bugs