; R5: msg
; R6: modulus
; R7: exponent
; R0: msg**exponent [modulus]
RSAsignature:
    MOV     R1, #1
    BTL     R0, R6                  ;modulus bit length
    FP      R6, R0                  ;initialize modular coprocessor
    MOVRR   R0                      ;get R**2 mod modulus in R0
    MM      R5, R5, R0              ;put msg in Montgomery form
    MM1     R0, R0                  ;initialize result with R
    BTL     R4, R7                  ;initialize i, to read bit i of exponent
    MOV     R3, R1
    JR      startExponentiation
exponentiation:
    SRL     R2, R7, R4              ;shift exponent of i bits
    AND     R2, R2, R1              ;get lsb
    ADD     R2, R2, R2              ;===
    XOR     R2, R2, R3              ;with two lookup tables,
    MOV     R3, =tabAtomic          ;select next operation (in R2)
    ADD     R3, R3, R2              ;(either square or mult)
    MOVCW   R3                      ;and how to update counter i (in R3)
    MOV     R2, =tabOperation       ;(decrement 'i' or not)
    ADD     R2, R2, R3              ;
    MOVCW   R2                      ;
    AND     R3, R3, R1              ;===
    CA      R2
startExponentiation:
    SUB     R4, R4, R3
    JCR     exponentiation
    MM1     R0, R0
    STP
tabAtomic:
    .word   1, 1, 3, 0
tabOperation:
    .word   =square, =square, 0, =mult

square:
    MM      R0, R0, R0
    RET
mult:
    MM      R0, R0, R5
    RET