///|
priv struct DecimalReading {
  coefficient : @bigint.BigInt
  exponent : @bigint.BigInt
}

///|
fn parse_decimal_reading(lexeme : String) -> DecimalReading raise {
  let text = lexeme.trim().to_owned().replace_all(old="E", new="e")
  let pieces = text.split("e").collect()
  let (mantissa, exponent) = match pieces {
    [mantissa] => (mantissa, @bigint.BigInt::from_int(0))
    [mantissa, exp] =>
      (mantissa, @string.parse_bigint(exp.strip_prefix("+").unwrap_or(exp)))
    _ => raise InvalidInput("invalid decimal exponent")
  }
  let negative = mantissa.has_prefix("-")
  let digits = mantissa
    .strip_prefix("-")
    .unwrap_or(mantissa.strip_prefix("+").unwrap_or(mantissa))
  let (whole, fraction) = match digits.split(".").collect() {
    [whole] => (whole, "")
    [whole, fraction] => (whole, fraction.to_owned())
    _ => raise InvalidInput("invalid decimal point")
  }
  let coefficient = @string.parse_bigint(whole.to_owned() + fraction)
  {
    coefficient: if negative {
      -coefficient
    } else {
      coefficient
    },
    exponent: exponent - @bigint.BigInt::from_int(fraction.length()),
  }
}

///|
fn DecimalReading::digits(self : DecimalReading) -> String {
  self.coefficient.abs().to_string()
}

///|
fn DecimalReading::order(self : DecimalReading) -> @bigint.BigInt {
  self.exponent + @bigint.BigInt::from_int(self.digits().length())
}

///|
fn DecimalReading::opposite(self : DecimalReading) -> DecimalReading {
  { ..self, coefficient: -self.coefficient, }
}

///|
fn decimal_abs_compare(a : DecimalReading, b : DecimalReading) -> Int32 {
  if a.coefficient.is_zero() || b.coefficient.is_zero() {
    return a.coefficient.abs().compare(b.coefficient.abs())
  }
  let order = a.order().compare(b.order())
  if order != 0 {
    return order
  }
  a
  .digits()
  .trim_end(char_set="0")
  .to_owned()
  .compare(b.digits().trim_end(char_set="0").to_owned())
}

///|
fn decimal_pair_sign(a : DecimalReading, b : DecimalReading) -> Int32 {
  let a_sign = a.coefficient.compare_int(0)
  let b_sign = b.coefficient.compare_int(0)
  if a_sign == b_sign || b_sign == 0 {
    a_sign
  } else if a_sign == 0 {
    b_sign
  } else {
    a_sign * decimal_abs_compare(a, b)
  }
}

///|
fn decimal_sum_sign(
  a : DecimalReading,
  b : DecimalReading,
  c : DecimalReading,
) -> Int32 {
  let terms = [a, b, c].filter(fn(term) { !term.coefficient.is_zero() })
  terms.sort_by(fn(a, b) { b.order().compare(a.order()) })
  match terms {
    [] => 0
    [a] => a.coefficient.compare_int(0)
    [a, b] => decimal_pair_sign(a, b)
    [a, b, c] => {
      // With a two-digit lead, the largest term dominates both others.
      if (a.order() - b.order()).compare_int(2) >= 0 {
        return a.coefficient.compare_int(0)
      }
      // The two leading orders are close. Their exponent gap is bounded
      // by the input coefficient lengths, regardless of absolute scale.
      let ten = @bigint.BigInt::from_int(10)
      let combined = if a.exponent >= b.exponent {
        {
          coefficient: a.coefficient * ten.pow(a.exponent - b.exponent) +
          b.coefficient,
          exponent: b.exponent,
        }
      } else {
        {
          coefficient: b.coefficient * ten.pow(b.exponent - a.exponent) +
          a.coefficient,
          exponent: a.exponent,
        }
      }
      decimal_pair_sign(combined, c)
    }
    _ => abort("decimal comparison has at most three terms")
  }
}

///|
fn exceeds_mm_tolerance(a : DecimalReading, b : DecimalReading) -> Bool {
  let minus_tolerance = {
    coefficient: @bigint.BigInt::from_int(-1),
    exponent: @bigint.BigInt::from_int(-9),
  }
  decimal_sum_sign(a, b.opposite(), minus_tolerance) > 0 ||
  decimal_sum_sign(b, a.opposite(), minus_tolerance) > 0
}

///|
fn decimal_sum(readings : Array[DecimalReading]) -> DecimalReading? {
  let by_exponent : Map[@bigint.BigInt, @bigint.BigInt] = Map([])
  let zero = @bigint.BigInt::from_int(0)
  for term in readings {
    by_exponent[term.exponent] = by_exponent.get(term.exponent).unwrap_or(zero) +
      term.coefficient
  }
  let terms : Array[DecimalReading] = []
  let mut max_digits = 0
  for exponent, coefficient in by_exponent {
    if !coefficient.is_zero() {
      let term = { coefficient, exponent, }
      max_digits = max_digits.max(term.digits().length())
      terms.push(term)
    }
  }
  if terms.is_empty() {
    return Some({ coefficient: zero, exponent: zero, })
  }
  terms.sort_by(fn(a, b) { a.exponent.compare(b.exponent) })
  let scale = terms[0].exponent
  // Beyond the decimal range of Double, only align when the input's
  // existing coefficient length already accounts for the scale gap.
  let limit = @bigint.BigInt::from_int(max_digits) +
    @bigint.BigInt::from_int(650)
  if terms[terms.length() - 1].exponent - scale > limit {
    return None
  }
  let ten = @bigint.BigInt::from_int(10)
  let mut coefficient = zero
  for term in terms {
    coefficient += term.coefficient * ten.pow(term.exponent - scale)
  }
  Some({ coefficient, exponent: scale, })
}

///|
fn DecimalReading::to_finite_double(self : DecimalReading) -> Double? {
  if self.coefficient.is_zero() {
    return Some(0.0)
  }
  let value = @string.parse_double("\{self.coefficient}e\{self.exponent}") catch {
    _ => return None
  }
  if value.is_finite() && value != 0.0 {
    Some(value)
  } else {
    None
  }
}