I tried to move the logic to a function as we discussed offline, but couldn't make it any clearer.

I've expanded the inline comment instead. It's duplicated but I think it's clearer to have it inline.