This function is nested pretty deep. The inner portion should be factored into a separate function.