
.global _start

_start:
	ldr r10, =SSD
	ldr r11, =table
	
main:
	// Clean R1 to R7 registers
	// R0-R3 hold value for seconds and minutes
	// R4-R7 hold value for digits to be displayed
	mov r0, #0
	mov r1, #0
	mov r2, #0
	mov r3, #0
	mov r4, #0
	mov r5, #0
	mov r6, #0
	mov r7, #0
	mov r8, #0

loop:
	// count to whatever is approximately one second
	// update display
	// reset loop and repeat
	add r8,r8,#1
	ldr r9, =1000000   // Load immediate literal into r9
	cmp r8, r9         // Compare r8 to 1,000,000
	blt loop
	bl tick_clock
	mov r8,#0
	bl display_clock
	b loop


// Digits are converted to SSD hex code and saved in R5 register one by one
// Registers:
// r0 = seconds ones
// r1 = seconds tens
// r2 = minutes ones
// r3 = minutes tens

tick_clock:
    // Increment seconds ones
    add r0, r0, #1
    cmp r0, #10
    bne done  // No overflow

    // Overflow: reset seconds ones, increment seconds tens
    mov r0, #0
    add r1, r1, #1
    cmp r1, #6
    bne done

    // Overflow: reset seconds tens, increment minutes ones
    mov r1, #0
    add r2, r2, #1
    cmp r2, #10
    bne done

    // Overflow: reset minutes ones, increment minutes tens
    mov r2, #0
    add r3, r3, #1
    cmp r3, #6
    bne done

    // Overflow: reset minutes tens (rollover after 59:59)
    mov r3, #0

done:
    bx lr



display_clock:
   push {r4-r7}
	// Convert r0 (sec ones)
    ldrb r4, [r11, r0]     // r4 = BCD(r0)
    // Convert r1 (sec tens)
    ldrb r5, [r11, r1]     // r5 = BCD(r1)
    // Convert r2 (min ones)
    ldrb r6, [r11, r2]     // r6 = BCD(r2)
    // Convert r3 (min tens)
    ldrb r7, [r11, r3]     // r7 = BCD(r3)

    // Write to 7-segment display
	 // r4 = sec ones (rightmost)
	// r5 = sec tens
	// r6 = min ones
	// r7 = min tens (leftmost)

	// Pack into r12 as: [r7][r6][r5][r4]
	mov   r12, r7        // Start with most significant byte
	lsl   r12, r12, #8   // Shift left to make room for r6
	add   r12, r12, r6   // Add r6
	lsl   r12, r12, #8   // Shift left to make room for r5
	add   r12, r12, r5   // Add r5
	lsl   r12, r12, #8   // Shift left to make room for r4
	add   r12, r12, r4   // Add r4

	// Now r12 holds: 0xMMSS → packed display value

	str   r12, [r10]     // Assume r10 = display base, and it supports packed writes
	pop {r4-r7}
	bx lr



.equ SSD, 0xFF200020
// Table of SSD values, 0-9

.data
table:            
	.byte 0x3F
	.byte 0x06
	.byte 0x5B
	.byte 0x4F
	.byte 0x66
	.byte 0x6D
	.byte 0x7D
	.byte 0x07
	.byte 0x7F
	.byte 0x6F

