Fix loop nesting