# File lib/html5/inputstream.rb, line 94
    def detect_encoding

      #First look for a BOM
      #This will also read past the BOM if present
      encoding = detect_bom

      #If there is no BOM need to look for meta elements with encoding 
      #information
      if encoding.nil? and @parse_meta
        encoding = detect_encoding_meta
      end

      #Guess with chardet, if avaliable
      if encoding.nil? and @chardet
        begin
          require 'rubygems'
          require 'UniversalDetector' # gem install chardet
          buffers = []
          detector = UniversalDetector::Detector.instance
          detector.reset
          until @raw_stream.eof?
            buffer = @raw_stream.read(@NUM_BYTES_CHARDET)
            break if !buffer or buffer.empty?
            buffers << buffer
            detector.feed(buffer)
            break if detector.instance_eval {@done}
            detector.instance_eval {
              @_mLastChar = @_mLastChar.chr if Fixnum === @_mLastChar
            }
          end
          detector.close
          encoding = detector.result['encoding']
          seek(buffers*'', 0)
        rescue LoadError
        end
      end

      # If all else fails use the default encoding
      if encoding.nil?
        encoding = @DEFAULT_ENCODING
      end
    
      #Substitute for equivalent encoding
      if 'iso-8859-1' == encoding.downcase
        encoding = 'windows-1252'
      end

      encoding
    end