Add tests. Various improvements and fixes