rewrote main algorithm