This function is doing a lot of things! How could it be improved?