The rest of the code inside the IF might also be a good candidate for a separate function.