remove some copy/paste structure

(and break up a big method)