Add tests, fix two bugs