def unescape_xml_html(text):
    text = text.replace('<br>', '\n') # this one first
    text = text.replace('&nbsp;', ' ')
    text = text.replace('&quot;', '"')
    text = text.replace('&lt;', '<')
    text = text.replace('&gt;', '>')
    text = text.replace('&amp;', '&') # this one last
    return text
    

def escape_xml_html(text):
    text = text.replace('&', '&amp;') # this one first
    text = text.replace('<', '&lt;')
    text = text.replace('>', '&gt;')
    # don't replace quotes
    text = text.replace('\n', '<br>') # this one last
    prefix = ''
    while text.startswith(' ') or text.startswith('\t'):
        c = text[0]
        text = text[1:]
        if c == ' ':
            prefix += '&nbsp;'
        if c == '\t':
            prefix += '&nbsp; &nbsp; '
    return prefix + text


def unescape_csv(text):
    if text.startswith('"'):
        text = text[1:]
        if text.endswith('"'):
            text = text[:-1]
        text = text.replace('""', '"')
    return text


def escape_csv(text):
    if ',' in text or '"' in text:
        text = text.replace('"', '""')
        text = '"' + text + '"'
    return text
