def merge_groundings(stmts_in):
    def surface_grounding(stmt):
        for idx, concept in enumerate(stmt.agent_list()):
            if concept is None:
                continue
            aggregate_groundings = {}
            for ev in stmt.evidence:
                if 'agents' in ev.annotations:
                    groundings = ev.annotations['agents']['raw_grounding'][idx]
                    for ns, value in groundings.items():
                        if ns not in aggregate_groundings:
                            aggregate_groundings[ns] = []
                        if isinstance(value, list):
                            aggregate_groundings[ns] += value
                        else:
                            aggregate_groundings[ns].append(value)
            best_groundings = get_best_groundings(aggregate_groundings)
            concept.db_refs = best_groundings
    def get_best_groundings(aggregate_groundings):
        best_groundings = {}
        for ns, values in aggregate_groundings.items():
            if all([isinstance(v, (tuple, list)) for v in values]):
                best_groundings[ns] = []
                for unique_value in {v[0] for v in values}:
                    scores = [v[1] for v in values if v[0] == unique_value]
                    best_groundings[ns].append((unique_value, max(scores)))
                best_groundings[ns] = \
                    sorted(best_groundings[ns], key=lambda x: x[1],
                           reverse=True)
            elif all([not isinstance(v, (tuple, list)) for v in values]):
                best_groundings[ns] = max(set(values), key=values.count)
            else:
                unscored_vals = [v for v in values
                                 if not isinstance(v, (tuple, list))]
                best_groundings[ns] = max(set(unscored_vals),
                                          key=unscored_vals.count)
        return best_groundings
    stmts_out = []
    for stmt in stmts_in:
        if not isinstance(stmt, (Complex, Conversion)):
            surface_grounding(stmt)
        stmts_out.append(stmt)
    return stmts_out