Extract this code into a function?