Reordered loops a bit to improve performance