+ duplicate = 0;
+ best_buf = NULL;
+ best_size = -1;
+ best_ref = -1;
+ skip_lvl = 0;
+ skip_reason = NULL;
+ for (r = 0; max_depth && r < nb_refs; r++) {
+ void *delta_buf, *comp_buf;
+ unsigned long delta_size, comp_size;
+ unsigned int l;
+
+ duplicate = !memcmp(trg.sha1, ref[r].sha1, 20);
+ if (duplicate) {
+ skip_reason = "already seen";
+ break;
+ }
+ if (ref[r].depth >= max_depth) {
+ if (skip_lvl < 1) {
+ skip_reason = "exceeding max link depth";
+ skip_lvl = 1;
+ }
+ continue;
+ }
+ for (l = 0; l < ref[r].depth; l++)
+ if (!memcmp(trg.sha1, ref[r].links + l*20, 20))
+ break;
+ if (l != ref[r].depth) {
+ if (skip_lvl < 2) {
+ skip_reason = "would create a loop";
+ skip_lvl = 2;
+ }
+ continue;
+ }
+ if (trg.depth < max_depth && r == orig_ref) {
+ if (skip_lvl < 3) {
+ skip_reason = "delta already in place";
+ skip_lvl = 3;
+ }
+ continue;
+ }
+ delta_buf = diff_delta(ref[r].buf, ref[r].size,
+ trg.buf, trg.size, &delta_size);
+ if (!delta_buf)
+ die("out of memory");
+ if (trg.depth < max_depth &&
+ delta_size+20 >= orig_size) {
+ /* no need to even try to compress if original
+ object is smaller than this delta */
+ free(delta_buf);
+ if (skip_lvl < 4) {
+ skip_reason = "no size reduction";
+ skip_lvl = 4;
+ }
+ continue;
+ }
+ comp_buf = create_delta_object(delta_buf, delta_size,
+ ref[r].sha1, &comp_size);
+ if (!comp_buf)
+ die("out of memory");
+ free(delta_buf);
+ if (trg.depth < max_depth &&
+ comp_size >= orig_compsize) {
+ free(comp_buf);
+ if (skip_lvl < 5) {
+ skip_reason = "no size reduction";
+ skip_lvl = 5;
+ }
+ continue;
+ }
+ if ((comp_size < best_size) ||
+ (comp_size == best_size &&
+ ref[r].depth < ref[best_ref].depth)) {
+ free(best_buf);
+ best_buf = comp_buf;
+ best_size = comp_size;
+ best_ref = r;
+ }