Function invertIfNecessary