; ***************************************************************************
; copyright   : (C) 2026 by Martin Preuss
; email       : martin@libchipcard.de
;
; ***************************************************************************
; * This file is part of the project "AqHome".                              *
; * Please see toplevel file COPYING of that project for license details.   *
; ***************************************************************************

#ifndef AQH_AVR_COMMON_WALKTABLE_ASM
#define AQH_AVR_COMMON_WALKTABLE_ASM



; ***************************************************************************
; code

.cseg



; ---------------------------------------------------------------------------
; @routine WalkTable
;
; Walks a given table and calls every routine whose table entry
; holds a value equal to the given one.
;
; The loop uses r16-r19 and Z.
;
; @param Z byte pointer to table (for LPM!)
; @param r16 value
; @clobbers (any)

WalkTable:
  mov r22, r16
WalkTable_loop:
    lpm r16, Z+
    adiw zh:zl, 1
    lpm r18, Z+
    lpm r19, Z+
    mov r17, r18                                ; routine==0?
    or r17, r19
    breq WalkTable_loopEnd      ; yes, end of table
    tst r16                                     ; timer==0?
    breq WalkTable_loopCall     ; yes, match any value
    cp r22, r16
    brne WalkTable_loopNext     ; skip
WalkTable_loopCall:
    push r22
      push zl
        push zh
          push yl
            push yh
              rcall walkTableCallR19R18
            pop yh
          pop yl
        pop zh
      pop zl
    pop r22
WalkTable_loopNext:
  rjmp WalkTable_loop
WalkTable_loopEnd:
  ret
; @end



; ---------------------------------------------------------------------------
; @routine walkTableCallR19R18
; Call route at address r19:r18

walkTableCallR19R18:
  push r18
  push r19
  ret
; @end



#endif


