assert contig_filenames, 'No contig sequences given'

    contigs = dict([
                 (name.split()[0], seq)
                 for filename in contig_filenames
                 for name, seq in io.read_sequences(filename)
              ])
    dir_contigs = { }
    for name in contigs:
        dir_contigs[name + '+'] = contigs[name]
        dir_contigs[name + '-'] = bio.reverse_complement(contigs[name])

    dir_contigs_used = { }
    for name in dir_contigs:
        dir_contigs_used[name] = [ False ] * len(dir_contigs[name])

    workspace = io.Workspace(output_dir)
    temp_prefix = workspace._object_filename('temp-pastiche')

"""

Paste together contigs to cover a reference

"""

import sys, os, collections, subprocess

from nesoni import io, bio, grace

USAGE = """

Use MUMMER to plaster a set of contigs over reference sequences.

Usage:

    nesoni pastiche: [options] <output-dir> <reference.fa> [...] contigs: <contigs.fa> [...]

Options:

    --mask yes/no  - What to do if nothing matches part of the reference.
                     If yes, retain reference in lowercase.
                     If no, output "n"s.
                     Default: no

    --min-leftover nnn
                   - Discard leftover sequence shorter than this.
                     Default: 20

"""

def run(args, stdin=None, stdout=subprocess.PIPE, stderr=None, bufsize=1<<20):
    return subprocess.Popen(
        args,
        bufsize=bufsize,
        stdin=stdin,
        stdout=stdout,
        stderr=stderr,
        close_fds=True,
    )

def execute(args, stdin=None, stdout=None):
    p = run(args, stdin=stdin, stdout=stdout, stderr=subprocess.PIPE)
    for line in p.stderr:
        pass
    assert p.wait() == 0, 'Failed to execute "%s"' % ' '.join(args)

def pastiche(args):
    if len(args) < 4:
        print USAGE
        return 1

    mask_only, args = grace.get_option_value(args, '--mask', grace.as_bool, False)
    min_leftover, args = grace.get_option_value(args, '--min-leftover', int, 20)

    output_dir, args = args[0], args[1:]

    ref_filenames = [ ]
    contig_filenames = [ ]
    grace.execute(args, {
        'contigs' : lambda args: contig_filenames.extend(args)
    }, lambda args: ref_filenames.extend(args))

    assert ref_filenames, 'No reference sequences given'

    out_f = workspace.open('pastiche.fa', 'wb')

    for ref_filename in ref_filenames:
      for ref_name, ref_seq in io.read_sequences(ref_filename):
        ref_name = ref_name.split()[0]

        grace.status(ref_name)

        f = open(temp_prefix + '.fa','wb')
        io.write_fasta(f, 'ref', ref_seq)
        f.close()

        scores = [ -1 ] * (len(ref_seq)*2)
        strings = [ 'N', '' ] * (len(ref_seq))
        contexts = [ None for i in xrange(len(ref_seq)*2) ]

        if mask_only:
            for i in xrange(len(ref_seq)):
                strings[i*2] = ref_seq[i].lower()

        def put(position, dir_contig_name, start, end, score):
            if scores[position] < score:
                scores[position] = score
                strings[position] = dir_contigs[dir_contig_name][start:end]
                contexts[position] = (dir_contig_name, start, end, score)

        for contig_filename in contig_filenames:
            execute(['nucmer',
                     '--prefix', temp_prefix,
                     '--nosimplify',
                     '--minmatch', '9',
                     '--mincluster', '50',
                     #'--breaklen', '1000', # Increasing this reduces Ns, but is slow
                     temp_prefix+'.fa',
                     contig_filename])

            for contig_name, contig_seq in io.read_sequences(contig_filename):
                contig_name = contig_name.split()[0]
                grace.status(ref_name + ' vs ' + contig_name)
                p = run(['show-aligns', temp_prefix+'.delta', 'ref', contig_name],
                        stderr=subprocess.PIPE)

                alignments = [ ]

                while True:
                    line = p.stdout.readline()
                    if not line: break
                    if not line.startswith('-- BEGIN'):
                        continue

                    parts = line.split()

                    ref_start = int(parts[5])
                    ref_end = int(parts[7])
                    query_start = int(parts[10])
                    query_end = int(parts[12])

                    #assert ref_start < ref_end
                    #ref_start -= 1 #Zero based coordinates

                    al_ref = [ ]
                    al_query = [ ]

                    while True:
                        block = [ ]
                        end = False
                        while True:
                            line = p.stdout.readline()
                            if line.startswith('--   END'):
                                end = True
                                break
                            if line == '\n':
                                if block:
                                    break
                                else:
                                    continue
                            block.append(line)

                        if end: break

                        al_ref.append(block[0].split()[1])
                        al_query.append(block[1].split()[1])

                    al_ref = ''.join(al_ref)
                    al_query = ''.join(al_query)

                    if ref_start > ref_end:
                       al_ref = bio.reverse_complement(al_ref)
                       al_query = bio.reverse_complement(al_query)
                       ref_start, ref_end = ref_end, ref_start
                       query_start, query_end = query_end, query_start

                    if query_start > query_end:
                       dir_contig_name = contig_name + '-'
                       query_start = len(contig_seq)+1-query_start
                       query_end = len(contig_seq)+1-query_end
                    else:
                       dir_contig_name = contig_name + '+'

                    ref_start -= 1 #Zero based coordinates
                    query_start -= 1

                    #print al_ref
                    #print al_query

                    #Pretty dumb scoring scheme
                    al_score = 0
                    for i in xrange(len(al_ref)):
                        if al_ref[i] == al_query[i]:
                            al_score += 1

                    #Pastiche alignment over reference
                    ref_pos = ref_start
                    query_pos = query_start
                    al_pos = 0
                    while al_pos < len(al_ref):
                        assert al_ref[al_pos] != '.'
                        if al_query[al_pos] == '.':
                            put(ref_pos*2, dir_contig_name, query_pos, query_pos, al_score)
                        else:
                            assert al_query[al_pos].lower() == dir_contigs[dir_contig_name][query_pos].lower()
                            put(ref_pos*2, dir_contig_name, query_pos, query_pos+1, al_score)
                            query_pos += 1
                        al_pos += 1

                        al_pos_end = al_pos
                        query_pos_end = query_pos
                        while al_pos_end < len(al_ref) and al_ref[al_pos_end] == '.':
                            al_pos_end += 1
                            query_pos_end += 1
                        assert al_query[al_pos:al_pos_end].lower() == dir_contigs[dir_contig_name][query_pos:query_pos_end].lower()
                        put(ref_pos*2+1, dir_contig_name, query_pos,query_pos_end, al_score)
                        al_pos = al_pos_end
                        query_pos = query_pos_end
                        ref_pos += 1

                p.wait()

        grace.status(ref_name)

        result = ''.join(strings)
        io.write_fasta(out_f, ref_name, result)

        for context in contexts:
            if context is None: continue
            name,start,end,score = context
            for i in xrange(start,end):
                dir_contigs_used[name][i] = True

        #Interpolation
        #    j = i
        #    i = j

    out_f.close()

    grace.status('')

    leftover_f = workspace.open('leftovers.fa','wb')

    for name in sorted(contigs):
        used = [ (a or b) for a,b in zip(dir_contigs_used[name+'+'],dir_contigs_used[name+'-'][::-1]) ]

        i = 0
        while i < len(used):
            j = i
            while j < len(used) and not used[j]:
                j += 1
            if j-i > min_leftover:
                if i == 0 and j == len(used):
                    out_name = name
                else:
                    out_name = name + ':%d..%d' % (i+1,j)
                io.write_fasta(leftover_f, out_name, contigs[name][i:j])

            i = j+1

    leftover_f.close()

    for suffix in ['.fa', '.delta']:
        os.unlink(temp_prefix + suffix)


out_f = workspace.open('pastiche.fa', 'wb')

    for ref_filename in ref_filenames:
      for ref_name, ref_seq in io.read_sequences(ref_filename):
        ref_name = ref_name.split()[0]

        grace.status(ref_name)

        f = open(temp_prefix + '.fa','wb')
        io.write_fasta(f, 'ref', ref_seq)
        f.close()

        scores = [ -1 ] * (len(ref_seq)*2)
        strings = [ 'N', '' ] * (len(ref_seq))
        contexts = [ None for i in xrange(len(ref_seq)*2) ]

        if mask_only:
            for i in xrange(len(ref_seq)):
                strings[i*2] = ref_seq[i].lower()

        def put(position, dir_contig_name, start, end, score):
            if scores[position] < score:
                scores[position] = score
                strings[position] = dir_contigs[dir_contig_name][start:end]
                contexts[position] = (dir_contig_name, start, end, score)

        for contig_filename in contig_filenames:
            execute(['nucmer',
                     '--prefix', temp_prefix,
                     '--nosimplify',
                     '--minmatch', '9',
                     '--mincluster', '50',
                     #'--breaklen', '1000', # Increasing this reduces Ns, but is slow
                     temp_prefix+'.fa',
                     contig_filename])

            for contig_name, contig_seq in io.read_sequences(contig_filename):
                contig_name = contig_name.split()[0]
                grace.status(ref_name + ' vs ' + contig_name)
                p = run(['show-aligns', temp_prefix+'.delta', 'ref', contig_name],
                        stderr=subprocess.PIPE)

                alignments = [ ]

                while True:
                    line = p.stdout.readline()
                    if not line: break
                    if not line.startswith('-- BEGIN'):
                        continue

                    parts = line.split()

                    ref_start = int(parts[5])
                    ref_end = int(parts[7])
                    query_start = int(parts[10])
                    query_end = int(parts[12])

                    #assert ref_start < ref_end
                    #ref_start -= 1 #Zero based coordinates

                    al_ref = [ ]
                    al_query = [ ]

                    while True:
                        block = [ ]
                        end = False
                        while True:
                            line = p.stdout.readline()
                            if line.startswith('--   END'):
                                end = True
                                break
                            if line == '\n':
                                if block:
                                    break
                                else:
                                    continue
                            block.append(line)

                        if end: break

                        al_ref.append(block[0].split()[1])
                        al_query.append(block[1].split()[1])

                    al_ref = ''.join(al_ref)
                    al_query = ''.join(al_query)

                    if ref_start > ref_end:
                       al_ref = bio.reverse_complement(al_ref)
                       al_query = bio.reverse_complement(al_query)
                       ref_start, ref_end = ref_end, ref_start
                       query_start, query_end = query_end, query_start

                    if query_start > query_end:
                       dir_contig_name = contig_name + '-'
                       query_start = len(contig_seq)+1-query_start
                       query_end = len(contig_seq)+1-query_end
                    else:
                       dir_contig_name = contig_name + '+'

                    ref_start -= 1 #Zero based coordinates
                    query_start -= 1

                    #print al_ref
                    #print al_query

                    #Pretty dumb scoring scheme
                    al_score = 0
                    for i in xrange(len(al_ref)):
                        if al_ref[i] == al_query[i]:
                            al_score += 1

                    #Pastiche alignment over reference
                    ref_pos = ref_start
                    query_pos = query_start
                    al_pos = 0
                    while al_pos < len(al_ref):
                        assert al_ref[al_pos] != '.'
                        if al_query[al_pos] == '.':
                            put(ref_pos*2, dir_contig_name, query_pos, query_pos, al_score)
                        else:
                            assert al_query[al_pos].lower() == dir_contigs[dir_contig_name][query_pos].lower()
                            put(ref_pos*2, dir_contig_name, query_pos, query_pos+1, al_score)
                            query_pos += 1
                        al_pos += 1

                        al_pos_end = al_pos
                        query_pos_end = query_pos
                        while al_pos_end < len(al_ref) and al_ref[al_pos_end] == '.':
                            al_pos_end += 1
                            query_pos_end += 1
                        assert al_query[al_pos:al_pos_end].lower() == dir_contigs[dir_contig_name][query_pos:query_pos_end].lower()
                        put(ref_pos*2+1, dir_contig_name, query_pos,query_pos_end, al_score)
                        al_pos = al_pos_end
                        query_pos = query_pos_end
                        ref_pos += 1

                p.wait()

        grace.status(ref_name)

        result = ''.join(strings)
        io.write_fasta(out_f, ref_name, result)

        for context in contexts:
            if context is None: continue
            name,start,end,score = context
            for i in xrange(start,end):
                dir_contigs_used[name][i] = True

        #Interpolation
        #    j = i
        #    i = j

    out_f.close()

    grace.status('')

    leftover_f = workspace.open('leftovers.fa','wb')

    for name in sorted(contigs):
        used = [ (a or b) for a,b in zip(dir_contigs_used[name+'+'],dir_contigs_used[name+'-'][::-1]) ]

        i = 0
        while i < len(used):
            j = i
            while j < len(used) and not used[j]:
                j += 1
            if j-i > min_leftover:
                if i == 0 and j == len(used):
                    out_name = name
                else:
                    out_name = name + ':%d..%d' % (i+1,j)
                io.write_fasta(leftover_f, out_name, contigs[name][i:j])

            i = j+1

    leftover_f.close()

    for suffix in ['.fa', '.delta']:
        os.unlink(temp_prefix + suffix)

"""

Paste together contigs to cover a reference

"""

import sys, os, collections, subprocess

from nesoni import io, bio, grace

USAGE = """

Use MUMMER to plaster a set of contigs over reference sequences.

Usage:

    nesoni pastiche: [options] <output-dir> <reference.fa> [...] contigs: <contigs.fa> [...]

Options:

    --mask yes/no  - What to do if nothing matches part of the reference.
                     If yes, retain reference in lowercase.
                     If no, output "n"s.
                     Default: no

    --min-leftover nnn
                   - Discard leftover sequence shorter than this.
                     Default: 20

"""

def run(args, stdin=None, stdout=subprocess.PIPE, stderr=None, bufsize=1<<20):
    return subprocess.Popen(
        args,
        bufsize=bufsize,
        stdin=stdin,
        stdout=stdout,
        stderr=stderr,
        close_fds=True,
    )

def execute(args, stdin=None, stdout=None):
    p = run(args, stdin=stdin, stdout=stdout, stderr=subprocess.PIPE)
    for line in p.stderr:
        pass
    assert p.wait() == 0, 'Failed to execute "%s"' % ' '.join(args)

def pastiche(args):
    if len(args) < 4:
        print USAGE
        return 1

    mask_only, args = grace.get_option_value(args, '--mask', grace.as_bool, False)
    min_leftover, args = grace.get_option_value(args, '--min-leftover', int, 20)

    output_dir, args = args[0], args[1:]

    ref_filenames = [ ]
    contig_filenames = [ ]
    grace.execute(args, {
        'contigs' : lambda args: contig_filenames.extend(args)
    }, lambda args: ref_filenames.extend(args))

    assert ref_filenames, 'No reference sequences given'
    assert contig_filenames, 'No contig sequences given'

    contigs = dict([
                 (name.split()[0], seq)
                 for filename in contig_filenames
                 for name, seq in io.read_sequences(filename)
              ])
    dir_contigs = { }
    for name in contigs:
        dir_contigs[name + '+'] = contigs[name]
        dir_contigs[name + '-'] = bio.reverse_complement(contigs[name])

    dir_contigs_used = { }
    for name in dir_contigs:
        dir_contigs_used[name] = [ False ] * len(dir_contigs[name])

    workspace = io.Workspace(output_dir)
    temp_prefix = workspace._object_filename('temp-pastiche')


"""

Paste together contigs to cover a reference

"""

import sys, os, collections, subprocess

from nesoni import io, bio, grace

USAGE = """

Use MUMMER to plaster a set of contigs over reference sequences.

Usage:

    nesoni pastiche: [options] <output-dir> <reference.fa> [...] contigs: <contigs.fa> [...]

Options:

    --mask yes/no  - What to do if nothing matches part of the reference.
                     If yes, retain reference in lowercase.
                     If no, output "n"s.
                     Default: no

    --min-leftover nnn
                   - Discard leftover sequence shorter than this.
                     Default: 20

"""

def run(args, stdin=None, stdout=subprocess.PIPE, stderr=None, bufsize=1<<20):
    return subprocess.Popen(
        args,
        bufsize=bufsize,
        stdin=stdin,
        stdout=stdout,
        stderr=stderr,
        close_fds=True,
    )

def execute(args, stdin=None, stdout=None):
    p = run(args, stdin=stdin, stdout=stdout, stderr=subprocess.PIPE)
    for line in p.stderr:
        pass
    assert p.wait() == 0, 'Failed to execute "%s"' % ' '.join(args)

def pastiche(args):
    if len(args) < 4:
        print USAGE
        return 1

    mask_only, args = grace.get_option_value(args, '--mask', grace.as_bool, False)
    min_leftover, args = grace.get_option_value(args, '--min-leftover', int, 20)

    output_dir, args = args[0], args[1:]

    ref_filenames = [ ]
    contig_filenames = [ ]
    grace.execute(args, {
        'contigs' : lambda args: contig_filenames.extend(args)
    }, lambda args: ref_filenames.extend(args))

    assert ref_filenames, 'No reference sequences given'
    assert contig_filenames, 'No contig sequences given'

    contigs = dict([
                 (name.split()[0], seq)
                 for filename in contig_filenames
                 for name, seq in io.read_sequences(filename)
              ])
    dir_contigs = { }
    for name in contigs:
        dir_contigs[name + '+'] = contigs[name]
        dir_contigs[name + '-'] = bio.reverse_complement(contigs[name])

    d

    for name in dir_contigs:
        dir_contigs_used[name] = [ False ] * len(dir_contigs[name])

    workspace = io.Workspace(output_dir)
    temp_prefix = workspace._object_filename('temp-pastiche')

    out_f = workspace.open('pastiche.fa', 'wb')

    for ref_filename in ref_filenames:
      for ref_name, ref_seq in io.read_sequences(ref_filename):
        ref_name = ref_name.split()[0]

        grace.status(ref_name)

        f = open(temp_prefix + '.fa','wb')
        io.write_fasta(f, 'ref', ref_seq)
        f.close()

        scores = [ -1 ] * (len(ref_seq)*2)
        strings = [ 'N', '' ] * (len(ref_seq))
        contexts = [ None for i in xrange(len(ref_seq)*2) ]

        if mask_only:
            for i in xrange(len(ref_seq)):
                strings[i*2] = ref_seq[i].lower()

        def put(position, dir_contig_name, start, end, score):
            if scores[position] < score:
                scores[position] = score
                strings[position] = dir_contigs[dir_contig_name][start:end]
                contexts[position] = (dir_contig_name, start, end, score)

        for contig_filename in contig_filenames:
            execute(['nucmer',
                     '--prefix', temp_prefix,
                     '--nosimplify',
                     '--minmatch', '9',
                     '--mincluster', '50',
                     #'--breaklen', '1000', # Increasing this reduces Ns, but is slow
                     temp_prefix+'.fa',
                     contig_filename])

            for contig_name, contig_seq in io.read_sequences(contig_filename):
                contig_name = contig_name.split()[0]
                grace.status(ref_name + ' vs ' + contig_name)
                p = run(['show-aligns', temp_prefix+'.delta', 'ref', contig_name],
                        stderr=subprocess.PIPE)

                alignments = [ ]

                while True:
                    line = p.stdout.readline()
                    if not line: break
                    if not line.startswith('-- BEGIN'):
                        continue

                    parts = line.split()

                    ref_start = int(parts[5])
                    ref_end = int(parts[7])
                    query_start = int(parts[10])
                    query_end = int(parts[12])

                    #assert ref_start < ref_end
                    #ref_start -= 1 #Zero based coordinates

                    al_ref = [ ]
                    al_query = [ ]

                    while True:
                        block = [ ]
                        end = False
                        while True:
                            line = p.stdout.readline()
                            if line.startswith('--   END'):
                                end = True
                                break
                            if line == '\n':
                                if block:
                                    break
                                else:
                                    continue
                            block.append(line)

                        if end: break

                        al_ref.append(block[0].split()[1])
                        al_query.append(block[1].split()[1])

                    al_ref = ''.join(al_ref)
                    al_query = ''.join(al_query)

                    if ref_start > ref_end:
                       al_ref = bio.reverse_complement(al_ref)
                       al_query = bio.reverse_complement(al_query)
                       ref_start, ref_end = ref_end, ref_start
                       query_start, query_end = query_end, query_start

                    if query_start > query_end:
                       dir_contig_name = contig_name + '-'
                       query_start = len(contig_seq)+1-query_start
                       query_end = len(contig_seq)+1-query_end
                    else:
                       dir_contig_name = contig_name + '+'

                    ref_start -= 1 #Zero based coordinates
                    query_start -= 1

                    #print al_ref
                    #print al_query

                    #Pretty dumb scoring scheme
                    al_score = 0
                    for i in xrange(len(al_ref)):
                        if al_ref[i] == al_query[i]:
                            al_score += 1

                    #Pastiche alignment over reference
                    ref_pos = ref_start
                    query_pos = query_start
                    al_pos = 0
                    while al_pos < len(al_ref):
                        assert al_ref[al_pos] != '.'
                        if al_query[al_pos] == '.':
                            put(ref_pos*2, dir_contig_name, query_pos, query_pos, al_score)
                        else:
                            assert al_query[al_pos].lower() == dir_contigs[dir_contig_name][query_pos].lower()
                            put(ref_pos*2, dir_contig_name, query_pos, query_pos+1, al_score)
                            query_pos += 1
                        al_pos += 1

                        al_pos_end = al_pos
                        query_pos_end = query_pos
                        while al_pos_end < len(al_ref) and al_ref[al_pos_end] == '.':
                            al_pos_end += 1
                            query_pos_end += 1
                        assert al_query[al_pos:al_pos_end].lower() == dir_contigs[dir_contig_name][query_pos:query_pos_end].lower()
                        put(ref_pos*2+1, dir_contig_name, query_pos,query_pos_end, al_score)
                        al_pos = al_pos_end
                        query_pos = query_pos_end
                        ref_pos += 1

                p.wait()

        grace.status(ref_name)

        result = ''.join(strings)
        io.write_fasta(out_f, ref_name, result)

        for context in contexts:
            if context is None: continue
            name,start,end,score = context
            for i in xrange(start,end):
                dir_contigs_used[name][i] = True

        #Interpolation
        #    j = i
        #    i = j

    out_f.close()

    grace.status('')

    leftover_f = workspace.open('leftovers.fa','wb')

    for name in sorted(contigs):
        used = [ (a or b) for a,b in zip(dir_contigs_used[name+'+'],dir_contigs_used[name+'-'][::-1]) ]

        i = 0
        while i < len(used):
            j = i
            while j < len(used) and not used[j]:
                j += 1
            if j-i > min_leftover:
                if i == 0 and j == len(used):
                    out_name = name
                else:
                    out_name = name + ':%d..%d' % (i+1,j)
                io.write_fasta(leftover_f, out_name, contigs[name][i:j])

            i = j+1

    leftover_f.close()

    for suffix in ['.fa', '.delta']:
        os.unlink(temp_prefix + suffix)


if not line.startswith('-- BEGIN'):
                        continue

"""

Paste together contigs to cover a reference

"""

import sys, os, collections, subprocess

from nesoni import io, bio, grace

USAGE = """

Use MUMMER to plaster a set of contigs over reference sequences.

Usage:

    nesoni pastiche: [options] <output-dir> <reference.fa> [...] contigs: <contigs.fa> [...]

Options:

    --mask yes/no  - What to do if nothing matches part of the reference.
                     If yes, retain reference in lowercase.
                     If no, output "n"s.
                     Default: no

    --min-leftover nnn
                   - Discard leftover sequence shorter than this.
                     Default: 20

"""

def run(args, stdin=None, stdout=subprocess.PIPE, stderr=None, bufsize=1<<20):
    return subprocess.Popen(
        args,
        bufsize=bufsize,
        stdin=stdin,
        stdout=stdout,
        stderr=stderr,
        close_fds=True,
    )

def execute(args, stdin=None, stdout=None):
    p = run(args, stdin=stdin, stdout=stdout, stderr=subprocess.PIPE)
    for line in p.stderr:
        pass
    assert p.wait() == 0, 'Failed to execute "%s"' % ' '.join(args)

def pastiche(args):
    if len(args) < 4:
        print USAGE
        return 1

    mask_only, args = grace.get_option_value(args, '--mask', grace.as_bool, False)
    min_leftover, args = grace.get_option_value(args, '--min-leftover', int, 20)

    output_dir, args = args[0], args[1:]

    ref_filenames = [ ]
    contig_filenames = [ ]
    grace.execute(args, {
        'contigs' : lambda args: contig_filenames.extend(args)
    }, lambda args: ref_filenames.extend(args))

    assert ref_filenames, 'No reference sequences given'
    assert contig_filenames, 'No contig sequences given'

    contigs = dict([
                 (name.split()[0], seq)
                 for filename in contig_filenames
                 for name, seq in io.read_sequences(filename)
              ])
    dir_contigs = { }
    for name in contigs:
        dir_contigs[name + '+'] = contigs[name]
        dir_contigs[name + '-'] = bio.reverse_complement(contigs[name])

    dir_contigs_used = { }
    for name in dir_contigs:
        dir_contigs_used[name] = [ False ] * len(dir_contigs[name])

    workspace = io.Workspace(output_dir)
    temp_prefix = workspace._object_filename('temp-pastiche')

    out_f = workspace.open('pastiche.fa', 'wb')

    for ref_filename in ref_filenames:
      for ref_name, ref_seq in io.read_sequences(ref_filename):
        ref_name = ref_name.split()[0]

        grace.status(ref_name)

        f = open(temp_prefix + '.fa','wb')
        io.write_fasta(f, 'ref', ref_seq)
        f.close()

        scores = [ -1 ] * (len(ref_seq)*2)
        strings = [ 'N', '' ] * (len(ref_seq))
        contexts = [ None for i in xrange(len(ref_seq)*2) ]

        if mask_only:
            for i in xrange(len(ref_seq)):
                strings[i*2] = ref_seq[i].lower()

        def put(position, dir_contig_name, start, end, score):
            if scores[position] < score:
                scores[position] = score
                strings[position] = dir_contigs[dir_contig_name][start:end]
                contexts[position] = (dir_contig_name, start, end, score)

        for contig_filename in contig_filenames:
            execute(['nucmer',
                     '--prefix', temp_prefix,
                     '--nosimplify',
                     '--minmatch', '9',
                     '--mincluster', '50',
                     #'--breaklen', '1000', # Increasing this reduces Ns, but is slow
                     temp_prefix+'.fa',
                     contig_filename])

            for contig_name, contig_seq in io.read_sequences(contig_filename):
                contig_name = contig_name.split()[0]
                grace.status(ref_name + ' vs ' + contig_name)
                p = run(['show-aligns', temp_prefix+'.delta', 'ref', contig_name],
                        stderr=subprocess.PIPE)

                alignments = [ ]

                while True:
                    line = p.stdout.readline()
                    if not line: break

                    parts = line.split()

                    ref_start = int(parts[5])
                    ref_end = int(parts[7])
                    query_start = int(parts[10])
                    query_end = int(parts[12])

                    #assert ref_start < ref_end
                    #ref_start -= 1 #Zero based coordinates

                    al_ref = [ ]
                    al_query = [ ]

                    while True:
                        block = [ ]
                        end = False
                        while True:
                            line = p.stdout.readline()
                            if line.startswith('--   END'):
                                end = True
                                break
                            if line == '\n':
                                if block:
                                    break
                                else:
                                    continue
                            block.append(line)

                        if end: break

                        al_ref.append(block[0].split()[1])
                        al_query.append(block[1].split()[1])

                    al_ref = ''.join(al_ref)
                    al_query = ''.join(al_query)

                    if ref_start > ref_end:
                       al_ref = bio.reverse_complement(al_ref)
                       al_query = bio.reverse_complement(al_query)
                       ref_start, ref_end = ref_end, ref_start
                       query_start, query_end = query_end, query_start

                    if query_start > query_end:
                       dir_contig_name = contig_name + '-'
                       query_start = len(contig_seq)+1-query_start
                       query_end = len(contig_seq)+1-query_end
                    else:
                       dir_contig_name = contig_name + '+'

                    ref_start -= 1 #Zero based coordinates
                    query_start -= 1

                    #print al_ref
                    #print al_query

                    #Pretty dumb scoring scheme
                    al_score = 0
                    for i in xrange(len(al_ref)):
                        if al_ref[i] == al_query[i]:
                            al_score += 1

                    #Pastiche alignment over reference
                    ref_pos = ref_start
                    query_pos = query_start
                    al_pos = 0
                    while al_pos < len(al_ref):
                        assert al_ref[al_pos] != '.'
                        if al_query[al_pos] == '.':
                            put(ref_pos*2, dir_contig_name, query_pos, query_pos, al_score)
                        else:
                            assert al_query[al_pos].lower() == dir_contigs[dir_contig_name][query_pos].lower()
                            put(ref_pos*2, dir_contig_name, query_pos, query_pos+1, al_score)
                            query_pos += 1
                        al_pos += 1

                        al_pos_end = al_pos
                        query_pos_end = query_pos
                        while al_pos_end < len(al_ref) and al_ref[al_pos_end] == '.':
                            al_pos_end += 1
                            query_pos_end += 1
                        assert al_query[al_pos:al_pos_end].lower() == dir_contigs[dir_contig_name][query_pos:query_pos_end].lower()
                        put(ref_pos*2+1, dir_contig_name, query_pos,query_pos_end, al_score)
                        al_pos = al_pos_end
                        query_pos = query_pos_end
                        ref_pos += 1

                p.wait()

        grace.status(ref_name)

        result = ''.join(strings)
        io.write_fasta(out_f, ref_name, result)

        for context in contexts:
            if context is None: continue
            name,start,end,score = context
            for i in xrange(start,end):
                dir_contigs_used[name][i] = True

        #Interpolation
        #    j = i
        #    i = j

    out_f.close()

    grace.status('')

    leftover_f = workspace.open('leftovers.fa','wb')

    for name in sorted(contigs):
        used = [ (a or b) for a,b in zip(dir_contigs_used[name+'+'],dir_contigs_used[name+'-'][::-1]) ]

        i = 0
        while i < len(used):
            j = i
            while j < len(used) and not used[j]:
                j += 1
            if j-i > min_leftover:
                if i == 0 and j == len(used):
                    out_name = name
                else:
                    out_name = name + ':%d..%d' % (i+1,j)
                io.write_fasta(leftover_f, out_name, contigs[name][i:j])

            i = j+1

    leftover_f.close()

    for suffix in ['.fa', '.delta']:
        os.unlink(temp_prefix + suffix)


for context in contexts:
            if context is None: continue
            name,start,end,score = context
            for i in xrange(start,end):
                dir_contigs_used[name][i] = True

"""

Paste together contigs to cover a reference

"""

import sys, os, collections, subprocess

from nesoni import io, bio, grace

USAGE = """

Use MUMMER to plaster a set of contigs over reference sequences.

Usage:

    nesoni pastiche: [options] <output-dir> <reference.fa> [...] contigs: <contigs.fa> [...]

Options:

    --mask yes/no  - What to do if nothing matches part of the reference.
                     If yes, retain reference in lowercase.
                     If no, output "n"s.
                     Default: no

    --min-leftover nnn
                   - Discard leftover sequence shorter than this.
                     Default: 20

"""

def run(args, stdin=None, stdout=subprocess.PIPE, stderr=None, bufsize=1<<20):
    return subprocess.Popen(
        args,
        bufsize=bufsize,
        stdin=stdin,
        stdout=stdout,
        stderr=stderr,
        close_fds=True,
    )

def execute(args, stdin=None, stdout=None):
    p = run(args, stdin=stdin, stdout=stdout, stderr=subprocess.PIPE)
    for line in p.stderr:
        pass
    assert p.wait() == 0, 'Failed to execute "%s"' % ' '.join(args)

def pastiche(args):
    if len(args) < 4:
        print USAGE
        return 1

    mask_only, args = grace.get_option_value(args, '--mask', grace.as_bool, False)
    min_leftover, args = grace.get_option_value(args, '--min-leftover', int, 20)

    output_dir, args = args[0], args[1:]

    ref_filenames = [ ]
    contig_filenames = [ ]
    grace.execute(args, {
        'contigs' : lambda args: contig_filenames.extend(args)
    }, lambda args: ref_filenames.extend(args))

    assert ref_filenames, 'No reference sequences given'
    assert contig_filenames, 'No contig sequences given'

    contigs = dict([
                 (name.split()[0], seq)
                 for filename in contig_filenames
                 for name, seq in io.read_sequences(filename)
              ])
    dir_contigs = { }
    for name in contigs:
        dir_contigs[name + '+'] = contigs[name]
        dir_contigs[name + '-'] = bio.reverse_complement(contigs[name])

    dir_contigs_used = { }
    for name in dir_contigs:
        dir_contigs_used[name] = [ False ] * len(dir_contigs[name])

    workspace = io.Workspace(output_dir)
    temp_prefix = workspace._object_filename('temp-pastiche')

    out_f = workspace.open('pastiche.fa', 'wb')

    for ref_filename in ref_filenames:
      for ref_name, ref_seq in io.read_sequences(ref_filename):
        ref_name = ref_name.split()[0]

        grace.status(ref_name)

        f = open(temp_prefix + '.fa','wb')
        io.write_fasta(f, 'ref', ref_seq)
        f.close()

        scores = [ -1 ] * (len(ref_seq)*2)
        strings = [ 'N', '' ] * (len(ref_seq))
        contexts = [ None for i in xrange(len(ref_seq)*2) ]

        if mask_only:
            for i in xrange(len(ref_seq)):
                strings[i*2] = ref_seq[i].lower()

        def put(position, dir_contig_name, start, end, score):
            if scores[position] < score:
                scores[position] = score
                strings[position] = dir_contigs[dir_contig_name][start:end]
                contexts[position] = (dir_contig_name, start, end, score)

        for contig_filename in contig_filenames:
            execute(['nucmer',
                     '--prefix', temp_prefix,
                     '--nosimplify',
                     '--minmatch', '9',
                     '--mincluster', '50',
                     #'--breaklen', '1000', # Increasing this reduces Ns, but is slow
                     temp_prefix+'.fa',
                     contig_filename])

            for contig_name, contig_seq in io.read_sequences(contig_filename):
                contig_name = contig_name.split()[0]
                grace.status(ref_name + ' vs ' + contig_name)
                p = run(['show-aligns', temp_prefix+'.delta', 'ref', contig_name],
                        stderr=subprocess.PIPE)

                alignments = [ ]

                while True:
                    line = p.stdout.readline()
                    if not line: break
                    if not line.startswith('-- BEGIN'):
                        continue

                    parts = line.split()

                    ref_start = int(parts[5])
                    ref_end = int(parts[7])
                    query_start = int(parts[10])
                    query_end = int(parts[12])

                    #assert ref_start < ref_end
                    #ref_start -= 1 #Zero based coordinates

                    al_ref = [ ]
                    al_query = [ ]

                    while True:
                        block = [ ]
                        end = False
                        while True:
                            line = p.stdout.readline()
                            if line.startswith('--   END'):
                                end = True
                                break
                            if line == '\n':
                                if block:
                                    break
                                else:
                                    continue
                            block.append(line)

                        if end: break

                        al_ref.append(block[0].split()[1])
                        al_query.append(block[1].split()[1])

                    al_ref = ''.join(al_ref)
                    al_query = ''.join(al_query)

                    if ref_start > ref_end:
                       al_ref = bio.reverse_complement(al_ref)
                       al_query = bio.reverse_complement(al_query)
                       ref_start, ref_end = ref_end, ref_start
                       query_start, query_end = query_end, query_start

                    if query_start > query_end:
                       dir_contig_name = contig_name + '-'
                       query_start = len(contig_seq)+1-query_start
                       query_end = len(contig_seq)+1-query_end
                    else:
                       dir_contig_name = contig_name + '+'

                    ref_start -= 1 #Zero based coordinates
                    query_start -= 1

                    #print al_ref
                    #print al_query

                    #Pretty dumb scoring scheme
                    al_score = 0
                    for i in xrange(len(al_ref)):
                        if al_ref[i] == al_query[i]:
                            al_score += 1

                    #Pastiche alignment over reference
                    ref_pos = ref_start
                    query_pos = query_start
                    al_pos = 0
                    while al_pos < len(al_ref):
                        assert al_ref[al_pos] != '.'
                        if al_query[al_pos] == '.':
                            put(ref_pos*2, dir_contig_name, query_pos, query_pos, al_score)
                        else:
                            assert al_query[al_pos].lower() == dir_contigs[dir_contig_name][query_pos].lower()
                            put(ref_pos*2, dir_contig_name, query_pos, query_pos+1, al_score)
                            query_pos += 1
                        al_pos += 1

                        al_pos_end = al_pos
                        query_pos_end = query_pos
                        while al_pos_end < len(al_ref) and al_ref[al_pos_end] == '.':
                            al_pos_end += 1
                            query_pos_end += 1
                        assert al_query[al_pos:al_pos_end].lower() == dir_contigs[dir_contig_name][query_pos:query_pos_end].lower()
                        put(ref_pos*2+1, dir_contig_name, query_pos,query_pos_end, al_score)
                        al_pos = al_pos_end
                        query_pos = query_pos_end
                        ref_pos += 1

                p.wait()

        grace.status(ref_name)

        result = ''.join(strings)
        io.write_fasta(out_f, ref_name, result)

        #Interpolation
        #    j = i
        #    i = j

    out_f.close()

    grace.status('')

    leftover_f = workspace.open('leftovers.fa','wb')

    for name in sorted(contigs):
        used = [ (a or b) for a,b in zip(dir_contigs_used[name+'+'],dir_contigs_used[name+'-'][::-1]) ]

        i = 0
        while i < len(used):
            j = i
            while j < len(used) and not used[j]:
                j += 1
            if j-i > min_leftover:
                if i == 0 and j == len(used):
                    out_name = name
                else:
                    out_name = name + ':%d..%d' % (i+1,j)
                io.write_fasta(leftover_f, out_name, contigs[name][i:j])

            i = j+1

    leftover_f.close()

    for suffix in ['.fa', '.delta']:
        os.unlink(temp_prefix + suffix)


while i < len(used):
            j = i
            while j < len(used) and not used[j]:
                j += 1
            if j-i > min_leftover:
                if i == 0 and j == len(used):
                    out_name = name
                else:
                    out_name = name + ':%d..%d' % (i+1,j)
                io.write_fasta(leftover_f, out_name, contigs[name][i:j])

            i = j+1

"""

Paste together contigs to cover a reference

"""

import sys, os, collections, subprocess

from nesoni import io, bio, grace

USAGE = """

Use MUMMER to plaster a set of contigs over reference sequences.

Usage:

    nesoni pastiche: [options] <output-dir> <reference.fa> [...] contigs: <contigs.fa> [...]

Options:

    --mask yes/no  - What to do if nothing matches part of the reference.
                     If yes, retain reference in lowercase.
                     If no, output "n"s.
                     Default: no

    --min-leftover nnn
                   - Discard leftover sequence shorter than this.
                     Default: 20

"""

def run(args, stdin=None, stdout=subprocess.PIPE, stderr=None, bufsize=1<<20):
    return subprocess.Popen(
        args,
        bufsize=bufsize,
        stdin=stdin,
        stdout=stdout,
        stderr=stderr,
        close_fds=True,
    )

def execute(args, stdin=None, stdout=None):
    p = run(args, stdin=stdin, stdout=stdout, stderr=subprocess.PIPE)
    for line in p.stderr:
        pass
    assert p.wait() == 0, 'Failed to execute "%s"' % ' '.join(args)

def pastiche(args):
    if len(args) < 4:
        print USAGE
        return 1

    mask_only, args = grace.get_option_value(args, '--mask', grace.as_bool, False)
    min_leftover, args = grace.get_option_value(args, '--min-leftover', int, 20)

    output_dir, args = args[0], args[1:]

    ref_filenames = [ ]
    contig_filenames = [ ]
    grace.execute(args, {
        'contigs' : lambda args: contig_filenames.extend(args)
    }, lambda args: ref_filenames.extend(args))

    assert ref_filenames, 'No reference sequences given'
    assert contig_filenames, 'No contig sequences given'

    contigs = dict([
                 (name.split()[0], seq)
                 for filename in contig_filenames
                 for name, seq in io.read_sequences(filename)
              ])
    dir_contigs = { }
    for name in contigs:
        dir_contigs[name + '+'] = contigs[name]
        dir_contigs[name + '-'] = bio.reverse_complement(contigs[name])

    dir_contigs_used = { }
    for name in dir_contigs:
        dir_contigs_used[name] = [ False ] * len(dir_contigs[name])

    workspace = io.Workspace(output_dir)
    temp_prefix = workspace._object_filename('temp-pastiche')

    out_f = workspace.open('pastiche.fa', 'wb')

    for ref_filename in ref_filenames:
      for ref_name, ref_seq in io.read_sequences(ref_filename):
        ref_name = ref_name.split()[0]

        grace.status(ref_name)

        f = open(temp_prefix + '.fa','wb')
        io.write_fasta(f, 'ref', ref_seq)
        f.close()

        scores = [ -1 ] * (len(ref_seq)*2)
        strings = [ 'N', '' ] * (len(ref_seq))
        contexts = [ None for i in xrange(len(ref_seq)*2) ]

        if mask_only:
            for i in xrange(len(ref_seq)):
                strings[i*2] = ref_seq[i].lower()

        def put(position, dir_contig_name, start, end, score):
            if scores[position] < score:
                scores[position] = score
                strings[position] = dir_contigs[dir_contig_name][start:end]
                contexts[position] = (dir_contig_name, start, end, score)

        for contig_filename in contig_filenames:
            execute(['nucmer',
                     '--prefix', temp_prefix,
                     '--nosimplify',
                     '--minmatch', '9',
                     '--mincluster', '50',
                     #'--breaklen', '1000', # Increasing this reduces Ns, but is slow
                     temp_prefix+'.fa',
                     contig_filename])

            for contig_name, contig_seq in io.read_sequences(contig_filename):
                contig_name = contig_name.split()[0]
                grace.status(ref_name + ' vs ' + contig_name)
                p = run(['show-aligns', temp_prefix+'.delta', 'ref', contig_name],
                        stderr=subprocess.PIPE)

                alignments = [ ]

                while True:
                    line = p.stdout.readline()
                    if not line: break
                    if not line.startswith('-- BEGIN'):
                        continue

                    parts = line.split()

                    ref_start = int(parts[5])
                    ref_end = int(parts[7])
                    query_start = int(parts[10])
                    query_end = int(parts[12])

                    #assert ref_start < ref_end
                    #ref_start -= 1 #Zero based coordinates

                    al_ref = [ ]
                    al_query = [ ]

                    while True:
                        block = [ ]
                        end = False
                        while True:
                            line = p.stdout.readline()
                            if line.startswith('--   END'):
                                end = True
                                break
                            if line == '\n':
                                if block:
                                    break
                                else:
                                    continue
                            block.append(line)

                        if end: break

                        al_ref.append(block[0].split()[1])
                        al_query.append(block[1].split()[1])

                    al_ref = ''.join(al_ref)
                    al_query = ''.join(al_query)

                    if ref_start > ref_end:
                       al_ref = bio.reverse_complement(al_ref)
                       al_query = bio.reverse_complement(al_query)
                       ref_start, ref_end = ref_end, ref_start
                       query_start, query_end = query_end, query_start

                    if query_start > query_end:
                       dir_contig_name = contig_name + '-'
                       query_start = len(contig_seq)+1-query_start
                       query_end = len(contig_seq)+1-query_end
                    else:
                       dir_contig_name = contig_name + '+'

                    ref_start -= 1 #Zero based coordinates
                    query_start -= 1

                    #print al_ref
                    #print al_query

                    #Pretty dumb scoring scheme
                    al_score = 0
                    for i in xrange(len(al_ref)):
                        if al_ref[i] == al_query[i]:
                            al_score += 1

                    #Pastiche alignment over reference
                    ref_pos = ref_start
                    query_pos = query_start
                    al_pos = 0
                    while al_pos < len(al_ref):
                        assert al_ref[al_pos] != '.'
                        if al_query[al_pos] == '.':
                            put(ref_pos*2, dir_contig_name, query_pos, query_pos, al_score)
                        else:
                            assert al_query[al_pos].lower() == dir_contigs[dir_contig_name][query_pos].lower()
                            put(ref_pos*2, dir_contig_name, query_pos, query_pos+1, al_score)
                            query_pos += 1
                        al_pos += 1

                        al_pos_end = al_pos
                        query_pos_end = query_pos
                        while al_pos_end < len(al_ref) and al_ref[al_pos_end] == '.':
                            al_pos_end += 1
                            query_pos_end += 1
                        assert al_query[al_pos:al_pos_end].lower() == dir_contigs[dir_contig_name][query_pos:query_pos_end].lower()
                        put(ref_pos*2+1, dir_contig_name, query_pos,query_pos_end, al_score)
                        al_pos = al_pos_end
                        query_pos = query_pos_end
                        ref_pos += 1

                p.wait()

        grace.status(ref_name)

        result = ''.join(strings)
        io.write_fasta(out_f, ref_name, result)

        for context in contexts:
            if context is None: continue
            name,start,end,score = context
            for i in xrange(start,end):
                dir_contigs_used[name][i] = True

        #Interpolation
        #    j = i
        #    i = j

    out_f.close()

    grace.status('')

    leftover_f = workspace.open('leftovers.fa','wb')

    for name in sorted(contigs):
        used = [ (a or b) for a,b in zip(dir_contigs_used[name+'+'],dir_contigs_used[name+'-'][::-1]) ]

        i = 0

    leftover_f.close()

    for suffix in ['.fa', '.delta']:
        os.unlink(temp_prefix + suffix)


"""

Paste together contigs to cover a reference

"""

import sys, os, collections, subprocess

from nesoni import io, bio, grace

USAGE = """

Use MUMMER to plaster a set of contigs over reference sequences.

Usage:

    nesoni pastiche: [options] <output-dir> <reference.fa> [...] contigs: <contigs.fa> [...]

Options:

    --mask yes/no  - What to do if nothing matches part of the reference.
                     If yes, retain reference in lowercase.
                     If no, output "n"s.
                     Default: no

    --min-leftover nnn
                   - Discard leftover sequence shorter than this.
                     Default: 20

"""

def run(args, stdin=None, stdout=subprocess.PIPE, stderr=None, bufsize=1<<20):
    return subprocess.Popen(
        args,
        bufsize=bufsize,
        stdin=stdin,
        stdout=stdout,
        stderr=stderr,
        close_fds=True,
    )

def execute(args, stdin=None, stdout=None):
    p = run(args, stdin=stdin, stdout=stdout, stderr=subprocess.PIPE)
    for line in p.stderr:
        pass
    assert p.wait() == 0, 'Failed to execute "%s"' % ' '.join(args)

def pastiche(args):
    if len(args) < 4:
        print USAGE
        return 1

    mask_only, args = grace.get_option_value(args, '--mask', grace.as_bool, False)
    min_leftover, args = grace.get_option_value(args, '--min-leftover', int, 20)

    output_dir, args = args[0], args[1:]

    ref_filenames = [ ]
    contig_filenames = [ ]
    grace.execute(args, {
        'contigs' : lambda args: contig_filenames.extend(args)
    }, lambda args: ref_filenames.extend(args))

    assert ref_filenames, 'No reference sequences given'
    assert contig_filenames, 'No contig sequences given'

    contigs = dict([
                 (name.split()[0], seq)
                 for filename in contig_filenames
                 for name, seq in io.read_sequences(filename)
              ])
    dir_contigs = { }
    for name in contigs:
        dir_contigs[name + '+'] = contigs[name]
        dir_contigs[name + '-'] = bio.reverse_complement(contigs[name])

    dir_contigs_used = { }
    for name in dir_contigs:
        dir_contigs_used[name] = [ False ] * len(dir_contigs[name])

    workspace = io.Workspace(output_dir)
    temp_prefix = workspace._object_filename('temp-pastiche')

    out_f = workspace.open('pastiche.fa', 'wb')

    for ref_filename in ref_filenames:
      for ref_name, ref_seq in io.read_sequences(ref_filename):
        ref_name = ref_name.split

()[0]

        grace.status(ref_name)

        f = open(temp_prefix + '.fa','wb')
        io.write_fasta(f, 'ref', ref_seq)
        f.close()

        scores = [ -1 ] * (len(ref_seq)*2)
        strings = [ 'N', '' ] * (len(ref_seq))
        contexts = [ None for i in xrange(len(ref_seq)*2) ]

        if mask_only:
            for i in xrange(len(ref_seq)):
                strings[i*2] = ref_seq[i].lower()

        def put(position, dir_contig_name, start, end, score):
            if scores[position] < score:
                scores[position] = score
                strings[position] = dir_contigs[dir_contig_name][start:end]
                contexts[position] = (dir_contig_name, start, end, score)

        for contig_filename in contig_filenames:
            execute(['nucmer',
                     '--prefix', temp_prefix,
                     '--nosimplify',
                     '--minmatch', '9',
                     '--mincluster', '50',
                     #'--breaklen', '1000', # Increasing this reduces Ns, but is slow
                     temp_prefix+'.fa',
                     contig_filename])

            for contig_name, contig_seq in io.read_sequences(contig_filename):
                contig_name = contig_name.split()[0]
                grace.status(ref_name + ' vs ' + contig_name)
                p = run(['show-aligns', temp_prefix+'.delta', 'ref', contig_name],
                        stderr=subprocess.PIPE)

                alignments = [ ]

                while True:
                    line = p.stdout.readline()
                    if not line: break
                    if not line.startswith('-- BEGIN'):
                        continue

                    parts = line.split()

                    ref_start = int(parts[5])
                    ref_end = int(parts[7])
                    query_start = int(parts[10])
                    query_end = int(parts[12])

                    #assert ref_start < ref_end
                    #ref_start -= 1 #Zero based coordinates

                    al_ref = [ ]
                    al_query = [ ]

                    while True:
                        block = [ ]
                        end = False
                        while True:
                            line = p.stdout.readline()
                            if line.startswith('--   END'):
                                end = True
                                break
                            if line == '\n':
                                if block:
                                    break
                                else:
                                    continue
                            block.append(line)

                        if end: break

                        al_ref.append(block[0].split()[1])
                        al_query.append(block[1].split()[1])

                    al_ref = ''.join(al_ref)
                    al_query = ''.join(al_query)

                    if ref_start > ref_end:
                       al_ref = bio.reverse_complement(al_ref)
                       al_query = bio.reverse_complement(al_query)
                       ref_start, ref_end = ref_end, ref_start
                       query_start, query_end = query_end, query_start

                    if query_start > query_end:
                       dir_contig_name = contig_name + '-'
                       query_start = len(contig_seq)+1-query_start
                       query_end = len(contig_seq)+1-query_end
                    else:
                       dir_contig_name = contig_name + '+'

                    ref_start -= 1 #Zero based coordinates
                    query_start -= 1

                    #print al_ref
                    #print al_query

                    #Pretty dumb scoring scheme
                    al_score = 0
                    for i in xrange(len(al_ref)):
                        if al_ref[i] == al_query[i]:
                            al_score += 1

                    #Pastiche alignment over reference
                    ref_pos = ref_start
                    query_pos = query_start
                    al_pos = 0
                    while al_pos < len(al_ref):
                        assert al_ref[al_pos] != '.'
                        if al_query[al_pos] == '.':
                            put(ref_pos*2, dir_contig_name, query_pos, query_pos, al_score)
                        else:
                            assert al_query[al_pos].lower() == dir_contigs[dir_contig_name][query_pos].lower()
                            put(ref_pos*2, dir_contig_name, query_pos, query_pos+1, al_score)
                            query_pos += 1
                        al_pos += 1

                        al_pos_end = al_pos
                        query_pos_end = query_pos
                        while al_pos_end < len(al_ref) and al_ref[al_pos_end] == '.':
                            al_pos_end += 1
                            query_pos_end += 1
                        assert al_query[al_pos:al_pos_end].lower() == dir_contigs[dir_contig_name][query_pos:query_pos_end].lower()
                        put(ref_pos*2+1, dir_contig_name, query_pos,query_pos_end, al_score)
                        al_pos = al_pos_end
                        query_pos = query_pos_end
                        ref_pos += 1

                p.wait()

        grace.status(ref_name)

        result = ''.join(strings)
        io.write_fasta(out_f, ref_name, result)

        for context in contexts:
            if context is None: continue
            name,start,end,score = context
            for i in xrange(start,end):
                dir_contigs_used[name][i] = True

        #Interpolation
        #    j = i
        #    i = j

    out_f.close()

    grace.status('')

    leftover_f = workspace.open('leftovers.fa','wb')

    for name in sorted(contigs):
        used = [ (a or b) for a,b in zip(dir_contigs_used[name+'+'],dir_contigs_used[name+'-'][::-1]) ]

        i = 0
        while i < len(used):
            j = i
            while j < len(used) and not used[j]:
                j += 1
            if j-i > min_leftover:
                if i == 0 and j == len(used):
                    out_name = name
                else:
                    out_name = name + ':%d..%d' % (i+1,j)
                io.write_fasta(leftover_f, out_name, contigs[name][i:j])

            i = j+1

    leftover_f.close()

    for suffix in ['.fa', '.delta']:
        os.unlink(temp_prefix + suffix)


## All rights reserved.
## Contact: example@nnthink.com
## This file is part of VisTrails.

"""module responsible for smartly importing python modules, checking
for necessary installs."""

from __future__ import division

import vistrails.core.bundles.installbundle
from vistrails.core.configuration import get_vistrails_configuration, \
    get_vistrails_persistent_configuration
from vistrails.core import debug

_previously_failed_pkgs = set()

class PyImportException(ImportError):
    pass

class PyImportBug(PyImportException):
    pass

return __import__(module_name, globals(), locals(), [])

def py_import(module_name, dependency_dictionary, store_in_config=False):
    """Tries to import a python module, installing if necessary.

    If the import doesn't succeed, we guess which system we are running on and
    install the corresponding package from the dictionary. We then run the
    import again.
    If the installation fails, we won't try to install that same module again
    for the session.
    """
    try:
        result = _vanilla_import(module_name)
        return result
    except ImportError:
        if not getattr(get_vistrails_configuration(), 'installBundles'):
            raise

    if module_name in _previously_failed_pkgs:
        raise PyImportException("Import of Python module '%s' failed again, "
                                "not triggering installation" % module_name)
    if store_in_config:
        ignored_packages_list = getattr(get_vistrails_configuration(),
                                        'bundleDeclinedList',
                                        None)
        if ignored_packages_list:
            ignored_packages = set(ignored_packages_list.split(';'))
        else:
            ignored_packages = set()
        if module_name in ignored_packages:
            raise PyImportException("Import of Python module '%s' failed "
                                    "again, installation disabled by "
                                    "configuration" % module_name)
    debug.warning("Import of python module '%s' failed. "
                  "Will try to install bundle." % module_name)

    success = vistrails.core.bundles.installbundle.install(
            dependency_dictionary)

    if store_in_config:
        if bool(success):
            ignored_packages.discard(module_name)
        else:
            ignored_packages.add(module_name)
        setattr(get_vistrails_configuration(),
                'bundleDeclinedList',
                ';'.join(sorted(ignored_packages)))
        setattr(get_vistrails_persistent_configuration(),
                'bundleDeclinedList',
                ';'.join(sorted(ignored_packages)))

    if not success:
        _previously_failed_pkgs.add(module_name)
        raise PyImportException("Installation of Python module '%s' failed." %
                                module_name)
    try:
        result = _vanilla_import(module_name)
        return result
    except ImportError, e:
        _previously_failed_pkgs.add(module_name)
        raise PyImportBug("Installation of package '%s' succeeded, but import "
                          "still fails." % module_name)


return __import__(module_name, globals(), locals(), [])

## All rights reserved.
## Contact: example@nnthink.com
## This file is part of VisTrails.

"""module responsible for smartly importing python modules, checking
for necessary installs."""

from __future__ import division

import vistrails.core.bundles.installbundle
from vistrails.core.configuration import get_vistrails_configuration, \
    get_vistrails_persistent_configuration
from vistrails.core import debug

_previously_failed_pkgs = set()

class PyImportException(ImportError):
    pass

class PyImportBug(PyImportException):
    pass

def _vanilla_import(module_name):

def py_import(module_name, dependency_dictionary, store_in_config=False):
    """Tries to import a python module, installing if necessary.

    If the import doesn't succeed, we guess which system we are running on and
    install the corresponding package from the dictionary. We then run the
    import again.
    If the installation fails, we won't try to install that same module again
    for the session.
    """
    try:
        result = _vanilla_import(module_name)
        return result
    except ImportError:
        if not getattr(get_vistrails_configuration(), 'installBundles'):
            raise

    if module_name in _previously_failed_pkgs:
        raise PyImportException("Import of Python module '%s' failed again, "
                                "not triggering installation" % module_name)
    if store_in_config:
        ignored_packages_list = getattr(get_vistrails_configuration(),
                                        'bundleDeclinedList',
                                        None)
        if ignored_packages_list:
            ignored_packages = set(ignored_packages_list.split(';'))
        else:
            ignored_packages = set()
        if module_name in ignored_packages:
            raise PyImportException("Import of Python module '%s' failed "
                                    "again, installation disabled by "
                                    "configuration" % module_name)
    debug.warning("Import of python module '%s' failed. "
                  "Will try to install bundle." % module_name)

    success = vistrails.core.bundles.installbundle.install(
            dependency_dictionary)

    if store_in_config:
        if bool(success):
            ignored_packages.discard(module_name)
        else:
            ignored_packages.add(module_name)
        setattr(get_vistrails_configuration(),
                'bundleDeclinedList',
                ';'.join(sorted(ignored_packages)))
        setattr(get_vistrails_persistent_configuration(),
                'bundleDeclinedList',
                ';'.join(sorted(ignored_packages)))

    if not success:
        _previously_failed_pkgs.add(module_name)
        raise PyImportException("Installation of Python module '%s' failed." %
                                module_name)
    try:
        result = _vanilla_import(module_name)
        return result
    except ImportError, e:
        _previously_failed_pkgs.add(module_name)
        raise PyImportBug("Installation of package '%s' succeeded, but import "
                          "still fails." % module_name)


"""Tries to import a python module, installing if necessary.

    If the import doesn't succeed, we guess which system we are running on and
    install the corresponding package from the dictionary. We then run the
    import again.
    If the installation fails, we won't try to install that same module again
    for the session.
    """
    try:
        result = _vanilla_import(module_name)
        return result
    except ImportError:
        if not getattr(get_vistrails_configuration(), 'installBundles'):
            raise

    if module_name in _previously_failed_pkgs:
        raise PyImportException("Import of Python module '%s' failed again, "
                                "not triggering installation" % module_name)

## All rights reserved.
## Contact: example@nnthink.com
## This file is part of VisTrails.

"""module responsible for smartly importing python modules, checking
for necessary installs."""

from __future__ import division

import vistrails.core.bundles.installbundle
from vistrails.core.configuration import get_vistrails_configuration, \
    get_vistrails_persistent_configuration
from vistrails.core import debug

_previously_failed_pkgs = set()

class PyImportException(ImportError):
    pass

class PyImportBug(PyImportException):
    pass

def _vanilla_import(module_name):
    return __import__(module_name, globals(), locals(), [])

def py_import(module_name, dependency_dictionary, store_in_config=False):

    if store_in_config:
        ignored_packages_list = getattr(get_vistrails_configuration(),
                                        'bundleDeclinedList',
                                        None)
        if ignored_packages_list:
            ignored_packages = set(ignored_packages_list.split(';'))
        else:
            ignored_packages = set()
        if module_name in ignored_packages:
            raise PyImportException("Import of Python module '%s' failed "
                                    "again, installation disabled by "
                                    "configuration" % module_name)
    debug.warning("Import of python module '%s' failed. "
                  "Will try to install bundle." % module_name)

    success = vistrails.core.bundles.installbundle.install(
            dependency_dictionary)

    if store_in_config:
        if bool(success):
            ignored_packages.discard(module_name)
        else:
            ignored_packages.add(module_name)
        setattr(get_vistrails_configuration(),
                'bundleDeclinedList',
                ';'.join(sorted(ignored_packages)))
        setattr(get_vistrails_persistent_configuration(),
                'bundleDeclinedList',
                ';'.join(sorted(ignored_packages)))

    if not success:
        _previously_failed_pkgs.add(module_name)
        raise PyImportException("Installation of Python module '%s' failed." %
                                module_name)
    try:
        result = _vanilla_import(module_name)
        return result
    except ImportError, e:
        _previously_failed_pkgs.add(module_name)
        raise PyImportBug("Installation of package '%s' succeeded, but import "
                          "still fails." % module_name)


if store_in_config:
        ignored_packages_list = getattr(get_vistrails_configuration(),
                                        'bundleDeclinedList',
                                        None)
        if ignored_packages_list:
            ignored_packages = set(ignored_packages_list.split(';'))
        else:
            ignored_packages = set()
        if module_name in ignored_packages:
            raise PyImportException("Import of Python module '%s' failed "
                                    "again, installation disabled by "
                                    "configuration" % module_name)
    debug.warning("Import of python module '%s' failed. "
                  "Will try to install bundle." % module_name)

    success = vistrails.core.bundles.installbundle.install(
            dependency_dictionary)

## All rights reserved.
## Contact: example@nnthink.com
## This file is part of VisTrails.

"""module responsible for smartly importing python modules, checking
for necessary installs."""

from __future__ import division

import vistrails.core.bundles.installbundle
from vistrails.core.configuration import get_vistrails_configuration, \
    get_vistrails_persistent_configuration
from vistrails.core import debug

_previously_failed_pkgs = set()

class PyImportException(ImportError):
    pass

class PyImportBug(PyImportException):
    pass

def _vanilla_import(module_name):
    return __import__(module_name, globals(), locals(), [])

def py_import(module_name, dependency_dictionary, store_in_config=False):
    """Tries to import a python module, installing if necessary.

    If the import doesn't succeed, we guess which system we are running on and
    install the corresponding package from the dictionary. We then run the
    import again.
    If the installation fails, we won't try to install that same module again
    for the session.
    """
    try:
        result = _vanilla_import(module_name)
        return result
    except ImportError:
        if not getattr(get_vistrails_configuration(), 'installBundles'):
            raise

    if module_name in _previously_failed_pkgs:
        raise PyImportException("Import of Python module '%s' failed again, "
                                "not triggering installation" % module_name)

    if store_in_config:
        if bool(success):
            ignored_packages.discard(module_name)
        else:
            ignored_packages.add(module_name)
        setattr(get_vistrails_configuration(),
                'bundleDeclinedList',
                ';'.join(sorted(ignored_packages)))
        setattr(get_vistrails_persistent_configuration(),
                'bundleDeclinedList',
                ';'.join(sorted(ignored_packages)))

    if not success:
        _previously_failed_pkgs.add(module_name)
        raise PyImportException("Installation of Python module '%s' failed." %
                                module_name)
    try:
        result = _vanilla_import(module_name)
        return result
    except ImportError, e:
        _previously_failed_pkgs.add(module_name)
        raise PyImportBug("Installation of package '%s' succeeded, but import "
                          "still fails." % module_name)


if store_in_config:
        if bool(success):
            ignored_packages.discard(module_name)
        else:
            ignored_packages.add(module_name)
        setattr(get_vistrails_configuration(),
                'bundleDeclinedList',
                ';'.join(sorted(ignored_packages)))
        setattr(get_vistrails_persistent_configuration(),
                'bundleDeclinedList',
                ';'.join(sorted(ignored_packages)))

    if not success:
        _previously_failed_pkgs.add(module_name)
        raise PyImportException("Installation of Python module '%s' failed." %
                                module_name)
    try:
        result = _vanilla_import(module_name)
        return result
    except ImportError, e:
        _previously_failed_pkgs.add(module_name)
        raise PyImportBug("Installation of package '%s' succeeded, but import "
                          "still fails." % module_name)

## All rights reserved.
## Contact: example@nnthink.com
## This file is part of VisTrails.

"""module responsible for smartly importing python modules, checking
for necessary installs."""

from __future__ import division

import vistrails.core.bundles.installbundle
from vistrails.core.configuration import get_vistrails_configuration, \
    get_vistrails_persistent_configuration
from vistrails.core import debug

_previously_failed_pkgs = set()

class PyImportException(ImportError):
    pass

class PyImportBug(PyImportException):
    pass

def _vanilla_import(module_name):
    return __import__(module_name, globals(), locals(), [])

def py_import(module_name, dependency_dictionary, store_in_config=False):
    """Tries to import a python module, installing if necessary.

    If the import doesn't succeed, we guess which system we are running on and
    install the corresponding package from the dictionary. We then run the
    import again.
    If the installation fails, we won't try to install that same module again
    for the session.
    """
    try:
        result = _vanilla_import(module_name)
        return result
    except ImportError:
        if not getattr(get_vistrails_configuration(), 'installBundles'):
            raise

    if module_name in _previously_failed_pkgs:
        raise PyImportException("Import of Python module '%s' failed again, "
                                "not triggering installation" % module_name)
    if store_in_config:
        ignored_packages_list = getattr(get_vistrails_configuration(),
                                        'bundleDeclinedList',
                                        None)
        if ignored_packages_list:
            ignored_packages = set(ignored_packages_list.split(';'))
        else:
            ignored_packages = set()
        if module_name in ignored_packages:
            raise PyImportException("Import of Python module '%s' failed "
                                    "again, installation disabled by "
                                    "configuration" % module_name)
    debug.warning("Import of python module '%s' failed. "
                  "Will try to install bundle." % module_name)

    success = vistrails.core.bundles.installbundle.install(
            dependency_dictionary)


## All rights reserved.
## Contact: example@nnthink.com
## This file is part of VisTrails.

"""module responsible for smartly importing python modules, checking
for necessary installs."""

from __future__ import division

import vistrails.core.bundles.installbundle
from vistrails.core.configuration import get_vistrails_configuration, \
    get_vistrails_persistent_configuration
from vistrails.core import debug

_previously_failed_pkgs = set()

class PyImportException(ImportError):
    pass

class PyImportBug(PyImportException):
    pass

def _vanilla_import(module_name):
    return __import__


if store_in_config:
        if bool(success):
            ignored_packages.discard(module_name)
        else:
            ignored_packages.add(module_name)
        setattr(get_vistrails_configuration(),
                'bundleDeclinedList',
                ';'.join(sorted(ignored_packages)))
        setattr(get_vistrails_persistent_configuration(),
                'bundleDeclinedList',
                ';'.join(sorted(ignored_packages)))

    if not success:
        _previously_failed_pkgs.add(module_name)
        raise PyImportException("Installation of Python module '%s' failed." %
                                module_name)
    try:
        result = _vanilla_import(module_name)
        return result
    except ImportError, e:
        _previously_failed_pkgs.add(module_name)
        raise PyImportBug("Installation of package '%s' succeeded, but import "
                          "still fails." % module_name)


try:
        result = _vanilla_import(module_name)
        return result
    except ImportError:
        if not getattr(get_vistrails_configuration(), 'installBundles'):
            raise

## All rights reserved.
## Contact: example@nnthink.com
## This file is part of VisTrails.

"""module responsible for smartly importing python modules, checking
for necessary installs."""

from __future__ import division

import vistrails.core.bundles.installbundle
from vistrails.core.configuration import get_vistrails_configuration, \
    get_vistrails_persistent_configuration
from vistrails.core import debug

_previously_failed_pkgs = set()

class PyImportException(ImportError):
    pass

class PyImportBug(PyImportException):
    pass

def _vanilla_import(module_name):
    return __import__(module_name, globals(), locals(), [])

def py_import(module_name, dependency_dictionary, store_in_config=False):
    """Tries to import a python module, installing if necessary.

    If the import doesn't succeed, we guess which system we are running on and
    install the corresponding package from the dictionary. We then run the
    import again.
    If the installation fails, we won't try to install that same module again
    for the session.
    """

    if module_name in _previously_failed_pkgs:
        raise PyImportException("Import of Python module '%s' failed again, "
                                "not triggering installation" % module_name)
    if store_in_config:
        ignored_packages_list = getattr(get_vistrails_configuration(),
                                        'bundleDeclinedList',
                                        None)
        if ignored_packages_list:
            ignored_packages = set(ignored_packages_list.split(';'))
        else:
            ignored_packages = set()
        if module_name in ignored_packages:
            raise PyImportException("Import of Python module '%s' failed "
                                    "again, installation disabled by "
                                    "configuration" % module_name)
    debug.warning("Import of python module '%s' failed. "
                  "Will try to install bundle." % module_name)

    success = vistrails.core.bundles.installbundle.install(
            dependency_dictionary)

    if store_in_config:
        if bool(success):
            ignored_packages.discard(module_name)
        else:
            ignored_packages.add(module_name)
        setattr(get_vistrails_configuration(),
                'bundleDeclinedList',
                ';'.join(sorted(ignored_packages)))
        setattr(get_vistrails_persistent_configuration(),
                'bundleDeclinedList',
                ';'.join(sorted(ignored_packages)))

    if not success:
        _previously_failed_pkgs.add(module_name)
        raise PyImportException("Installation of Python module '%s' failed." %
                                module_name)
    try:
        result = _vanilla_import(module_name)
        return result
    except ImportError, e:
        _previously_failed_pkgs.add(module_name)
        raise PyImportBug("Installation of package '%s' succeeded, but import "
                          "still fails." % module_name)


## All rights reserved.
## Contact: example@nnthink.com
## This file is part of VisTrails.

"""module responsible for smartly importing python modules, checking
for necessary installs."""

from __future__ import division

import vistrails.core.bundles.installbundle
from vistrails.core.configuration import get_vistrails_configuration, \
    get_vistrails_persistent_configuration
from vistrails.core import debug

_previously_failed_pkgs = set()

class PyImportException(ImportError):
    pass

class PyImportBug(PyImportException):
    pass

def _vanilla_import(module_name):
    return __import__(module_name, globals(), locals(), [])

def py_import(module_name, dependency_dictionary, store_in_config=False):
    """Tries to import a python module, installing if necessary.

    If the import doesn't succeed, we guess which system we are running on and
    install the corresponding package from the dictionary. We then run the
    import again.
    If the installation fails, we won't try to install that same module again
    for the session.
    """
    try:
        result = _vanilla_import(module_name)
        return result
    except ImportError:
        if not getattr(get_vistrails_configuration(), 'installBundles'):
            raise

    if module_name in _previously_failed_pkgs:
        raise PyImportException("Import of Python module '%s' failed again, "
                                "not triggering installation" % module_name)
    if store_in_config:
        ignored_packages_list = getattr(get_vistrails_configuration(),
                                        'bundleDeclinedList',
                                        None)
        if ignored_packages_list:
            ignored_packages = set(ignored_packages_list.split(';'))
        else:
            ignored_packages = set()
        if module_name in ignored_packages:
            raise PyImportException("Import of Python module '%s' failed "
                                    "again, installation disabl

ed by "
                                    "configuration" % module_name)
    debug.warning("Import of python module '%s' failed. "
                  "Will try to install bundle." % module_name)

    success = vistrails.core.bundles.installbundle.install(
            dependency_dictionary)

    if store_in_config:
        if bool(success):
            ignored_packages.discard(module_name)
        else:
            ignored_packages.add(module_name)
        setattr(get_vistrails_configuration(),
                'bundleDeclinedList',
                ';'.join(sorted(ignored_packages)))
        setattr(get_vistrails_persistent_configuration(),
                'bundleDeclinedList',
                ';'.join(sorted(ignored_packages)))

    if not success:
        _previously_failed_pkgs.add(module_name)
        raise PyImportException("Installation of Python module '%s' failed." %
                                module_name)
    try:
        result = _vanilla_import(module_name)
        return result
    except ImportError, e:
        _previously_failed_pkgs.add(module_name)
        raise PyImportBug("Installation of package '%s' succeeded, but import "
                          "still fails." % module_name)


"""Tests for clif.testing.python.const_pointer_return."""

from absl.testing import absltest

from clif.testing.python import const_pointer_return

class ConstPointerReturnTest(absltest.TestCase):

myclass = const_pointer_return.MyClass(100, 1000)
    self.assertEqual(const_pointer_return.Pod, type(myclass.get_pod_ptr()))
    self.assertEqual(myclass.get_pod_ptr().get_x(), 100)
    self.assertEqual(int, type(myclass.get_int_ptr()))
    self.assertEqual(myclass.get_int_ptr(), 1000)
    myclass.get_pod_ptr().set_x(10000)
    # Modification to the return value, whose C++ types is "const Pod *",
    # is not reflected at C++ side because Clif makes a copy of the return value
    # and have Python own the copy.
    self.assertEqual(myclass.get_pod_ptr().get_x(), 100)

  def testNonConstPointerCopyableReturn(self):
    myclass = const_pointer_return.MyClass2(100)
    self.assertEqual(const_pointer_return.Pod, type(myclass.get_pod_ptr()))
    self.assertEqual(myclass.get_pod_ptr().get_x(), 200)
    myclass.get_pod_ptr().set_x(10000)
    # Modification to the return value, whose C++ types is "Pod *",
    # is reflected at C++ side because C++ share the same myclass object with
    # the Python side.
    self.assertEqual(myclass.get_pod_ptr().get_x(), 10000)

  def testNonConstPointerUncopyableReturn(self):
    myclass = const_pointer_return.MyClass2(100)
    self.assertEqual(const_pointer_return.NoCopy, type(myclass.get_no_copy()))
    self.assertEqual(myclass.get_no_copy().get_x(), 100)
    myclass.get_no_copy().set_x(10000)
    self.assertEqual(myclass.get_no_copy().get_x(), 10000)

if __name__ == '__main__':
  absltest.main()


myclass = const_pointer_return.MyClass2(100)
    self.assertEqual(const_pointer_return.NoCopy, type(myclass.get_no_copy()))
    self.assertEqual(myclass.get_no_copy().get_x(), 100)
    myclass.get_no_copy().set_x(10000)
    self.assertEqual(myclass.get_no_copy().get_x(), 10000)

"""Tests for clif.testing.python.const_pointer_return."""

from absl.testing import absltest

from clif.testing.python import const_pointer_return

class ConstPointerReturnTest(absltest.TestCase):

  def testConstPointerReturn(self):
    myclass = const_pointer_return.MyClass(100, 1000)
    self.assertEqual(const_pointer_return.Pod, type(myclass.get_pod_ptr()))
    self.assertEqual(myclass.get_pod_ptr().get_x(), 100)
    self.assertEqual(int, type(myclass.get_int_ptr()))
    self.assertEqual(myclass.get_int_ptr(), 1000)
    myclass.get_pod_ptr().set_x(10000)
    # Modification to the return value, whose C++ types is "const Pod *",
    # is not reflected at C++ side because Clif makes a copy of the return value
    # and have Python own the copy.
    self.assertEqual(myclass.get_pod_ptr().get_x(), 100)

  def testNonConstPointerCopyableReturn(self):
    myclass = const_pointer_return.MyClass2(100)
    self.assertEqual(const_pointer_return.Pod, type(myclass.get_pod_ptr()))
    self.assertEqual(myclass.get_pod_ptr().get_x(), 200)
    myclass.get_pod_ptr().set_x(10000)
    # Modification to the return value, whose C++ types is "Pod *",
    # is reflected at C++ side because C++ share the same myclass object with
    # the Python side.
    self.assertEqual(myclass.get_pod_ptr().get_x(), 10000)

  def testNonConstPointerUncopyableReturn(self):

if __name__ == '__main__':
  absltest.main()


myclass = const_pointer_return.MyClass2(100)
    self.assertEqual(const_pointer_return.Pod, type(myclass.get_pod_ptr()))
    self.assertEqual(myclass.get_pod_ptr().get_x(), 200)

"""Tests for clif.testing.python.const_pointer_return."""

from absl.testing import absltest

from clif.testing.python import const_pointer_return

class ConstPointerReturnTest(absltest.TestCase):

  def testConstPointerReturn(self):
    myclass = const_pointer_return.MyClass(100, 1000)
    self.assertEqual(const_pointer_return.Pod, type(myclass.get_pod_ptr()))
    self.assertEqual(myclass.get_pod_ptr().get_x(), 100)
    self.assertEqual(int, type(myclass.get_int_ptr()))
    self.assertEqual(myclass.get_int_ptr(), 1000)
    myclass.get_pod_ptr().set_x(10000)
    # Modification to the return value, whose C++ types is "const Pod *",
    # is not reflected at C++ side because Clif makes a copy of the return value
    # and have Python own the copy.
    self.assertEqual(myclass.get_pod_ptr().get_x(), 100)

  def testNonConstPointerCopyableReturn(self):

    myclass.get_pod_ptr().set_x(10000)
    # Modification to the return value, whose C++ types is "Pod *",
    # is reflected at C++ side because C++ share the same myclass object with
    # the Python side.
    self.assertEqual(myclass.get_pod_ptr().get_x(), 10000)

  def testNonConstPointerUncopyableReturn(self):
    myclass = const_pointer_return.MyClass2(100)
    self.assertEqual(const_pointer_return.NoCopy, type(myclass.get_no_copy()))
    self.assertEqual(myclass.get_no_copy().get_x(), 100)
    myclass.get_no_copy().set_x(10000)
    self.assertEqual(myclass.get_no_copy().get_x(), 10000)

if __name__ == '__main__':
  absltest.main()


myclass.get_pod_ptr().set_x(10000)
    # Modification to the return value, whose C++ types is "Pod *",

"""Tests for clif.testing.python.const_pointer_return."""

from absl.testing import absltest

from clif.testing.python import const_pointer_return

class ConstPointerReturnTest(absltest.TestCase):

  def testConstPointerReturn(self):
    myclass = const_pointer_return.MyClass(100, 1000)
    self.assertEqual(const_pointer_return.Pod, type(myclass.get_pod_ptr()))
    self.assertEqual(myclass.get_pod_ptr().get_x(), 100)
    self.assertEqual(int, type(myclass.get_int_ptr()))
    self.assertEqual(myclass.get_int_ptr(), 1000)
    myclass.get_pod_ptr().set_x(10000)
    # Modification to the return value, whose C++ types is "const Pod *",
    # is not reflected at C++ side because Clif makes a copy of the return value
    # and have Python own the copy.
    self.assertEqual(myclass.get_pod_ptr().get_x(), 100)

  def testNonConstPointerCopyableReturn(self):
    myclass = const_pointer_return.MyClass2(100)
    self.assertEqual(const_pointer_return.Pod, type(myclass.get_pod_ptr()))
    self.assertEqual(myclass.get_pod_ptr().get_x(), 200)

    # is reflected at C++ side because C++ share the same myclass object with
    # the Python side.
    self.assertEqual(myclass.get_pod_ptr().get_x(), 10000)

  def testNonConstPointerUncopyableReturn(self):
    myclass = const_pointer_return.MyClass2(100)
    self.assertEqual(const_pointer_return.NoCopy, type(myclass.get_no_copy()))
    self.assertEqual(myclass.get_no_copy().get_x(), 100)
    myclass.get_no_copy().set_x(10000)
    self.assertEqual(myclass.get_no_copy().get_x(), 10000)

if __name__ == '__main__':
  absltest.main()


# is reflected at C++ side because C++ share the same myclass object with
    # the Python side.
    self.assertEqual(myclass.get_pod_ptr().get_x(), 10000)

"""Tests for clif.testing.python.const_pointer_return."""

from absl.testing import absltest

from clif.testing.python import const_pointer_return

class ConstPointerReturnTest(absltest.TestCase):

  def testConstPointerReturn(self):
    myclass = const_pointer_return.MyClass(100, 1000)
    self.assertEqual(const_pointer_return.Pod, type(myclass.get_pod_ptr()))
    self.assertEqual(myclass.get_pod_ptr().get_x(), 100)
    self.assertEqual(int, type(myclass.get_int_ptr()))
    self.assertEqual(myclass.get_int_ptr(), 1000)
    myclass.get_pod_ptr().set_x(10000)
    # Modification to the return value, whose C++ types is "const Pod *",
    # is not reflected at C++ side because Clif makes a copy of the return value
    # and have Python own the copy.
    self.assertEqual(myclass.get_pod_ptr().get_x(), 100)

  def testNonConstPointerCopyableReturn(self):
    myclass = const_pointer_return.MyClass2(100)
    self.assertEqual(const_pointer_return.Pod, type(myclass.get_pod_ptr()))
    self.assertEqual(myclass.get_pod_ptr().get_x(), 200)
    myclass.get_pod_ptr().set_x(10000)
    # Modification to the return value, whose C++ types is "Pod *",

  def testNonConstPointerUncopyableReturn(self):
    myclass = const_pointer_return.MyClass2(100)
    self.assertEqual(const_pointer_return.NoCopy, type(myclass.get_no_copy()))
    self.assertEqual(myclass.get_no_copy().get_x(), 100)
    myclass.get_no_copy().set_x(10000)
    self.assertEqual(myclass.get_no_copy().get_x(), 10000)

if __name__ == '__main__':
  absltest.main()


"""Tests for clif.testing.python.const_pointer_return."""

from absl.testing import absltest

from clif.testing.python import const_pointer_return

class ConstPointerReturnTest(absltest.TestCase):

  def testConstPointerReturn(self):
    myclass = const_pointer_return.MyClass(100, 1000)
    self.assertEqual(const_pointer_return.Pod, type(myclass.get_pod_ptr()))
    self.assertEqual(myclass.get_pod_ptr().get_x(), 100)
    self.assertEqual(int, type(myclass.get_int_ptr()))
    self.assertEqual(myclass.get_int_ptr(), 1000)
    myclass.get_pod_ptr().set_x(10000)
    # Modification to the return value, whose C++ types is "const Pod *",
    # is not reflected at C++ side because Clif makes a copy of the return value
    # and have Python own the copy.
    self.assertEqual(myclass.get_pod_ptr().get_x(), 100)

  def testNonConstPointerCopyableReturn(self):
    myclass = const_pointer_return.MyClass2(100)
    self.assertEqual(const_pointer_return.Pod, type(myclass.get_pod_ptr()))
    self.assertEqual(myclass.get_pod_ptr().get_x(), 200)
    myclass.get_pod_ptr().set_x(10000)
    # Modification to the return value, whose C++ types is "Pod *",
    # is reflected at C++ side because C++ share the same myclass object with
    # the Python side.
    self.assertEqual(myclass.get_pod_ptr().get_x(), 10000)

  def testNonConstPointerUncopyableReturn(self):
    myclass = const_pointe

    self.assertEqual(const_pointer_return.NoCopy, type(myclass.get_no_copy()))
    self.assertEqual(myclass.get_no_copy().get_x(), 100)
    myclass.get_no_copy().set_x(10000)
    self.assertEqual(myclass.get_no_copy().get_x(), 10000)

if __name__ == '__main__':
  absltest.main()


if __name__ == '__main__':
  absltest.main()

"""Tests for clif.testing.python.const_pointer_return."""

from absl.testing import absltest

from clif.testing.python import const_pointer_return

class ConstPointerReturnTest(absltest.TestCase):

  def testConstPointerReturn(self):
    myclass = const_pointer_return.MyClass(100, 1000)
    self.assertEqual(const_pointer_return.Pod, type(myclass.get_pod_ptr()))
    self.assertEqual(myclass.get_pod_ptr().get_x(), 100)
    self.assertEqual(int, type(myclass.get_int_ptr()))
    self.assertEqual(myclass.get_int_ptr(), 1000)
    myclass.get_pod_ptr().set_x(10000)
    # Modification to the return value, whose C++ types is "const Pod *",
    # is not reflected at C++ side because Clif makes a copy of the return value
    # and have Python own the copy.
    self.assertEqual(myclass.get_pod_ptr().get_x(), 100)

  def testNonConstPointerCopyableReturn(self):
    myclass = const_pointer_return.MyClass2(100)
    self.assertEqual(const_pointer_return.Pod, type(myclass.get_pod_ptr()))
    self.assertEqual(myclass.get_pod_ptr().get_x(), 200)
    myclass.get_pod_ptr().set_x(10000)
    # Modification to the return value, whose C++ types is "Pod *",
    # is reflected at C++ side because C++ share the same myclass object with
    # the Python side.
    self.assertEqual(myclass.get_pod_ptr().get_x(), 10000)

  def testNonConstPointerUncopyableReturn(self):
    myclass = const_pointer_return.MyClass2(100)
    self.assertEqual(const_pointer_return.NoCopy, type(myclass.get_no_copy()))
    self.assertEqual(myclass.get_no_copy().get_x(), 100)
    myclass.get_no_copy().set_x(10000)
    self.assertEqual(myclass.get_no_copy().get_x(), 10000)