Exchanged the order of some more  nested loops.