def getGenomeChunkLength(bamHandles, tile_size, mappedList):
    """
    Tries to estimate the length of the genome sent to the workers
    based on the density of reads per bam file and the number
    of bam files.

    The chunk length should be a multiple of the tileSize

    """

    genomeLength = sum(bamHandles[0].lengths)

    max_reads_per_bp = max([float(x) / genomeLength for x in mappedList])

    # 2e6 is an empirical estimate
    genomeChunkLength = int(min(5e6, int(2e6 / (max_reads_per_bp * len(bamHandles)))))

    genomeChunkLength -= genomeChunkLength % tile_size
    return genomeChunkLength