'use strict';
var util = require('util');
var events = require('events');



/**
 * ReplayBuffer
 * Buffers a readable stream &
 *   replays chunks on as many writable stream as needed
 *
 * @param {?Object=} opt_options
 *
 * @constructor
 */
function ReplayBuffer(opt_options) {
  opt_options = opt_options || {};

  this.max = opt_options.max || 134217728; // 128 MiB

  this.chunks = [];
  this.encodings = [];
  this.length = 0; // number of chunk bytes

  this.closed = false;
}
module.exports = ReplayBuffer;


ReplayBuffer.prototype.push = function(chunk, encoding) {
  if (this.closed) {
    return false;
  }
  this.chunks.push(chunk);
  this.length += chunk.length;
  this.encodings.push(encoding);

  if (this.length > this.max) {
    return false;
  }

  return true;
};


ReplayBuffer.prototype.replay = function(writable, callback) {
  var self = this;
  var i = 0;

  if (!this.chunks.length) {
    return setImmediate(function() {
      callback();
    });
  }


  // async variation of _duff's device_
  //   https://en.wikipedia.org/wiki/Duff%27s_device
  (function next() {
    var mod = 0;

    if (self.chunks.length < 4) {
      mod = (self.chunks.length - i) % 4;
    }
    // TODO: write callback!

    switch (mod) {
      case 0:
        writable.write(self.chunks[i], self.encodings[i++]); /* falls through */
      case 3:
        writable.write(self.chunks[i], self.encodings[i++]); /* falls through */
      case 2:
        writable.write(self.chunks[i], self.encodings[i++]); /* falls through */
      case 1:
        writable.write(self.chunks[i], self.encodings[i++]); /* falls through */
    }

    if (self.chunks[i]) {
      setImmediate(next);
    } else {
      setImmediate(callback);
    }
  })(/* auto-exec */);
};

@@ -1104,25 +1104,28 @@
 od = 0;%0A
-%0A
     
-if (
+var n = 
 self.chu
@@ -1135,16 +1135,32 @@
 .length 
+- i;%0A%0A    if (n 
 %3C 4) %7B%0A 
@@ -1174,32 +1174,9 @@
 d = 
-(self.chunks.length - i)
+n
  %25 4

fix duff's device