small change to ordering of loops for speed