.include 'M64DEF.INC'

.ORG 0x0000
JMP MAIN
.ORG 0x0006
JMP INT2_loop
.ORG 0x000E
JMP INT6_loop

-----------------------
.ORG 0X0050
MAIN:
LDI R16,low(RAMEND)
OUT SPL,R16
LDI R16,high(RAMEND)
OUT SPH,R16
LDI R16,0b00100000  ;  وقفه 2 در لبه پایین رونده
STS EICRA,R16
LDI R16,0b00110000  ; وقفه 6 در لبه بالا رونده
STS EICRB,R16
LDI R16 , 0b01000100
OUT EIMSK,R16
CLR R2  ; Encode Decode flag
SEI

----------------------
loop:
CPI R1,0
BRNE decode_loop

encode_loop:
LDS R16,0x54F0
MUL R16,R17
STS 0x3232 ,R0
STT 0x3233 ,R1
LDS R16,0x54F1
MUL R16,R18
STS 0x3234 ,R0
STT 0x3235 ,R1
LDS R16,0x54F2
MUL R16,R19
STS 0x3236 ,R0
STT 0x3237 ,R1
LDS R16,0x54F3
MUL R16,R20
STS 0x3238 ,R0
STT 0x3239 ,R1
LDS R16,0x54F4
MUL R16,R21
STS 0x323A ,R0
STT 0x323B ,R1
JMP loop

decode_loop:
LDI R26,0x32
LDI R27,0x32
MOV R16,R17
CALL division_loop
STS 0x54F0,R30
MOV R16,R18
CALL division_loop
STS 0x54F1,R30
MOV R16,R19
CALL division_loop
STS 0x54F2,R30
MOV R16,R20
CALL division_loop
STS 0x54F3,R30
MOV R16,R21
CALL division_loop
STS 0x54F4,R30
JMP loop

-----------------------
INT2_loop: 
push R16
MOV R16,R17
LSR R16
AND R16,R17  ;  ضرب بیت به بیت : and
BRNE next1
LSR R17
next1: 
MOV R16,R18
LSR R16
AND R16,R18  ;  ضرب بیت به بیت : and
BRNE next2
LSR R18
next2:
MOV R16,R19
LSR R16
AND R16,R19  ;  ضرب بیت به بیت : and
BRNE next3
LSR R19
next3:
MOV R16,R20
LSR R16
AND R16,R20  ;  ضرب بیت به بیت : and
BRNE next4
LSR R20
next4:
MOV R16,R21
LSR R16
AND R16,R21  ;  ضرب بیت به بیت : and
BRNE INT2_end
LSR R21

INT2_end:
pop R16
RETI

-------------------------
INT6_loop:
COM R2
RETI

-------------------------
division_loop:
LDS R30,X+
LDS R31,X+

div_loop:
CP R30,R16
BRCS smaller
SUB R30,R16
JMP div_loop
smaller:
CPI R31,0
BRNE continue
RET

continue:
SUBI R31,1
MOV R29,R16
SUB R29,R30
DEC R29
LDI R30,255
SUB R30,R29
JMP div_loop









