This is a lot to be stuffed into one function block. Could this be broken out into some functions to handle various parts?