# Path: inmembrane/helpers.py
# def run(cmd, out_file=None):
#     """
#     Wrapper function to run external program so that existence
#     of binary can be checked and the output directed to a specific
#     file.
#     """
#     log_stderr("# " + cmd + " > " + out_file)
#     if os.path.isfile(out_file) and (out_file != None):
#         log_stderr("# -> skipped: %s already exists" % out_file)
#         return
#     binary = cmd.split()[0]
#     is_binary_there = False
#     if os.path.isfile(binary):
#         is_binary_there = True
#     if run_with_output('which ' + binary):
#         is_binary_there = True
#     if not is_binary_there:
#         raise IOError("Couldn't find executable binary '" + binary + "'")
#     if out_file:
#         os.system(cmd + " > " + out_file)
#     else:
#         os.system(cmd)
# 
# def parse_fasta_header(header):
#     """
#     Parses a FASTA format header (with our without the initial '>') and returns a
#     tuple of sequence id and sequence name/description.
# 
#     If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected
#     the first id in the list is used as the canonical id (see see
#     http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ).
#     """
#     if header[0] == '>':
#         header = header[1:]
#     tokens = header.split('|')
#     # check to see if we have an NCBI-style header
#     if header.find("|") != -1 and len(tokens[0]) <= 3:
#         # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber"
#         seqid = "%s|%s" % (tokens[0], tokens[1].split()[0])
#         name = tokens[-1:][0].strip()
#     # otherwise just split on spaces & hope for the best
#     else:
#         tokens = header.split()
#         seqid = tokens[0]
#         name = header[0:-1].strip()
# 
#     return seqid, name


from inmembrane.helpers import run, parse_fasta_header
      - 'tmhmm_helices', a list of tuples describing the first and last residue
        number of each transmembrane segment;

      - 'tmhmm_scores', a list of confidence scores (floats) for each predicted
        tm segment;

      - 'tmhmm_inner_loops', a list of tuples describing the first and last residue
         number of each predicted internal loop segment;

      - 'tmhmm_outer_loops', a list of tuples describing the first and last residue
         number of each predicted outer loop segment;
    """

    tmhmm_out = 'tmhmm.out'
    run('%(tmhmm_bin)s %(fasta)s' % params, tmhmm_out)
    return parse_tmhmm(open('tmhmm.out').read(), proteins)


def parse_tmhmm(text, proteins, id_mapping=[]):
    seqid = None
    for i_line, l in enumerate(text.split('\n')):
        if i_line == 0:
            continue
        words = l.split()
        if not words:
            continue

        if l.startswith("#"):
            seqid = parse_fasta_header(words[1])[0]
        else:

# Path: inmembrane/helpers.py
# def run(cmd, out_file=None):
#     """
#     Wrapper function to run external program so that existence
#     of binary can be checked and the output directed to a specific
#     file.
#     """
#     log_stderr("# " + cmd + " > " + out_file)
#     if os.path.isfile(out_file) and (out_file != None):
#         log_stderr("# -> skipped: %s already exists" % out_file)
#         return
#     binary = cmd.split()[0]
#     is_binary_there = False
#     if os.path.isfile(binary):
#         is_binary_there = True
#     if run_with_output('which ' + binary):
#         is_binary_there = True
#     if not is_binary_there:
#         raise IOError("Couldn't find executable binary '" + binary + "'")
#     if out_file:
#         os.system(cmd + " > " + out_file)
#     else:
#         os.system(cmd)
# 
# def parse_fasta_header(header):
#     """
#     Parses a FASTA format header (with our without the initial '>') and returns a
#     tuple of sequence id and sequence name/description.
# 
#     If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected
#     the first id in the list is used as the canonical id (see see
#     http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ).
#     """
#     if header[0] == '>':
#         header = header[1:]
#     tokens = header.split('|')
#     # check to see if we have an NCBI-style header
#     if header.find("|") != -1 and len(tokens[0]) <= 3:
#         # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber"
#         seqid = "%s|%s" % (tokens[0], tokens[1].split()[0])
#         name = tokens[-1:][0].strip()
#     # otherwise just split on spaces & hope for the best
#     else:
#         tokens = header.split()
#         seqid = tokens[0]
#         name = header[0:-1].strip()
# 
#     return seqid, name


# Path: inmembrane/plugins/tmhmm.py
from inmembrane.helpers import run, parse_fasta_header

      - 'tmhmm_helices', a list of tuples describing the first and last residue
        number of each transmembrane segment;

      - 'tmhmm_scores', a list of confidence scores (floats) for each predicted
        tm segment;

      - 'tmhmm_inner_loops', a list of tuples describing the first and last residue
         number of each predicted internal loop segment;

      - 'tmhmm_outer_loops', a list of tuples describing the first and last residue
         number of each predicted outer loop segment;
    """

    tmhmm_out = 'tmhmm.out'
    run('%(tmhmm_bin)s %(fasta)s' % params, tmhmm_out)
    return parse_tmhmm(open('tmhmm.out').read(), proteins)


def parse_tmhmm(text, proteins, id_mapping=[]):
    seqid = None
    for i_line, l in enumerate(text.split('\n')):
        if i_line == 0:
            continue
        words = l.split()
        if not words:
            continue

        if l.startswith("#"):
            seqid = parse_fasta_header(words[1])[0]
        else:

            seqid = parse_fasta_header(words[0])[0]