You're doing this in more than one place.  Is there a way to abstract it into a function that all such places call, instead of duplicating a whole heap of code ?