export default function(area) {
  var x = area.x();
  var y0 = area.y0();
  var y1 = area.y1();
  var bisectorX = d3.bisector(x).right;

  // Returns true if there is at least one rectangle
  // of the given aspect ratio and scale
  // that fits somewhere within the area.
  function fits(data, aspect, height, justTest) {
    var x0, x1, i0, i1, j, d, top, bottom, ceiling, floor,
        width = aspect * height,
        xMax = x(data[data.length - 1]);

    for(i0 = 0; i0 < data.length; i0++) {
      d = data[i0];
      x0 = x(d);
      x1 = x0 + width;

      if (x1 > xMax) {
        break;
      }
      
      i1 = bisectorX(data, x1);
      ceiling = -Infinity;
      floor = Infinity;
      for(j = i0; j < i1; j++) {
        d = data[j];

        bottom = y0(d);
        if(bottom < floor) {
          floor = bottom;
        }

        top = y1(d);
        if(top > ceiling) {
          ceiling = top;
        }
      }
      if ((floor - ceiling) >= height) {
        if (justTest) {
          return true;
        }
        return {
          x: x0,
          y: ceiling
        };
      }
    }
    return false;
  }

  return function (data) {
  
    // TODO make this configurable
    var minHeight = 2;

    var bbox = this.getBBox();
    var aspect = bbox.width / bbox.height;

    // Find largest integer scale where label would fit.
    // TODO use Bisector method to speed up this part.
    var height = minHeight;
    while (fits(data, aspect, height, true)) {
      height++;
    }
    height--;
    var fit = fits(data, aspect, height);

    var scale = height / bbox.height;
    var translate = [ fit.x, fit.y ];
    d3.select(this)
        .attr("transform", [
          "translate(" + translate + ")",
          "scale(" + scale + ")",
          "translate(" + [-bbox.x, -bbox.y] + ")"
        ].join(" "));
  }
};

@@ -971,64 +971,200 @@
 ) %7B%0A
-        if (justTest) %7B%0A          return true;%0A        %7D
+%0A        // Avoid creating new objects unnecessarily while just testing.%0A        if (justTest) %7B%0A          return true;%0A        %7D%0A%0A        // Output the coordinates for use in label transform.
 %0A   
@@ -1451,21 +1451,14 @@
 est 
-integer scale
+height
  whe
@@ -1499,18 +1499,19 @@
 e Bisect
-or
+ion
  method 
@@ -1517,27 +1517,103 @@
  to 
-speed up this part.
+get more precision with fewer iterations.%0A    // https://en.wikipedia.org/wiki/Bisection_method
 %0A   
@@ -1767,84 +1767,8 @@
 );%0A%0A
-    var scale = height / bbox.height;%0A    var translate = %5B fit.x, fit.y %5D;%0A
     
@@ -1837,25 +1837,35 @@
 ate(%22 + 
-translate
+fit.x + %22,%22 + fit.y
  + %22)%22,%0A
@@ -1885,21 +1885,36 @@
 ale(%22 + 
-scale
+height / bbox.height
  + %22)%22,%0A
@@ -1942,25 +1942,31 @@
 %22 + 
-%5B
 -bbox.x
-,
+ + %22,%22 +
  -bbox.y
 %5D + 
@@ -1961,17 +1961,16 @@
  -bbox.y
-%5D
  + %22)%22%0A 

Clean up transform generation, add comments