Really confused why this code is repeated verbatim three times (and more below, with slight variations?). Should this be extracted into a method? Must be something really wrong with the control flow in this method...