changed order of loops, should speed up memory access