fix ordering of loops