
    .module rnc

    .globl  _rnc2, rnc2
    ; void rnc2 (unsigned vram_offset, void *data);

    .area _CODE

_rnc2:

    pop bc
    pop de
    pop hl
    push hl
    push de
    push bc
    
;; ASM routine entry point
;; IN : DE = VRAM OFFSET
;;       HL = PACKED DATA
;; OUT : ALL GABARGE AF, BC, DE, HL

rnc2:
    ; OFFSET VRAM
    ld  c,#0xbf
      
    out (c),e
    set 6,d
    out (c),d
    res 6,d

    ;; SEEMS TO SIMPLY PASS THE USELESS DATA HEADER
    ld bc,#0x0012 ; = 18
    add hl,bc
    
    scf   ; flag c <- 1
    ld a,(hl)
    inc hl
    adc a,a
    add a,a
    jp xloop
    
raw:
    ld c,#4
x4bits:
    call get1bit
    rl b
    dec c
    jr nz,x4bits
    
    push af
    ld a,#3
    add a,b
    add a,a
    ld c,a
rawlpb:
    ld a,(hl)
    inc hl
    out(0xbe),a   ;ld (de),a
    inc de
    ld a,(hl)
    inc hl
    out(0xbe),a
    inc de
    
    dec c
    jr nz,rawlpb
    
    pop af
    jr xloop
    
getlen:
    call get1bit
    rl c
    call get1bit
    jr nc,copy
    call get1bit
    dec c
    push hl
    
    ld h,a
    ld a,c
    adc a,a
    ld c,a
    cp #9
    ld a,h
    
    pop hl
    jr z,raw

; - - - - - - - - - - - - - - - - - -

copy:
    call get1bit
    jr nc,bytedisp
    call get1bit
    rl b
    call get1bit
    jr c,bigdisp
    inc b
    dec b
    jr nz, bytedisp
    inc b
another:
    call get1bit
    rl b
bytedisp:
    push af
    ld a,e
    sub (hl)
    push hl
    ld l,a
    ld a,d
    sbc a,b
    ld h,a
    dec hl
    
    push bc
    ld b,c
    ld c,#0xbf
bytelp:
    out (c),l
    out (c),h
    nop
    in a,(#0xbe)
    out (c),e
    set 6,d
    out (c),d
    nop
    out (#0xbe),a
    res 6,d
    djnz bytelp
    pop bc
    xor a
    ld c,a
    
    pop hl
    inc hl
    
    pop af
    jr xloop
    
; - - - - - - - - - - - - - - - - - -

getbits:

    ld a,(hl)
    adc a,a
    jr c,string
xbyte:
    ld b,a
    ld a,(hl)
    inc hl
    out(0xbe),a
    inc de
    ld a,b
xloop:
    add a,a
    jr c,chkz
    ld b,a
    ld a,(hl)
    inc hl
    out(0xbe),a
    inc de
    ld a,b
    
    add a,a
    jr nc,xbyte
chkz:
    jr z,getbits
    
; - - - - - - - - - - - - - - - - - -

string:
    ld bc,#0x0002
    call get1bit
    jr nc,getlen
smalls:
    call get1bit
    jr nc,bytedisp
    
    inc c
    call get1bit
    jr nc,copy
    
    ld c,(hl)
    inc hl
    inc c
    dec c
    jr z,overnout
    
    push af
    
    ld a,c
    add a,#8
    ld c,a
    
    pop af
    
    jr copy
    
; - - - - - - - - - - - - - - - - - -
    
bigdisp:
    call get1bit
    rl b
    set 2,b
    call get1bit
    jr c,bytedisp
    jr another
overnout:
    call get1bit
    jr c,xloop
    ret
    
get1bit:
    add a,a
    ret nz
    ld a,(hl)
    inc hl
    adc a,a
    ret