Elite on the BBC Micro

# Maths (Arithmetic): DVID4_DUPLICATE (Master version)

```       Name: DVID4_DUPLICATE                                   [View in context]
Type: Subroutine                                       [Compare versions]
Category: Maths (Arithmetic)
Summary: Calculate (P R) = 256 * A / Q
Deep dive: Shift-and-subtract division

Calculate the following division and remainder:

P = A / Q

R = remainder as a fraction of Q, where 1.0 = 255

Another way of saying the above is this:

(P R) = 256 * A / Q

This uses the same shift-and-subtract algorithm as TIS2, but this time we
keep the remainder.

Returns:

C flag               The C flag is cleared

.DVID4_DUPLICATE

\ This is an exact duplicate of the DVID4 routine, which
\ is also present in this source, so it isn't clear why
\ this duplicate exists (especially as the other version
\ is slightly faster, as it unrolls the loop)

LDX #8                 \ Set a counter in X to count the 8 bits in A

ASL A                  \ Shift A left and store in P (we will build the result
STA P                  \ in P)

LDA #0                 \ Set A = 0 for us to build a remainder

.DVL4

ROL A                  \ Shift A to the left

BCS DV8                \ If the C flag is set (i.e. bit 7 of A was set) then
\ skip straight to the subtraction

CMP Q                  \ If A < Q skip the following subtraction
BCC DV5

.DV8

SBC Q                  \ A >= Q, so set A = A - Q

.DV5

ROL P                  \ Shift P to the left, pulling the C flag into bit 0

DEX                    \ Decrement the loop counter

BNE DVL4               \ Loop back for the next bit until we have done all 8
\ bits of P

RTS                    \ Return from the subroutine
```