This code seems repeated in multiple places, why not move it into a separate function?