package charsets

import (
	
	
	htmlcharset 
	
	
)

var boms = []struct {
	bom []byte
	enc string
}{
	{[]byte{0xfe, 0xff}, "utf-16be"},
	{[]byte{0xff, 0xfe}, "utf-16le"},
	{[]byte{0xef, 0xbb, 0xbf}, "utf-8"},
}

// FindEncoding sniff and find the encoding of the content.
func ( []byte) ( encoding.Encoding,  string) {
	if len() == 0 {
		return
	}
	for ,  := range boms {
		if bytes.HasPrefix(, .bom) {
			,  = htmlcharset.Lookup(.enc)
			if  != nil {
				if strings.ToLower() == "utf-8" {
					 = nil
				}
				return
			}
		}
	}
	,  = prescan()
	if strings.ToLower() == "utf-8" {
		 = nil
	}
	return
}

func prescan( []byte) ( encoding.Encoding,  string) {
	 := html.NewTokenizer(bytes.NewReader())
	for {
		switch .Next() {
		case html.ErrorToken:
			return nil, ""

		case html.StartTagToken, html.SelfClosingTagToken:
			,  := .TagName()
			if !bytes.Equal(, []byte("meta")) {
				continue
			}
			 := make(map[string]bool)
			 := false

			const (
				 = iota
				
				
			)
			 := 

			 = ""
			 = nil
			for  {
				var ,  []byte
				, ,  = .TagAttr()
				 := string()
				if [] {
					continue
				}
				[] = true
				for ,  := range  {
					if 'A' <=  &&  <= 'Z' {
						[] =  + 0x20
					}
				}

				switch  {
				case "http-equiv":
					if bytes.Equal(, []byte("content-type")) {
						 = true
					}

				case "content":
					if  == nil {
						 = fromMetaElement(string())
						if  != "" {
							,  = htmlcharset.Lookup()
							if  != nil {
								 = 
							}
						}
					}

				case "charset":
					,  = htmlcharset.Lookup(string())
					 = 
				}
			}

			if  ==  ||  ==  && ! {
				continue
			}

			if strings.HasPrefix(, "utf-16") {
				 = "utf-8"
				 = encoding.Nop
			}

			if  != nil {
				return , 
			}
		}
	}
}

func fromMetaElement( string) string {
	for  != "" {
		 := strings.Index(, "charset")
		if  == -1 {
			return ""
		}
		 = [+len("charset"):]
		 = strings.TrimLeft(, " \t\n\f\r")
		if !strings.HasPrefix(, "=") {
			continue
		}
		 = [1:]
		 = strings.TrimLeft(, " \t\n\f\r")
		if  == "" {
			return ""
		}
		if  := [0];  == '"' ||  == '\'' {
			 = [1:]
			 := strings.IndexRune(, rune())
			if  == -1 {
				return ""
			}
			return [:]
		}

		 := strings.IndexAny(, "; \t\n\f\r")
		if  == -1 {
			 = len()
		}
		return [:]
	}
	return ""
}