var terminus = require('terminus');

module.exports = function(identifier, constructor, options){
  options = options || {};
  var streams = {};
  var cloggedStreams = 0;

  return terminus(options, function(chunk, enc, cb){
    var self = this;
    var streamName = identifier(chunk, enc);

    if (streamName === false) {
      cb();
      return true;
    }

    if (typeof streams[streamName] == 'undefined') {
      streams[streamName] = constructor(streamName);
      streams[streamName].__clogged = false;
      streams[streamName].on('drain', function(){
        this.__clogged = false;
        cloggedStreams--;
        if (!cloggedStreams) {
          self.emit('drain');
        }
      });
    }

    var success = streams[streamName].write(chunk);
    if (!success && !streams[streamName].__clogged) {
      streams[streamName].__clogged = true;
      cloggedStreams++;
    }

    cb();
    return !cloggedStreams;
  });
};
@@ -141,34 +141,8 @@
  %7B%7D;
-%0A  var cloggedStreams = 0;
 %0A%0A  
@@ -196,29 +196,8 @@
 b)%7B%0A
-    var self = this;%0A
     
@@ -294,21 +294,16 @@
   return
- true
 ;%0A    %7D%0A
@@ -340,16 +340,17 @@
 Name%5D ==
+=
  'undefi
@@ -414,242 +414,8 @@
 e);%0A
-      streams%5BstreamName%5D.__clogged = false;%0A      streams%5BstreamName%5D.on('drain', function()%7B%0A        this.__clogged = false;%0A        cloggedStreams--;%0A        if (!cloggedStreams) %7B%0A          self.emit('drain');%0A        %7D%0A      %7D);%0A
     
@@ -469,24 +469,25 @@
 chunk);%0A
+%0A
     if (
 !success
@@ -482,17 +482,16 @@
 if (
-!
 success 
 && !
@@ -490,157 +490,113 @@
 ess 
-&& !streams%5BstreamName%5D.__clogged) %7B%0A      streams%5BstreamName%5D.__clogged = true;%0A      cloggedStreams++;%0A    %7D%0A%0A    cb();%0A    return !cloggedStreams;
+=== false) %7B%0A      streams%5BstreamName%5D.once('drain', cb.bind(null, null));%0A    %7D else %7B%0A      cb();%0A    %7D
 %0A  %7D

fix major memory leak in streamSplitter