Updated with Harold's improved loop.