I've seen this logic in a few places, might be worth putting in a function.