BITS    16
        org 0x0

        ;; GIF header, without global color table
        db  0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x23, 0x00
        db  0x20, 0x00, 0x00, 0x01, 0x00
        ;; Comment extension
        db  0x21
        db  0xfe
        ;; chunk size
        db  2
        jmp short _main
        ;; chunk size
        db  _bin_done - _z80jmp
_z80jmp:
        db  0xc3, 137, 0x00
_main:
        ;; Cancel the effect of popa
        sub SP, 14

        mov DI, 3

        mov SI, cnt+1

        call _org1
_org1:
        pop AX
        add SI, AX
        sub SI, _org1

_loop:
        mov DX, SI
        mov CX, 6

        inc byte[SI]

        cmp byte[SI], 58
        je  _buzz_carry

        cmp byte[SI], 53
        je  _buzz

        dec DI
        jnz _cnt

_fizz:
        add DX, fizz + 6 - cnt - 1

_fizz_output:
        mov DI, 3
        jmp short _output

_buzz_output:
        add DX, buzz + 6 - cnt - 1
        jmp short _output

_buzz_carry:
        inc byte[SI-1]
        mov byte[SI], 48
_buzz:
        dec DI
        jnz _buzz_output

_fzbz:
        add DX, fzbz + 10 - cnt - 1
        add CX, 4
        jmp short _fizz_output

_cnt:
        add DX, 3
        cmp byte[SI-1], 48
        setg CL
        add CL, 3

_output:
        sub DX, CX

_putc:
        mov AH, 0x0e
        mov AL, [EDX]
        mov BH, 0
        mov BL, 7
        int 0x10
        inc DX
        loop _putc

        cmp byte[SI-1], 58
        jne _loop

_done:
        xor AX, AX
        int 0x21
        hlt

_main_done:
_z80_code:
        resb 85

cnt:
        db  "00", 13, 10
        db  ";'"
fizz:
        db  "Fizz", 13, 10
fzbz:
        db  "Fizz"
buzz:
        db  "Buzz", 13, 10

_bin_done:

        ;; chunk size
        db  _rbpl_done - _rbpl

_rbpl:
        db "'"
        resb 137
_rbpl_done:

        ;; End of GIF comment extension
        db 0

;;         resb 512 - 16 * 4 - 2 + $$ - $

;;         db  0x80, 0x01, 0x01, 0x00, 0x83, 0xfe, 0x3f, 0x1e, 0x3f, 0x00, 0x00, 0x00, 0x20, 0x99, 0x07, 0x00
;;         db  0x00, 0x00, 0x01, 0x1f, 0x05, 0xfe, 0xff, 0xff, 0x5f, 0x99, 0x07, 0x00, 0x62, 0x9e, 0xf1, 0x0d
;;         dd  0, 0, 0, 0
;;         dd  0, 0, 0, 0

        resb 512 - 2 + $$ - $

        dw  0xaa55

