OK, I cleaned things up a bit, replaced several for loops with list comprehensions and for the more complex ones like this one, got it down to a single for loop.