# Path: checkm/common.py
# def binIdFromFilename(filename):
#     """Extract bin id from bin filename."""
#     binId = os.path.basename(filename)
#     binId = os.path.splitext(binId)[0]
# 
#     return binId
# 
# Path: checkm/util/seqUtils.py
# def readFasta(fastaFile, trimHeader=True):
#     '''Read sequences from FASTA file.'''
#     try:
#         if fastaFile.endswith('.gz'):
#             openFile = gzip.open
#         else:
#             openFile = open
# 
#         seqs = {}
#         for line in openFile(fastaFile):
#             # skip blank lines
#             if not line.strip():
#                 continue
# 
#             if line[0] == '>':
#                 if trimHeader:
#                     seqId = line[1:].split(None, 1)[0]
#                 else:
#                     seqId = line[1:].rstrip()
#                 seqs[seqId] = []
#             else:
#                 seqs[seqId].append(line[0:-1])
# 
#         for seqId, seq in seqs.items():
#             seqs[seqId] = ''.join(seq)
#     except:
#         logger = logging.getLogger('timestamp')
#         logger.error("Failed to process sequence file: {}".format(fastaFile))
#         sys.exit(1)
# 
#     return seqs
# 
# def readFastaSeqIds(fastaFile):
#     '''Read sequence ids from FASTA file.'''
#     if fastaFile.endswith('.gz'):
#         openFile = gzip.open
#     else:
#         openFile = open
# 
#     seqIds = []
#     for line in openFile(fastaFile):
#         if line[0] == '>':
#             seqId = line[1:].split(None, 1)[0]
#             seqIds.append(seqId)
# 
#     return seqIds


import os
import logging
from collections import defaultdict
from checkm.defaultValues import DefaultValues
from checkm.common import binIdFromFilename
from checkm.util.seqUtils import readFasta, readFastaSeqIds
#    You should have received a copy of the GNU General Public License        #
#    along with this program. If not, see <http://www.gnu.org/licenses/>.     #
#                                                                             #
###############################################################################




class SSU_Finder(object):
    def __init__(self, threads):
        self.logger = logging.getLogger('timestamp')

        self.totalThreads = threads

        self.bacteriaModelFile = os.path.join(DefaultValues.CHECKM_DATA_DIR, 'hmms_ssu', 'SSU_bacteria.hmm')
        self.archaeaModelFile = os.path.join(DefaultValues.CHECKM_DATA_DIR, 'hmms_ssu', 'SSU_archaea.hmm')
        self.eukModelFile = os.path.join(DefaultValues.CHECKM_DATA_DIR, 'hmms_ssu', 'SSU_euk.hmm')

    def __hmmSearch(self, seqFile, evalue, outputPrefix):
        if seqFile.endswith('gz'):
            pipe = 'zcat ' + seqFile + ' | '
        else:
            pipe = 'cat ' + seqFile + ' | '

        self.logger.info('Identifying bacterial 16S.')
        os.system(pipe + 'nhmmer --noali --cpu ' + str(self.totalThreads) + ' -o ' + outputPrefix + '.bacteria.txt --tblout ' + outputPrefix + '.bacteria.table.txt -E ' + str(evalue) + ' ' + self.bacteriaModelFile + ' -')

        self.logger.info('Identifying archaeal 16S.')
        os.system(pipe + 'nhmmer --noali --cpu ' + str(self.totalThreads) + ' -o ' + outputPrefix + '.archaea.txt --tblout ' + outputPrefix + '.archaea.table.txt -E ' + str(evalue) + ' ' + self.archaeaModelFile + ' -')


# Path: checkm/common.py
# def binIdFromFilename(filename):
#     """Extract bin id from bin filename."""
#     binId = os.path.basename(filename)
#     binId = os.path.splitext(binId)[0]
# 
#     return binId
# 
# Path: checkm/util/seqUtils.py
# def readFasta(fastaFile, trimHeader=True):
#     '''Read sequences from FASTA file.'''
#     try:
#         if fastaFile.endswith('.gz'):
#             openFile = gzip.open
#         else:
#             openFile = open
# 
#         seqs = {}
#         for line in openFile(fastaFile):
#             # skip blank lines
#             if not line.strip():
#                 continue
# 
#             if line[0] == '>':
#                 if trimHeader:
#                     seqId = line[1:].split(None, 1)[0]
#                 else:
#                     seqId = line[1:].rstrip()
#                 seqs[seqId] = []
#             else:
#                 seqs[seqId].append(line[0:-1])
# 
#         for seqId, seq in seqs.items():
#             seqs[seqId] = ''.join(seq)
#     except:
#         logger = logging.getLogger('timestamp')
#         logger.error("Failed to process sequence file: {}".format(fastaFile))
#         sys.exit(1)
# 
#     return seqs
# 
# def readFastaSeqIds(fastaFile):
#     '''Read sequence ids from FASTA file.'''
#     if fastaFile.endswith('.gz'):
#         openFile = gzip.open
#     else:
#         openFile = open
# 
#     seqIds = []
#     for line in openFile(fastaFile):
#         if line[0] == '>':
#             seqId = line[1:].split(None, 1)[0]
#             seqIds.append(seqId)
# 
#     return seqIds


# Path: checkm/ssuFinder.py
import os
import logging
from collections import defaultdict
from checkm.defaultValues import DefaultValues
from checkm.common import binIdFromFilename
from checkm.util.seqUtils import readFasta, readFastaSeqIds

#    You should have received a copy of the GNU General Public License        #
#    along with this program. If not, see <http://www.gnu.org/licenses/>.     #
#                                                                             #
###############################################################################




class SSU_Finder(object):
    def __init__(self, threads):
        self.logger = logging.getLogger('timestamp')

        self.totalThreads = threads

        self.bacteriaModelFile = os.path.join(DefaultValues.CHECKM_DATA_DIR, 'hmms_ssu', 'SSU_bacteria.hmm')
        self.archaeaModelFile = os.path.join(DefaultValues.CHECKM_DATA_DIR, 'hmms_ssu', 'SSU_archaea.hmm')
        self.eukModelFile = os.path.join(DefaultValues.CHECKM_DATA_DIR, 'hmms_ssu', 'SSU_euk.hmm')

    def __hmmSearch(self, seqFile, evalue, outputPrefix):
        if seqFile.endswith('gz'):
            pipe = 'zcat ' + seqFile + ' | '
        else:
            pipe = 'cat ' + seqFile + ' | '

        self.logger.info('Identifying bacterial 16S.')
        os.system(pipe + 'nhmmer --noali --cpu ' + str(self.totalThreads) + ' -o ' + outputPrefix + '.bacteria.txt --tblout ' + outputPrefix + '.bacteria.table.txt -E ' + str(evalue) + ' ' + self.bacteriaModelFile + ' -')

        self.logger.info('Identifying archaeal 16S.')
        os.system(pipe + 'nhmmer --noali --cpu ' + str(self.totalThreads) + ' -o ' + outputPrefix + '.archaea.txt --tblout ' + outputPrefix + '.archaea.table.txt -E ' + str(evalue) + ' ' + self.archaeaModelFile + ' -')


        self.logger.info('Identifying eukaryotic 18S.')