It would be good to make this function more readable and shorter, don't you think?