#name ^.Object.ReadBack
#type &ffd

#include <Bolmaster$Path>Sources.Structures
#include <Bolmaster$Path>Sources.Variables

;Reads sprite entries from the backdrop file and places their addresses in
;the backtab

;wipe the backtab table
ADD R11,R12,#v.backtab
MOV R8,#256
MOV R0,#0
.loop4
STR R0,[R11],#4
SUBS R8,R8,#1
BGT loop4
;point R11 at the sprite file

LDR R11,[R12,#v.backdropadr]
CMP R11,#0
BEQ fail
SUB R11,R11,#4
LDR R8,[R11,#4]; number of sprites
CMP R8,#256
BGT fail
LDR R1,[R11,#8]
ADD R11,R11,R1;indirect to first sprite
.loop
.decodenum
MOV R7,#0      ;sprite number to be filled in
LDRB R0,[R11,#4]  ;load first figure
CMP R0,#"0"
BLT skip
CMP R0,#"9"
BGT skip
SUB R0,R0,#"0"
MOV R7,R0

LDRB R0,[R11,#5]  ;load second figure
CMP R0,#"0"
BLT decoded
CMP R0,#"9"
BGT decoded
ADD R7,R7,R7,LSL #2 ;} multiply R7 by 10
MOV R7,R7,LSL #1 ;}
SUB R0,R0,#"0"
ADD R7,R7,R0

LDRB R0,[R11,#6] ;load third figure
CMP R0,#"0"
BLT decoded
CMP R0,#"9"
BGT decoded
ADD R7,R7,R7,LSL #2 ;} multiply R7 by 10
MOV R7,R7,LSL #1 ;}
SUB R0,R0,#"0"
ADD R7,R7,R0

.decoded
;R7 now contains the number of our sprite
CMP R7,#256
BGE fail

LDR R0,[R11,#32]
ADD R0,R0,R11; R0 now points to the sprite data
ADD R1,R12,#v.backtab
STR R0,[R1,R7,LSL #2] ;store the sprite data address in the
;back table at offset R7

.skip
CMP R8,#1
BLE done

LDR R0,[R11]
ADD R11,R11,R0;indirect to next sprite
SUB R8,R8,#1
B loop

.fail
ADR R0,failtext
MOV R1,PC
ORR R1,R1,#1<<28
TEQP PC,R1
B end
.failtext
DCD &666
DCB "Backdrop file read failed",0
ALIGN

.done
;now fill in the blank entries with the first available sprite

ADD R11,R12,#v.backtab
MOV R8,#256
.loop2
LDR R0,[R11],#4
CMP R0,#0
BNE foundfirst
SUBS R8,R8,#1
BGT loop2
B fail

.foundfirst
MOV R1,R0
ADD R11,R12,#v.backtab
MOV R8,#256
.loop3
LDR R0,[R11]
CMP R0,#0
STREQ R1,[R11]
ADD R11,R11,#4
SUBS R8,R8,#1
BGT loop3

.placehell
LDR R11,[R12,#v.hellcache]
CMP R11,#0
BEQ fail
ADD R10,R12,#v.backtab
MOV R9,#18
.loop6
STR R11,[R10],#4
ADD R11,R11,#32*32
SUBS R9,R9,#1
BGT loop6

LDR R11,[R12,#v.backpixadr]
CMP R11,#0
BEQ fail

SUB R11,R11,#4
LDR R8,[R11,#4]; number of sprites
CMP R8,#256
BGT fail
LDR R1,[R11,#8]
ADD R11,R11,R1;indirect to first sprite
ADD R10,R12,#v.backpixtab
MOV R9,#9
.loop5
LDR R0,[R11,#32]
ADD R0,R0,R11   ;address of sprite data
STR R0,[R10],#4
SUBS R8,R8,#1
LDRGT R0,[R11]
ADDGT R11,R11,R0
SUBS R9,R9,#1
BGT loop5
.end