fixed the loop ordering bug