'use strict';

var $ = require('./helpers');

var find = require('./find-reference');

var deepExtend = require('deep-extend');

function copy(obj, refs, parent, resolve) {
  var target =  Array.isArray(obj) ? [] : {};

  if (typeof obj.$ref === 'string') {
    var base = $.getDocumentURI(obj.$ref);
    var local = obj.$ref.indexOf('#/') > -1;

    if (local || (resolve && base !== parent)) {
      var fixed = find(obj.$ref, refs);

      deepExtend(obj, fixed);

      delete obj.$ref;
      delete obj.id;
    }
  }

  for (var prop in obj) {
    if (typeof obj[prop] === 'object' && obj[prop] !== null && !$.isKeyword(prop)) {
      target[prop] = copy(obj[prop], refs, parent, resolve);
    } else {
      target[prop] = obj[prop];
    }
  }

  return target;
}

module.exports = function(obj, refs, resolve) {
  var fixedId = $.resolveURL(obj.$schema, obj.id),
      parent = $.getDocumentURI(fixedId);

  return copy(obj, refs, parent, resolve);
};

@@ -132,24 +132,27 @@
 nction copy(
+_, 
 obj, refs, p
@@ -165,24 +165,24 @@
  resolve) %7B%0A
-
   var target
@@ -250,24 +250,47 @@
 'string') %7B%0A
+    var id = obj.$ref;%0A
     var base
@@ -309,24 +309,18 @@
 mentURI(
-obj.$ref
+id
 );%0A    v
@@ -330,24 +330,18 @@
 local = 
-obj.$ref
+id
 .indexOf
@@ -426,24 +426,18 @@
  = find(
-obj.$ref
+id
 , refs);
@@ -514,24 +514,82 @@
 bj.id;%0A    %7D
+%0A%0A    if (_%5Bid%5D) %7B%0A      return obj;%0A    %7D%0A%0A    _%5Bid%5D = 1;
 %0A  %7D%0A%0A  for 
@@ -719,16 +719,19 @@
  = copy(
+_, 
 obj%5Bprop
@@ -975,16 +975,16 @@
 edId);%0A%0A
-
   return
@@ -989,16 +989,20 @@
 rn copy(
+%7B%7D, 
 obj, ref

stop overflows by skipping circular refs