; LOOKDOWN key, table
; Searches a table for an element that matches key. If a match 
; is found, Lookdown returns its position in the table in the 
; variable index and a 0 in the w register. If no element matches key, 
; Lookdown returns a 1 in the w register as an error code. 

; Device data and reset vector
        device  pic16c55,xt_osc,wdt_off,protect_off
        reset   start

        org     8
key     ds      1	; Element to find. 
index   ds      1	; Position of key in table. 

        org     0

start   mov     !rb,#0  	; Output to show index on LEDs.
        mov     key,#'G'        ; Search for byte corresponding to 
        call    Lookdown        ; ASCII G and return index no. 
        mov     rb,index        ; Show index on LEDs hooked to RB.
        jmp     $       	; Endless loop. 

; The table to be searched must include the number of searchable elements 
; as element no. 0 (the very first element in the table). 
Table   jmp     pc+w
        retw    10      	; No. of searchable elements. 
        retw    'ABCDEFGHIJ'    ; Table of ASCII characters. 

; Locate table element corresponding to key. 
; Return with the corresponding element number in index. Key is not
; altered by Lookdown. Note that when the element is found, :done
; decrements index so that the first element = 0, second = 1...
; just as with the PBASIC instruction. 

Lookdown        clr     w       ; Retrieve element 0. 
        call    Table
        mov     index,w 	; Copy table length to index. 
:loop   call    Table   	; Retrieve element. 
        subwf   key,0   	; W = key - W
        snz             
        jmp     :done   	; If w = 0, we have a match. 
        dec     index   	; If not, try next lower element.
        mov     w,index 	; Put index into w for table. 
        sz              	; If zero, element is not in table. 
        jmp     :loop   	; Try next lower element
        retw    1       	; Error code: element not in table. 
:done   dec     index   	; index=index-1 to match PBASIC.
        ret             	; Element found: return a 0 in w.

