Add unit tests and fixes