This loop appears 3 times in this pull request. Is there a way to avoid duplication? Wouldn't it suffice to distinguish this only once during semantic?