# ------------------------------------------------
# KAAU CS212 - Spring 2007
# Sample MIPS assembly program (TAL)
# Dr. Muhammad Al-Hashimi

# program purpose:
# return the opcode of an instruction in the program

# program parameters:
# $t2 <- program length (instruction count)
# $s0 <- instruction index (instr numbered 0 to $t2-1) 
# $t4 <- program start address (value of the label main)

# program output:
# $t0 <- opcode of instruction at index $s0

# sample run: set $t2=9 (9 instr), $s0=7 (the lw instr),
# $t4=0x00400024 (hex addr of first instr)

# ------------------------------------------------

main:                                 # label program start (instr 0)
            slt      $t3,$s0,$zero    # 0 begin check instr number ($s0) in range
            bne      $t3,$zero,Exit   # 1 exit program if less than 0 ($s0 < $zero is true , or $t3=1)
            slt      $t3,$s0,$t2      # 2 is instr number less than max?
            beq      $t3,$zero,Exit   # 3 end check instr number in range (exit program if $s0 < $t2 false)
            add      $t1,$s0,$s0      # 4 multiply instr index by 2 
            add      $t1,$t1,$t1      # 5 multiply instr index by 4
            add      $t1,$t1,$t4      # 6 compute instr effective address
            lw       $t0,0($t1)       # 7 fetch instr word
            srl      $t0,$t0,26       # 8 isolate upper 6 bits (opcode)

# ------------------------------------------------
Exit:       ori      $2,$0,10         # system call: exit program
            syscall
