'Parse the given data from a terminal server, dispatching to event
handlers defined by C{self.terminal}.'

def dataReceived(self, data):

    toWrite = []
    for b in iterbytes(data):
        if (self.state == 'data'):
            if (b == '\x1b'):
                if toWrite:
                    self.terminal.write(''.join(toWrite))
                    del toWrite[:]
                self.state = 'escaped'
            elif (b == '\x14'):
                if toWrite:
                    self.terminal.write(''.join(toWrite))
                    del toWrite[:]
                self.terminal.shiftOut()
            elif (b == '\x15'):
                if toWrite:
                    self.terminal.write(''.join(toWrite))
                    del toWrite[:]
                self.terminal.shiftIn()
            elif (b == '\x08'):
                if toWrite:
                    self.terminal.write(''.join(toWrite))
                    del toWrite[:]
                self.terminal.cursorBackward()
            else:
                toWrite.append(b)
        elif (self.state == 'escaped'):
            fName = self._shorts.get(b)
            if (fName is not None):
                self.state = 'data'
                getattr(self.terminal, fName.decode('ascii'))()
            else:
                state = self._longs.get(b)
                if (state is not None):
                    self.state = state
                else:
                    self.terminal.unhandledControlSequence(('\x1b' + b))
                    self.state = 'data'
        elif (self.state == 'bracket-escape'):
            if (self._escBuf is None):
                self._escBuf = []
            if (b.isalpha() or (b == '~')):
                self._handleControlSequence(''.join(self._escBuf), b)
                del self._escBuf
                self.state = 'data'
            else:
                self._escBuf.append(b)
        elif (self.state == 'select-g0'):
            self.terminal.selectCharacterSet(self._charsets.get(b, b), G0)
            self.state = 'data'
        elif (self.state == 'select-g1'):
            self.terminal.selectCharacterSet(self._charsets.get(b, b), G1)
            self.state = 'data'
        elif (self.state == 'select-height-width'):
            self._handleHeightWidth(b)
            self.state = 'data'
        else:
            raise ValueError('Illegal    state')
    if toWrite:
        self.terminal.write(''.join(toWrite))
