Updates file of alleles if the new allele passes length and identity checks
        :param sample: sample object
        :param gene: name of gene of interest
        :param targetallele: closest allele in database

def alleleupdater1(self, sample, gene, targetallele):
        """
        Updates file of alleles if the new allele passes length and identity checks
        :param sample: sample object
        :param gene: name of gene of interest
        :param targetallele: closest allele in database
        """
        from io import StringIO
        from Bio.Blast import NCBIXML
        from Bio.SeqRecord import SeqRecord
        from Bio.Seq import Seq
        from Bio.Alphabet import generic_dna
        # Find the name of the allele file based on whether the gene name is found in the file name
        genefile = [x for x in sample[self.analysistype].alleles if gene in x][0]
        # Remove the extension of the gene file for use in makeblastdb and blastn
        genefilenoext = genefile.split(".")[0]
        # Create the blast databases every time the method is called
        subprocess.call(shlex.split('makeblastdb -in {} -parse_seqids -max_file_sz 2GB -dbtype nucl -out {}'
                                    .format(genefile, genefilenoext)), stdout=self.fnull, stderr=self.fnull)
        # Re-perform BLAST analyses, but using an XML output that stores the alignment
        blastn = NcbiblastnCommandline(query=sample.general.bestassemblyfile, db=genefilenoext, evalue=0.1, outfmt=5)
        # Note that there is no output file specified -  the search results are currently stored in stdout
        stdout, stderr = blastn()
        if stdout.find('Hsp') != -1:
            # Map the blast record to memory
            blast_handle = StringIO(stdout)
            # Open record from memory-mapped file
            records = NCBIXML.parse(blast_handle)
            # Iterate through the records in the blast results
            for record in records:  # This process is just to retrieve HSPs from xml files
                for alignment in record.alignments:
                    for hsp in alignment.hsps:
                        # Extract the allele name from the blast result
                        allele = str(alignment.accession.split("_")[-1]) if "_" in alignment.accession else \
                            str(alignment.accession.split("-")[-1])
                        # The point of this blast is to extract the sequence of the allele
                        # If the allele name matches the target allele (the closest match e.g. BACT000063_20 -> 20)
                        if allele == str(targetallele):
                            # As there is some discrepancy with the capitalisation of terms, make sure it is consistent
                            analysistype = 'rMLST' if self.analysistype.lower() == 'rmlst' else 'MLST'
                            # Set the directory containing the profile and alleles
                            alleledir = self.referencefilepath + analysistype if self.pipeline else \
                                self.referencefilepath
                            # The name of the supplemental allele file (without and with the .fa extension)
                            allelefilenoext = '{}/OLC_{}_alleles'.format(alleledir, analysistype) if self.pipeline \
                                else '{}/rMLST_combined'.format(alleledir)
                            allelefile = allelefilenoext + '.fa' if self.pipeline else allelefilenoext + '.fasta'
                            # Create the file if it doesn't exist
                            open(allelefile, 'a').close()
                            # Create a list of all the blast database files in the folder
                            dbfiles = glob('{}.n*'.format(allelefilenoext))
                            # Remove the database files
                            map(lambda y: os.remove(y), dbfiles)
                            # Create the necessary blast database files
                            subprocess.call(
                                shlex.split('makeblastdb -in {} -parse_seqids -max_file_sz 2GB -dbtype nucl -out {}'
                                            .format(allelefile, allelefilenoext)), stdout=self.fnull, stderr=self.fnull)

                            # Perform BLAST analysis using the supplemental allele file as the database
                            nestedblastn = NcbiblastnCommandline(db=allelefilenoext, evalue=0.1, outfmt=5)
                            # There is no output file specified; the search results are currently stored in stdout
                            # Additionally, the sequence from the previous BLAST query is used as stdin in this BLAST
                            import Bio.Application
                            try:
                                nestedstdout, nestedstderr = nestedblastn(stdin=hsp.query)
                            except Bio.Application.ApplicationError:
                                nestedstdout = ''
                                pass
                            # Search stdout for matches - if the term Hsp appears (the .find function will NOT
                            # return -1), a match has been found, and stdout is written to file
                            if nestedstdout.find('Hsp') != -1:
                                nested_blast_handle = StringIO(nestedstdout)
                                # Open record from memory-mapped file
                                nestedrecords = NCBIXML.parse(nested_blast_handle)
                                # Initialise variables
                                previousallele = ''
                                bitscore = ''
                                # Iterate through the records
                                for nestedrecord in nestedrecords:
                                    for nestedalignment in nestedrecord.alignments:
                                        for nestedhsp in nestedalignment.hsps:
                                            # Calculate the percent identity
                                            percentidentity = float("%.2f" % float(float(nestedhsp.identities) /
                                                                                   float(nestedalignment.length) * 100))
                                            # Only set the previous allele and the bitscore if the % identity is 100%
                                            if percentidentity == 100:
                                                # Get the allele number
                                                previousallele = nestedalignment.accession.split("_")[-1]
                                                bitscore = nestedhsp.score

                                # If this allele has already been found in the supplemental file, return these data
                                if previousallele:
                                    return gene, previousallele, 100.0, bitscore
                                # Otherwise, get the allele sequence into the supplemental file
                                else:
                                    # Initialise variables
                                    allelelist = []
                                    allelenumber = 1000000
                                    # Open the allele file to append
                                    with open(allelefile, 'ab+') as supplemental:
                                        for line in supplemental:
                                            # As there are multiple genes (e.g. BACT000001, BACT000063, etc.) check to
                                            # see if the gene of interest is in the line
                                            if gene in line:
                                                # Append the header to the list
                                                allelelist.append(line)
                                        # Find the last allele number from the header
                                        try:
                                            allelenumber = int(allelelist[-1].split("_")[1]) + 1
                                        # If there are no alleles for the gene of interest, then pass
                                        except IndexError:
                                            pass
                                        # Puts the HSP in the correct order -  hits to the negative strand will be
                                        # reversed compared to what we're looking for
                                        allelesequence = Seq(hsp.query, generic_dna)
                                        if hsp.sbjct_start < hsp.sbjct_end:
                                            end = hsp.sbjct_end
                                        else:
                                            end = hsp.sbjct_start
                                            allelesequence = allelesequence.reverse_complement()
                                        # Screen out hits that are shorter than the targets
                                        # Keeping this format though this statement could be re-written more efficiently
                                        if end < alignment.length:
                                            pass
                                        # The header will be >BACT00001_1000000
                                        definitionline = '{}_{}'.format(gene, allelenumber)
                                        # Create a sequence record using BioPython
                                        fasta = SeqRecord(allelesequence,
                                                          # Without this, the header will be improperly formatted
                                                          description='',
                                                          # Use >:definitionline as the header
                                                          id=definitionline)
                                        # Use the SeqIO module to properly format the new sequence record
                                        SeqIO.write(fasta, supplemental, "fasta")
                                        # Return the necessary values
                                        return gene, allelenumber, 100.0, hsp.score
                            # If there are hits in the supplemental allele file
                            else:
                                # Initialise variables
                                allelelist = []
                                allelenumber = 1000000
                                # Open the allele file to find the last allele associated with the gene of interest
                                with open(allelefile, 'a+') as supplemental:
                                    for line in supplemental:
                                        if gene in line:
                                            allelelist.append(line)
                                    try:
                                        allelenumber = int(allelelist[-1].split("_")[1]) + 1
                                    except IndexError:
                                        pass
                                    # Puts the HSP in the correct order -  hits to the negative strand will be
                                    # reversed compared to what we're looking for
                                    allelesequence = Seq(hsp.query, generic_dna)
                                    if hsp.sbjct_start < hsp.sbjct_end:
                                        end = hsp.sbjct_end
                                    else:
                                        end = hsp.sbjct_start
                                        allelesequence = allelesequence.reverse_complement()
                                    # Screen out hits that are shorter than the targets
                                    # Keeping this format, though this if statement could be re-written more efficiently
                                    if end < alignment.length:
                                        pass
                                    definitionline = '{}_{}'.format(gene, allelenumber)
                                    # Create a sequence record using BioPython
                                    fasta = SeqRecord(allelesequence,
                                                      # If this is not added, the header will not be formatted properly
                                                      description='',
                                                      # Use >:definitionline as the header
                                                      id=definitionline)
                                    # Use the SeqIO module to properly format the new sequence record
                                    SeqIO.write(fasta, supplemental, "fasta")
                                    # Return the appropriate information
                                    return gene, allelenumber, 100.0, hsp.score