Add tests, fix bug revealed by tests