Fixing bug of infinite loop