Fixed bugs, added some unit tests.