rewrote algorithm