This function strikes me as being too long and too complex, trying to do too many things. Do you think it would be possible to break it up into a few more manageable functions?