####################################################################
# FILE:   mipsSim.s                                                #
# AUTHOR: John Zahorjan                                            #
# DATE:   1/4/2007                                                 #
#                                                                  #
# NAME:                                                            #
#                                                                  #
####################################################################

#====================================================================
#       Static data allocation and initialization
#====================================================================

.data

# Allocate space for the simulated registers.
registers: .space 128   # 32 registers x 4 bytes/register

# Allocate space for the program to simulate.
# For simplicity, we assume it won't be more than 10 instructions.
program:   .space 40   # 10 instructions x 4 bytes/instruction

#====================================================================
#       Program text
#====================================================================

.text
.global main

main:
        # read number of instructions
        ori     $v0, $0, 5      # set up for readint syscall
        syscall                 # result will be in $v0
        or      $s0, $0, $v0    # save count of number of instructions

        # loop reading instructions into simulated memory
        ori     $t0, $0, program # fetch offset past $gp of program space
        add     $t0, $t0, $gp   # $t0 now points at program memory

        # while ($s0 > 0) read an instruction
rdPgm:  beq     $s0, $0, pgmReadDone
        ori     $v0, $0, 5      # prepare for readint call
        syscall
        sw      $v0, 0($t0)     # save instruction to program memory
        addi    $t0, $t0, 4     # increment pointer to next word of program memory
        addi    $s0, $s0, -1    # decrement count of number of instructions
        j       rdPgm

pgmReadDone:
        # initialize $0 to 0
        sw      $0, registers($gp)
        
        #  $s0 will be the simulated PC.
        ori     $s0, $0, program
        add     $s0, $s0, $gp

        # now go into fetch/increment/decode/execute loop
        #   $s0  - PC (as a pointer into program memory)
        #   $t0  - IR (fetched instruction)
        #   $t1  - 0x10 (literal value)
        ori     $t1, $0, 0x10   # halt opcode
fetchInst:          
        lw      $t0, 0($s0)     # fetch next instruction
        addi    $s0, $s0, 4     # increment PC
        
        #---------------- you will replace from here... --------------------------
        # skeleton just looks for halt instruction
        srl     $t7, $t0, 26
        bne     $t7, $t1, fetchInst
        #---------------- to here ------------------------------------------------
        
        halt