Add tests and minor code improvements