Infinite loop algorytm fix