Can this be extracted into a function? Seems like a fair amount of repetition here.