Also, extract related functions and types. There are no behavioral changes in this commit. Only refactorings.