rewrote inner loop (simpler)