Add and tweak some tests.
Fix bugs. All tests passed.