# init1d.s
# SPIM code to initialize the elements of a 1-d array
#  with the value stored in location val

.data
ar1:        .word   0:20		# array of 20 integers (4 bytes each)
val:        .float  1.e-3		# value to store in array elements
nelems:     .word   20			# no. of array elements - 1; max. value
                      			#   of array index
size:       .word   4			# size of an array element, in bytes

# Register usage
# For clarity, each register holds only one variable
#  Nobody would program in this way, because some registers can be re-used
#
# $t0       base address (address of ar1[0])
# $t1       size = size of an array element (in bytes)
# $t2       nelems = number of array elements
# $t3       nmax = nelems - 1 = max. value of array index
# $t4       index = array index of current element
# $t5       addr = absolute address of ar1[index]
# $t6       offset = index * size
# $t7       n = counter to be decremented
# $t8       val = value to be stored in each array element

.text
__start:
		la		$t0,ar1				# get absolute address of ar1[0]
		                            # addresses of other array elements
		                            #  will be computed as base + offset
		lw		$t1,size
		lw		$t2,nelems
		addi    $t3,$t2,-1          # calculate nmax = nelems - 1
		ori     $t4, $0, 0          # initialize index to 0
		lwc1    $f0, val
		mfc1    $t8, $0 
loop:   mul     $t6,$t4,$t1			# loop begins here; offset in bytes
        add     $t5,$t6,$t0			# compute absolute address of ar1[index]
		sw		$t8,0($t5)			# store val in ar1[index]
		addi	$t4,$t4,1			# increment array index
		sub		$t7,$t3,$t4			# subtract array index from (nelems - 1)
		bgez	$t7, loop			# branch back to loop if diff >= 0
		ori     $v0,$0,10
		syscall	

