var chunky, nx = 16, ny = 16;

function drawChunky() {
  for (var y = 0; y < ny; y++) {
    for (var x = 0; x < nx; x++) {
      var e = document.getElementById("chunky-" + x + "-" + y);
      var xx = -16 * (
	  (chunky[(y * 4 + 1) * 64 + (x * 4 + 0)] << 7) +
	  (chunky[(y * 4 + 1) * 64 + (x * 4 + 1)] << 6) +
	  (chunky[(y * 4 + 1) * 64 + (x * 4 + 2)] << 5) +
	  (chunky[(y * 4 + 1) * 64 + (x * 4 + 3)] << 4) +
	  (chunky[(y * 4 + 0) * 64 + (x * 4 + 0)] << 3) +
	  (chunky[(y * 4 + 0) * 64 + (x * 4 + 1)] << 2) +
	  (chunky[(y * 4 + 0) * 64 + (x * 4 + 2)] << 1) +
	  (chunky[(y * 4 + 0) * 64 + (x * 4 + 3)] << 0));
      var yy = -16 * (
	  (chunky[(y * 4 + 3) * 64 + (x * 4 + 0)] << 7) +
	  (chunky[(y * 4 + 3) * 64 + (x * 4 + 1)] << 6) +
	  (chunky[(y * 4 + 3) * 64 + (x * 4 + 2)] << 5) +
	  (chunky[(y * 4 + 3) * 64 + (x * 4 + 3)] << 4) +
	  (chunky[(y * 4 + 2) * 64 + (x * 4 + 0)] << 3) +
	  (chunky[(y * 4 + 2) * 64 + (x * 4 + 1)] << 2) +
	  (chunky[(y * 4 + 2) * 64 + (x * 4 + 2)] << 1) +
	  (chunky[(y * 4 + 2) * 64 + (x * 4 + 3)] << 0));
      e.style.backgroundPosition = xx + "px " + yy + "px";
    }
  }
}

function initializeChunky() {
  document.write('<style type="text/css">');
  document.write('div.chunky {');
  document.write('position: absolute;');
  document.write('left: 1px;');
  document.write('top: 1px;');
  document.write('width: 16px;');
  document.write('height: 16px;');
  document.write('background-image: url("img/chunky.png");');
  document.write('z-index: 3;');
  document.write('}');
  document.write('</style>');
  for (var y = 0; y < ny; y++) {
    for (var x = 0; x < nx; x++) {
      document.write("<div id=\"chunky-" + x + "-" + y +"\" class=\"chunky\"></div>");
      var e = document.getElementById("chunky-" + x + "-" + y);
      e.style.left = (1 + 16 * x) + "px";
      e.style.top = (1 + 16 * y) + "px";
    }
  }

  chunky = new Array(64 * 64);
}

