#	Program to compute the sum of squares (i^2) i=1..n

#	Usage of registers, plus prompt user to get n

#	Remember:
#		need to start with label main
#		$sp is the stack pointer
#		$ra save return address (i.e. where to return when we're done)
#		$zero aslways equall to zero

main:
	subu	$sp, $sp, 8	# make space for parameters on stack (2 words)
    				# $sp = $sp - 8

	#			# sw $register offset($base-adress)
	#			# store the resiter offset bytes from the base-adress
	sw	$ra, 0($sp)	# save register $ra on stack
	sw	$a0, 4($sp)	# save register $a0 on stack

    	move	$s0, $zero	# $s0 : i
	move	$s1, $zero	# $s1 : sum

	#			# Ask for a number
	li	$v0, 4		# syscall 4 : print string
	la	$a0, ask	# ask: string label
	syscall

	li	$v0, 5		# read integer
	syscall

	move	$s2, $v0	# $s2 : n

loop:
	mul	$t0, $s0, $s0	# Compute i^2
	add	$s1, $s1, $t0	# Accumulate sum
	addi	$s0, $s0, 1	# Increase i
	ble	$s0, $s2, loop	# Loop control
				# if (i <= n) goto loop

	#			# Prepare to print result
	li	$v0, 4		# load syscall option: 4 = print string
	la	$a0, str1	# load the string address into $a0 (argument)
	syscall			# call syscall.

	li	$v0, 1
	move	$a0, $s2
	syscall

	li	$v0, 4
	la	$a0, str2
	syscall

	li	$v0, 1		# same idea, syscall option 1 = print integer
	move	$a0, $s1
	syscall			# call syscall.

	li	$v0, 4		# once again.
	la	$a0, newl	# print text in newline as a string
	syscall

	#			# All right. We're done. 
	#			# free space on stack, and jump back to the original $ra
	lw	$ra, 0($sp)	# Restore register $ra
	addu	$sp, $sp, 8	# Pop stack
	jr	$ra		# return

	# Here data is stored
	.data
ask:
	.asciiz "\nEnter number > "
str1:
	.asciiz	"\nThe sum of i^2 from 1 .. "
str2:
	.asciiz " = "
newl:
	.asciiz	"\n"

