Make a bed file with the start and stop coordinates for all of a particular
    feature in Gencode. Valid features are the features present in the third
    column of the Gencode GTF file.

    Parameters
    ----------
    gtf : str
        Filename of the Gencode gtf file.

    feature : str
        Feature from third column of Gencode GTF file. As of v19, these include
        CDS, exon, gene, Selenocysteine, start_codon, stop_codon, transcript,
        and UTR.

    out : str
        If provided, the bed file will be written to a file with this name.

    Returns
    -------
    bed : pybedtools.BedTool
        A sorted pybedtools BedTool object.

def make_feature_bed(gtf, feature, out=None):
    """
    Make a bed file with the start and stop coordinates for all of a particular
    feature in Gencode. Valid features are the features present in the third
    column of the Gencode GTF file.

    Parameters
    ----------
    gtf : str
        Filename of the Gencode gtf file.

    feature : str
        Feature from third column of Gencode GTF file. As of v19, these include
        CDS, exon, gene, Selenocysteine, start_codon, stop_codon, transcript,
        and UTR.

    out : str
        If provided, the bed file will be written to a file with this name.

    Returns
    -------
    bed : pybedtools.BedTool
        A sorted pybedtools BedTool object. 

    """
    bed_lines = []
    with open(gtf) as f:
        line = f.readline().strip()
        while line != '':
            if line[0] != '#':
                line = line.split('\t')
                if line[2] == feature:
                    chrom = line[0]
                    start = str(int(line[3]) - 1)
                    end = line[4]
                    if feature == 'gene':
                        name = line[8].split(';')[0].split(' ')[1].strip('"')
                    else:
                        # TODO: I may want to have some smarter naming for
                        # things that aren't genes or transcripts.
                        name = line[8].split(';')[1].split(' ')[2].strip('"')
                    strand = line[6]
                    bed_lines.append('\t'.join([chrom, start, end, name, '.',
                                                strand]) + '\n')
            line = f.readline().strip()
    bt = pbt.BedTool(''.join(bed_lines), from_string=True)
    # We'll sort so bedtools operations can be done faster.
    bt = bt.sort()
    if out:
        bt.saveas(out)
    return bt