         return next err if err?
 
         # Get the answering target
-        for t in doc.targets
-            if t.recipientUrl is answer.recipientUrl
-                target = t
+        i = 0
+        while t = doc.targets[i++]
+            if t.recipientUrl is answer.recipientUrl then target = t
 
         unless target?
             err = new Error "#{answer.recipientUrl} not found for this sharing"

        db.merge doc._id, doc, (err, result) ->
            return next err if err?

            # Retrieve all the docIDs
            docIDs = (rule.id for rule in doc.rules)

            # Params structure for the replication
            replicate =
                target    : target
                id        : doc._id
                docIDs    : docIDs
                continuous: doc.continuous

            req.replicate = replicate
            next()


# Replicate documents to the target url

# Params must contain:
#   id         -> the Sharing id, used as a login
#   target     -> contains the url and the token of the target
#   docIDs     -> the docIDs to replicate
#   continuous -> [optionnal] if the sharing is synchronous or not
module.exports.replicate = (req, res, next) ->
    replicate = req.replicate

    # Replicate only if the target has accepted, i.e. gave a token
    if replicate.target.token?
        Sharing.replicateDocs replicate, (err, repID) ->
            if err?
                next err

                err.status = 500
                next err
            else
                log.info "Data sent to #{target.recipientUrl}"

                # Update the target with the repID if the sharing is continuous
                if replicate.continuous

                    i = doc.targets.indexOf target
                    doc.targets[i].repID = repID

                    db.merge doc._id, doc, (err, result) ->
                        return next err if err?

                        res.status(200).send success: true
                else
                    res.status(200).send success: true

