// MAP 

var fs = require('fs')
var asyncMap = require('slide').asyncMap
var browserify = require('browserify')
var uglify = require('uglify-js')
var through = require('through')

module.exports = function Map (opts) {
  var MAP = {
    browser: {},
    node: {}
  }

  var dir = opts.wilds
  var b = browserify(opts.browserify)

  if (dir[dir.length-1] !=='/') dir += '/'
  fs.readdir(dir, function moduleList (e, modules) {
    if (e) console.error(e)
    if (!e) asyncMap(modules, readPkg, function () {

      s.write({key:'^:', value:MAP, valueEncoding:'json'})
      
      bundleJS()
    })
  })

  function readPkg (modDir, next) {
    var jsn = fs.readFileSync(dir+modDir+'/package.json').toString()
    if (jsn !== 'undefined' && jsn !== '' && jsn[0] === '{') { // do better json validation
      var pkg = JSON.parse(jsn)
      if (pkg.nimoy) { 
        if (pkg.nimoy.process === 'browser') b.require(dir+pkg.name, {expose:pkg.name})

        MAP[pkg.nimoy.process][pkg.name] = pkg

        next() 
      } else next()
    } else next()
  }

  function bundleJS () {
    var bundle = fs.createWriteStream(opts.bundle)
    b.bundle().pipe(bundle)
    bundle.on('finish', function () {
      if (opts.min === true ) {
        var min = uglify.minify(opts.bundle)
        fs.writeFileSync(opts.bundle, min.code)
        s.end()
      } else s.end()
    })
    b.on('error', function (e) {
      console.error(e)
    })
  }

  var s = through(function write (chunk) {
    this.emit('data', chunk)
  }, function end () {
    this.emit('end')
  })

  return s
}

@@ -66,16 +66,61 @@
 syncMap%0A
+var Emitter = require('events').EventEmitter%0A
 var brow
@@ -150,16 +150,16 @@
 erify')%0A
-
 var ugli
@@ -187,41 +187,8 @@
 js')
-%0Avar through = require('through')
 %0A%0Amo
@@ -224,16 +224,93 @@
 opts) %7B%0A
+%0A  // add an option to watch dir and recompile%0A%0A  var emitter = new Emitter%0A%0A
   var MA
@@ -346,24 +346,25 @@
 de: %7B%7D%0A  %7D%0A%0A
+%0A
   var dir = 
@@ -601,59 +601,52 @@
     
-s.write(%7Bkey:'%5E:', value:MAP, valueEncoding:'json'%7D
+emitter.emit('map', '%5E', JSON.stringify(MAP)
 )%0A  
@@ -1404,22 +1404,34 @@
         
-s.end(
+emitter.emit('end'
 )%0A      
@@ -1441,14 +1441,26 @@
 lse 
-s.end(
+emitter.emit('end'
 )%0A  
@@ -1486,189 +1486,43 @@
 r', 
-function (e) %7B%0A      console.error(e)%0A    %7D)%0A  %7D%0A%0A  var s = through(function write (chunk) %7B%0A    this.emit('data', chunk)%0A  %7D, function end () %7B%0A    this.emit('end')%0A  %7D)%0A%0A  return s
+console.error)%0A  %7D%0A%0A  return emitter
 %0A%7D%0A

change _map to an eventEmitter