Fixed a few infinite loop bugs