// Generated by IcedCoffeeScript 1.7.1-c
(function() {
  var Gets;

  exports.Gets = Gets = (function() {
    function Gets(_stream, opts) {
      this._stream = _stream;
      if (opts == null) {
        opts = {};
      }
      this._lines = [];
      this._curr = [];
      this._n = 0;
      this._hiwat = (opts != null ? opts.hiwat : void 0) || 0x1000;
      this._lowat = (opts != null ? opts.lowat : void 0) || 0x800;
      this._include_newline = !!(opts != null ? opts.include_newline : void 0);
      this._eof = false;
      this._err = null;
      this._cbs = [];
    }

    Gets.prototype.run = function() {
      this._stream.resume();
      this._stream.on('data', this._buffer_data.bind(this));
      this._stream.on('end', this._got_eof.bind(this));
      this._stream.on('err', this._got_err.bind(this));
      return this;
    };

    Gets.prototype._got_eof = function() {
      this._eof = true;
      return this._poke();
    };

    Gets.prototype._got_err = function(e) {
      this._err = e;
      return this._poke();
    };

    Gets.prototype._maybe_pause = function() {
      if (this._n >= this._hiwat) {
        this._paused = true;
        return this._stream.pause();
      }
    };

    Gets.prototype._maybe_resume = function() {
      if (this._paused && this._n <= this._lowat) {
        this._paused = false;
        return this._stream.resume();
      }
    };

    Gets.prototype._buffer_data = function(dat) {
      var end, i, rest;
      dat = dat.toString('utf8');
      while ((i = dat.indexOf('\n')) >= 0) {
        end = i;
        rest = dat.slice(i + 1);
        if (this._include_newline) {
          i++;
        }
        this._n += i;
        this._curr.push(dat.slice(0, i));
        this._lines.push(this._curr.join(''));
        this._curr = [];
        if (!this._include_newline) {
          i++;
        }
        dat = rest;
        this._poke();
      }
      return this._maybe_pause();
    };

    Gets.prototype.gets = function(cb) {
      this._cbs.push(cb);
      return this._poke();
    };

    Gets.prototype._poke = function() {
      var cb, line, _results;
      while (this._lines.length && this._cbs.length) {
        cb = this._cbs.shift();
        line = this._lines.shift();
        this._n -= line.length;
        this._maybe_resume();
        cb(null, line);
      }
      while (this._cbs.length && (this._err != null)) {
        cb = this._cbs.shift();
        cb(this._err);
      }
      _results = [];
      while (this._cbs.length && this._eof) {
        cb = this._cbs.shift();
        _results.push(cb(null, null));
      }
      return _results;
    };

    return Gets;

  })();

}).call(this);
