Fix bugs found through unit tests after refactoring