def filter_clusters(clusters, reference, minsize, mincontigs, checkpresence=True):
    """Creates a shallow copy of clusters, but without any clusters with a total size
    smaller than minsize, or fewer contigs than mincontigs.
    If checkpresence is True, raise error if a contig is not present in reference, else
    ignores it when counting cluster size.
    """

    filtered = dict()
    for binname, contignames in clusters.items():
        if len(contignames) < mincontigs:
            continue

        size = 0
        for contigname in contignames:
            contig = reference.contigs.get(contigname)

            if contig is not None:
                size += len(contig)
            elif checkpresence:
                raise KeyError('Contigname {} not in reference'.format(contigname))
            else:
                pass

        if size >= minsize:
            filtered[binname] = contignames.copy()

    return filtered