I would add a docstring to this function as now it implements a not trivial logic.