Maybe I fixed just the result of incorrect algorithm but it works generally