This function is very long. Might there be an opportunity to break it into smaller functions?