   ipToLegacy: (ip) ->
     switch ip.type
       when 'openBracket'
-        @braceCount++
-        if @braceCount is 1
+        if @brackets.length is 1
           return legacy =
             event: 'connect'
             payload: @

    ip = @legacyToIp event, payload

    # Handle state transitions
    if ip.type is 'data' and not @connected and autoConnect
      # Connect before sending data
      @handleSocketEvent 'connect', null

    if ip.type is 'openBracket' and ip.data
      if not @connected and autoConnect
        # Connect before sending bracket
        @handleSocketEvent 'connect', null
      # Append bracket to socket group list
      @groups.push ip.data

    if ip.type is 'openBracket' and ip.data is null
      # If we're already connected, no need to connect again
      return if @connected
      @connected = true

    if ip.type is 'closeBracket'
      if @groups.length
        # Add group name to bracket
        ip.data = @groups.pop()
      else
        # If we were already disconnected, no need to disconnect again
        return unless @connected
        # Last bracket was closed, we're disconnected
        @connected = false
        ip.data = null

    # Emit the IP Object
    @emitEvent 'ip', ip

    # Emit the legacy event
    legacyEvent = @ipToLegacy ip
    @emitEvent 'connect' if ip.type is 'data' and @braceCount is 0 and not @connected
    @emitEvent legacyEvent.event, legacyEvent.payload
    @emitEvent 'disconnect' if ip.type is 'data' and @braceCount is 0 and @connected

exports.InternalSocket = InternalSocket


        metadata: @metadata

  constructor: (@metadata = {}) ->
    @brackets = []
    @dataDelegate = null
    @debug = false
    @emitEvent = @regularEmitEvent

  # ## Socket connections
  #
