Worth pulling this logic out into a short function?  (I'm happy for you not to do this if you disagree.)