Q2 Computer - Division and Modulus

; Divide x2 = x0 / x1, remainder in x3
; Destroys x0, x1, x2, x3, x4, x5 (assumed to be in the zero page).
div:
  sta   =x5
  lea   =0
  sta   =x2   ; quotient
  sta   =x3   ; remainder
  lea   =12
div_loop:
  add   #-1
  sta   =x4

  ; x3 <<= 1
  lda   =x3
  add   =x3
  sta   =x3

  ; x2 <<= 1
  lda   =x2
  add   =x2
  sta   =x2

  ; x3 = x3 | x0[x4]
  lda   =x0
  add   =x0
  sta   =x0
  jfc   div_not_set
  lea   =1
  add   =x3
  sta   =x3
div_not_set:

  ; if x3 < x1 goto div_skip
  lda   =x1
  nor   #0
  add   #1
  add   =x3
  jfc   div_skip

  ; x3 -= x1
  sta   =x3

  ; x2 |= 1
  lea   =1
  add   =x2
  sta   =x2

div_skip:
  lda   =x4
  jfc   div_loop
  jmp   @=x5