# File lib/facet/bbcode.rb, line 134
    def BBCode.ansi_to_bbcode(string)
        return "" if string.nil? || string.to_s.strip.empty?
        result = ""
        tagstack = []

        ## Iterate over input lines
        string.split("\n").each do |line|
            ansi = line.scan(/\e\[[0-9;]+m/)
            continue if ansi.nil? || ansi.empty?

            ## Iterate over found ansi sequences
            ansi.each do |seq|  
                ansiname = ANSINAME2CODE.invert["#{seq}"]

                ## Pop last tag and form closing tag
                if ansiname == "reset"
                    lasttag = tagstack.pop
                    bbname = "/" + String.new( lasttag.split("=")[0] )

                ## Get corresponding BBCode tag + Push to stack
                else
                    bbname   = ANSINAME2BBCODE[ansiname]
                    tagstack.push(bbname) 
                end

                ## Replace ansi sequence by BBCode tag
                replace = sprintf("[%s]", bbname)
                line.sub!("#{Regexp.quote(seq)}", replace)
            end

            ## Append converted line
            result << sprintf("%s\n", line)
        end


        ## Some tags are unclosed
        while !tagstack.empty?
            result << sprintf("[/%s]", String.new(tagstack.pop.split("=")[0])  )
        end

        return result
    end