'use strict';

// MODULES //

var spawn = require( 'child_process' ).spawn;


// FUNCTIONS //

/**
* Callback invoked upon encountering an error.
*
* @private
* @param {Error} error - error object
*/
function onError( error ) {
	process.stderr.write( error.message+'\n', 'utf8' );
	process.exit( 1 );
} // end FUNCTION onError()

/**
* Callback invoked upon child process close.
*
* @private
* @param {number} code - exit code
* @returns {void}
*/
function onFinish( code ) {
	if ( code !== 0 ) {
		process.stderr.write( '`make` process exited with code `'+code + '.\n' );
		return process.exit( code );
	}
	// Cannot write to `stdout` and then immediately `exit` as `buffer` may not yet have drained https://github.com/nodejs/node/issues/6456.
	// process.exit( 0 );

	// HACK: workaround is to use `console.log` and no exit:
	console.log( '' );
} // end FUNCTION onFinish()

/**
* Callback invoked upon receiving data from `stdout`.
*
* @private
* @param {Buffer} data - standard output
*/
function stdout( data ) {
	process.stdout.write( data );
} // end FUNCTION stdout()

/**
* Callback invoked upon receiving data from `stderr`.
*
* @private
* @param {Buffer} data - standard error
*/
function stderr( data ) {
	process.stderr.write( data );
} // end FUNCTION stderr()


// MAIN //

/**
* Plugin to compile WebAssembly.
*
* @param {string} dir - Makefile directory
* @param {string} cwd - current working directory
* @param {string} subpath - subdirectory path
*/
function plugin( dir, cwd, subpath ) {
	var opts;
	var args;
	var proc;

	opts = {};
	opts.cwd = dir;

	args = [];

	// Environment variables:
	if ( subpath ) {
		args.push( 'PKGS_WASM_PATTERN='+subpath );
	}
	// Target:
	args.push( 'wasm' );

	proc = spawn( 'make', args, opts );
	proc.on( 'error', onError );
	proc.stdout.on( 'data', stdout );
	proc.stderr.on( 'data', stderr );
	proc.on( 'close', onFinish );
} // end FUNCTION plugin()


// EXPORTS //

module.exports = plugin;

@@ -234,68 +234,51 @@
 ess.
-stderr.write( error.message+'%5Cn', 'utf8' );%0A%09process.exit( 1
+exitCode = 1;%0A%09console.error( error.message
  );%0A
@@ -487,72 +487,23 @@
 ess.
-stderr.write( '%60make%60 process exited with c
+exitC
 ode 
-%60'+
+= 
 code
- + '.%5Cn' )
 ;%0A%09%09
@@ -513,182 +513,38 @@
 urn 
-process.exit( code );%0A%09%7D%0A%09// Cannot write to %60stdout%60 and then immediately %60exit%60 as %60buffer%60 may not yet have drained https://github.com/nodejs/node/issues/6456.%0A%09//
+console.error( '%60make%60
  process
 .exi
@@ -543,99 +543,48 @@
 cess
-.
+ 
 exit
-( 0 );%0A%0A%09// HACK: workaround is to use %60console.log%60 and no exit:%0A%09console.log( '
+ed with code %60'+code + '.%5Cn
 ' );%0A
+%09%7D%0A
 %7D //
@@ -1363,16 +1363,84 @@
 ath ) %7B%0A
+%09%09subpath = subpath.substring( 17 ); // removes 'lib/node_modules/'%0A
 %09%09args.p

Fix setting of environment variable