Add unit tests. Fixed bugs found by unit tests.