def write_clusters(filehandle, clusters, max_clusters=None, min_size=1, header=None, rename=True):
    """Writes clusters to an open filehandle.
    Inputs:
        filehandle: An open filehandle that can be written to
        clusters: An iterator generated by function `clusters` or a dict
        max_clusters: Stop printing after this many clusters [None]
        min_size: Don't output clusters smaller than N contigs
        header: Commented one-line header to add
        rename: Rename clusters to "cluster_1", "cluster_2" etc.

    Outputs:
        clusternumber: Number of clusters written
        ncontigs: Number of contigs written
    """

    if not hasattr(filehandle, "writable") or not filehandle.writable():
        raise ValueError("Filehandle must be a writable file")

    # Special case to allows dicts even though they are not iterators of
    # clustername, {cluster}
    if isinstance(clusters, dict):
        clusters = clusters.items()

    if max_clusters is not None and max_clusters < 1:
        raise ValueError("max_clusters must None or at least 1, not {}".format(max_clusters))

    if header is not None and len(header) > 0:
        if "\n" in header:
            raise ValueError("Header cannot contain newline")

        if header[0] != "#":
            header = "# " + header

        print(header, file=filehandle)

    clusternumber = 0
    ncontigs = 0

    for clustername, contigs in clusters:
        if len(contigs) < min_size:
            continue

        if rename:
            clustername = "cluster_" + str(clusternumber + 1)

        for contig in contigs:
            print(clustername, contig, sep="\t", file=filehandle)
        filehandle.flush()

        clusternumber += 1
        ncontigs += len(contigs)

        if clusternumber == max_clusters:
            break

    return clusternumber, ncontigs