Fix some bugs introduced from refactoring; added test cases.