redid algorithm again. fixes some bugs