///|
/// Presentation attributes that inherit from ancestors.
let inheritable : Array[String] = [
  "clip-rule", "color", "color-interpolation", "color-rendering", "cursor", "direction",
  "fill", "fill-opacity", "fill-rule", "font", "font-family", "font-size", "font-style",
  "font-variant", "font-weight", "letter-spacing", "marker-end", "marker-mid", "marker-start",
  "paint-order", "pointer-events", "shape-rendering", "stroke", "stroke-dasharray",
  "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit",
  "stroke-opacity", "stroke-width", "text-anchor", "text-rendering", "visibility",
  "word-spacing", "writing-mode",
]

///|
/// Default values of presentation attributes: an attribute equal to its
/// default can be dropped when no ancestor overrides it.
let default_values : Map[String, String] = {
  "fill": "#000",
  "fill-opacity": "1",
  "stroke-opacity": "1",
  "opacity": "1",
  "stroke-width": "1",
  "stroke-linecap": "butt",
  "stroke-linejoin": "miter",
  "stroke-miterlimit": "4",
  "stroke-dasharray": "none",
  "stroke-dashoffset": "0",
  "fill-rule": "nonzero",
  "clip-rule": "nonzero",
  "stroke": "none",
  "font-style": "normal",
  "font-weight": "normal",
  "font-variant": "normal",
  "text-anchor": "start",
  "visibility": "visible",
  "display": "inline",
  "overflow": "visible",
  "clip-path": "none",
  "mask": "none",
  "filter": "none",
  "letter-spacing": "normal",
  "word-spacing": "normal",
  "writing-mode": "lr-tb",
  "color-interpolation": "sRGB",
  "color-rendering": "auto",
  "shape-rendering": "auto",
  "text-rendering": "auto",
  "image-rendering": "auto",
  "pointer-events": "visiblePainted",
  "paint-order": "normal",
}

///|
/// Presentation attributes whose value may be a `url(#…)` reference to
/// paint, markers, clipping, masking or filtering. When such a reference is
/// present the transform must stay on the element because the referenced
/// resource is also subject to it.
let references_props : Set[String] = Set([
  "clip-path", "color-profile", "fill", "filter", "marker-end", "marker-mid", "marker-start",
  "mask", "stroke", "style",
])

///|
/// Attributes that are 0 by default on these elements.
let zero_defaults : Map[String, Array[String]] = {
  "rect": ["x", "y", "rx", "ry"],
  "circle": ["cx", "cy"],
  "ellipse": ["cx", "cy"],
  "image": ["x", "y"],
  "use": ["x", "y"],
  "svg": ["x", "y"],
  "pattern": ["x", "y"],
  "text": ["x", "y", "dx", "dy"],
  "tspan": ["dx", "dy"],
  "line": ["x1", "y1", "x2", "y2"],
  "foreignObject": ["x", "y"],
  "mask": [],
  "marker": ["refX", "refY"],
}

///|
fn ancestors_define(chain : Array[@xml.Element], attr : String) -> Bool {
  for a in chain {
    if a.attrs.contains(attr) {
      return true
    }
    if a.attrs.get("style") is Some(s) && s.contains(attr) {
      return true
    }
  }
  false
}

///|
/// Remove unknown elements and attributes, and attributes whose value equals
/// the element's default (when no ancestor overrides it).
let remove_unknowns_and_defaults : Plugin = {
  name: "removeUnknownsAndDefaults",
  description: "remove unknown elements/attributes and default attribute values",
  run: (doc, ctx) => {
    let tables = svg_tables()
    let mut changed = false
    // collect CSS text to detect attribute selectors that would make a
    // default-valued attribute meaningful
    let css = style_text(doc)
    let unknown_content = ctx.param_bool("unknownContent", true)
    let unknown_attrs = ctx.param_bool("unknownAttrs", true)
    let default_attrs = ctx.param_bool("defaultAttrs", true)
    let useless_overrides = ctx.param_bool("uselessOverrides", true)
    let keep_data_attrs = ctx.param_bool("keepDataAttrs", true)
    let keep_aria_attrs = ctx.param_bool("keepAriaAttrs", true)
    let keep_role_attr = ctx.param_bool("keepRoleAttr", false)
    // remove standalone="no" from the XML declaration
    for node in doc.children {
      match node {
        ProcInst("xml", v) => {
          let cleaned = remove_standalone_no(v)
          if cleaned != v {
            let idx = doc.children.search_by(n => n is ProcInst("xml", _))
            match idx {
              Some(i) => {
                doc.children[i] = ProcInst("xml", cleaned)
                changed = true
              }
              None => ()
            }
          }
        }
        _ => ()
      }
    }
    fn walk(e : @xml.Element, chain : Array[@xml.Element]) {
      // foreignObject holds arbitrary (non-SVG) content; leave it alone
      if e.name == "foreignObject" {
        return
      }
      // namespaced elements are not ours to judge
      if e.name.contains(":") {
        return
      }
      let parent = chain.last()
      // remove elements that are not allowed in their parent.
      // svgo's rule: if the parent has a non-empty allowed-children set,
      // only those children are kept; otherwise (empty or no set), only
      // unknown elements are removed.
      let parent_allowed = match parent {
        Some(p) => tables.element(p.name).map(t => t.allowed_children)
        None => None
      }
      let is_unknown = !tables.known_elements.contains(e.name)
      let not_allowed = match parent_allowed {
        Some(allowed) if allowed.length() > 0 => !allowed.contains(e.name)
        _ => is_unknown
      }
      if unknown_content && not_allowed {
        match parent {
          Some(p) => {
            let idx = p.children.search_by(c => {
              c is @xml.Element(x) && physical_equal(x, e)
            })
            match idx {
              Some(i) => {
                ignore(p.children.remove(i))
                changed = true
              }
              None => ()
            }
          }
          None => ()
        }
        return
      }
      let has_id = e.attrs.contains("id")
      let element_tables = tables.element(e.name)
      let allowed = element_tables.map(t => t.allowed_attrs)
      let defaults = element_tables.map(t => t.defaults)
      for kv in e.attrs.to_array() {
        let (k, v) = kv
        // always keep data-*, aria-*, xmlns and xmlns:*
        if (keep_data_attrs && k.has_prefix("data-")) ||
          (keep_aria_attrs && k.has_prefix("aria-")) ||
          (keep_role_attr && k == "role") ||
          k == "xmlns" ||
          k.has_prefix("xmlns:") {
          continue
        }
        // role is removed by default (keepRoleAttr = false)
        if k == "role" && !keep_role_attr {
          e.attrs.remove(k)
          changed = true
          continue
        }
        // version and baseProfile on  are noise
        if unknown_attrs &&
          e.name == "svg" &&
          (k == "version" || k == "baseProfile") {
          e.attrs.remove(k)
          changed = true
          continue
        }
        // remove unknown attributes; namespaced attrs other than xml:*/xlink:*
        // are always kept (they belong to other namespaces)
        let is_namespaced = k.contains(":")
        let is_xml_xlink = k.has_prefix("xml:") || k.has_prefix("xlink:")
        if unknown_attrs && (!is_namespaced || is_xml_xlink) {
          match allowed {
            Some(set) if !set.contains(k) => {
              e.attrs.remove(k)
              changed = true
              continue
            }
            _ => ()
          }
        }
        // remove attributes set to their default value, unless the element
        // has an id (it may be referenced), an ancestor overrides it, or a
        // CSS rule selects on this attribute
        let default_val = match defaults {
          Some(d) => d.get(k)
          None => None
        }
        let is_default = match default_val {
          Some(d) => d == v
          None =>
            match default_values.get(k) {
              Some(d) => d == v
              None => false
            }
        }
        if default_attrs && is_default && !has_id {
          let ancestor_sets = inheritable.contains(k) &&
            ancestors_define(chain, k)
          let css_selects = css.contains("[" + k + "]")
          if !ancestor_sets && !css_selects {
            e.attrs.remove(k)
            changed = true
            continue
          }
        }
        // useless override: an inheritable attr whose value equals the
        // inherited value from the nearest ancestor that sets it
        if useless_overrides &&
          !has_id &&
          inheritable.contains(k) &&
          !tables.presentation_non_inheritable.contains(k) {
          let mut inherited : String? = None
          let mut i = chain.length() - 1
          while i >= 0 {
            match chain[i].attrs.get(k) {
              Some(v) => {
                inherited = Some(v)
                break
              }
              None => i -= 1
            }
          }
          if inherited == Some(v) {
            e.attrs.remove(k)
            changed = true
            continue
          }
        }
      }
      // zero-valued geometry attributes default to 0
      match zero_defaults.get(e.name) {
        Some(list) if default_attrs =>
          for k in list {
            match e.attrs.get(k) {
              Some(v) =>
                match split_unit(v) {
                  Some((n, _)) if @num.round_to(n, ctx.precision) == 0.0 => {
                    // rx/ry default to each other on 
                    if (k == "rx" || k == "ry") && e.name == "rect" {
                      let other = if k == "rx" { "ry" } else { "rx" }
                      match e.attrs.get(other) {
                        Some(o) if !(split_unit(o) is Some((on, _)) &&
                          @num.round_to(on, ctx.precision) == 0.0) => continue
                        _ => ()
                      }
                    }
                    e.attrs.remove(k)
                    changed = true
                  }
                  _ => ()
                }
              None => ()
            }
          }
        _ => ()
      }
      chain.push(e)
      // iterate over a copy because unknown children are removed in place
      let kids = e.children[:].to_owned()
      for c in kids {
        if c is @xml.Element(child) {
          walk(child, chain)
        }
      }
      ignore(chain.pop())
    }
    if doc.root() is Some(root) {
      walk(root, [])
    }
    changed
  },
}

///|
/// Strip `standalone="no"` (single or double quotes) from an XML declaration.
fn remove_standalone_no(v : String) -> String {
  let mut s = v
  for q in ["\"", "'"] {
    let pat = "standalone=" + q + "no" + q
    s = s.replace(old=pat, new="")
  }
  // collapse any double spaces and trim trailing whitespace
  s.replace(old="  ", new=" ").trim().to_owned()
}

///|
/// Elements removeUselessStrokeAndFill inspects.
let stroke_and_fill_elements : Set[String] = Set([
  "path", "rect", "circle", "ellipse", "line", "polyline", "polygon", "g", "text",
])

///|
/// Drop stroke-* attributes when there is no stroke and fill-* when fill is none.
let remove_useless_stroke_and_fill : Plugin = {
  name: "removeUselessStrokeAndFill",
  description: "remove useless stroke and fill attributes",
  run: (doc, ctx) => {
    let mut changed = false
    // A stylesheet, script or event handler can restyle any element, so the
    // stroke/fill attributes are not provably useless.
    let mut deoptimized = false
    doc.each_element((e, _) => {
      if e.name == "style" ||
        e.name == "script" ||
        e.attrs.iter().any(kv => kv.0.has_prefix("on")) {
        deoptimized = true
      }
    })
    if deoptimized {
      return false
    }
    let remove_none = ctx.param_bool("removeNone", false)
    // elements with ids may be referenced by  under different inherited values
    let ids = referenced_ids(doc)
    fn walk(e : @xml.Element, chain : Array[@xml.Element]) {
      let shape = stroke_and_fill_elements.contains(e.name)
      // ...and so may anything below a referenced element or inside :
      // a  can put a stroke on it that is not visible here
      let referenced = (e.attrs.get("id") is Some(id) && ids.contains(id)) ||
        chain
        .iter()
        .any(a => {
          a.name == "defs" ||
          a.name == "symbol" ||
          (a.attrs.get("id") is Some(id) && ids.contains(id))
        })
      if shape && !referenced && e.name != "g" {
        let stroke = e.attrs.get("stroke")
        let stroke_width = e.attrs.get("stroke-width")
        let stroke_opacity = e.attrs.get("stroke-opacity")
        let stroke_is_none = stroke == Some("none")
        let stroke_invisible = stroke_width == Some("0") ||
          stroke_opacity == Some("0")
        let no_stroke = stroke_is_none || stroke_invisible
        let ancestor_stroke = ancestors_define(chain, "stroke")
        if ctx.param_bool("stroke", true) && no_stroke {
          let before = e.attrs.to_array()
          if stroke_invisible {
            // stroke is invisible because of zero width or opacity: keep it
            // that way even if an ancestor defines a visible stroke
            e.attrs.remove("stroke")
            if ancestor_stroke {
              e.attrs["stroke"] = "none"
            }
          } else if !ancestor_stroke {
            // stroke is explicitly "none" and no ancestor overrides it
            e.attrs.remove("stroke")
          } else {
            // stroke is "none" but an ancestor sets a visible stroke: keep
            // the override, moved to the end like svgo does
            e.attrs.remove("stroke")
            e.attrs["stroke"] = "none"
          }
          // drop all stroke-* presentation attributes
          for kv in e.attrs.to_array() {
            let (k, _) = kv
            if k.has_prefix("stroke-") {
              e.attrs.remove(k)
            }
          }
          if e.attrs.to_array() != before {
            changed = true
          }
        } else if ctx.param_bool("stroke", true) &&
          stroke is None &&
          !ancestor_stroke {
          // no stroke anywhere: stroke-* attributes are noise
          for kv in e.attrs.to_array() {
            let (k, _) = kv
            if k.has_prefix("stroke-") {
              e.attrs.remove(k)
              changed = true
            }
          }
        }
        let fill = match e.attrs.get("fill") {
          Some(v) => Some(v)
          None => inherited_attr(chain, "fill")
        }
        let fill_opacity = e.attrs.get("fill-opacity")
        if ctx.param_bool("fill", true) &&
          (fill == Some("none") || fill_opacity == Some("0")) {
          for kv in e.attrs.to_array() {
            let (k, _) = kv
            if k.has_prefix("fill-") {
              e.attrs.remove(k)
              changed = true
            }
          }
          if fill != Some("none") {
            e.attrs["fill"] = "none"
            changed = true
          }
        }
        if remove_none &&
          (
            stroke == Some("none") ||
            (stroke is None && !ancestor_stroke) ||
            no_stroke
          ) &&
          (fill == Some("none") || e.attrs.get("fill") == Some("none")) &&
          !has_animation_child(e) &&
          ![
            "style", "filter", "marker", "marker-start", "marker-mid", "marker-end",
          ]
          .iter()
          .any(k => e.attrs.contains(k) || ancestors_define(chain, k)) &&
          !ancestors_define(chain, "marker-end") &&
          !e.attrs.contains("marker-end") {
          if chain.last() is Some(parent) {
            parent.children.retain(n => {
              !(n is Element(child) && physical_equal(child, e))
            })
            changed = true
          }
          return
        }
      }
      chain.push(e)
      for c in e.children.copy() {
        if c is Element(child) {
          walk(child, chain)
        }
      }
      ignore(chain.pop())
    }
    if doc.root() is Some(root) {
      walk(root, [])
    }
    changed
  },
}

///|
/// SVG animation elements: they add attributes to their parent at runtime,
/// so a group containing one must be preserved.
let animation_elements : Set[String] = Set([
  "animate", "animateColor", "animateMotion", "animateTransform", "set",
])

///|
/// True when `e` or any descendant is an animation element whose
/// `attributeName` equals `name`.
fn has_animated_attr(e : @xml.Element, name : String) -> Bool {
  if animation_elements.contains(e.name) &&
    e.attrs.get("attributeName") == Some(name) {
    return true
  }
  for c in e.children {
    match c {
      Element(x) if has_animated_attr(x, name) => return true
      _ => ()
    }
  }
  false
}

///|
/// True when `e` or any descendant is an animation element.
fn has_animation_child(e : @xml.Element) -> Bool {
  for c in e.children {
    match c {
      Element(x) =>
        if animation_elements.contains(x.name) || has_animation_child(x) {
          return true
        }
      _ => ()
    }
  }
  false
}

///|
/// Extract the value of a CSS property from an inline `style` attribute
/// ("a:b; filter:url(#x)"). Returns None if absent.
fn style_prop(style : String, prop : String) -> String? {
  for decl in style.split(";") {
    let kv = decl.split(":").to_array()
    if kv.length() == 2 && kv[0].trim() == prop {
      return Some(kv[1].trim().to_owned())
    }
  }
  None
}

///|
/// True when the element has a `filter` either as an attribute or inside its
/// `style` attribute.
fn has_filter(e : @xml.Element) -> Bool {
  if e.attrs.contains("filter") {
    return true
  }
  match e.attrs.get("style") {
    Some(s) => style_prop(s, "filter") is Some(_)
    None => false
  }
}

///|
/// Unwrap groups that carry nothing, and move attributes of single-child
/// groups onto the child.
let collapse_groups : Plugin = {
  name: "collapseGroups",
  description: "collapse useless groups",
  run: (doc, _) => {
    let mut changed = false
    doc.each_element_post((g, parent) => {
      guard g.name == "g" && parent is Some(p) && p.name != "switch" else {
        return
      }
      // svgo only collapses non-empty groups; empty containers are handled
      // by removeEmptyContainers.
      guard g.children.length() > 0 else { return }
      let elems = g.elements()
      // move attributes onto a single child element when that is unambiguous
      if elems.length() == 1 && g.children.length() == 1 && g.attrs.length() > 0 {
        let child = elems[0]
        let group_has_filter = has_filter(g)
        let group_has_clip_mask = g.attrs.contains("clip-path") ||
          g.attrs.contains("mask")
        // conditions under which moving attrs to the child is safe:
        //  - child has no id (it would be wrong to rename a referenced id)
        //  - group has no filter (filters apply to the group's subtree)
        //  - not both group and child carry a class (would merge class lists)
        //  - if the group has clip-path/mask, the child must be a  and
        //    neither may have a transform (clip/mask coords are tricky)
        if child.attrs.contains("id") ||
          group_has_filter ||
          (g.attrs.contains("class") && child.attrs.contains("class")) ||
          (
            group_has_clip_mask &&
            !(child.name == "g" &&
            !g.attrs.contains("transform") &&
            !child.attrs.contains("transform"))
          ) {
          // fall through to the no-attrs collapse check below
        } else {
          let mut ok = true
          for k, v in g.attrs {
            // an animated attribute on the child must not be overridden
            if has_animated_attr(child, k) {
              ok = false
              break
            }
            match child.attrs.get(k) {
              None => () // will be copied from the group
              Some(cv) =>
                if k == "transform" {
                  // transforms compose: group's transform applies first
                  ()
                } else if cv == "inherit" {
                  // inherit resolves to the group's value
                  ()
                } else if !inheritable.contains(k) && cv != v {
                  // non-inheritable attr with a different value: cannot move
                  ok = false
                  break
                } else {
                  // inheritable or equal value: child's value wins, group's
                  // copy is redundant
                  ()
                }
            }
          }
          if ok {
            for k, v in g.attrs {
              match child.attrs.get(k) {
                None => child.attrs[k] = v
                Some(cv) =>
                  if k == "transform" {
                    child.attrs[k] = v + " " + cv
                  } else if cv == "inherit" {
                    child.attrs[k] = v
                  }
                // else keep child's value
              }
            }
            g.attrs.clear()
            changed = true
          }
        }
      }
      // collapse groups that now (or originally) have no attributes, unless
      // they contain an animation element that targets one of their attrs
      if g.attrs.length() == 0 && !has_animation_child(g) {
        let idx = p.children.search_by(c => {
          c is Element(x) && physical_equal(x, g)
        })
        match idx {
          Some(i) => {
            ignore(p.children.remove(i))
            for j, c in g.children {
              p.children.insert(i + j, c)
            }
            changed = true
          }
          None => ()
        }
      }
    })
    changed
  },
}

///|
/// Convert basic shapes into paths when the path is not longer.
let convert_shape_to_path : Plugin = {
  name: "convertShapeToPath",
  description: "convert rect, line, polyline and polygon to path",
  run: (doc, ctx) => {
    let mut changed = false
    let p = ctx.param_int("floatPrecision", ctx.precision)
    let num = fn(v : Double) -> String { @num.format_number(v, p) }
    doc.each_element((e, _) => {
      let d : String? = match e.name {
        "rect" if !e.attrs.contains("rx") && !e.attrs.contains("ry") => {
          let x = attr_num(e, "x", 0.0)
          let y = attr_num(e, "y", 0.0)
          let w = attr_num(e, "width", -1.0)
          let h = attr_num(e, "height", -1.0)
          guard w > 0.0 &&
            h > 0.0 &&
            attr_is_plain(e, "x") &&
            attr_is_plain(e, "y") &&
            attr_is_plain(e, "width") &&
            attr_is_plain(e, "height") else {
            None
          }
          Some("M\{num(x)} \{num(y)}H\{num(x + w)}V\{num(y + h)}H\{num(x)}z")
        }
        "circle" | "ellipse" if ctx.param_bool("convertArcs", false) => {
          let cx = attr_num(e, "cx", 0.0)
          let cy = attr_num(e, "cy", 0.0)
          let rx = attr_num(e, if e.name == "circle" { "r" } else { "rx" }, 0.0)
          let ry = if e.name == "circle" { rx } else { attr_num(e, "ry", 0.0) }
          guard rx > 0.0 &&
            ry > 0.0 &&
            ["cx", "cy", "r", "rx", "ry"].iter().all(k => attr_is_plain(e, k)) else {
            None
          }
          Some(
            @path.stringify(
              [
                { cmd: 'M', args: [cx, cy - ry], },
                { cmd: 'A', args: [rx, ry, 0.0, 1.0, 0.0, cx, cy + ry], },
                { cmd: 'A', args: [rx, ry, 0.0, 1.0, 0.0, cx, cy - ry], },
                { cmd: 'z', args: [], },
              ],
              precision=p,
            ),
          )
        }
        "line" => {
          let x1 = attr_num(e, "x1", 0.0)
          let y1 = attr_num(e, "y1", 0.0)
          let x2 = attr_num(e, "x2", 0.0)
          let y2 = attr_num(e, "y2", 0.0)
          guard attr_is_plain(e, "x1") &&
            attr_is_plain(e, "y1") &&
            attr_is_plain(e, "x2") &&
            attr_is_plain(e, "y2") else {
            None
          }
          Some("M\{num(x1)} \{num(y1)} \{num(x2)} \{num(y2)}")
        }
        "polyline" | "polygon" =>
          match e.attrs.get("points") {
            Some(points) =>
              match parse_points(points) {
                Some(nums) =>
                  if nums.length() >= 4 && nums.length() % 2 == 0 {
                    let cmds : Array[@path.Segment] = []
                    cmds.push({ cmd: 'M', args: [nums[0], nums[1]], })
                    for i in 1..<(nums.length() / 2) {
                      cmds.push({
                        cmd: 'L',
                        args: [nums[i * 2], nums[i * 2 + 1]],
                      })
                    }
                    if e.name == "polygon" {
                      cmds.push({ cmd: 'z', args: [], })
                    }
                    Some(@path.stringify(cmds, precision=p))
                  } else {
                    None
                  }
                None => None
              }
            None => None
          }
        _ => None
      }
      match d {
        Some(d) => {
          for
            k in [
              "x", "y", "x1", "y1", "x2", "y2", "width", "height", "points", "cx",
              "cy", "r", "rx", "ry",
            ] {
            e.attrs.remove(k)
          }
          e.attrs["d"] = d
          e.name = "path"
          changed = true
        }
        None => ()
      }
    })
    // polyline/polygon with fewer than two points (or no points) draw nothing
    if remove_elements(doc, is_empty_poly) {
      changed = true
    }
    changed
  },
}

///|
/// True for a polyline/polygon that has fewer than two points (or none),
/// so it cannot draw anything.
fn is_empty_poly(e : @xml.Element, _ : @xml.Element?) -> Bool {
  if e.name != "polyline" && e.name != "polygon" {
    return false
  }
  match e.attrs.get("points") {
    Some(points) =>
      match parse_points(points) {
        Some(nums) => nums.length() < 4
        // unparsable points: a renderer draws what it can, keep the element
        None => false
      }
    None => true
  }
}

///|
/// Parse a `points` attribute into a flat array of numbers. Returns `None`
/// if any value is not a plain number; an odd count is the caller's problem.
/// Numbers may be separated by whitespace, commas, or a sign character that
/// follows a digit.
fn parse_points(points : String) -> Array[Double]? {
  let nums : Array[Double] = []
  let mut i = 0
  let n = points.length()
  while i < n {
    // skip separators: space, comma, tab, newline
    while i < n {
      let c = points.get_char(i).unwrap()
      if c == ' ' || c == ',' || c == '\t' || c == '\n' || c == '\r' {
        i += 1
      } else {
        break
      }
    }
    if i >= n {
      break
    }
    // a sign starts a new number only at the beginning or after a separator;
    // after a digit, a '-' or '+' begins the next number
    let start = i
    // optional sign
    if points.get_char(i).unwrap() == '-' || points.get_char(i).unwrap() == '+' {
      i += 1
    }
    let mut has_digit = false
    let mut has_dot = false
    while i < n {
      let c = points.get_char(i).unwrap()
      if c.is_ascii_digit() {
        has_digit = true
        i += 1
      } else if c == '.' && !has_dot {
        has_dot = true
        i += 1
      } else {
        break
      }
    }
    // optional exponent
    if i < n &&
      (points.get_char(i).unwrap() == 'e' || points.get_char(i).unwrap() == 'E') {
      i += 1
      if i < n &&
        (
          points.get_char(i).unwrap() == '+' ||
          points.get_char(i).unwrap() == '-'
        ) {
        i += 1
      }
      while i < n && points.get_char(i).unwrap().is_ascii_digit() {
        i += 1
      }
    }
    if !has_digit {
      return None
    }
    let token = points[start:i].to_owned()
    match split_unit(token) {
      Some((num, "")) => nums.push(num)
      _ => return None
    }
  }
  Some(nums)
}

///|
fn attr_num(e : @xml.Element, name : String, default : Double) -> Double {
  match e.attrs.get(name) {
    Some(v) =>
      match split_unit(v) {
        Some((n, _)) => n
        None => default
      }
    None => default
  }
}

///|
/// True when the attribute is absent or a unitless number (no %, em, ...).
fn attr_is_plain(e : @xml.Element, name : String) -> Bool {
  match e.attrs.get(name) {
    None => true
    Some(v) =>
      match split_unit(v) {
        Some((_, "")) | Some((_, "px")) => true
        _ => false
      }
  }
}

///|
/// `` with `rx == ry` (or one radius `auto`) is a ``.
let convert_ellipse_to_circle : Plugin = {
  name: "convertEllipseToCircle",
  description: "convert ellipses with equal radii to circles",
  run: (doc, _) => {
    let mut changed = false
    doc.each_element((e, _) => {
      if e.name == "ellipse" {
        let rx = e.attrs.get("rx").unwrap_or("auto")
        let ry = e.attrs.get("ry").unwrap_or("auto")
        if rx == ry || rx == "auto" || ry == "auto" {
          let r = if rx == "auto" && ry == "auto" {
            "0"
          } else if rx == "auto" {
            ry
          } else {
            rx
          }
          e.name = "circle"
          e.attrs.remove("rx")
          e.attrs.remove("ry")
          e.attrs["r"] = r
          changed = true
        }
      }
    })
    changed
  },
}

///|
/// Optimize the `d` attribute of every path.
let convert_path_data : Plugin = {
  name: "convertPathData",
  description: "optimize path data",
  run: (doc, ctx) => {
    let mut changed = false
    // floatPrecision overrides the global precision for this plugin.
    let precision = ctx.param_int("floatPrecision", ctx.precision)
    // makeArcs: convert runs of cubic beziers approximating a circular arc
    // into `A` commands. Defaults to { threshold: 2.5, tolerance: 0.5 };
    // `makeArcs: false` disables it.
    let (make_arcs, ma_threshold, ma_tolerance) = match ctx.param("makeArcs") {
      Some(False) => (false, 2.5, 0.5)
      Some(Object(obj)) => {
        let threshold = match obj.get("threshold") {
          Some(Number(n, ..)) => n
          _ => 2.5
        }
        let tolerance = match obj.get("tolerance") {
          Some(Number(n, ..)) => n
          _ => 0.5
        }
        (true, threshold, tolerance)
      }
      _ => (true, 2.5, 0.5)
    }
    // applyTransforms: bake an element's transform into its path data when
    // it is safe to do so (see the walk below)
    let apply_transforms = ctx.param_bool("applyTransforms", true)
    let apply_stroked = ctx.param_bool("applyTransformsStroked", true)
    let options = {
      ..@path.Options::default(),
      precision,
      make_arcs,
      make_arcs_threshold: ma_threshold,
      make_arcs_tolerance: ma_tolerance,
    }
    // Build class -> property maps from