;*****************************************************************
; Procedure Name  : copy_tile_data
;
; Author          : Marc Gale (Xalthorn or Eldara)
;
; Description     : This procedure is designed to copy data from
;                   the cartridge ROM to the required place in
;                   one of the banks of tile data.
;
; On Entry        : bc holds a pointer to the source data
;                   a holds the bank number (0 or 1)
;                   h holds the set number (0=low set, 1=high set)
;                   d holds the tile number
;                   e holds the number of tiles to copy
;
; During          : All registers are used
;
; On Exit         : Nothing intentional
;*****************************************************************
copy_tile_data:
 and    1               ; clear all but the last bit
 ldh    [$4F],a         ; select the bank

 ld     a,h             ; get the set number
 and    1               ; mask out all but bit 0
 cp     0               ; is it set 0 (the first set)
 jr     nz,.highset     ; if it isn't, do the highset part
.lowset:
 ld     hl,$8000        ; set the pointer to the lowset
 jr     .doneset        ; we've done the set pointer, carry on
.highset:
 ld     hl,$8800        ; set the pointer to the highset
 ld     a,d             ; get the tile number (-128 to 127)
 add    a,128           ; add 128 to it
 ld     d,a		; put it back in d
.doneset:

 push   de              ; we need to preserve these for a moment
                        ; we're going to use e as a loop to
                        ; quickly move the data pointer to the
                        ; right place.
 ld     e,16
.point_loop
 ld     a,l             ; get the low byte of the pointer
 add    a,d             ; add (with carry) the tile number
 ld     l,a             ; put it back
 ld     a,0             ; clear a
 adc    a,h             ; add (with carry) a and h
 ld     h,a             ; put it back
 dec    e               ; decrease e by one
 jr     nz,.point_loop  ; if we've not reached the end, carry on

 pop    de              ; grab the old data back

; now we can copy the actual data.

.main_loop
 ld     d,16            ; there are 16 bytes per tile
.copy_loop
 ld     a,[bc]          ; get a byte of data
 ld     [hli],a         ; put it at the target and increment hl
 ld     a,c             ; get the low byte
 add    a,1             ; add 1 to c
 ld     c,a             ; put it back
 ld     a,0             ; clear a
 adc    a,b             ; add (with carry) a and b
 ld     b,a             ; put it back
 dec    d
 jr     nz,.copy_loop   ; if we've not reached the end, keep going
 dec    e               ; decrease the counter
 jr     nz,.main_loop   ; if we've not reached the end, keep going

 ret
