Add many unit tests, correct some bugs.