Fix potential infinite loop issue. Thanks: zwutz