Changed nested loop order for better cache-efficiency