Simply the logic to get rid of nested for loops