fixed some corner cases, with tests