fix nested for loops

Break up the nested for loops into two functions. Please double-double-check that it still works the same.