add more tests and improve logic