Add unit tests and fix two issues