       @robot.logger.info "Successfully connected #{@options.name} with Fleep"
       @emit 'authenticated', @
 
+  # Destroy Fleep session
   logout: ->
     @post 'account/logout', {}, (err, resp) ->
+      if err isnt null
+        return @robot.logger.error 'Unable to destroy Fleep session'
       @robot.logger.debug 'User session with Fleep closed.'
 
+  # The result of a long poll request to account/poll is passed here
+  # Handle all of its 'stream' items (conversations, contacts...) ie
+  # events that happened during the poll request
   handleStreamEvents: (resp) =>
+
+    # The poll response gives us our next "last seen" event horizon
+    if resp.event_horizon?
+      @setLastEventHorizon resp.event_horizon
+      @robot.logger.debug 'Updating last seen event horizon to '+
+        resp.event_horizon
+
+    # Handle stream items individually
     if resp.stream? and resp.stream.length
       @handleStreamEvent event for event in resp.stream
     else
       @robot.logger.debug 'Response stream length 0, nothing to parse.'
-    if resp.event_horizon?
-      @setLastEventHorizon resp.event_horizon
-      @robot.logger.debug 'Updating last seen event horizon to '+
-      resp.event_horizon
     @robot.logger.debug 'Finished handling long poll response'
 
   # Save the conversation into the internal "known conversations" list

    textMessage = new TextMessage author, text
    @emit 'gotMessage', textMessage

  poll: =>
    @robot.logger.debug 'Starting long poll request'
    data =
      wait: true,
      event_horizon: @getLastEventHorizon()
      poll_flags: ['skip_hidden']
    @post 'account/poll', data, (err, resp) =>
      @emit 'pollcomplete', resp

  send: (envelope, message) =>
    @robot.logger.debug 'Sending new message to conversation ' + envelope.room

    @post "message/send/#{envelope.room}", {message: message}, (err, resp) ->
      @robot.logger.debug 'Callback for send called'


  reply: (envelope, message) ->
    @robot.logger.debug 'Sending private message to user ' + envelope.user.id
    @post 'conversation/create', {
      topic: null, # Topic is currently empty, the default is the bot's name
      emails:envelope.user.email,
      message: message
    }, (err, resp) ->
      @robot.logger.debug 'Callback for reply called'

  # Get a hash of known conversations
  getKnownConversations: =>
    @robot.brain.get('conversations') ? {}

  markRead: (conversation_id, message_nr) =>

    # Save the last message number into an internal tracker

        @robot.logger.emergency 'Unable to login to Fleep: ' + err.error_message
        process.exit 1

      # Save Fleep profile info
      @profile.account_id = resp.account_id
      @profile.display_name = resp.display_name

