
_BULID_LIB_ EQU 1

extern data T
extern data _tmpA
extern data _tmpB
extern data _tmpC

INCLUDE chip.def

;include "sn8cc_macros.asm"

; R0 = counter
;	@HL = @YZ
public __INIT@global_
;.CODE
sn8cc_lib@RTSegment SEGMENT CODE INBANK USING _sn8cc_lib_data_
__INIT@global_:
// Marked by Joe to save creating another library type
/*
IF H != 0
	; chip has H, L 
	;__SelectBankCNST 0
	IF RBANK != 0
		IF __NO_B0MOVMI_INSTRUCTOIN == 0
			B0MOV RBANK, #0
		ELSE	
			B0MOV _tmpA, A
			MOV A, #0
			B0MOV RBANK, A
			B0MOV A, _tmpA
		ENDIF
	ENDIF	
	B0MOV A, R3
	B0MOV Y, A
	B0MOV A, R2
	B0MOV Z, A

	MOV A, R1
	B0MOV H, A
	B0MOV A, R0
	B0MOV L, A

LOOP:
	MOVC
	MOV @HL, A

	B0MOV A, R3
	B0BTS1 FZ
	JMP _ENDIF
;IF size != 1	
	MOV A, #1
	ADD L, A
	B0MOV A, R
	MOV @HL, A
_ENDIF:

	; INC Z,L
	MOV A, #1
	ADD L, A
	ADD Z, A
	MOV	A, #0
	ADC Y, A

	DECMS R0
	JMP LOOP
	RET
ELSE
*/

/*
	; parameter
	; destnation : R0, R1
	; source : R2, R3
	; size : A

	; local
	; size : R4
	; temp : R5

	; chip does not have H,L
	; Save initialize size to R4
	B0MOV R4, A
	IF RBANK != 0
		IF __NO_B0MOVMI_INSTRUCTOIN == 0
			B0MOV RBANK, #0
		ELSE	
			B0MOV _tmpA, A
			MOV A, #0
			B0MOV RBANK, A
			B0MOV A, _tmpA
		ENDIF
	ENDIF	

	
LOOP:
	B0MOV A, R3
	B0MOV Y, A
	B0MOV A, R2
	B0MOV Z, A
	MOVC

	; Save target value to R5
	B0MOV R5, A
	B0MOV A, R1
	B0MOV Y, A
	B0MOV A, R0
	B0MOV Z, A
	B0MOV A, R5
	B0MOV @YZ, A
	DECMS R4
	JMP MOV_high
	RET
MOV_high:
	MOV A, #1
	B0ADD R0, A 	;ram is in byte
	B0ADD R0, A
	B0ADD R2, A  ;rom is in word
	B0ADD Z, A
	B0MOV A, R
	B0MOV @YZ, A
	DECMS R4
	JMP LOOP
	RET
*/

//2007.08.12 SOL MODIFY FOR Virtual register optimization
	if RBANK != 0
			B0MOV RBANK, #0
	ENDIF	
		
LOOP:
	
	MOVC
  B0MOV _tmpC, A

  B0MOV A, _tmpB
  XCH A, Y             //_tmpB <-> Y
  B0MOV _tmpB, A
  
  B0MOV A, _tmpA
  XCH A, Z             //_tmpA <-> Z
  B0MOV _tmpA, A
  
  B0MOV A, _tmpC
	B0MOV @YZ, A

	DECMS T
	JMP _Continue1
	JMP _END
	
_Continue1:	

	MOV A, #1
	ADD Z, A
	B0MOV A, R
	B0MOV @YZ, A

	DECMS T
	JMP _Continue2
	JMP _END
	
_Continue2:		
 	MOV A, #1
	ADD Z, A
  
  B0MOV A, _tmpB
  XCH A, Y             //_tmpB <-> Y
  B0MOV _tmpB, A
  
  B0MOV A, _tmpA
  XCH A, Z             //_tmpA <-> Z
  B0MOV _tmpA, A
	
	MOV A, #1
	ADD Z, A
	JMP LOOP
	  
_END:
	RET



if 0
	B0MOV A, R3
	B0BTS1 FZ
	JMP _ENDIF
;IF size != 1	
	MOV A, #1
	ADD Z, A
	ADD R0, A
	MOV A, #0
	ADC R1, A
	B0MOV A, R
	B0MOV @YZ, A
	MOV A, #2
_ENDIF:
	
	MOV A, #1
	ADD	R0, A
	ADD R2, A
	MOV A, #0
	ADC R3, A
	ADC R1, A

	DECMS R0
	JMP LOOP
	RET
endif	
	
/*
ENDIF
*/