AG-4388: rewrote algorithm