refactor and detect a couple more corner cases for #796