# ------------------------------------------------
# KAAU CS212 - Spring 2005
# 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

# ------------------------------------------------

main:                                  # label program start (instr 0)

# ------------------------------------------------
# Program inputs section
   
            addi     $t2,$zero,13      # load const 13 using machine instr: now the program is 13 instr long
            ori      $s0,$zero,11      # load const 11 using machine instr: now lw is at line 11 (not 7)
            lui      $t4,0x0040        # load addr using machine instr (step 1): begin 2-step 32-bit address load
            ori      $t4,$t4,0x0024    # load addr using machine instr (step 2)

# ------------------------------------------------

            slt      $t3,$s0,$zero     # begin check instr number in range
            bne      $t3,$zero,Exit
            slt      $t3,$s0,$t2
            beq      $t3,$zero,Exit    # end check instr number in range
            add      $t1,$s0,$s0       # multiply instr index by 2 
            add      $t1,$t1,$t1       # multiply instr index by 4
            add      $t1,$t1,$t4       # compute instr address
            lw       $t0,0($t1)        # fetch instr word
            srl      $t0,$t0,26        # isolate upper 6 bits (opcode)

# ------------------------------------------------
Exit:       ori      $2,$0,10          # system call: exit program
            syscall
