added new tests and fixed algorithm