Add tests, fix bugs