Fix bugs exposed by tests