this logic resembles to the one from the tree (that's kind of duplicated there also)
I think it could be unified in one place