             @template.on(event, this["on#{event}"].bind(this))
 
     write: (data) ->
-        @stream.emit('data', data) if data
+        return unless data
+        @emit('error', "write data while paused") if @paused
+        @emit('data', data)
 
     close: () =>
         @builder.closed = yes
-        @stream.emit 'end'
+        @readable = no
+        @emit 'end'
+        @emit 'close'
+
+    # Readable API
+
+    setEncoding: (@encoding) ->
+
+    pause: () ->
+        return if @paused
+        @paused = yes
+        @emit 'pause'
+
+    resume: () ->
+        if @paused
+            @emit 'resume'
+            @paused = no
+        @queue.shift()?() while not @paused and @queue.length
+        return
 
     # eventlisteners
 

            @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

        @released = yes



class StreamAdapter extends Stream # Readable
    constructor: (@template, opts = {}) ->
        super()
        @builder = @template.xml ? @template
        @encoding = opts.encoding ? 'utf8'
        @opened_tags = 0
        @readable = yes
        @paused = no
        @queue = []
        # initialize
        @pipe(opts.stream) if opts.stream
        @initialize()

    initialize: () ->
        @template.stream = this
        @builder._stream = new Entry this, @builder
        do @listen
        # register ready handler
        @template.register('ready', @approve_ready)
