'Perform various markup transforms to get the output to render correctly
in the quirky ADE.'

def workaround_ade_quirks(self):

    from calibre.ebooks.oeb.base import XPath, XHTML, barename, urlunquote
    stylesheet = self.oeb.manifest.main_stylesheet
    frag_pat = re.compile('[-A-Za-z0-9_:.]+$')
    for node in self.oeb.toc.iter():
        href = getattr(node, 'href', None)
        if hasattr(href, 'partition'):
            (base, _, frag) = href.partition('#')
            frag = urlunquote(frag)
            if (frag and (frag_pat.match(frag) is None)):
                self.log.warn(('Removing    fragment    identifier    %r    from    TOC    as    Adobe    Digital    Editions    cannot    handle    it' % frag))
                node.href = base
    for x in self.oeb.spine:
        root = x.data
        body = XPath('//h:body')(root)
        if body:
            body = body[0]
        if hasattr(body, 'xpath'):
            bad = []
            for x in XPath('//h:img')(body):
                src = x.get('src', '').strip()
                if ((src in ('', '#')) or src.startswith('http:')):
                    bad.append(x)
            for img in bad:
                img.getparent().remove(img)
            for x in XPath('//h:a[@name]')(body):
                if (not x.get('id', False)):
                    x.set('id', x.get('name'))
                x.attrib.pop('name')
            for br in XPath('./h:br')(body):
                if (br.getparent() is None):
                    continue
                try:
                    prior = br.itersiblings(preceding=True).next()
                    priortag = barename(prior.tag)
                    priortext = prior.tail
                except:
                    priortag = 'body'
                    priortext = body.text
                if priortext:
                    priortext = priortext.strip()
                br.tag = XHTML('p')
                br.text = u'\xa0'
                style = br.get('style', '').split(';')
                style = filter(None, map((lambda x: x.strip()), style))
                style.append('margin:0pt;    border:0pt')
                if ((not priortext) and (priortag in block_level_tags)):
                    style.append('height:1em')
                else:
                    style.append('height:0pt')
                br.set('style', ';    '.join(style))
        for tag in XPath('//h:embed')(root):
            tag.getparent().remove(tag)
        for tag in XPath('//h:object')(root):
            if (tag.get('type', '').lower().strip() in {'image/svg+xml', 'application/svg+xml'}):
                continue
            tag.getparent().remove(tag)
        for tag in XPath('//h:title|//h:style')(root):
            if (not tag.text):
                tag.getparent().remove(tag)
        for tag in XPath('//h:script')(root):
            if ((not tag.text) and (not tag.get('src', False)) and (tag.get('type', None) != 'text/x-mathjax-config')):
                tag.getparent().remove(tag)
        for tag in XPath('//h:body/descendant::h:script')(root):
            tag.getparent().remove(tag)
        formchildren = XPath('./h:input|./h:button|./h:textarea|./h:label|./h:fieldset|./h:legend')
        for tag in XPath('//h:form')(root):
            if formchildren(tag):
                tag.getparent().remove(tag)
            else:
                tag.tag = XHTML('div')
        for tag in XPath('//h:center')(root):
            tag.tag = XHTML('div')
            tag.set('style', 'text-align:center')
        for tag in XPath('//h:img[@src]')(root):
            tag.set('src', tag.get('src', '').replace('&', ''))
        in_table = XPath('ancestor::h:table')
        for tag in XPath('//h:td|//h:tr|//h:th')(root):
            if (not in_table(tag)):
                tag.tag = XHTML('div')
        special_chars = re.compile(u'[\u200b\xad]')
        for elem in root.iterdescendants('*'):
            if elem.text:
                elem.text = special_chars.sub('', elem.text)
                elem.text = elem.text.replace(u'\u2011', '-')
            if elem.tail:
                elem.tail = special_chars.sub('', elem.tail)
                elem.tail = elem.tail.replace(u'\u2011', '-')
        if (stylesheet is not None):
            from cssutils.css import CSSRule
            for lb in XPath('//h:ul[@class]|//h:ol[@class]')(root):
                sel = ('.' + lb.get('class'))
                for rule in stylesheet.data.cssRules.rulesOfType(CSSRule.STYLE_RULE):
                    if (sel == rule.selectorList.selectorText):
                        rule.style.removeProperty('margin-left')
                        rule.style.removeProperty('padding-left')
            for rule in stylesheet.data.cssRules.rulesOfType(CSSRule.STYLE_RULE):
                style = rule.style
                ws = style.getPropertyValue('white-space')
                if (ws == 'pre'):
                    style.setProperty('white-space', 'pre-wrap')
