changed order of some nested loops