;
; Divide HL with DE (HL = HL div DE, mod DE) - Word version!
;
; Source: This routine is based on the 16-bits division routine from
; the book 'Z80 Machinetaal Subroutines' by Lance A. Leventhal and
; Winthrop Saville.
;
; In : HL = Value
;      DE = Divider
;
; Out: HL = Result
;      DE = Modulus
;      Carry reset when correctly calculated
;
; Chg: A, C
;
DIVWRD: LD    A,E             ; Division by zero?
        OR    D
        JR    NZ,DO_DIV       ; Continue of not
        LD    HL,0
        LD    DE,0
        SCF                   ; Set Carry to indicate an error
        RET

DO_DIV: LD    C,L             ; AC = HL
        LD    A,H
        LD    HL,0            ; HL = Modulus
        LD    B,16            ; 16-bit division
        OR    A               ; Start with carry reset

DIV_LP: RL    C               ; AC = AC * 2
        RLA                   ; (set Carry to bit 0)
        RL    L               ; HL = HL * 2
        RL    H               ; (reset Carry again (HL = 0))

        PUSH  HL
        SBC   HL,DE
        CCF                   ; Carry set when Ok

        JR    C,ENDDIV        ; Modulus cannot be >= Value
        EX    (SP),HL         ; Restore Modulus

ENDDIV: INC   SP              ; Get Modulus from Stack
        INC   SP
        DJNZ  DIV_LP          ; Repeat for all bits

; Shift last Carry-bit to divider

        EX    DE,HL           ; DE = Modulus
        RL    C               ; Carry to C
        LD    L,C             ; HL = AC
        RLA
        LD    H,A
        OR    A               ; Reset Carry (valid result)
        RET
