separated for loops to minimize memory usage