anchor.diff:           websocket_init/3, websocket_handle/3,
            websocket_info/3, websocket_terminate/3]).
   
  +-record(http_state, {action, config, sid, heartbeat_tref, messages}).
  +
   init({tcp, http}, Req, [Config]) ->
       {PathInfo, _} = cowboy_req:path_info(Req),
       {Method, _} = cowboy_req:method(Req),
       case PathInfo of
           [] ->
  -            {ok, Req, {create_session, Config}};
  +            {ok, Req, #http_state{action = create_session, config = Config}};
           [<<"xhr-polling">>, Sid] ->
               case {socketio_session:find(Sid), Method} of
                   {{ok, Pid}, <<"GET">>} ->
                       case socketio_session:pull_no_wait(Pid, self()) of
                           session_in_use ->
  -                            {ok, Req, {session_in_use, Config}};
  +                            {ok, Req, #http_state{action = session_in_use, config = Config, sid = Sid}};
                           [] ->
  -                            erlang:start_timer(Config#config.heartbeat, self(), {?MODULE, Pid}),
  -                            {loop, Req, {heartbeat, Config}, infinity};
  +                            TRef = erlang:start_timer(Config#config.heartbeat, self(), {?MODULE, Pid}),
  +                            {loop, Req, #http_state{action = heartbeat, config = Config, sid = Sid, heartbeat_tref = TRef}, infinity};
                           Messages ->
  -                            {ok, Req, {data, Messages, Config}}
  +                            {ok, Req, #http_state{action = data, messages = Messages, config = Config, sid = Sid}}
                       end;
                   {{ok, Pid}, <<"POST">>} ->
                       Protocol = Config#config.protocol,
  
positive.code:     Packet = Protocol:encode(Messages),
      cowboy_req:reply(200, text_headers(), Packet, Req).
  
  safe_poll(Req, Config = #config{protocol = Protocol}, Pid, WaitIfEmpty) ->
      try
          Messages = socketio_session:poll(Pid),
          case {WaitIfEmpty, Messages} of
              {true, []} ->
                  {loop, Req, Config, infinity};
              _ ->
                  {ok, Req1} = reply_messages(Req, Messages, Config),
                  {ok, Req1, Config}
          end
      catch
          exit:{noproc, _} ->
              {ok, RD} = cowboy_req:reply(200, text_headers(), Protocol:encode(disconnect), Req),
              {ok, RD, Config}
      end.
  
  %% Websocket handlers
  
negative.code:     end.
  
  %% Http handlers
  handle(Req, HttpState = #http_state{action = create_session, config = #config{heartbeat_timeout = HeartbeatTimeout,
                                                                                session_timeout = SessionTimeout,
                                                                                callback = Callback}}) ->
      Sid = uuids:new(),
  
      HeartbeatTimeoutBin = list_to_binary(integer_to_list(HeartbeatTimeout div 1000)),
  