# 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 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 sys, os, time, StringIO
import twill
from twill.commands import find, formfile, follow, fv, go, show, \
    showforms, showlinks, submit, agent
from inmembrane.helpers import log_stderr, parse_fasta_header
             url="http://signalfind.org/tatfind.html", force=False):
    """
    Interfaces with the TatFind web service at (http://signalfind.org/tatfind.html)
    to predict if protein sequences contain Twin-Arginine Translocation (Tat)
    signal peptides.
    """
    # set the user-agent so web services can block us if they want ... :/
    python_version = sys.version.split()[0]
    agent("Python-urllib/%s (twill; inmembrane)" % python_version)

    outfn = 'tatfind.out'
    log_stderr("# TatFind(web) %s > %s" % (params['fasta'], outfn))

    if not force and os.path.isfile(outfn):
        log_stderr("# -> skipped: %s already exists" % outfn)
        fh = open(outfn, 'r')
        proteins = parse_tatfind_output(fh, proteins)
        fh.close()
        return proteins

    # dump extraneous output into this blackhole so we don't see it
    if not __DEBUG__: twill.set_output(StringIO.StringIO())

    go(url)
    if __DEBUG__: showforms()
    formfile("1", "seqFile", params["fasta"])
    submit()
    if __DEBUG__: show()

    tatfind_output = show()

# 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 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/tatfind_web.py
import sys, os, time, StringIO
import twill
from twill.commands import find, formfile, follow, fv, go, show, \
    showforms, showlinks, submit, agent
from inmembrane.helpers import log_stderr, parse_fasta_header

             url="http://signalfind.org/tatfind.html", force=False):
    """
    Interfaces with the TatFind web service at (http://signalfind.org/tatfind.html)
    to predict if protein sequences contain Twin-Arginine Translocation (Tat)
    signal peptides.
    """
    # set the user-agent so web services can block us if they want ... :/
    python_version = sys.version.split()[0]
    agent("Python-urllib/%s (twill; inmembrane)" % python_version)

    outfn = 'tatfind.out'
    log_stderr("# TatFind(web) %s > %s" % (params['fasta'], outfn))

    if not force and os.path.isfile(outfn):
        log_stderr("# -> skipped: %s already exists" % outfn)
        fh = open(outfn, 'r')
        proteins = parse_tatfind_output(fh, proteins)
        fh.close()
        return proteins

    # dump extraneous output into this blackhole so we don't see it
    if not __DEBUG__: twill.set_output(StringIO.StringIO())

    go(url)
    if __DEBUG__: showforms()
    formfile("1", "seqFile", params["fasta"])
    submit()
    if __DEBUG__: show()

    tatfind_output = show()

    if __DEBUG__: log_stderr(tatfind_output)