var blob = use('blob')

var iter = 50, limit = 2.0;
var zr, zi, cr, ci, tr, ti;

var h = Number(arg[0]) || 500
var w = h

log.console(`P4\n${w} ${h}`);

for (let y = 0; y < h; ++y) {
  // Create a blob for the row - we need w bits
  var row = new blob(w);

  for (let x = 0; x < w; ++x) {
    zr = zi = tr = ti = 0;
    cr = 2 * x / w - 1.5;
    ci = 2 * y / h - 1;
    for (let i = 0; i < iter && (tr + ti <= limit * limit); ++i) {
      zi = 2 * zr * zi + ci;
      zr = tr - ti + cr;
      tr = zr * zr;
      ti = zi * zi;
    }

    // Write a 1 bit if inside the set, 0 if outside
    if (tr + ti <= limit * limit)
      row.write_bit(1);
    else
      row.write_bit(0);
  }
  
  // Convert the blob to stone (immutable) to prepare for output
  stone(row)
  
  // Output the blob data as raw bytes
  log.console(text(row, 'b'));  
}

$_.stop()