def bed_merge_file_select_top_ids(in_merged_bed, id2sc_dic,
                                  rev_filter=False):
    """
    Given a merged .bed file (using mergeBed or bed_merge_file() ),
    select the top scoring region IDs from the merged file, where in case
    of overlaps the best scoring region ID is picked.
    rev_filter=True leads to lower scores regarded as better, e.g. in case
    of p-values.

    >>> test_merged = "test_data/test.sorted.merged.bed"
    >>> id2sc_dic = {'r1': 1, 'r2': 2, 'r4': 4, 'r7' : 3}
    >>> bed_merge_file_select_top_ids(test_merged, id2sc_dic)
    {'r4': 4, 'r7': 3}
    >>> bed_merge_file_select_top_ids(test_merged, id2sc_dic, rev_filter=True)
    {'r1': 1, 'r7': 3}

    """
    ids2keep_dic = {}
    assert id2sc_dic, "given ID to score dictionary seems to be empty"
    with open(in_merged_bed) as f:
        for line in f:
            cols = line.strip().split("\t")
            ids = cols[3].split(";")
            best_id = "-"
            best_sc = -6666666
            if rev_filter:
                best_sc = 6666666
            for site_id in ids:
                assert site_id in id2sc_dic, "site ID \"%s\" not found in given site ID to score dictionary" % (site_id)
                site_sc = id2sc_dic[site_id]
                if rev_filter:
                    if site_sc < best_sc:
                        best_sc = site_sc
                        best_id = site_id
                else:
                    if site_sc > best_sc:
                        best_sc = site_sc
                        best_id = site_id
            ids2keep_dic[best_id] = best_sc
    f.closed
    assert ids2keep_dic, "No IDs read into dictionary (input file \"%s\" empty or malformatted?)" % (in_merged_bed)
    return ids2keep_dic