;   ####             #    #     # #
;   #   #            #    #       #          The FreeWare C library for
;   #   #  ##   ###  #  # #     # ###             RISC OS machines
;   #   # #  # #     # #  #     # #  #   ___________________________________
;   #   # ####  ###  ##   #     # #  #
;   #   # #        # # #  #     # #  #    Please refer to the accompanying
;   ####   ### ####  #  # ##### # ###    documentation for conditions of use
;   ________________________________________________________________________
;
;   File:    Misc.Dispatch.s
;   Author:  Copyright  1993 Shaun Blackmore
;   Version: 1.00 (03 Apr 1993)
;   Purpose: See below

        GET     RegDefs.h
        GET     SwiNos.h
        GET     Macros.h

; int Dispatch(int value, int size, int *table, void *functions[], int arg0, int arg1, int arg2, int arg3)

; Perform a table look up of value in table[size]
; call the corrseponding procedure in functions[size]
; with count arguments (0 <= count <= 4)
; If the table contains a -1 then this is always taken
;       - Use this for a default action

        IMPORT  |x$stack_overflow|
        PREAMBLE
        STARTCODE Dispatch
;
        MOV     ip,sp
        STMFD   sp!, {r4,r5,r6,r7,fp,ip,lr,pc}
        SUB     fp,ip,#4
        CMPS    sp,sl
        BLLT    |x$stack_overflow|

Loop
        LDR     r4,[r2,#0]
        CMP     r4,r0
        CMPNE   r4,#-1           ; Always match a -1
        BEQ     Cont
        ADD     r2,r2,#4        ; increase table
        ADD     r3,r3,#4
        SUBS    r1,r1,#1        ; Decrease count
        BNE     Loop
        MOV	r0,#-1
        B       Exit
Cont
        LDR     r7,[r3,#0]      ; Load address into r7
        TEQ     r7,#0
        BEQ     Exit
        LDR     r0,[ip,#0]
        LDR     r1,[ip,#4]
        LDR     r2,[ip,#8]
        LDR     r3,[ip,#12]
        MOV     lr,pc           ; Return after 2 instructions
        MOV     pc,r7
Exit
        LDMEA   fp, {r4,r5,r6,r7,fp,sp,pc}
;
        END
