This code block is really, really dense.  It could use an initial large comment explaining exactly what you're doing below.  Trying to unpack the code alone is tricky.