                 end_tag.call this, args...
 
         ##
-        # pipe events through and add hooks to be able to alter event behavoir
+        # pipe events through and add hooks to be able to alter event behavior
         # (eg injecting events before others)
         # override method "on#{event}" to access the hook
         EVENTS.forEach (event) =>


class Template extends EventEmitter
    constructor: (opts = {}, template) ->
        [template, opts] = [opts, {}] if typeof opts is 'function'
        opts.encoding ?= 'utf-8'
        opts.doctype ?= off
        schema_input = opts.schema
        s = aliases[schema_input] or schema_input or 'xml'
        opts.self_closing = self_closing[s]?(opts)
        opts.schema = schema[s]?(opts).split(' ')
        opts.end ?= on
        # get builder class from options
        Builder = opts.Builder ? DefaultBuilder

        class ExtendedBuilder extends Builder
        ff ExtendedBuilder::, opts.schema

        @xml = new ExtendedBuilder opts
        @end = @xml.end
        Tag = @xml.Tag
        class ExtendedTag extends Tag
        ff ExtendedTag::, opts.schema
        @xml.Tag = @xml.opts.Tag = ExtendedTag

        end_tag = Tag::end
        @xml.Tag::end = (args...) ->
            if opts.self_closing is on or opts.self_closing.match @name

            @xml.on event, (args...) =>
                @["on#{event}"](args...)

        ##
        # start the templating process after user listened for events
        process.nextTick =>
            # load doctype if enabled
            if opts.doctype is on
                opts.doctype = 'html'
            # resolve doctype name input
            d = aliases[opts.doctype] or opts.doctype
            # write doctype
            if opts.doctype and (dt = doctype[d]?(opts))
                dt += "\n" if opts.pretty
                @xml.emit 'data', dt
            # templating process ...
            if typeof template is 'function'
                template.call @xml
                @end() if opts.end
