Let's split this function up. The comments you have seem to be separating it into its logical components, let's make each a function.