def escape(x, lb=False):
    """
    Ensure a string does not contain HTML-reserved characters (including
    double quotes)
    Optionally also insert a linebreak if the string is too long
    """
    if lb:
        l = len(x)
        if l >= 10:
            l >>= 1
            s1 = x.find(' ', l)
            s2 = x.rfind(' ', 0, l)
            if s2 > 0:
                s = s2 if s1 < 0 or l - s1 > s2 - l else s1
                x = x[:s] + '\\n' + x[s + 1:]
            elif s1 > 0:
                x = x[:s1] + '\\n' + x[s1 + 1:]
    return x.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;'
        ).replace('"', '&quot;')
