
//the first line is header, in JSON format, with no whitespace.

function merge (a, b) {
  for (var k in b)
    a[k] = a[k] || b[k]
}

module.exports = 
function header (stream) {

  var emit = stream.emit
  var write = stream.write
  var soFar = ''

  stream.emit = function (event, data) {
    if(event !== 'data')
      return emit.apply(stream, arguments)

    soFar += data
    var m
    if(!(m = /\n/.exec(soFar))) return
    var meta = JSON.parse(soFar.substring(0, m.index))
    //+ 1 to get past the newline
    soFar = soFar.substring(m.index + 1)
    stream.emit = emit
    stream.meta = meta
    stream.emit('header', meta)
    //check that the stream is still readable,
    //it may have been ended during the 'header'
    //event.
    if('' !== soFar  && stream.readable)
      stream.emit('data', soFar)
  }

  var meta = {}

  stream.setHeader = function (key) {
    if('string' === typeof key)
      meta[key] = val
    else
      merge(meta, key)
    return stream
  }

  stream.writeHead = function (_meta) {
    if(_meta) merge(meta, _meta)
    stream.write = write
    stream.write(JSON.stringify(meta)+'\n')    
  })

  stream.write = function (data) {
    stream.writeHead()
    return stream.write(data)
  }

  return stream
}


//the first line is header, in JSON format, with no whitespace.

function merge (a, b) {
  for (var k in b)
    a[k] = a[k] || b[k]
}

module.exports = 
function header (stream) {

  var emit = stream.emit
  var write = stream.write
  var soFar = ''

  stream.emit = function (event, data) {
    if(event !== 'data')
      return emit.apply(stream, arguments)

    soFar += data
    var m
    if(!(m = /\n/.exec(soFar))) return
    var meta = JSON.parse(soFar.substring(0, m.index))
    //+ 1 to get past the newline
    soFar = soFar.substring(m.index + 1)
    stream.emit = emit
    stream.meta = meta
    stream.emit('header', meta)
    //check that the stream is still readable,
    //it may have been ended during the 'header'
    //event.
    if('' !== soFar  && stream.readable)
      stream.emit('data', soFar)
  }

  var meta = {}

  stream.setHeader = function (key) {
    if('string' === typeof key)
      meta[key] = val
    else
      merge(meta, key)
    return stream
  }

  stream.writeHead = function (_meta) {
    if(_meta) merge(meta, _meta)
    stream.write = write
    stream.write(JSON.stringify(meta)+'\n')    
  }

  stream.write = function (data) {
    stream.writeHead()
    return stream.write(data)
  }

  return stream
}

fix syntax error (jetlag)