completely rewrote the alg