def bam_minorallele(bam_fname, ref_fname, min_qual=0, min_count=0, num_alleles=0, name=None, min_ci_low=None):
    bam = pysam.Samfile(bam_fname, "rb")
    ref = pysam.Fastafile(ref_fname)

    if not name:
        name = os.path.basename(bam_fname)

    if num_alleles:
        print "# %s" % num_alleles

    sys.stdout.write('\t'.join("chrom pos refbase altbase total refcount altcount background refback altback".split()))
    if num_alleles and rscript:
        sys.stdout.write("\tci_low\tci_high\tallele_lowt\tallele_high")
    sys.stdout.write('\n')

    for pileup in bam_pileup_iter(bam, mask=1540):
        chrom = bam.getrname(pileup.tid)

        counts = {'A': 0, 'C': 0, 'G': 0, 'T': 0}
        total = 0

        for pileupread in pileup.pileups:
            if not pileupread.is_del:
                if min_qual:
                    if pileupread.alignment.qual[pileupread.qpos] < min_qual:
                        continue
                if pileupread.indel == 0:
                    base = pileupread.alignment.seq[pileupread.qpos].upper()
                    if base != 'N':
                        counts[base] += 1
                        total += 1

        if total > min_count:
            refbase = ref.fetch(chrom, pileup.pos, pileup.pos + 1).upper()
            if not refbase in counts:
                continue

            refcount = counts[refbase]

            # sort non-ref counts.  first is alt, next is background

            scounts = []
            for c in counts:
                if c != refbase:
                    scounts.append((counts[c], c))

            scounts.sort()
            scounts.reverse()

            altbase = scounts[0][1]
            altcount = scounts[0][0]
            background = scounts[1][0]

            refback = refcount - background
            altback = altcount - background

            if (altback + refback) == 0:
                altfreq = 0
            else:
                altfreq = float(altback) / (altback + refback)

            cols = [chrom, pileup.pos + 1, refbase, altbase, total, refcount, altcount, background, refback, altback, altfreq]
            if num_alleles and rscript:
                ci_low, ci_high = calc_cp_ci(refback + altback, altback, num_alleles)
                allele_low = ci_low * num_alleles
                allele_high = ci_high * num_alleles

                cols.append(ci_low)
                cols.append(ci_high)
                cols.append(allele_low)
                cols.append(allele_high)
            else:
                ci_low = 0

            if not math.isnan(ci_low) and (min_ci_low is None or ci_low > min_ci_low):
                print '\t'.join([str(x) for x in cols])

    bam.close()
    ref.close()
dataset/ETHPy150Open ngsutils/ngsutils/ngsutils/bam/minorallele.py/bam_minorallele/original