Fixes for loop ordering (#149), props @thelar