
#name RAMLoader

;	Quick hack! (by James MacDonald) Beware of evil code! 
;	Assemble with extASM. Size ~1608 bytes

.entry

	SWI	XOS_GetEnv
	MOV	R13, R1

	MOV	R0, #17
	ADR	R1, fname
	
	SWI	OS_File		; Get exec addr; must match the end of the RAM drive
	
	SWI	OS_ReadRAMFsLimits
	
	CMP	R0, R1
	MOVEQ	R7, #1		; A RAM drive may have been created
	BLEQ	make_ram_drive	; No RAM drive, will have to make one..
	
	SWI	OS_ReadRAMFsLimits
	
	CMP	R1, R3		; No need to update R7, as we will exit if no RAM drive now
	BLO	ram_drive_not_correct_size
	
	CMP	R7, #1
	BEQ	skip_exist
	
	BL	ram_qfull	; Check to see if the RAM drive contains files
	BVS	ram_exists	; RAM drive contains files!
	
.skip_exist	
	
	MOV	R2, R0
	
	MOV	R0, #16
	ADR	R1, fname
	MOV	R3, #0
	
	;	SWI	OS_EnterOS	; There is no need
					; to enter SVC mode
					; as OS_File runs in
					; SVC mode anyway.
					
	SWI	OS_File
	
	;	TEQP	PC, #0
	;	MOV	R0, R0
	
	ADR	R0, kickfs
	SWI	OS_CLI			; I don't like this way of doing it.
	
	TST	R7, #1	
	SWIEQ	OS_Exit
	
	MVN	R0, #0			; R0 = -1
	SWI	Wimp_CommandWindow	; Need screen refresh to display a new RAMFSFiler icon
	
	SWI	OS_Exit
	
.make_ram_drive

	STMFD	R13!, {R0-R1, R14}
	
	SUB	R1, R3, R0
	MOV	R0, #5
	SWI	XOS_ChangeDynamicArea
	
	LDMFD	R13!, {R0-R1, PC}^
	 		
.ram_qfull
        
        STMFD	R13!, {R0-R7, R14}
        
        MOV	R0, #5
        MOV	R1, #-4096
        SWI	XOS_ChangeDynamicArea
        
        LDMVSFD	R13!, {R0-R7, PC}
        
        MOV	R1, #4096
        SWI	XOS_ChangeDynamicArea
	
	LDMFD	R13!, {R0-R7, PC}^
	
.ram_drive_not_correct_size

	ADR	R0, siz_blk
	B	report_error

.no_ram_drive

	ADR 	R0, nrd_blk
        B	report_error

.ram_exists

	ADR	R0, exs_blk
	B	report_error

.report_error

	MOV 	R1, #13
	ADR 	R2, title

	SWI	Wimp_ReportError

	SWI	OS_Exit

.exs_blk

	DCD 1
	DCB "The RAM drive already exists and contains files. You will toast the contents if you restore this image. Is that what you want to do?",0

	ALIGN

.nrd_blk 

	DCD 1
     	DCB "Unable to create RAM drive of appropriate size to load image",0
     	ALIGN

.siz_blk

	DCD 1
	DCB "The RAM drive could not be resized correctly; the image cannot be loaded.",0

.title 	DCB "RAMLoader",0
	ALIGN
	
.fname	DCB	"RContents",0
	ALIGN

.kickfs DCB	"RAM:Dismount",0
	ALIGN
	
.ram_path

	DCB	"RAM::0.$.",0
	ALIGN
	
.ram_file

	DCB	"*",0
	ALIGN	