Add some unit tests and fixes