Add unit tests and fix bugs found by them