Unit tests and bugfixes