This file is gnarly! You did a great job documenting it, and it's relatively easy to read.    My main worry is there is a lot of looping going on here. Have you measured this function at a site of decent scale to see how heavy it is?