///|
fn seed_code(
  field : BytesView,
  optional~ : Bool,
  dash~ : Bool = false,
) -> String raise RecordError {
  let mut end = field.length()
  while end > 0 && (field[end - 1] == b' ' || field[end - 1] == 0) {
    end -= 1
  }
  let code = field[:end]
  guard optional || !code.is_empty() else {
    raise BadHeader("missing network, station or channel source code")
  }
  guard code
    .iter()
    .all(c => {
      (c >= b'A' && c <= b'Z') ||
      (c >= b'a' && c <= b'z') ||
      (c >= b'0' && c <= b'9') ||
      (dash && c == b'-')
    }) else {
    raise BadHeader("invalid miniSEED 2 source code")
  }
  @utf8.decode_lossy(code)
}

///|
fn seed_source(data : Bytes) -> String raise RecordError {
  let net = seed_code(data[18:20], optional=false)
  let station = seed_code(data[8:13], optional=false, dash=true)
  let location = seed_code(data[13:15], optional=true, dash=true)
  let band = seed_code(data[15:16], optional=true)
  let source = seed_code(data[16:17], optional=false)
  let orientation = seed_code(data[17:18], optional=true)
  "FDSN:\{net}_\{station}_\{location}_\{band}_\{source}_\{orientation}"
}

///|
fn legacy_rate(data : Bytes, layout : LegacyLayout) -> Double {
  if layout.rate_hz is Some(hz) {
    return if hz > 0.0 && hz < 1.0 { -1.0 / hz } else { hz }
  }
  let factor = signed_word(word(data, 32, layout.header_little))
  let multiplier = signed_word(word(data, 34, layout.header_little))
  if factor == 0 || multiplier == 0 {
    return 0.0
  }
  // Each negative factor contributes its magnitude to the denominator.
  let numerator = (factor.max(1) * multiplier.max(1)).to_double()
  let denominator = ((-factor).max(1) * (-multiplier).max(1)).to_double()
  if numerator < denominator {
    -denominator / numerator
  } else {
    numerator / denominator
  }
}

///|
fn adjust_legacy_time(
  header : Header,
  ticks : Int32,
  micros : Int32,
) -> Header raise RecordError {
  validate_time(header)
  let nanos = header.nanosecond.to_int64() +
    ticks.to_int64() * 100_000L +
    (micros * 1000).to_int64()
  let mut carry = (nanos / 1_000_000_000L).to_int()
  let mut nanosecond = (nanos % 1_000_000_000L).to_int()
  if nanosecond < 0 {
    nanosecond += 1_000_000_000
    carry -= 1
  }
  if carry == 0 {
    return { ..header, nanosecond, }
  }
  // The instant one second after an explicitly tagged leap second is :00.
  if header.second == 60 && carry > 0 {
    carry -= 1
  }
  let mut seconds = header.hour * 3600 +
    header.minute * 60 +
    header.second +
    carry
  let mut day = header.day
  let mut year = header.year
  while seconds < 0 {
    seconds += 86400
    day -= 1
  }
  while seconds >= 86400 {
    seconds -= 86400
    day += 1
  }
  if day < 1 {
    year -= 1
    day += days_in_year(year)
  } else if day > days_in_year(year) {
    day -= days_in_year(year)
    year += 1
  }
  guard year >= 0 && year <= 65535 else {
    raise BadHeader("corrected time lies outside the representable year range")
  }
  {
    ..header,
    year,
    day,
    hour: seconds / 3600,
    minute: seconds / 60 % 60,
    second: seconds % 60,
    nanosecond,
  }
}

///|
fn set_flag_fields(
  fields : Map[String, Json],
  bits : Int32,
  names : Array[String],
) -> Unit {
  for i, name in names {
    if !name.is_empty() && (bits & (1 << i)) != 0 {
      fields[name] = true
    }
  }
}

///|
fn legacy_extras(data : Bytes, correction : Int32, quality : Int32?) -> Bytes {
  let fdsn : Map[String, Json] = {
    "DataQuality": Json::string(data[6].to_char().to_string()),
  }
  let mut sequence = 0
  let mut has_sequence = false
  for c in data[:6] {
    if c >= b'0' && c <= b'9' {
      sequence = sequence * 10 + c.to_int() - b'0'.to_int()
      has_sequence = true
    }
  }
  if has_sequence {
    fdsn["Sequence"] = Json::number(sequence.to_double())
  }
  let activity = data[36].to_int()
  let time : Map[String, Json] = Map([])
  if quality is Some(percent) {
    time["Quality"] = Json::number(percent.to_double())
  }
  if correction != 0 {
    time["Correction"] = Json::number(correction.to_double() / 10000.0)
  }
  if (activity & 16) != 0 {
    time["LeapSecond"] = 1
  } else if (activity & 32) != 0 {
    time["LeapSecond"] = -1
  }
  if !time.is_empty() {
    fdsn["Time"] = Json::object(time)
  }
  let event : Map[String, Json] = Map([])
  set_flag_fields(event, activity >> 2, ["Begin", "End", "", "", "InProgress"])
  if !event.is_empty() {
    fdsn["Event"] = Json::object(event)
  }
  let flags : Map[String, Json] = Map([])
  set_flag_fields(flags, data[37].to_int(), [
    "StationVolumeParityError", "LongRecordRead", "ShortRecordRead", "StartOfTimeSeries",
    "EndOfTimeSeries",
  ])
  set_flag_fields(flags, data[38].to_int(), [
    "AmplifierSaturation", "DigitizerClipping", "Spikes", "Glitches", "MissingData",
    "TelemetrySyncError", "FilterCharging",
  ])
  if !flags.is_empty() {
    fdsn["Flags"] = Json::object(flags)
  }
  @utf8.encode(Json::object({ "FDSN": Json::object(fdsn) }).stringify())
}