Improve tests and fix bugs