# Path: checkm/common.py
# def checkDirExists(inputDir):
#     """Check if directory exists."""
#     if not os.path.exists(inputDir):
#         logger = logging.getLogger('timestamp')
#         logger.error('Input directory does not exists: ' + inputDir + '\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 shutil
import subprocess
import logging
from collections import defaultdict
from checkm.defaultValues import DefaultValues
from checkm.common import checkDirExists
from checkm.util.seqUtils import readFasta, writeFasta

        # (this can occur when all genomes have no phylogenetically informative marker genes)
        if os.stat(concatenatedAlignFile)[stat.ST_SIZE] == 0:
            self.logger.info('No genomes were identified that could be placed in the reference genome tree.')
            shutil.copyfile(os.path.join(pplacerRefPkg, DefaultValues.GENOME_TREE), treeFile)
            return

        # run pplacer to place bins in reference genome tree
        self.logger.info('Placing %d bins into the genome tree with pplacer (be patient).' % len(binFiles))
        cmd = 'pplacer -j %d -c %s -o %s %s > %s' % (self.numThreads,
                                                     pplacerRefPkg,
                                                     pplacerJsonOut,
                                                     concatenatedAlignFile,
                                                     pplacerOut)
        os.system(cmd)

        # extract tree
        cmd = 'guppy tog -o %s %s' % (treeFile, pplacerJsonOut)
        os.system(cmd)

    def __createConcatenatedAlignment(self, binFiles, resultsParser, alignOutputDir):
        """Create a concatenated alignment of marker genes for each bin."""

        # read alignment files
        self.logger.info('Reading marker alignment files.')
        alignments = defaultdict(dict)
        files = os.listdir(alignOutputDir)
        binIds = set()
        for f in files:
            if f.endswith('.masked.faa'):
                markerId = f[0:f.find('.masked.faa')]

# Path: checkm/common.py
# def checkDirExists(inputDir):
#     """Check if directory exists."""
#     if not os.path.exists(inputDir):
#         logger = logging.getLogger('timestamp')
#         logger.error('Input directory does not exists: ' + inputDir + '\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/pplacer.py
import os
import sys
import stat
import shutil
import subprocess
import logging
from collections import defaultdict
from checkm.defaultValues import DefaultValues
from checkm.common import checkDirExists
from checkm.util.seqUtils import readFasta, writeFasta

        # (this can occur when all genomes have no phylogenetically informative marker genes)
        if os.stat(concatenatedAlignFile)[stat.ST_SIZE] == 0:
            self.logger.info('No genomes were identified that could be placed in the reference genome tree.')
            shutil.copyfile(os.path.join(pplacerRefPkg, DefaultValues.GENOME_TREE), treeFile)
            return

        # run pplacer to place bins in reference genome tree
        self.logger.info('Placing %d bins into the genome tree with pplacer (be patient).' % len(binFiles))
        cmd = 'pplacer -j %d -c %s -o %s %s > %s' % (self.numThreads,
                                                     pplacerRefPkg,
                                                     pplacerJsonOut,
                                                     concatenatedAlignFile,
                                                     pplacerOut)
        os.system(cmd)

        # extract tree
        cmd = 'guppy tog -o %s %s' % (treeFile, pplacerJsonOut)
        os.system(cmd)

    def __createConcatenatedAlignment(self, binFiles, resultsParser, alignOutputDir):
        """Create a concatenated alignment of marker genes for each bin."""

        # read alignment files
        self.logger.info('Reading marker alignment files.')
        alignments = defaultdict(dict)
        files = os.listdir(alignOutputDir)
        binIds = set()
        for f in files:
            if f.endswith('.masked.faa'):
                markerId = f[0:f.find('.masked.faa')]

                seqs = readFasta(os.path.join(alignOutputDir, f))
