"use strict"

function callHandler (event, handler, next, reject) {
    setImmediate(() => {
        try {
            handler.fn(event, handler.state, handler.args, next);
        } catch (err) {
            reject(err);
        }
    });
}

module.exports = (args) => {

    const call = args[0]
    const sequence = args[1];
    const event = args[2];
    let data = args[3];

    return new Promise((resolve, reject) => {

        let handler = sequence[sequence.first];
        const next = (err, chunk, stream) => {

            if (err) {
                return reject(err);
            }

            if (chunk !== undefined && chunk !== null) {
                data = chunk;
            }

            if (stream) {
                event.output = stream;
            } else {
                stream = event.output;
            }

            stream.flow = call;
            stream.args = sequence.args;
            stream.data = data;

            // emit stream errors on event
            if (stream.listenerCount('error') < 1) {
                stream.on('error', (err) => event.emit('error', err));
            }

            handler = sequence[handler.next];
            if (!handler) {
                return resolve(event.output);
            }

            callHandler(stream, handler, next, reject);
        };

        callHandler(event, handler, next, reject);
    });
};

@@ -708,135 +708,40 @@
     
-if (
 stream
-) %7B%0A                event.output = stream;%0A            %7D else %7B%0A                stream = event.output;%0A            %7D%0A
+ = stream %7C%7C event.output;
 %0A   
@@ -841,16 +841,51 @@
  = data;
+%0A            event.output = stream;
 %0A%0A      
@@ -1165,28 +1165,22 @@
 resolve(
-event.output
+stream
 );%0A     
@@ -1257,16 +1257,50 @@
     %7D;%0A%0A
+        event.output.data = data;%0A
         
@@ -1312,24 +1312,31 @@
 andler(event
+.output
 , handler, n

set event data on first handler call