'Commit all changes caused by the split. Calculates an *anchor_map* for
all anchors in the original tree. Internal links are re-directed. The
original file is deleted and the split files are saved.'

def commit(self):

    if (not self.was_split):
        return
    self.anchor_map = collections.defaultdict((lambda : (self.base % 0)))
    self.files = []
    for (i, tree) in enumerate(self.trees):
        root = tree.getroot()
        self.files.append((self.base % i))
        for elem in root.xpath('//*[@id    or    @name]'):
            for anchor in (elem.get('id', ''), elem.get('name', '')):
                if ((anchor != '') and (anchor not in self.anchor_map)):
                    self.anchor_map[anchor] = self.files[(-1)]
        for elem in root.xpath(('//*[@%s]' % SPLIT_POINT_ATTR)):
            elem.attrib.pop(SPLIT_POINT_ATTR, '0')
    spine_pos = self.item.spine_position
    for (current, tree) in zip(*map(reversed, (self.files, self.trees))):
        for a in tree.getroot().xpath('//h:a[@href]', namespaces=NAMESPACES):
            href = a.get('href').strip()
            if href.startswith('#'):
                anchor = href[1:]
                file = self.anchor_map[anchor]
                file = self.item.relhref(file)
                if (file != current):
                    a.set('href', (file + href))
        new_id = self.oeb.manifest.generate(id=self.item.id)[0]
        new_item = self.oeb.manifest.add(new_id, current, self.item.media_type, data=tree.getroot())
        self.oeb.spine.insert(spine_pos, new_item, self.item.linear)
    if self.oeb.guide:
        for ref in self.oeb.guide.values():
            (href, frag) = urldefrag(ref.href)
            if (href == self.item.href):
                nhref = self.anchor_map[(frag if frag else None)]
                if frag:
                    nhref = '#'.join((nhref, frag))
                ref.href = nhref
    def fix_toc_entry(toc):
        if toc.href:
            (href, frag) = urldefrag(toc.href)
            if (href == self.item.href):
                nhref = self.anchor_map[(frag if frag else None)]
                if frag:
                    nhref = '#'.join((nhref, frag))
                toc.href = nhref
        for x in toc:
            fix_toc_entry(x)
    if self.oeb.toc:
        fix_toc_entry(self.oeb.toc)
    if self.oeb.pages:
        for page in self.oeb.pages:
            (href, frag) = urldefrag(page.href)
            if (href == self.item.href):
                nhref = self.anchor_map[(frag if frag else None)]
                if frag:
                    nhref = '#'.join((nhref, frag))
                page.href = nhref
    self.oeb.manifest.remove(self.item)
