It took me a second looking at this to realize what `inverted` meant.  I think it might be clearer to break this into two steps, since the checking logic is significantly different between the two cases.  But that's a minor style call, so I'll leave it up to you.