Fixed bugs causing infinite loops.