This set of loops could do with a comment explaining what they're doing