made looping more robust, at the expense of some elegance