def writeFragments(outfile_fasta,
                   outfile_index,
                   fragments,
                   mangler, size,
                   write_all=False):
    """write mangled fragments to *outfile_fasta* in chunks of *size*
    updating *outfile_index*.

    returns part of last fragment that has not been written and is
    less than *size* and the number of fragments output.

    If *write_all* is True, all of the fragments are written to
    the file and the last file position is added to *outfile_index*
    as well.
    """

    s = "".join(fragments)
    rest = len(s) % size
    if len(s) > size:
        for x in range(0, len(s) - rest, size):
            outfile_index.write("\t%i" % outfile_fasta.tell())
            outfile_fasta.write(mangler(s[x:x + size]))

    if rest:
        if write_all:
            outfile_index.write("\t%i" % outfile_fasta.tell())
            outfile_fasta.write(mangler(s[-rest:]))
            outfile_index.write("\t%i" % outfile_fasta.tell())
            return ""
        else:
            return s[-rest:]
    else:
        return ""