Could you move this code into a library function?  This would be good to do on CC anyway.  Also, I need to look in the git history - Dale wrote a much more compact version of this in the past which we should check.