full algorithm complete, ready for tests