'use strict'
const thru = require('through2')
const split = require('split2')

function parse () {
  function parseStream (dat) {
    if (!dat) return null
    let obj
    try {
      obj = JSON.parse(dat)
    } catch (err) {
      const open = _count(dat, '{')
      const close = _count(dat, '}')
      if (open > close) dat = `${dat}}`
      else if (open < close) dat = `{${dat}`
      else dat = `{${dat}}`
      try {
        obj = JSON.parse(dat)
      } catch (err) {
        this.emit('error', err)
      }
    }
    return obj
  }
  return split('}{', parseStream)
}

function serialize () {
  return thru.obj((chunk, enc, cb) => {
    try {
      return cb(null, JSON.stringify(chunk))
    } catch (err) {
      return cb(err)
    }
  })
}

function _count (str, c) {
  let count = 0
  let inContent = false
  for (let i = 0; i < str.length; i += 1) {
    if (str.charAt(i) === '"') {
      if (!(i > 0 && str.charAt(i - 1) === '\\')) inContent = !inContent
    } else if (str.charAt(i) === c && !inContent) count += 1
  }
  return count
}

module.exports = {
  parse: parse,
  serialize: serialize,
  stringify: serialize
}

@@ -92,16 +92,51 @@
 se () %7B%0A
+  return split('%7D%7B', parseStream)%0A%0A
   functi
@@ -273,17 +273,16 @@
  open = 
-_
 count(da
@@ -309,17 +309,16 @@
 close = 
-_
 count(da
@@ -571,188 +571,42 @@
   %7D%0A
+%0A
   
-return split('%7D%7B', parseStream)%0A%7D%0A%0Afunction serialize () %7B%0A  return thru.obj((chunk, enc, cb) =%3E %7B%0A    try %7B%0A      return cb(null, JSON.stringify(chunk))%0A    %7D catch (err
+function count (str, ch
 ) %7B%0A    
   re
@@ -605,82 +605,20 @@
     
-  
-return cb(err)%0A    %7D%0A  %7D)%0A%7D%0A%0Afunction _count (str, c) %7B%0A  
 let c
-ount
  = 0%0A
+  
   le
@@ -637,16 +637,18 @@
 = false%0A
+  
   for (l
@@ -679,24 +679,26 @@
 ; i += 1) %7B%0A
+  
     if (str.
@@ -720,24 +720,26 @@
 %22') %7B%0A      
+  
 if (!(i %3E 0 
@@ -797,16 +797,18 @@
 ent%0A    
+ 
+ 
 %7D else i
@@ -829,16 +829,17 @@
 i) === c
+h
  && !inC
@@ -851,20 +851,16 @@
 t) c
-ount
  += 1%0A  
 %7D%0A  
@@ -855,18 +855,22 @@
  += 1%0A  
-%7D%0A
+  %7D%0A  
   return
@@ -871,20 +871,194 @@
 return c
-ount
+%0A  %7D%0A%7D%0A%0Afunction serialize () %7B%0A  return thru.obj((chunk, enc, cb) =%3E %7B%0A    try %7B%0A      return cb(null, JSON.stringify(chunk))%0A    %7D catch (err) %7B%0A      return cb(err)%0A    %7D%0A  %7D)
 %0A%7D%0A%0Amodu

Refactor parse function