# Lab 01, Exercise 2
# Preserve v1 order; store each matching v1 element once, even if
# that value occurs multiple times in v2. Repeated v1 elements remain.
.section .data
v1:       .byte 2, 6, -3, 11, 9, 18, -13, 16, 5, 1
v2:       .byte 4, 2, -13, 3, 9, 9, 7, 16, 4, 7
v3:       .space 10
v3_len:   .byte 0
flag1:    .byte 0
flag2:    .byte 0
flag3:    .byte 0

# The text section contains the instructions that the CPU runs.
.section .text
# Make _start visible as the point where the program begins.
.globl _start
_start:
    la x5, v1
    la x6, v2
    la x7, v3
    li x8, 10               # Remaining v1 elements
    li x9, 0                # Length of v3

outer_loop:
    beq x8, x0, matching_done
    lb x10, 0(x5)           # Signed 8-bit v1 value
    mv x11, x6
    li x12, 10

inner_loop:
    beq x12, x0, next_v1
    lb x13, 0(x11)
    beq x10, x13, match_found
    addi x11, x11, 1
    addi x12, x12, -1
    j inner_loop

match_found:
    sb x10, 0(x7)
    addi x7, x7, 1
    addi x9, x9, 1
    # Stop scanning v2 after the first match.

next_v1:
    addi x5, x5, 1
    addi x8, x8, -1
    j outer_loop

matching_done:
    la x14, v3_len
    sb x9, 0(x14)
    la x15, flag1
    la x16, flag2
    la x17, flag3
    sb x0, 0(x15)
    sb x0, 0(x16)
    sb x0, 0(x17)
    bne x9, x0, nonempty

    li x18, 1
    sb x18, 0(x15)          # Empty: flags = 1, 0, 0
    j End

nonempty:
    li x18, 1
    sb x18, 0(x16)          # Assume increasing until disproved
    sb x18, 0(x17)          # Assume decreasing until disproved
    addi x19, x9, -1        # Number of adjacent pairs
    beq x19, x0, End        # Singleton: both order flags are 1
    la x20, v3
    lb x21, 0(x20)

check_order:
    lb x22, 1(x20)
    blt x21, x22, increasing_ok
    sb x0, 0(x16)          # Equal or falling: not strictly increasing
increasing_ok:
    blt x22, x21, decreasing_ok
    sb x0, 0(x17)          # Equal or rising: not strictly decreasing
decreasing_ok:
    mv x21, x22
    addi x20, x20, 1
    addi x19, x19, -1
    bne x19, x0, check_order

# The End block stops the program and returns control to the simulator.
End:
    li a0, 0                # exit(0)
    li a7, 93
    ecall
