completed algorithm and tests