Properly switch encodings when detecting BOM (#339)