---

- name: capital-letter-as-big
  tag: mi
  match: "string-length(.)=1 and contains('ABCDEFGHIJKLMNOPQRSTUVWXYZ', text()) and ancestor::*[self::m:large-op]"
  replace:
  - x: "translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')"
  - t: "большое"

- name: leading-negative-plus
  tag: mrow
  match:
  - "count(*)=3 and *[2][.='+'] and"
  - "(*[1][self::m:minus] or"
  - " *[1][self::m:mrow[IsBracketed(., '(', ')') and .//m:minus]])"
  replace:
  - x: "*[1]"
  - pause: short
  - x: "*[2]"
  - x: "*[3]"

# number-sets are a little messy in that the base was converted to a number-set, so we have to match that (simple) case last
- name: pos-neg-number-sets
  tag: number-sets
  match: "count(*)=2 and *[2][.='+' or .='-']"
  replace:
  - bookmark: "*[2]/@id"
  - test:
    - if: "*[2][.='+']"
      then: [t: "положительные"]      # phrase(set of all 'positive' integers less than 10)
      else: [t: "отрицательные"]      # phrase(set of all 'negative' integers less than minus 10)
  - bookmark: "*[1]/@id"
  - test:
    - if: "*[1][.='ℂ']"
      then: [t: "комплексные числа"]      # phrase('complex numbers' consist of two parts)
    - else_if: "*[1][.='ℕ']"
      then: [t: "натуральные числа"]      # phrase('natural numbers' are numbers from 1 to infinity)
    - else_if: "*[1][.='ℚ']"
      then: [t: "рациональные числа"]      # phrase('rational numbers' are the fraction of 2 integers)
    - else_if: "*[1][.='ℝ']"
      then: [t: "действительные числа"]      # phrase('real numbers' can be both positive and negative)
    - else_if: "*[1][.='ℤ']"
      then: [t: "целые числа"]      # phrase(positive 'integers' are natural numbers above 0)
      else: [x: "*[1][text()]"] # shouldn't happen

- name: dimension-number-sets

  # should be single digit integer at this point (e.g, R^3)
  tag: number-sets
  match: "count(*)=2"
  replace:
  - bookmark: "*[1]/@id"
  - test:
    - if: "*[1][.='ℂ']"
      then: [t: "цэ"]      # phrase(the letter 'C' used to represent complex number)
    - else_if: "*[1][.='ℕ']"
      then: [t: "эн"]      # phrase(the letter 'N' may represent natural numbers)
    - else_if: "*[1][.='ℚ']"
      then: [t: "ку"]      # phrase(the letter 'Q' may represent rational numbers)
    - else_if: "*[1][.='ℝ']"
      then: [t: "эр"]      # phrase(the letter 'R' may represent real numbers)
    - else_if: "*[1][.='ℤ']"
      then:
      - test:
          if: "$SpeechStyle='ClearSpeak'"
          then: [t: "зэт"]
          else: [t: "зэт"]
      else: [x: "*[1][text()]"] # shouldn't happen
  - bookmark: "*[2]/@id"
  - x: "*[2]"

- name: simple-number-sets
  tag: number-sets
  match: "count(*)=0"
  replace:
  - bookmark: "@id"
  - test:
    - if: ".='ℂ'"
      then: [t: "комплексные числа"]      # phrase('the complex numbers' include 2 parts)
    - else_if: ".='ℕ'"
      then: [t: "натуральные числа"]      # phrase('the natural numbers' begin at 1)
    - else_if: ".='ℚ'"
      then: [t: "рациональные числа"]      # phrase('the rational numbers' are the fraction of 2 integers)
    - else_if: ".='ℝ'"
      then: [t: "действительные числа"]      # phrase('the real numbers' can be both positive and negative)
    - else_if: ".='ℤ'"
      then: [t: "целые числа"]      # phrase('the integers' are natural numbers above 0)
      else: [x: "text()"] # shouldn't happen

- name: real-part
  tag: real-part
  match: "."
  replace:
  - bookmark: "@id"
  - t: "действительная часть"      # phrase('the real part' of a complex number does not include the imaginary part)

- name: imaginary-part
  tag: imaginary-part
  match: "."
  replace:
  - bookmark: "@id"
  - t: "комплексная часть"      # phrase('the imaginary part' is part of a complex number)

# rules on scripted vertical bars ('evaluated at')
- name: evaluated-at-2
  tag: evaluate
  match: "count(*)=2"
  replace:
  - x: "*[1]"
  - pause: auto
  - t: "вычисленное при"      # phrase(results were 'evaluated at' a given point)
  - pause: auto
  - x: "*[2]"

- name: evaluated-at-3
  tag: evaluate
  match: "count(*)=3"
  replace:
  - x: "*[1]"
  - pause: short
  - t: "вычисленное при"      # phrase(results were 'evaluated at' this point)
  - pause: auto
  - x: "*[3]"
  - t: "минус то же выражение, вычисленное при"      # phrase(this result is 'minus the same expression evaluated at' an earlier point)
  - x: "*[2]"

- name: limit
  tag: limit
  match: "count(*)=1 and following-sibling::*"
  replace:
  - t: "предел при"
  - x: "*[1]"
  - pause: short
  - t: "от"
  - test:
      if: "following-sibling::*[1][self::*[name()='fraction' or name()='mfrac'] or .//*[name()='fraction' or name()='mfrac']]"
      then_test:
        if: "$Impairment='LearningDisability'"
        then: [pause: medium]
        else: [pause: short]

- name: limit
  tag: limit
  match: "count(*)=2"
  replace:
  - t: "предел при"
  - x: "*[1]"
  - pause: short
  - t: "от"
  - test:
      if: "$Impairment='LearningDisability'"
      then: [pause: medium]
      else: [pause: short]
  - x: "*[2]"

- name: binomial
  tag: binomial
  match: "count(*)=2"
  replace:
  - t: "число сочетаний из"
  - test:
      if: "*[1][self::m:mrow and count(*)=3 and *[1][self::m:mi[.='n' or .='k']] and *[2][.='+'] and *[3][self::m:mn]]"
      then:
      - test:
        - if: "*[1]/*[1][.='n']"
          then: [t: "эн"]
        - else: [t: "ка"]
      - x: "*[1]/*[2]"
      - x: "*[1]/*[3]"
      else: [x: "*[1]"]
  - t: "по"
  - test:
      if: "*[2][self::m:mrow and count(*)=3 and *[1][self::m:mi[.='n' or .='k']] and *[2][.='+'] and *[3][self::m:mn]]"
      then:
      - test:
        - if: "*[2]/*[1][.='n']"
          then: [t: "эн"]
        - else: [t: "ка"]
      - x: "*[2]/*[2]"
      - x: "*[2]/*[3]"
      else: [x: "*[2]"]
  - test:
      if: "not(IsNode(*[2], 'simple'))"
      then: [t: "конец числа сочетаний"]

- name: permutation
  # Not a default because the order of the args is reversed
  tag: pochhammer
  match: "count(*)=2 and contains(@data-intent-property, ':infix:')"
  replace:
  - t: "число размещений из"
  - x: "*[1]"
  - t: "по"
  - x: "*[2]"

- name: numeric-half-open-interval
  tag: closed-open-interval
  match: "count(*)=2 and *[1][self::m:mn] and *[2][.//m:mi[.='π'] or .='π']"
  replace:
  - t: "полуинтервал"
  - t: "от"
  - x: "*[1]"
  - t: "до"
  - x: "*[2]"

- name: intervals
  tag: [open-interval, open-closed-interval, closed-interval, closed-open-interval]
  match: "count(*)=2"
  replace:
  - test:
    - if: "name(.)='open-interval'"
      then: [t: "открытый интервал"]
    - else_if: "name(.)='closed-interval'"
      then: [t: "закрытый интервал"]
    - else_if: "name(.)='open-closed-interval'"
      then: [t: "открыто-закрытый интервал"]
      else: [t: "закрыто-открытый интервал"]
  - t: "от"
  - test:
      if: "*[1][self::m:minus and count(*)=1 and *[1][.='∞']]"
      then: [t: "минус бесконечности"]
      else: [x: "*[1]"]
  - t: "до"
  - test:
    - if: "*[2][self::m:plus and count(*)=1 and *[1][.='∞']]"
      then: [t: "плюс бесконечности"]
    - else_if: "*[2][.='∞']"
      then: [t: "бесконечности"]
      else: [x: "*[2]"]

- name: default-point
  tag: point
  match: "count(*)=2"
  replace:
  - test:
      if: "$Verbosity!='Terse'"
      then:
      - t: "а"      # phrase('the' square root of 25 equals 5)
  - t: "точка"      # phrase(a decimal 'point' indicates the fraction component of a number)
  - x: "*[1]"
  - t: "запятую"      # phrase(use a 'comma' to divide large numbers or as a decimal point)
  - x: "*[2]"

- name: bigop-both
  tag: large-op
  match: "count(*) = 3"
  replace:
  - x: "*[1]"
  - t: "от"      # phrase(subtracting 5 'from' 10 gives 5)
  - x: "*[2]"
  - t: "до"      # phrase(adding 6 'to' 6 equals  12)
  - x: "*[3]"
  - test:
      if: "following-sibling::*"
      then:
      - t: "от"      # phrase(the square root 'of' 25 equals 5)
      - test:
        - if: "*[1][.='∫']"
          then: [pause: short]
        - else_if: "following-sibling::*[1][self::m:indexed-by or self::m:msub]"
          then: [pause: medium]

- name: bigop-under
  tag: large-op
  match: "count(*)=2"
  replace:
  - x: "*[1]"
  - t: "по"      # phrase(2 'over' 3 equals two thirds)
  - test:
      if: "*[1][.='∫'] and *[2][.='ℝ']"
      then: [t: "действительным числам"]
      else: [x: "*[2]"]
  - test:
      if: "following-sibling::*"
      then:
      - t: "от"      # phrase(the square root 'of' 25 equals 5)
      - test:
        - if: "*[1][.='∫']"
          then: [pause: medium]
        - else_if: "following-sibling::*[1][self::m:indexed-by or self::m:msub]"
          then: [pause: short]
        - else_if: "following-sibling::*[1][self::m:fraction or self::m:mfrac]"
          then: [pause: medium]

- name: integral-with-separated-differential
  tag: mrow
  match:
  - "count(*)=5 and *[1][self::m:mrow[m:large-op]] and"
  - "*[2][.='⁢'] and *[3][self::m:mi[.='d']] and *[4][.='⁢']"
  replace:
  - x: "*[1]"
  - pause: medium
  - x: "*[3]"
  - x: "*[5]"

- name: largeop
  tag: mrow
  match: "count(*)=2 and IsInDefinition(*[1], 'LargeOperators')"
  replace:
  - x: "*[1]"
  - test:
      if: "*[1][.='∫']"
      then: [t: "от"]      # phrase(the square root 'of' 25 equals 5)
  - x: "*[2]"

- name: repeating-decimal
  tag: repeating-decimal
  match: "."
  replace:
  - x: "*[1]"
  - t: "с повторяющимися цифрами"      # phrase('with repeating digits')
  - spell: "*[2]"

- name: msubsup-skip-super
  # handles single, double, etc., prime
  tag: [skip-super, say-super]
  match: "count(*)=3"
  replace:
  - x: "*[1]"
  - test:
      if: "$Verbosity='Verbose'"
      then: [t: "нижний индекс"]      # phrase(a 'subscript' may be used to indicate an index)
      else: [t: "нижний индекс"]      # phrase(the result is 'sub' optimal)
  - x: "*[2]"
  - test:
      if: "not(IsNode(*[2],'leaf') and $Impairment = 'Blindness')"
      then:
      - test:
          if: "$Verbosity='Verbose'"
          then: [t: "конец нижнего индекса"]      # phrase(this is the 'end subscript' position)
          else: [t: "конец нижнего индекса"]      # phrase(this is the 'end sub' position)
      - pause: short
      else_test:
          if: "*[2][self::m:mi]"   # need a pause in "x sub k prime" so the prime is not associated with the 'k'
          then: [pause: short]
  - test:
      if: "name(.)='say-super'"
      then_test:
        if: "$Verbosity='Verbose'"
        then: [t: "верхний индекс"]      # phrase(a 'superscript' number indicates raised to a power)
        else: [t: "верхний индекс"]      # phrase(this is a 'super' set of numbers)
  - x: "*[3]"
  - pause: short


# the order of matching is
# 1. does it match the base of an SI unit
# 2. does it match an English unit (if in an English language)
# 3. does it match an SI prefix followed by an SI that accepts SI prefixes
# Due to this order, some things like "ft" and "cd" mean "feet" vs "femto-tonnes" and "pints" vs "pico-tonnes"
- name: unit
  tag: unit
  match: "$Verbosity != 'Terse' and contains(@data-intent-property, ':unit')"
  variables:
    # we need to look at preceding-sibling::*[2] because invisible times should have been added
    # if in a fraction, only count if we are in the numerator
  - IsSingular: "(parent::m:mrow and preceding-sibling::*[2][self::m:mn and . = 1]) or  
                 (ancestor::*[2][self::m:mrow] and parent::m:fraction and
                  (preceding-sibling::* or parent::*[preceding-sibling::*[2][self::m:mn and . = 1]])
                 )"
  - Prefix: "''"
  - Word: "''"  
  replace:
  - bookmark: "@id"
  - test:
    # is the whole string match a SI Unit without a prefix?
    - if: "DefinitionValue(., 'Speech', 'SIUnits') != ''"
      then:
      - set_variables: [Word: "DefinitionValue(., 'Speech', 'SIUnits')"]
    - else_if: "DefinitionValue(., 'Speech', 'UnitsWithoutPrefixes') != ''"
      then:
      - set_variables: [Word: "DefinitionValue(., 'Speech', 'UnitsWithoutPrefixes')"]
    - else_if: "DefinitionValue(., 'Speech', 'EnglishUnits') != ''"
      then:
      - set_variables: [Word: "DefinitionValue(., 'Speech', 'EnglishUnits')"]

    # do the first two chars match "da" and the remainder match an SIUnit
    - else_if: "string-length(.) >= 3 and 
                substring(., 1, 2) = 'da' and
                DefinitionValue(substring(., 3), 'Speech', 'SIUnits') != ''"
      then:
      - set_variables:
        - Prefix: "DefinitionValue('da', 'Speech', 'SIPrefixes')"
        - Word: "DefinitionValue(substring(., 3), 'Speech', 'SIUnits')"

    # does the first char match a prefix and the remainder match an SIUnit
    - else_if: "string-length(.) >= 2 and 
                DefinitionValue(substring(., 1, 1), 'Speech', 'SIPrefixes') != ''  and
                DefinitionValue(substring(., 2), 'Speech', 'SIUnits') != ''"
      then:
      - set_variables:
        - Prefix: "DefinitionValue(substring(., 1, 1), 'Speech', 'SIPrefixes')"
        - Word: "DefinitionValue(substring(., 2), 'Speech', 'SIUnits')"

    # not a known unit -- just speak the text, possibly as a plural
    - else:
      - set_variables:
        - Word: "text()"

  # somewhat complicated logic to avoid spaces around "-" as in "centi-grams" vs "centi - grams" -- probably doesn't matter
  - test:
      if: "$Prefix = ''"
      then:
      - test:
        - if: "$IsSingular"
          # HACK: '\uF8FE' is used internally for the concatenation char by 'ct' -- this gets the prefix concatenated to the base
          then: [x: "$Word"]
        - else_if: "DefinitionValue($Word, 'Speech', 'PluralForms') != ''"
          then: [x: "DefinitionValue($Word, 'Speech', 'PluralForms')"]
          else: [x: "$Word", ct: "с"]
      else:
      - x: "$Prefix"
      - ct: "-"
      - test:
        - if: "$IsSingular"
          # HACK: '\uF8FE' is used internally for the concatenation char by 'ct' -- this gets the prefix concatenated to the base
          then: [x: "concat('\uF8FE', $Word)"]
        - else_if: "$Word='грамм' and not(preceding-sibling::*[1][self::m:mn])"
          then: [x: "concat('\uF8FE', 'граммы')"]
        - else_if: "DefinitionValue($Word, 'Speech', 'PluralForms') != ''"
          then: [x: "concat('\uF8FE', DefinitionValue($Word, 'Speech', 'PluralForms'))"]
          else: [x: "concat('\uF8FE', $Word)", ct: "с"]
    
- name: sin
  tag: mi
  match: ".='sin'"
  replace:
  - bookmark: "@id"
  - t: "синус"      # phrase(the 'sine' of the angle)
- name: cos
  tag: mi
  match: ".='cos'"
  replace:
  - bookmark: "@id"
  - test:
      if: "$Verbosity='Terse'"
      then: [t: "кос"]      # phrase('cos' is the abbreviation for cosine)
      else: [t: "косинус"]      # phrase(find the 'cosine' in a right-angle triangle)
- name: tan
  tag: mi
  match: ".='tan' or .='tg'"
  replace:
  - bookmark: "@id"
  - t: "тангенс"
- name: sec
  tag: mi
  match: ".='sec'"
  replace:
  - bookmark: "@id"
  - t: "секанс"
- name: csc
  tag: mi
  match: ".='csc'"
  replace:
  - bookmark: "@id"
  - t: "косеканс"
- name: cot
  tag: mi
  match: ".='cot'"
  replace:
  - bookmark: "@id"
  - test:
      if: "$Verbosity='Terse'"
      then: [t: "котангенс"]      # phrase(find the 'cotangent' in a right-angle triangle)
      else: [t: "котангенс"]      # phrase(the 'cotangent' is the reciprocal of the tangent)

- name: sinh
  tag: mi
  match: ".='sinh'"
  replace:
  - bookmark: "@id"
  - test:
      if: "$Verbosity='Terse'"
      then: [t: "синч"]      # phrase(the word 'sinch' is an abbreviation for hyperbolic sine)
      else: [t: "гиперболический синус"]      # phrase(the 'hyperbolic sine' is used in mathematics)
- name: cosh
  tag: mi
  match: ".='cosh'"
  replace:
  - bookmark: "@id"
  - test:
      if: "$Verbosity='Terse'"
      then: [t: "гиперболический косинус"]      # phrase('cosh' is an abbreviation of hyperbolic cosine)
      else: [t: "гиперболический косинус"]      # phrase(the 'hyperbolic cosine' is a mathematical function)
- name: tanh
  tag: mi
  match: ".='tanh'"
  replace:
  - bookmark: "@id"
  - test:
      if: "$Verbosity='Terse'"
      then: [t: "танч"]      # phrase('tanch' is shorthand for hyperbolic tangent)
      else: [t: "гиперболический тангенс"]      # phrase('hyperbolic tangent' is a mathematical function)
- name: sech
  tag: mi
  match: ".='sech'"
  replace:
  - bookmark: "@id"
  - test:
      if: "$Verbosity='Terse'"
      then: [t: "шек"]      # phrase('sheck' is shorthand for hyperbolic secant)
      else: [t: "гиперболический секанс"]      # phrase('hyperbolic secant' is a mathematical function)
- name: csch
  tag: mi
  match: ".='csch'"
  replace:
  - bookmark: "@id"
  - test:
      if: "$Verbosity='Terse'"
      then: [t: "гиперболический косеканс"]      # phrase('cosheck' is shorthand for hyperbolic cosecant)
      else: [t: "гиперболический косеканс"]      # phrase('hyperbolic cosecant' is a mathematical function)
- name: coth
  tag: mi
  match: ".='coth'"
  replace:
  - bookmark: "@id"
  - test:
      if: "$Verbosity='Terse'"
      then: [t: "гиперболический котангенс"]      # phrase('cotanch' is shorthand for hyperbolic cotangent)
      else: [t: "гиперболический котангенс"]      # phrase(the 'hyperbolic cotangent' is a mathematical function)

- name: trig-name-sequence-canonical
  tag: mrow
  match:
  - "count(*)=11 and *[1]/*[1][.='sin'] and *[3]/*[1][.='cos'] and *[5]/*[1][.='tan'] and "
  - "*[7]/*[1][.='sec'] and *[9]/*[1][.='csc'] and *[11]/*[1][.='cot']"
  replace:
  - x: "*[1]"
  - x: "*[2]"
  - x: "*[3]"
  - x: "*[4]"
  - x: "*[5]"
  - x: "*[6]"
  - x: "*[7]"
  - pause: short
  - x: "*[8]"
  - x: "*[9]"
  - pause: short
  - x: "*[10]"
  - x: "*[11]"

- name: hyperbolic-trig-name-sequence-canonical
  tag: mrow
  match:
  - "count(*)=11 and *[1]/*[1][.='sinh'] and *[3]/*[1][.='cosh'] and *[5]/*[1][.='tanh'] and "
  - "*[7]/*[1][.='sech'] and *[9]/*[1][.='csch'] and *[11]/*[1][.='coth']"
  replace:
  - x: "*[1]"
  - pause: short
  - x: "*[2]"
  - x: "*[3]"
  - pause: short
  - x: "*[4]"
  - x: "*[5]"
  - pause: short
  - x: "*[6]"
  - x: "*[7]"
  - pause: short
  - x: "*[8]"
  - x: "*[9]"
  - pause: short
  - x: "*[10]"
  - x: "*[11]"

- name: trig-name-sequence
  tag: mrow
  match:
  - "count(*)=23 and *[1][.='sin'] and *[5][.='cos'] and *[9][.='tan'] and "
  - "*[13][.='sec'] and *[17][.='csc'] and *[21][.='cot']"
  replace:
  - x: "*[1]"
  - x: "*[3]"
  - x: "*[4]"
  - x: "*[5]"
  - x: "*[7]"
  - x: "*[8]"
  - x: "*[9]"
  - x: "*[11]"
  - x: "*[12]"
  - x: "*[13]"
  - x: "*[15]"
  - pause: short
  - x: "*[16]"
  - x: "*[17]"
  - x: "*[19]"
  - pause: short
  - x: "*[20]"
  - x: "*[21]"
  - x: "*[23]"

- name: trig-name-sequence-no-apply
  tag: mrow
  match:
  - "count(*)=17 and *[1][.='sin'] and *[4][.='cos'] and *[7][.='tan'] and "
  - "*[10][.='sec'] and *[13][.='csc'] and *[16][.='cot']"
  replace:
  - x: "*[1]"
  - x: "*[2]"
  - x: "*[3]"
  - x: "*[4]"
  - x: "*[5]"
  - x: "*[6]"
  - x: "*[7]"
  - x: "*[8]"
  - x: "*[9]"
  - x: "*[10]"
  - x: "*[11]"
  - pause: short
  - x: "*[12]"
  - x: "*[13]"
  - x: "*[14]"
  - pause: short
  - x: "*[15]"
  - x: "*[16]"
  - x: "*[17]"
- name: exponential
  tag: mi
  match: ".='exp'"
  replace:
  - bookmark: "@id"
  - test:
      if: "$Verbosity='Terse'"
      then: [t: "эксп"]      # phrase('exp' means exponential function)
      else: [t: "экспонента"]      # phrase('exponential' function)
- name: covariance
  tag: mi
  match: ".='Cov'"
  replace:
  - bookmark: "@id"
  - test:
      if: "$Verbosity='Terse'"
      then: [t: "ков"]      # phrase('Cov' is shorthand for the covariance function)
      else: [t: "ковариация"]      # phrase('covariance' function)

-
  name: log    # handle both log and ln (if in an mrow, 'intents' are used)
  tag: mi
  match: ".='log' or .='ln'"
  replace:
  - bookmark: "@id"
  - test:
    - if: ".= 'log'"
      then: [t: "логарифм"]      # phrase(the 'log' function is used in mathematics)
    - else_if: "$Verbosity='Terse'"
      then: [t: "эл эн"]
      else: [t: "натуральный логарифм"]      # phrase(the 'natural log' function is used in mathematics)


- name: multi-line
  #   that eliminates the need for the if: else_if: ...
  # IDEA:  set a variable with the word to say for the row (e.g., RowLabel = Row/Case/Line/...)
  tag: [piecewise, system-of-equations, lines]
  match: "."
  variables:
    # Wikipedia has some tables where all the entire first column is empty (e.g., https://en.wikipedia.org/wiki/List_of_trigonometric_identities)
  - LineCount: "count(*[not(contains(@data-intent-property, ':continued-row:'))])"
  - NextLineIsContinuedRow: "false()"   # default value
  - IsColumnSilent: true()
  replace:
  - x: "$LineCount"
  - test:
    - if: "self::m:piecewise"
      then_test:
        if: "$LineCount = 1"
        then: [t: "случай"]
        else: [t: "случая"]      # phrase(this is the first 'case' of three cases)
    - else_if: "self::m:system-of-equations"
      then_test:
        if: "$LineCount = 1"
        then: [t: "уравнение"]
        else: [t: "уравнения"]      # phrase(this is the first 'equation' of three equations)
      else_test:
        if: "$LineCount = 1"
        then: [t: "строка"]
        else: [t: "строки"]      # phrase(this is the first 'line' of three lines)
  - pause: short
  - x: "*"
  - pause: long


- name: default-multiline
  tag: [mtr, mlabeledtr]
  match: "parent::m:piecewise or parent::m:system-of-equations or parent::m:lines"
  variables: [NextLineIsContinuedRow: "following-sibling::*[1][contains(@data-intent-property, ':continued-row:')]"]
  replace:
  - test:
      if: "not($LineCount=1 or contains(@data-intent-property, ':continued-row:'))"
      then:
      - pause: medium
      - test:
        - if: "parent::m:piecewise"
          then: [t: "случай"]     # phrase('case' 1 of 10 cases)
        - else_if: "parent::m:system-of-equations"
          then: [t: "уравнение"] # phrase('equation' 1 of 10 equations)
          else: [t: "строка"]     # phrase('line 1 of 10 lines)
      - x: "count(preceding-sibling::*[not(contains(@data-intent-property, ':continued-row:'))]) + 1"
  - test:
      if: "self::m:mlabeledtr"
      then:
      - t: "с меткой"      # phrase(the diagram is complete 'with label')
      - x: "*[1]/*"
  - test:
      if: "not(contains(@data-intent-property, ':continued-row:'))"
      then: [pause: medium]
  - test:
      if: "self::m:mlabeledtr"
      then: [x: "*[position()>1]"]
      else: [x: "*"]

- name: default-multiline
  tag: mtd
  match: "parent::*[parent::m:piecewise or parent::m:system-of-equations or parent::m:lines]"
  variables: [LongPause: "$SpeechStyle = 'ClearSpeak' and $ClearSpeak_MultiLinePausesBetweenColumns = 'Long'"]
  replace:
  - test:
      if: "IsInDefinition(*[1], 'ComparisonOperators')"
      then: [pause: short]
  - test:
      if: "*[1][@data-added!='missing-content']"
      then: [x: "*"]
  - test:
    # no pause after each element; medium pause if last element in a row; long pause for last element in matrix unless ClearSpeak override
    - if: "count(following-sibling::*) = 0 and not($NextLineIsContinuedRow)"
      then_test:
          if: "count(../following-sibling::*) > 0"
          then_test:
              if: "$LongPause"
              then: [pause: long]
              else: [pause: medium]
      else_test:
          if: "IsInDefinition(*[1], 'ComparisonOperators')"
          then: [pause: short]
          else: [pause: auto]

# Matrix/Determinant rules
# matrix and determinant are the same other than "matrix"/"determinant" based on the bracketing chars
# the pausing logic is pushed down to the <mtd>
# the rules either speak the <mtr>s (to get "row n") or the <mtd>s. "column n" spoken if $IsColumnSilent is false
- name: 1x1-matrix
  tag: [matrix, determinant]
  variables: [IsColumnSilent: true()]
  match: "count(*)=1 and *[self::m:mtr][count(*) = 1]"
  replace:
  - test:
      if: "self::m:determinant" # just need to check the first bracket since we know it must be (, [, or |
      then: [t: "определитель"]      # phrase(the 2 by 2 'determinant'))
      else: [t: "матрица"]      # phrase(the 2 by 2 'matrix')
  - t: "1 на 1"      # phrase(the '1 by 1' matrix)
  - t: "с элементом"      # phrase(the 2 by 2 matrix 'with entry' x)
  - x: "*[1]/*"

# simpler reading methods for special case matrices
- name: zero-matrix
  tag: matrix
  # select all the non-zero entries -- if there are none of them, then it is a zero matrix
  match: "not( */*/*[not(self::m:mn and .= 0)] )"
  replace:
  - t: "нулевая матрица"   # phrase(the 2 by 2 'zero matrix')
  - x: count(*)
  - t: "на"       # phrase(the 1 'by' 2 matrix)
  - x: count(*[self::m:mtr][1]/*)
  - pause: long

- name: identity-matrix
  tag: matrix
  # select all the non-zero entries...if they are not on the diagonal, or are != 1
  #   if there are any of them, then this isn't an identity matrix
  match:
  - "count(*) = count(*[1]/*) and "
  - "not( */*/*[not(self::m:mn and .= 0)]"
  - "          [count(../preceding-sibling::*)!=count(../../preceding-sibling::*) or .!= 1]"
  - "    )"
  replace:
  - t: "единичная матрица"   # phrase(the 2 by 2 'identity matrix')
  - x: count(*)
  - t: "на"       # phrase(the 1 'by' 2 matrix)
  - x: count(*[self::m:mtr][1]/*)
  - pause: long

- name: diagonal-matrix
  tag: matrix
  # select all the non-zero entries...if they are not on the diagonal
  #   if there are any of them, then this isn't an identity matrix
  match:
  - "count(*) = count(*[1]/*) and "
  - "not( */*/*[not(self::m:mn and .= 0)]"
  - "          [count(../preceding-sibling::*)!=count(../../preceding-sibling::*)]"
  - "    )"
  replace:
  - t: "диагональная матрица"   # phrase(the 2 by 2 'diagonal matrix')
  - x: count(*)
  - t: "на"       # phrase(the 1 'by' 2 matrix)
  - x: count(*[self::m:mtr][1]/*)
  - pause: long
  - insert:
      # this lists the diagonal 'mtd's to be read, and they say "column nnn" before reading the contents
      # there seems to be an xpath bug -- without the parens, the match fails for the
      #   test Languages::en::mtable::diagonal_matrix due to match failure (the third matching element seems to be missing)
      nodes: "(*/*/*[not(self::m:mn and .= 0)]/..)"
      replace: [pause: auto]
  - pause: long

# simpler reading methods for smaller matrices if the entries are simple
- name: 2-or-3x1-matrix
  tag: matrix
  variables: [IsColumnSilent: true()]
  match:
  - "$ClearSpeak_Matrix != 'SpeakColNum' and " # "simple" isn't used for this preference
  - "*[self::m:mtr][count(*) = 1] and " # one column
  - count(*)<=3 and # at least two rows
  - IsNode(*/*/*,'simple') # IsNode() returns true if all the nodes are simple
  replace:
  - test:
      if: "$ClearSpeak_Matrix = 'Vector' or $ClearSpeak_Matrix = 'EndVector'"
      then: [t: "вектор-столбец"]
      else: [t: "матрица-столбец"]
  - x: count(*)
  - t: "на 1"      # phrase(the 2 'by 1 column' matrix)
  - pause: long
  - x: "*/*"
  - test:
      if: "$ClearSpeak_Matrix = 'EndMatrix' or $ClearSpeak_Matrix = 'EndVector'"
      then:
      - test:
          if: $ClearSpeak_Matrix = 'EndVector'
          then: [t: "конец вектора"]      # phrase(the 2 column 'vector')
          else: [t: "конец матрицы"]      # phrase(the 2 by 2 'matrix')

- name: default-column-matrix
  tag: matrix
  variables: [IsColumnSilent: true()]
  match: "*[self::m:mtr][count(*) = 1]"
  replace:
  - test:
      if: "$ClearSpeak_Matrix = 'Vector' or $ClearSpeak_Matrix = 'EndVector'"
      then: [t: "вектор-столбец"]
      else: [t: "матрица-столбец"]
  - x: "count(*)"
  - t: "на 1"      # phrase(the 2 'by 1 column' matrix)
  - pause: long
  - x: "*" # select the rows (mtr)
  - test:
      if: "$ClearSpeak_Matrix = 'EndMatrix' or $ClearSpeak_Matrix = 'EndVector'"
      then: [t: "конец матрицы"]      # phrase(the 'end of matrix' has been reached)

- name: 1x2-or-3-matrix
  tag: matrix
  variables: [IsColumnSilent: "$SpeechStyle = 'SimpleSpeak' or ($SpeechStyle = 'ClearSpeak' and $ClearSpeak_Matrix != 'SpeakColNum')"]
  match:
  - "$ClearSpeak_Matrix != 'SpeakColNum' and " # "simple" isn't used for this preference
  - count(*)=1  and # one row
  - count(*[1]/*)<=3 and # at least two cols
  - IsNode(*/*/*,'simple') # IsNode() returns true if all the nodes are simple
  replace:
  - test:
      if: "$ClearSpeak_Matrix = 'Vector' or $ClearSpeak_Matrix = 'EndVector'"
      then: [t: "вектор-строка"]
      else: [t: "матрица-строка"]
  - t: "1 на"      # phrase('the 1 by' 2 matrix)
  - x: count(*/*)
  - pause: long
  - x: "*/*"
  - test:
      if: "$ClearSpeak_Matrix = 'EndMatrix' or $ClearSpeak_Matrix = 'EndVector'"
      then:
      - test:
          if: $ClearSpeak_Matrix = 'EndMatrix'
          then: [t: "конец матрицы"]      # phrase(the 2 by 2 'matrix')
          else: [t: "конец вектора"]      # phrase(the 2 by 1 'vector')

- name: default-row-matrix
  tag: matrix
  variables: [IsColumnSilent: "$SpeechStyle = 'ClearSpeak' and $ClearSpeak_Matrix = 'SilentColNum'"]
  match: "count(*)=1" # one row
  replace:
  - test:
      if: "$ClearSpeak_Matrix = 'Vector' or $ClearSpeak_Matrix = 'EndVector'"
      then: [t: "вектор-строка"]
      else: [t: "матрица-строка"]
  - t: "1 на"      # phrase('the 1 by' 2 matrix)
  - x: "count(*/*)"
  - pause: long
  - pause: medium
  - x: "*/*" # select the cols (mtd)
  - test:
      if: "$ClearSpeak_Matrix = 'EndMatrix' or $ClearSpeak_Matrix = 'EndVector'"
      then:
      - test:
          if: $ClearSpeak_Matrix = 'EndMatrix'
          then: [t: "конец матрицы"]      # phrase(the 2 by 2 'matrix')
          else: [t: "конец вектора"]      # phrase(the 2 by 1 'vector')

- name: simple-small-matrix
  tag: [matrix, determinant]
  match:
  - "$ClearSpeak_Matrix != 'SpeakColNum' and " # "simple" isn't used for this preference
  - (count(*)<=3 and count(*[1]/*)<=3) and # no bigger than a 3x3 matrix
  - IsNode(*/*/*,'simple') # IsNode() returns true if all the nodes are simple
  variables: [IsColumnSilent: "$SpeechStyle = 'SimpleSpeak' or ($SpeechStyle = 'ClearSpeak' and $ClearSpeak_Matrix != 'SpeakColNum')"]
  replace:
  - test:
      if: "self::m:determinant"
      then: [t: "определитель"]      # phrase(the 2 by 2 'determinant')
      else: [t: "матрица"]      # phrase(the 2 by 2 'matrix')
  - x: count(*)
  - t: "на"      # phrase(the 1 'by' 2 matrix)
  - x: count(*[self::m:mtr][1]/*)
  - pause: long
  - x: "*"
  - test:
      if: "$ClearSpeak_Matrix = 'EndMatrix' or $ClearSpeak_Matrix = 'EndVector'"
      then:
      - test:
          if: "self::m:determinant"
          then: [t: "конец определителя"]      # phrase(the 2 by 2 'determinant')
          else: [t: "конец матрицы"]      # phrase(the 2 by 2 'matrix')

- name: default-matrix
  tag: [matrix, determinant]
  variables: [IsColumnSilent: "$SpeechStyle = 'ClearSpeak' and $ClearSpeak_Matrix = 'SilentColNum'"]
  match: "."
  replace:
  - test:
      if: "self::m:determinant"
      then: [t: "определитель"]      # phrase(the 2 by 2 'determinant')
      else: [t: "матрица"]      # phrase(the 2 by 2 'matrix')
  - x: "count(*)"
  - t: "на"      # phrase(the 1 'by' 2 matrix)
  - x: "count(*[self::m:mtr][1]/*)"
  - pause: long
  - x: "*"
  - test:
      if: "$ClearSpeak_Matrix = 'EndMatrix' or $ClearSpeak_Matrix = 'EndVector'"
      then:
      - test:
          if: "self::m:determinant"
          then: [t: "конец определителя"]      # phrase(the 2 by 2 'determinant')
          else: [t: "конец матрицы"]      # phrase(the 2 by 2 'matrix's)

- name: chemistry-msub
  tag: [chemical-formula]
  match: "*[1][.='msub']"
  replace:
  - x: "*[2]"
  - test:
      if: "$Verbosity='Verbose'"
      then: [t: "нижний индекс"]      # phrase(H 'subscript' 2)
      else_test:
        if: "$Verbosity='Medium'"
        then: [t: "нижний индекс"]      # phrase(H 'sub' 2)
  - x: "*[3]"

- name: dimension-by
  tag: mrow
  match: dimension-product
  replace:
  - insert:
      nodes: "*"
      replace: [t: "по", pause: auto]      # phrase(3 'by' 5 matrix)

- name: chemistry-msup
  tag: [chemical-formula]
  match: "count(*)=3 and *[1][.='msup']"
  replace:
  - x: "*[2]"
  - test:
      if: "$Verbosity='Verbose'"
      then: [t: "верхний индекс"]      # phrase(H 'superscript' 2)
      else_test:
        if: "$Verbosity='Medium'"
        then: [t: "верхний индекс"]      # phrase(H 'super' 2)
  - x: "*[3]"
  - test:
      if: "following-sibling::*[1][.='+' or .='-']" # a little lazy -- assumes chemistry superscripts end with + or -
      then: [pause: medium]

-
  # There currently is no way to do sub/super for n-ary number of args
  # Instead, we just deal with up to two prescripts and up to four postscripts (repeating blocks of similar code [UGLY!])
  # This hopefully covers all reasonable cases...
  name: chemistry-scripts
  tag: [chemical-formula, chemical-nuclide]
  variables:
  # computing the number of postscripts is messy because of <mprescripts> being optionally present -- we use "mod" to get the count right
  - Prescripts: "m:mprescripts/following-sibling::*"
  - NumChildren: "count(*)" # need to stash this since the count is wrong inside '*[...]' below
  - Postscripts: "*[position()>1 and position() < (last() + ($NumChildren mod 2) -count($Prescripts))]"
  match: . # should only be msubsup or mmultiscripts at this point
  replace:
  - test:
      if: "$Prescripts" # we have at least one pre sub/super 
      then:
      # nuclide: speak the superscript first
      - test:
          if: "not($Prescripts[2][self::m:none])"
          then:
          - test:
              if: "$Verbosity='Verbose'"
              then: [t: "верхний индекс"]      # phrase(H 'superscript' 2)
              else_test:
                if: "$Verbosity='Medium'"
                then: [t: "верхний индекс"]      # phrase(H 'super' 2)
          - x: "$Prescripts[2]"
          - pause: "short"
      - test:
          if: "not($Prescripts[1][self::m:none])"
          then:
          - test:
              if: "$Verbosity='Verbose'"
              then: [t: "нижний индекс"]      # phrase(a 'subscript' may be used to indicate an index)
              else_test:
                if: "$Verbosity='Medium'"
                then: [t: "нижний индекс"]      # phrase(here is a 'sub' total)
          - x: "$Prescripts[1]"
          - pause: "short"
      - test:
          if: "count($Prescripts) > 2" # can this happen for chemistry??? we allow for one *extra* pre sub/super pair
          then:
          - test:
              if: "not($Prescripts[4][self::m:none])"
              then:
              - test:
                  if: "$Verbosity='Verbose'"
                  then: [t: "верхний индекс"]      # phrase(H 'superscript' 2)
                  else_test:
                    if: "$Verbosity='Medium'"
                    then: [t: "верхний индекс"]      # phrase(H 'super' 2)
              - x: "$Prescripts[4]"
              - pause: "short"
          - test:
              if: "not($Prescripts[3][self::m:none])"
              then:
              - test:
                  if: "$Verbosity='Verbose'"
                  then: [t: "нижний индекс"]      # phrase(H 'subscript' 2)
                  else_test:
                    if: "$Verbosity='Medium'"
                    then: [t: "нижний индекс"]      # phrase(H 'sub' 2)
              - x: "$Prescripts[3]"
              - pause: "short"
  - x: "*[1]" # base
  - test:
      if: "$Postscripts"
      then:
      - test:
          if: "not($Postscripts[1][self::m:none])"
          then:
          - test:
              if: "$Verbosity='Verbose'"
              then: [t: "нижний индекс"]      # phrase(phrase(H 'subscript' 2)
              else_test:
                if: "$Verbosity='Medium'"
                then: [t: "нижний индекс"]      # phrase(phrase(H 'sub' 2)
          - x: "$Postscripts[1]"
          - pause: "short"
      - test:
          if: "not($Postscripts[2][self::m:none])"
          then:
          - test:
              if: "$Verbosity='Verbose'"
              then: [t: "верхний индекс"]      # phrase(H 'superscript' 2)
              else_test:
                if: "$Verbosity='Medium'"
                then: [t: "верхний индекс"]          # phrase(H 'super' 2)
          - x: "$Postscripts[2]"
          - pause: "short"
      - test:
          if: "count($Postscripts) > 2"
          then:
          - test:
              if: "not($Postscripts[3][self::m:none])"
              then:
              - test:
                  if: "$Verbosity='Verbose'"
                  then: [t: "нижний индекс"]      # phrase(H 'subscript' 2)
                  else_test:
                    if: "$Verbosity='Medium'"
                    then: [t: "нижний индекс"]          # phrase(H 'sub' 2)
              - x: "$Postscripts[3]"
              - pause: "short"
          - test:
              if: "not($Postscripts[4][self::m:none])"
              then:
              - test:
                  if: "$Verbosity='Verbose'"
                  then: [t: "верхний индекс"]      # phrase(H 'superscript' 2)
                  else_test:
                    if: "$Verbosity='Medium'"
                    then: [t: "верхний индекс"]          # phrase(H 'super' 2)
              - x: "$Postscripts[4]"
              - pause: "short"
          - test:
              if: "count($Postscripts) > 4"
              then:
              - test:
                  if: "not($Postscripts[5][self::m:none])"
                  then:
                  - test:
                      if: "$Verbosity='Verbose'"
                      then: [t: "нижний индекс"]    # phrase(H 'subscript' 2)
                      else_test:
                        if: "$Verbosity='Medium'"
                        then: [t: "нижний индекс"]        # phrase(H 'sub' 2)
                  - x: "$Postscripts[5]"
                  - pause: "short"
              - test:
                  if: "not($Postscripts[6][self::m:none])"
                  then:
                  - test:
                      if: "$Verbosity='Verbose'"
                      then: [t: "верхний индекс"]  # phrase(H 'superscript' 2)
                      else_test:
                        if: "$Verbosity='Medium'"
                        then: [t: "верхний индекс"]      # phrase(H 'super' 2)
                  - x: "$Postscripts[6]"
                  - pause: "short"
              - test:
                  if: "count($Postscripts) > 6"
                  then:
                  - test:
                      if: "not($Postscripts[7][self::m:none])"
                      then:
                      - test:
                          if: "$Verbosity='Verbose'"
                          then: [t: "нижний индекс"]      # phrase(H 'subscript' 2)
                          else_test:
                            if: "$Verbosity='Medium'"
                            then: [t: "нижний индекс"]      # phrase(H 'sub' 2)
                      - x: "$Postscripts[7]"
                      - pause: "short"
                  - test:
                      if: "not($Postscripts[8][self::m:none])"
                      then:
                      - test:
                          if: "$Verbosity='Verbose'"
                          then: [t: "верхний индекс"]      # phrase(H 'superscript' 2)
                          else_test:
                            if: "$Verbosity='Medium'"
                            then: [t: "верхний индекс"]      # phrase(H 'super' 2)
                      - x: "$Postscripts[8]"
                      - pause: "short"
      - test:
          if: "$Postscripts[last()][not(self::m:none)] and following-sibling::*[1][.='+' or .='-']"
          then: [pause: medium]

- name: chemistry
  tag: chemical-equation
  match: "."
  replace:
  - x: "*"

- name: chemical-element
  tag: chemical-element
  match: "."
  replace:
  - bookmark: "@id"
  - spell: text()
  - pause: short

- name: chemical-state
  tag: chemical-state
  match: "count(*)=1"
  replace:
  - bookmark: "*[1]/@id"
  - test:
    - if: ".='s'"
      then: [t: "твердый"]      # phrase(Boron is a 'solid' in its natural state)
    - else_if: ".='l'"
      then: [t: "жидкость"]      # phrase(water is a 'liquid')
    - else_if: ".='g'"
      then: [t: "газ"]      # phrase(hydrogen is a 'gas' )
      else: [t: "водный"]      # phrase(an 'aqueous' solution is contained in water)
  - pause: short

- name: chemical-formula-operator-bond
  tag: chemical-formula-operator
  match: "@data-chemical-bond"
  replace:
  # FIX: this might be better/more efficient if in unicode.yaml
  - bookmark: "@id"
  - test:
    - if: ".='-' or .=':'"
      then: [t: "одинарная связь"]      # phrase(a 'single bond' is formed when two atoms share one pair of electrons)
    - else_if: ".='=' or .='∷'"
      then: [t: "двойная связь"]      # phrase(a 'double bond' may occur when two atoms share two pairs of electrons)
    - else_if: ".='≡'"
      then: [t: "тройная связь"]      # phrase(a 'triple bond' occurs when two atoms share three pairs of electrons)
    - else_if: ".='≣'"
      then: [t: "четырехкратная связь"]      # phrase(a 'quadruple bond' occurs when two atoms share four pairs of electrons)
      else: [x: "text()"]

- name: chemical-formula-operator
  tag: chemical-formula-operator
  match: "."
  replace:
    x: "text()"

- name: chemical-arrow-operator
  tag: chemical-arrow-operator
  match: "."
  replace:
  # FIX: this might be better/more efficient if in unicode.yaml
  - bookmark: "@id"
  - test:
    - if: ".='→' or .='⟶'"
      then_test:
        if: "$Verbosity='Terse'"
        then: [t: "образует"]      # phrase(hydrogen and oxygen 'forms' water )
        else: [t: "реагирует с образованием"]      # phrase(hydrogen and oxygen 'reacts to form' water)
    - else_if: ".='⇌' or .='\u1f8d2'"
      then: [t: "находится в равновесии с"]      # phrase(a reactant 'is in equilibrium with' a product)
    - else_if: ".='\u1f8d4'"
      then: [t: "находится в равновесии, смещено влево с"]      # phrase(the reactant 'is in equilibrium biased to the left with' the product)
    - else_if: ".='\u1f8d3'"
      then: [t: "находится в равновесии, смещено вправо с"]      # phrase(the reactant 'is in equilibrium biased to the right with' the product)
      else: [x: "*"]

- name: chemical-equation-operator
  tag: chemical-equation-operator
  match: "."
  replace:
  - bookmark: "@id"
  - x: "text()"

- name: none
  tag: none
  match: "../../*[self::m:chemical-formula or self::m:chemical-nuclide]"
  replace:
  - t: "" # don't say anything

- name: ignore-intent-wrapper
  tag: intent-wrapper
  match: "."
  replace:
  - x: "*"
