Fixed algorithm. Prev algo completely wrong.