///|
/// State of a single GBA hardware timer (TM0–TM3).
pub struct TimerChannel {
  mut reload : UInt32
  mut counter : UInt32
  mut ctrl : UInt32
  mut sub_cycles : Int32
}

///|
pub fn TimerChannel::new() -> TimerChannel {
  { reload: 0U, counter: 0U, ctrl: 0U, sub_cycles: 0, }
}

///|
pub fn TimerChannel::reset(self : TimerChannel) -> Unit {
  self.reload = 0U
  self.counter = 0U
  self.ctrl = 0U
  self.sub_cycles = 0
}

///|
fn timer_prescaler(ctrl : UInt32) -> Int32 {
  match ctrl & 3U {
    0U => 1
    1U => 64
    2U => 256
    _ => 1024
  }
}

///|
/// Advance all 4 hardware timers by `cycles` CPU cycles, handling cascade and IRQ flags.
pub fn tick_timers(bus : GbaBus, cycles : Int32) -> Unit {
  let mut prev_overflow = 0
  for i = 0; i < 4; i = i + 1 {
    let tm = bus.timers[i]
    let enabled = ((tm.ctrl >> 7) & 1U) != 0U
    let cascade = i > 0 && ((tm.ctrl >> 2) & 1U) != 0U
    let mut overflows = 0
    if enabled {
      let ticks = if cascade {
        prev_overflow
      } else {
        let prescale = timer_prescaler(tm.ctrl)
        let total = tm.sub_cycles + cycles
        tm.sub_cycles = total % prescale
        total / prescale
      }
      if ticks > 0 {
        let mut cur = tm.counter.reinterpret_as_int() + ticks
        while cur >= 0x10000 {
          overflows += 1
          cur = cur - 0x10000 + tm.reload.reinterpret_as_int()
        }
        tm.counter = (cur & 0xFFFF).reinterpret_as_uint()
        if overflows > 0 && ((tm.ctrl >> 6) & 1U) != 0U {
          bus.irq_if = bus.irq_if | (1U << (3 + i))
        }
      }
    }
    prev_overflow = overflows
  }
}