Fix infinite loop

This depends on the 0.9.5 branch, so you might want to merge that first before reviewing.