The algorithm works properly now