Fixing infinite loop bug