<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def gaps(args):
 """ %prog gaps agpfile Print out the distribution of gapsizes. Option --merge allows merging of adjacent gaps which is used by tidy(). """

    from jcvi.graphics.histogram import loghistogram

    p = OptionParser(gaps.__doc__)
    p.add_option("--merge", dest="merge", default=False, action="store_true",
            help="Merge adjacent gaps (to conform to AGP specification)")
    p.add_option("--header", default=False, action="store_true",
            help="Produce an AGP header [default: %default]")

    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    merge = opts.merge
    agpfile, = args

    if merge:
        merged_agpfile = agpfile.replace(".agp", ".merged.agp")
        fw = open(merged_agpfile, "w")

    agp = AGP(agpfile)
    sizes = []
    data = []  # store merged AGPLine's
    priorities = ("centromere", "telomere", "scaffold", "contig", \
            "clone", "fragment")

    for is_gap, alines in groupby(agp, key=lambda x: (x.object, x.is_gap)):
        alines = list(alines)
        is_gap = is_gap[1]
        if is_gap:
            gap_size = sum(x.gap_length for x in alines)
            gap_types = set(x.gap_type for x in alines)
            for gtype in ("centromere", "telomere"):
                if gtype in gap_types:
                    gap_size = gtype

            sizes.append(gap_size)
            b = deepcopy(alines[0])
            b.object_beg = min(x.object_beg for x in alines)
            b.object_end = max(x.object_end for x in alines)
            b.gap_length = sum(x.gap_length for x in alines)

            assert b.gap_length == b.object_end - b.object_beg + 1
            b.component_type = 'U' if b.gap_length == 100 else 'N'

            gtypes = [x.gap_type for x in alines]
            for gtype in priorities:
                if gtype in gtypes:
                    b.gap_type = gtype
                    break

            linkages = [x.linkage for x in alines]
            for linkage in ("no", "yes"):
                if linkage in linkages:
                    b.linkage = linkage
                    break

            alines = [b]

        data.extend(alines)

    loghistogram(sizes)

    if opts.header:
        AGP.print_header(fw, organism="Medicago truncatula",
                         taxid=3880, source="J. Craig Venter Institute")

    if merge:
        for ob, bb in groupby(data, lambda x: x.object):
            for i, b in enumerate(bb):
                b.part_number = i + 1
                print(b, file=fw)
        return merged_agpfile