     write: (data) ->
         @stream.emit('data', data) if data
 
+    close: () =>
+        @builder.closed = yes
+        @stream.emit 'end'
+
     # eventlisteners
 
     onadd: (parent, el) ->
         el._stream = new Entry el, parent
+        @opened_tags++
         el._stream.write =>
             if el.closed is 'self'
                 @write prettify el, "<#{el.name}#{attrStr el.attrs}/>"
             else
                 @write prettify el, "<#{el.name}#{attrStr el.attrs}>"
+        el.ready =>
+            # close stream if builder is already closed
+            @opened_tags--
+            if @opened_tags is 0
+                @closed?()
+                @closed = yes
 
     onclose: (el) ->
         el._stream.write =>

        # placeholder for close
        @parent?._stream.children++
        # when this entry is ready resume parent
        el.once 'ready', =>
            @parent?._stream.order.emit('close', order:@idx+1)

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

    release: () =>
        @order.emit 'release', {order:0} unless @released
        @released = yes



        console.warn "attributes of #{el.toString()} don't change anymore"

    onend: () ->
        if @closed? and @opened_tags is 0
            @close()
        else
            @builder.closed = 'pending'
            @closed = @close




