         @headers = "<#{@name}#{new_attrs @attrs}"
         @children children, @opts
 
-    $tag: =>
-        # sync tag, - same as normal tag, but closes it automaticly
-        sync_tag.apply this, arguments
-
-    tag: =>
-        if @headers
-            @emit 'data', "#{indent this}#{@headers}>"
-            delete @headers
-        new_tag.apply this, arguments
+    tag: (args...) =>
+        @builder._new_tag.apply this, [this].concat args
+
+    $tag: (args...) =>
+        @builder._new_sync_tag.apply this, [this].concat args
 
     attr: (key, value) =>
         if typeof key is 'string'

            @attrs ?= {}
            @opts ?= {}
        @level = @opts.level
        @Tag = @opts.Tag or Tag # inherit (maybe) extended tag class
        @buffer = [] # after this tag all children emitted data
        @pending = [] # no open child tag
        @closed = false

        this



class Builder extends EventEmitter
    constructor: (@opts = {}) ->
        @builder = this
        @buffer = [] # for child output
        @closed = no
        @pending = [] # no open child tag
        @opts.builder ?= this
        @opts.pretty ?= off
        @level = @opts.level ? 0
        @Tag = @opts.Tag or Tag

    _new_tag: (parent, args...) =>
        if parent.headers
            parent.emit 'data', "#{indent parent}#{parent.headers}>"
            delete parent.headers
        new_tag.apply parent, [this].concat args

    _new_sync_tag: (parent, name, attrs, children, opts) =>
        # sync tag, - same as normal tag, but closes it automaticly
        unless typeof attrs is 'object'
            [opts, children, attrs] = [children, attrs, {}]
        else
            attrs ?= {}
        opts ?= {}
        self_ending_children_scope = ->
            @children children
            @end()
        @_new_tag parent, name, attrs, self_ending_children_scope, opts

    tag: (args...) =>
        @level--
        tag = @_new_tag.apply this, [this].concat args
        @level++
        tag

    $tag: (args...) =>
        @level--
        tag = @_new_sync_tag.apply this, [this].concat args
        @level++
        tag

    end: (data) =>
        if @pending.length
