Phew, this is one hell of a for loop. It would be easier to understand with some formating / helper functions.