# Path: inmembrane/helpers.py
# def log_stderr(s, width=76, comment=True):
#     """
#     Wrapper for all stderr out. Allows future customization.
#     """
#     if LOG_SILENT:
#         return
#     if s and s[-1] != "\n":
#         s += "\n"
#     if not s.startswith("#"):
#         s = "# " + s
#     sys.stderr.write(s)
# 
# 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


import os
import glob
from inmembrane.helpers import log_stderr, run, parse_fasta_header
      - 'hmmsearch': a list of motifs that are found in the protein. The
         motifs correspond to the basename of the .hmm files found in the directory
         indicated by the 'hmm_profiles_dir' field of 'params'.
    """

    log_stderr(
        "# Searching for HMMER profiles in " + params['hmm_profiles_dir'])

    file_tag = os.path.join(params['hmm_profiles_dir'], '*.hmm')
    for hmm_profile in glob.glob(file_tag):
        params['hmm_profile'] = hmm_profile

        hmm_profile = os.path.basename(params['hmm_profile'])
        hmm_name = hmm_profile.replace('.hmm', '')
        hmmsearch3_out = 'hmm.%s.out' % hmm_name

        cmd = '%(hmmsearch3_bin)s -Z 2000 -E 10 %(hmm_profile)s %(fasta)s' % params
        run(cmd, hmmsearch3_out)

        # init proteins data structure with blank hmmsearch field first
        for seqid in proteins:
            if 'hmmsearch' not in proteins[seqid]:
                proteins[seqid]['hmmsearch'] = []

        # parse the hmmsearch output file
        seqid = None
        for l in open(hmmsearch3_out):
            words = l.split()

            if l.startswith(">>"):

# Path: inmembrane/helpers.py
# def log_stderr(s, width=76, comment=True):
#     """
#     Wrapper for all stderr out. Allows future customization.
#     """
#     if LOG_SILENT:
#         return
#     if s and s[-1] != "\n":
#         s += "\n"
#     if not s.startswith("#"):
#         s = "# " + s
#     sys.stderr.write(s)
# 
# 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/hmmsearch3.py
import os
import glob
from inmembrane.helpers import log_stderr, run, parse_fasta_header

      - 'hmmsearch': a list of motifs that are found in the protein. The
         motifs correspond to the basename of the .hmm files found in the directory
         indicated by the 'hmm_profiles_dir' field of 'params'.
    """

    log_stderr(
        "# Searching for HMMER profiles in " + params['hmm_profiles_dir'])

    file_tag = os.path.join(params['hmm_profiles_dir'], '*.hmm')
    for hmm_profile in glob.glob(file_tag):
        params['hmm_profile'] = hmm_profile

        hmm_profile = os.path.basename(params['hmm_profile'])
        hmm_name = hmm_profile.replace('.hmm', '')
        hmmsearch3_out = 'hmm.%s.out' % hmm_name

        cmd = '%(hmmsearch3_bin)s -Z 2000 -E 10 %(hmm_profile)s %(fasta)s' % params
        run(cmd, hmmsearch3_out)

        # init proteins data structure with blank hmmsearch field first
        for seqid in proteins:
            if 'hmmsearch' not in proteins[seqid]:
                proteins[seqid]['hmmsearch'] = []

        # parse the hmmsearch output file
        seqid = None
        for l in open(hmmsearch3_out):
            words = l.split()

            if l.startswith(">>"):

                seqid = parse_fasta_header(l[3:])[0]