         @released = yes
 
 
-class StreamAdapter
+
+class StreamAdapter extends Stream # Readable
     constructor: (@template, opts = {}) ->
+        super()
         @builder = @template.xml ? @template
-        @stream = opts.stream ? new Stream
-        @stream.readable ?= on
+        @encoding = opts.encoding ? 'utf8'
         @opened_tags = 0
+        @readable = yes
+        @paused = no
+        @queue = []
+        # initialize
+        @pipe(opts.stream) if opts.stream
         @initialize()
 
     initialize: () ->
-        @template.stream = @stream
-        @builder._stream = new Entry @builder
-        @builder._stream.release()
+        @template.stream = this
+        @builder._stream = new Entry this, @builder
         do @listen
         # register ready handler
         @template.register('ready', @approve_ready)

            @parent?._stream.emit('close scope', order:idx+1)
        @parent?._stream.release()

    emit: ->
        @order.emit(arguments...)

    write: (job) ->
        # no self closing tags please
        @release() if @children and @isnext
        @emit 'entry', {job, order:(++@children)}

    release: () =>
        return if @released

    'attr','text', 'raw', 'data'
]

# TODO dont emit data from hidden tags


class Entry
    constructor: (@stream, el, @parent) ->
        @order = new OrderedEmitter span:yes
        # states
        @released = no
        @isnext = if @parent? then no else yes
        @children = 0 # we start with 1 to use 0 as pause bit
        # just run the job when it got ready
        @order.on('entry', @do_job)
        return if @isnext
        # tell the parent to write this entry when its time
        @parent?._stream.write =>
            @release() if not el.isempty or el.closed is yes
