# 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

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

                for seqId, seq in seqs.items():
                    binId = seqId[0:seqId.find(DefaultValues.SEQ_CONCAT_CHAR)]

                    alignments[markerId][binId] = seq
                    binIds.add(binId)

        # get all markers and their lengths
        markerIds = resultsParser.models[list(resultsParser.models.keys())[0]].keys()
        markerIdLens = {}
        for markerId in markerIds:
            markerIdLens[markerId] = resultsParser.models[list(resultsParser.models.keys())[0]][markerId].leng

        # create concatenated alignment
        self.logger.info('Concatenating alignments.')
        concatenatedSeqs = {}
        for markerId in sorted(markerIds):
            seqs = alignments[markerId]

            for binId in binIds:
                if binId in seqs:
                    # append alignment
                    concatenatedSeqs[binId] = concatenatedSeqs.get(binId, '') + seqs[binId]
                else:
                    # missing gene
                    concatenatedSeqs[binId] = concatenatedSeqs.get(binId, '') + '-' * markerIdLens[markerId]

        # save concatenated alignment
        concatenatedAlignFile = os.path.join(alignOutputDir, DefaultValues.PPLACER_CONCAT_SEQ_OUT)

# 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

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

                for seqId, seq in seqs.items():
                    binId = seqId[0:seqId.find(DefaultValues.SEQ_CONCAT_CHAR)]

                    alignments[markerId][binId] = seq
                    binIds.add(binId)

        # get all markers and their lengths
        markerIds = resultsParser.models[list(resultsParser.models.keys())[0]].keys()
        markerIdLens = {}
        for markerId in markerIds:
            markerIdLens[markerId] = resultsParser.models[list(resultsParser.models.keys())[0]][markerId].leng

        # create concatenated alignment
        self.logger.info('Concatenating alignments.')
        concatenatedSeqs = {}
        for markerId in sorted(markerIds):
            seqs = alignments[markerId]

            for binId in binIds:
                if binId in seqs:
                    # append alignment
                    concatenatedSeqs[binId] = concatenatedSeqs.get(binId, '') + seqs[binId]
                else:
                    # missing gene
                    concatenatedSeqs[binId] = concatenatedSeqs.get(binId, '') + '-' * markerIdLens[markerId]

        # save concatenated alignment
        concatenatedAlignFile = os.path.join(alignOutputDir, DefaultValues.PPLACER_CONCAT_SEQ_OUT)

        writeFasta(concatenatedSeqs, concatenatedAlignFile)
