-spawn = require('spawn-cmd').spawn
-through  = require 'through2'
-gutil = require 'gulp-util'
+spawn       = require('spawn-cmd').spawn
+through     = require 'through2'
+gutil       = require 'gulp-util'
+PluginError = gutil.PluginError
 
 PLUGIN_NAME = 'gulp-slim'
 

  through.obj (file, encoding, callback) ->

    if file.isNull()
      @push file
      return callback()

    if file.isStream()
      @emit 'error', new gutil.PluginError PLUGIN_NAME, 'Streaming not supported'
      return callback()

    # relace the extension
    original_file_path = file.path

    eb = new Buffer 0

    # add data to buffer
    program.stdout.on 'readable', ->
      while chunk = program.stdout.read()
        b = Buffer.concat [b, chunk], b.length + chunk.length

    # return data
    program.stdout.on 'end', ->
      file.contents = b
      callback null, file

    # handle errors
    program.stderr.on 'readable', ->
      while chunk = program.stderr.read()
        eb = Buffer.concat [eb, chunk], eb.length + chunk.length

    program.stderr.on 'end', ->
      if eb.length > 0
        err = eb.toString()
        msg = "Slim error in file (#{original_file_path}):\n#{err}"
        return callback new PluginError PLUGIN_NAME, msg

    # pass data to standard input
    program.stdin.write file.contents, ->
      program.stdin.end()
