'use strict';

var Writable = require('stream').Writable;
var Parser = require('./parser.js');

function Streamer(options) {
  Writable.call(this, options);
  this.buffer = '';
  this.sep = (options && options.separator) ? options.separator : undefined;
  this.quo = (options && options.quote) ? options.quote : undefined;
}

Streamer.prototype = Object.create(
  Writable.prototype, { constructor: { value: Streamer }});


Streamer.prototype._write = function (chunk, encoding, done) {

  this.buffer = this.buffer.concat(chunk.toString());

  if (this.sep === undefined) {
    // try to detect the separator if not provided
    this.sep = require('./csv.js').detect(this.buffer);
  }

  var csv = new Parser(this.buffer, this.sep, this.quo);
  var rows = csv.File();

  if (csv.pointer > this.buffer.length) {
    this.buffer = this.buffer.slice(csv.pointer);
  }
  else {
    if (csv.pointer === this.buffer.length) {
      rows.pop();
    }
    this.buffer = this.buffer.slice(csv.linePointer);
  }
  if (rows.length > 0) {
    var self = this;
    rows.forEach(function (row) {
        self.emit('data', row);
      }
    )
  }
  done();
}

Streamer.prototype.end = function () {
  var csv = new Parser(this.buffer, this.sep, this.quo);
  var rows = csv.File();
  if (rows.length > 0) {
    var self = this;
    rows.forEach(function (row) {
        self.emit('data', row);
      }
    )
  }
  this.emit('end');
};

module.exports = Streamer;

@@ -12,24 +12,25 @@
 ';%0A%0Avar 
-Writable
+Transform
  = requi
@@ -42,24 +42,25 @@
 tream').
-Writable
+Transform
 ;%0Avar Pa
@@ -122,24 +122,25 @@
 ns) %7B%0A  
-Writable
+Transform
 .call(th
@@ -143,23 +143,83 @@
 l(this, 
-options
+ %7B%0A    readableObjectMode: true,%0A    writableObjectMode: false,%0A  %7D
 );%0A  thi
@@ -424,16 +424,17 @@
 (%0A  
-Writable
+Transform
 .pro
@@ -505,13 +505,17 @@
 pe._
-write
+transform
  = f
@@ -521,17 +521,16 @@
 function
- 
 (chunk, 
@@ -602,17 +602,16 @@
 ing());%0A
-%0A
   if (th
@@ -1151,37 +1151,29 @@
        self.
-emit('data', 
+push(
 row);%0A      
@@ -1216,19 +1216,22 @@
 ototype.
-end
+_flush
  = funct
@@ -1235,16 +1235,20 @@
 nction (
+done
 ) %7B%0A  va
@@ -1422,21 +1422,13 @@
 elf.
-emit('data', 
+push(
 row)
@@ -1453,23 +1453,13 @@
 %7D%0A  
-this.emit('end'
+done(
 );%0A%7D

use transformer