I think this logic can be improved in this func