'Given a style find the embedded font that matches it. Returns None if
no match is found (can happen if no family matches).'

def used_font(self, style):

    ff = style.get(u'font-family', [])
    lnames = {unicode(x).lower() for x in ff}
    matching_set = []
    for ef in self.embedded_fonts:
        flnames = {x.lower() for x in ef.get(u'font-family', [])}
        if (not lnames.intersection(flnames)):
            continue
        matching_set.append(ef)
    if (not matching_set):
        return None
    widths = {x: i for (i, x) in enumerate((u'ultra-condensed', u'extra-condensed', u'condensed', u'semi-condensed', u'normal', u'semi-expanded', u'expanded', u'extra-expanded', u'ultra-expanded'))}
    width = widths[style.get(u'font-stretch', u'normal')]
    for f in matching_set:
        f[u'width'] = widths[style.get(u'font-stretch', u'normal')]
    min_dist = min((abs((width - f[u'width'])) for f in matching_set))
    nearest = [f for f in matching_set if (abs((width - f[u'width'])) == min_dist)]
    if (width <= 4):
        lmatches = [f for f in nearest if (f[u'width'] <= width)]
    else:
        lmatches = [f for f in nearest if (f[u'width'] >= width)]
    matching_set = (lmatches or nearest)
    fs = style.get(u'font-style', u'normal')
    order = {u'oblique': [u'oblique', u'italic', u'normal'], u'normal': [u'normal', u'oblique', u'italic']}.get(fs, [u'italic', u'oblique', u'normal'])
    for q in order:
        matches = [f for f in matching_set if (f.get(u'font-style', u'normal') == q)]
        if matches:
            matching_set = matches
            break
    fw = int(style.get(u'font-weight', u'400'))
    if (fw == 400):
        q = [400, 500, 300, 200, 100, 600, 700, 800, 900]
    elif (fw == 500):
        q = [500, 400, 300, 200, 100, 600, 700, 800, 900]
    elif (fw < 400):
        q = (([fw] + list(xrange((fw - 100), (-100), (-100)))) + list(xrange((fw + 100), 100, 1000)))
    else:
        q = (([fw] + list(xrange((fw + 100), 100, 1000))) + list(xrange((fw - 100), (-100), (-100))))
    for wt in q:
        matches = [f for f in matching_set if (f[u'weight'] == wt)]
        if matches:
            return matches[0]
