Fix ordering of loop nesting