 $(document).ready ->
 
+  nodes = JSON.parse localStorage.getItem 'nodes' or '[]'
+  links = JSON.parse localStorage.getItem 'links' or '[]'
   nodes = []
   links = []
+
   sx = null
   sy = null
   cx = 0
   cy = 0
 
+  MAX = 200
+  PUSH = 5
+
+  getRandomNumber = (a) ->
+    r = Math.random() * a
+    if r < 10 and r > 0
+      r += 20
+    if r > -10 and r < 0
+      r -= 20
+    r
+
   class Node
-    @ids = 0
+    @ids = nodes.length
 
     constructor: ->
       @id = Node.ids++
       @x = 0
       @y = 0
       @parent = null
-      @text = ''
       @children = []
+      @link = null
+      @text = 'asdfasdf'
       nodes.push @
 
     setParent: (parent) ->
-      if @parent
-        @parent.remove @
-      @parent = parent
-      parent.children.push @
-      @x = parent.x - Math.random() * 20 + 10
-      @y = parent.y - Math.random() * 20 + 10
-      links.push new Link parent, @
+      @parent = parent.id
+      sum = V 0, 0
+      inner = V parent.x, parent.y
+      for id, j in parent.children
+        n2 = nodes[id]
+        outer = V n2.x, n2.y
+        sum = sum.add inner.sub outer
+      dir = sum.unit()
+      if (not isNaN dir.x) and (not isNaN dir.y) and parent.children.length > 2
+        dir = dir.mult 50
+        @x = dir.x + parent.x
+        @y = dir.y + parent.y
+      else
+        @x = parent.x + getRandomNumber 50
+        @y = parent.y + getRandomNumber 50
+
+      parent.children.push @id
+      links.push new Link parent.id, @id
       @
 
-    remove: (child) ->
-      @children.splice @children.indexOf child, 1
-      child
-
   class Link
-    @ids = 0
-
+    @ids = links.length
     constructor: (source, target) ->
       @id = Link.ids++
       @source = source

        mag = dif.mag()
        norm = 1.0 - Math.min(mag, MAX) / MAX
        dir = dif.unit()
        sum = sum.add dir.mult norm * PUSH
      inner = inner.add sum
      n1.x = inner.x
      n1.y = inner.y

  render = ->
    svg.selectAll('.link')
      .attr('x1', (d) -> d.source.x + cx)
      .attr('y1', (d) -> d.source.y + cy)
      .attr('x2', (d) -> d.target.x + cx)
      .attr('y2', (d) -> d.target.y + cy)

    svg.selectAll('.node')
      .attr('cx', (d) -> d.x + cx)
      .attr('cy', (d) -> d.y + cy)
      .attr('r', 40)

  setInterval ->
    update()

      cx += dx
      cy += dy

  if nodes.length is 0
    head = new Node()
    head.x = w / 2
    head.y = h / 2

  circles = null
  rects = null
  texts = null

  refresh = ->
    svg.selectAll('.link')
