'Steps through CSS rules and applies each to all the proper elements
as @style attributes prepending any current @style attributes.'

def _apply_styles(self):

    rules = self.stylesheet.cssRules.rulesOfType(1)
    elem_prop_map = {}
    elem_style_map = {}
    for rule in rules:
        selectors = rule.selectorText.split(',')
        elements = []
        for selector in selectors:
            elements += select(self.soup, selector)
        for elem in elements:
            if (elem not in elem_prop_map):
                elem_prop_map[elem] = []
            elem_prop_map[elem].append({'specificity': self._get_rule_specificity(rule), 'props': rule.style.getProperties()})
    for (elem, props) in elem_prop_map.items():
        if (elem not in elem_style_map):
            elem_style_map[elem] = cssutils.css.CSSStyleDeclaration()
        props = sorted(props, key=(lambda p: p['specificity']))
        for prop_list in map((lambda obj: obj['props']), props):
            for prop in prop_list:
                elem_style_map[elem][prop.name] = prop.value
    for (elem, style_declaration) in elem_style_map.items():
        if elem.has_key('style'):
            elem['style'] = (u'%s;    %s' % (style_declaration.cssText.replace('\n', '    '), elem['style']))
        else:
            elem['style'] = style_declaration.cssText.replace('\n', '    ')
