The logic in this function is now very complicated. I've learned that comments describing how something in the code works (in contrast to comments that describe why something is done) are usually a good indicator of code that should be simplified/reorganized.

Please break this function up into smaller functions and/or reorganize the code.