   offset: (x, y) =>
     if x >= 0 and x < @width and y >= 0 and y < @height
       x + y * @width
+
+  fromOffset: (offset) =>
+    [offset % @width, Math.floor(offset / @width)]
 
   appendSVGElements: =>
     # size is 2px bigger to leave room for outside lines on grid

      .attr('y1', (d, i) => @lineSegment(d)[1])
      .attr('x2', (d, i) => @lineSegment(d)[2])
      .attr('y2', (d, i) => @lineSegment(d)[3])
      .attr('class', kind)
      .attr('marker-end', "url(#arrowhead-#{kind})")

    paths.exit().remove()

  drawSquares: (points, kind) =>

    squares = @grid.mapSelection.selectAll("rect.#{kind}")
      .data(points, (d, i) -> [d[0], d[1]])

    squares.enter()
      .append('rect')
      .attr('x', (d, i) => @grid.size * d[0])
      .attr('y', (d, i) => @grid.size * d[1])
      .attr('width', @grid.size)
      .attr('height', @grid.size)
      .attr('class',kind)

    squares.exit().remove

  # path goes from center of node to a little before the center of the next
  # returns [ x1, y1, x2, y2 ]
  lineSegment: (d) =>
    [ [x1, y1], [x2, y2] ] = d
    dx = x2 - x1
    dy = y2 - y1
    a = Math.sqrt((dx * dx) + (dy * dy))


  pathsToPoints: (list) =>
    _.map list.split(","), (pair) =>
      _.map pair.split("-"), _.compose(@grid.fromOffset, (s) -> parseInt s)

class Grid
  constructor: (el, @width, @height, @size) ->
