def garbage(stream):
    """Skip over any garbage in the stream, properly handling escaped (!)
    characters, and counting all characters.

    :stream: stream of characters
    :returns: number of garbage characters
    """
    count = 0

    for c in stream:
        if c == '!':
            # escape, skip the next char
            next(stream)
        elif c == '>':
            return count
        else:
            count += 1