Add unit tests and fix some bugs.