fixed the algorithm (thx to my cousin Finn)