# ------------------------------------------------
# KAAU CS212 - Spring 2005
# Sample MIPS assembly program (MAL)
# 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

.text

# ------------------------------------------------
main:                                  # label program start (instr 0)

# ------------------------------------------------
# Program inputs section
   
            lw       $t2,instr_count   # now the program is 15 instr long
            lw       $s0,instr_ndx     # now lw is at line 13 (not 7)
            lw       $t4,start_addr

# ------------------------------------------------

            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

.data

# ------------------------------------------------
instr_count: .word 15
instr_ndx:   .word 13
start_addr:  .word 0x00400024
