# Path: checkm/common.py
# def checkFileExists(inputFile):
#     """Check if file exists."""
#     if not os.path.exists(inputFile):
#         logger = logging.getLogger('timestamp')
#         logger.error('Input file does not exists: ' + inputFile + '\n')
#         sys.exit(1)
# 
# 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 writeFasta(seqs, outputFile):
#     '''write sequences to FASTA file'''
#     if outputFile.endswith('.gz'):
#         fout = gzip.open(outputFile, 'wb')
#     else:
#         fout = open(outputFile, 'w')
# 
#     for seqId, seq in seqs.items():
#         fout.write('>' + seqId + '\n')
#         fout.write(seq + '\n')
#     fout.close()


import os
import sys
import stat
import subprocess
import logging
import shutil
import numpy as np
from checkm.defaultValues import DefaultValues
from checkm.common import checkFileExists
from checkm.util.seqUtils import readFasta, writeFasta





class ProdigalError(BaseException):
    pass


class ProdigalRunner():
    """Wrapper for running prodigal."""

    def __init__(self, outDir):
        self.logger = logging.getLogger('timestamp')

        # make sure prodigal is installed
        self.checkForProdigal()

        self.aaGeneFile = os.path.join(outDir, DefaultValues.PRODIGAL_AA)
        self.ntGeneFile = os.path.join(outDir, DefaultValues.PRODIGAL_NT)
        self.gffFile = os.path.join(outDir, DefaultValues.PRODIGAL_GFF)

    def run(self, query, bNucORFs=True):

        prodigal_input = query

        # decompress gzip input files
        if prodigal_input.endswith('.gz'):
            tmp_dir = tempfile.mkdtemp()
            prodigal_input = os.path.join(tmp_dir, os.path.basename(prodigal_input[0:-3]) + '.fna')

# Path: checkm/common.py
# def checkFileExists(inputFile):
#     """Check if file exists."""
#     if not os.path.exists(inputFile):
#         logger = logging.getLogger('timestamp')
#         logger.error('Input file does not exists: ' + inputFile + '\n')
#         sys.exit(1)
# 
# 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 writeFasta(seqs, outputFile):
#     '''write sequences to FASTA file'''
#     if outputFile.endswith('.gz'):
#         fout = gzip.open(outputFile, 'wb')
#     else:
#         fout = open(outputFile, 'w')
# 
#     for seqId, seq in seqs.items():
#         fout.write('>' + seqId + '\n')
#         fout.write(seq + '\n')
#     fout.close()


# Path: checkm/prodigal.py
import os
import sys
import stat
import subprocess
import logging
import shutil
import numpy as np
from checkm.defaultValues import DefaultValues
from checkm.common import checkFileExists
from checkm.util.seqUtils import readFasta, writeFasta






class ProdigalError(BaseException):
    pass


class ProdigalRunner():
    """Wrapper for running prodigal."""

    def __init__(self, outDir):
        self.logger = logging.getLogger('timestamp')

        # make sure prodigal is installed
        self.checkForProdigal()

        self.aaGeneFile = os.path.join(outDir, DefaultValues.PRODIGAL_AA)
        self.ntGeneFile = os.path.join(outDir, DefaultValues.PRODIGAL_NT)
        self.gffFile = os.path.join(outDir, DefaultValues.PRODIGAL_GFF)

    def run(self, query, bNucORFs=True):

        prodigal_input = query

        # decompress gzip input files
        if prodigal_input.endswith('.gz'):
            tmp_dir = tempfile.mkdtemp()
            prodigal_input = os.path.join(tmp_dir, os.path.basename(prodigal_input[0:-3]) + '.fna')

            writeFasta(seqs, prodigal_input)