Unit tests and bug fixes