add tests and improve logic