Refactor duplicated sequence flattening code