Extract this code into a new function perhaps?