           # Node.js seems to reuse the broken socket, so we add a small
           # delay.
           #
-          # TODO Magic number!!!
+          # FIXME Magic number!!!
           #
           # I would like to be able to use a shorter delay but for
           # some reason, when we connect to XAPI at a given moment,
           # the connection hangs.
-          $sleep 500
+          $wait $sleep 5e3
           helper()
 
         # XAPI is sometimes reinitialized and sessions are lost.
         # We try log in again if necessary.
         when 'SESSION_INVALID'
+          @logIn()
+          helper()
+
+        # Except during the login process, catch this error and try to
+        # log in again.
+        when 'SESSION_AUTHENTICATION_FAILED'
+          throw error unless @sessionId
+
           @logIn()
           helper()
 

          throw error

  logIn: ->
    @sessionId = @call 'session.login_with_password', @username, @password

#=====================================================================

  call: (method, args...) ->
    @connect() unless @xmlrpc

    tries = @tries
    do helper = =>
      try
        result = $wait (callback) =>
          actualArgs = if @sessionId
            [@sessionId, args...]
          else
            args

          @xmlrpc.methodCall method, actualArgs, callback

        # Returns the plain result if it does not have a valid XAPI format.
        return result unless result.Status?
