Rewrote the algorithm