u'''write text at current cursor position and interpret color escapes.

    return the number of characters written.

def write_color_old( text, attr=None):
    u'''write text at current cursor position and interpret color escapes.

    return the number of characters written.
    '''
    res = []
    chunks = terminal_escape.split(text)
    n = 0 # count the characters we actually write, omitting the escapes
    if attr is None:#use attribute from initial console
        attr = 15
    for chunk in chunks:
        m = escape_parts.match(chunk)
        if m:
            for part in m.group(1).split(u";"):
                if part == u"0": # No text attribute
                    attr = 0
                elif part == u"7": # switch on reverse
                    attr |= 0x4000
                if part == u"1": # switch on bold (i.e. intensify foreground color)
                    attr |= 0x08
                elif len(part) == 2 and u"30" <= part <= u"37": # set foreground color
                    part = int(part)-30
                    # we have to mirror bits
                    attr = (attr & ~0x07) | ((part & 0x1) << 2) | (part & 0x2) | ((part & 0x4) >> 2)
                elif len(part) == 2 and u"40" <= part <= u"47": # set background color
                    part = int(part) - 40
                    # we have to mirror bits
                    attr = (attr & ~0x70) | ((part & 0x1) << 6) | ((part & 0x2) << 4) | ((part & 0x4) << 2)
                # ignore blink, underline and anything we don't understand
            continue
        n += len(chunk)
        if chunk:
            res.append((u"0x%x"%attr, chunk))
    return res