#---------------------------------
# Lab 9
#
# Name: <Joe Puccio>
# Onyen: <jpuccio>
#
# --------------------------------
# Below is the expected output.
# 
# Converting pixels to grayscale:
# 0
# 1
# 2
# 34
# 5
# 67
# 89
# Finished.
# -- program is finished running --
#---------------------------------

.data 0x0
	spaceForStringThatIsRead: 	.space 15
	sum:				.word 0x00000000
	powerOfTen:			.word 0x00000000
	j:				.word 0x00000000
	stringLength:			.word 0x00000000
	newLine:			.asciiz "\n"
	
.text 0x3000

main:
	
	#clean out previous read
	ori $t3, $0, 0
	sw $t3, spaceForStringThatIsRead
	
	
	#read in int
	
	ori $v0, $0, 5 				#tell it to do readint
	#la $a0, spaceForStringThatIsRead	#space for it to be put. This will be in the first spot. 
	#ori $a1, $0, 15				#max char to read	
	syscall
	
	
	
	#lw $a0, spaceForStringThatIsRead
	
	#branch out if the value is 0
	ori $t1, $0, 0
	beq $v0, $t1, exiting
	
	#print word for debugging
	#la $a0, spaceForStringThatIsRead
	#ori $v0, $0, 4
	#syscall
	
	
	#The address of the string read by main must be passed to a_to_i in register $a0
	#la $a0, spaceForStringThatIsRead
	
	#put user entered input into function input 
	ori $a0, $v0, 0
	#then we call the subroutine 
	jal fibonacci
	
	
	
	#print out the returned value, stored in register v0
	or $a0, $0, $v0				
	ori $v0, $0, 1				#sys code 1 prints int in a0
	syscall
	
	#print newLine
	la $a0, newLine				#loads New Line
	ori $v0, $0, 4
	syscall
	
	beq $0, $0, main
	

fibonacci: 

	#do the storing
	
	#store return address
	addi $sp, $sp, -4
	sw $ra, ($sp)
	
	#store input (which is a0)
	addi $sp, $sp, -4
	sw $a0, ($sp)
	
	#if greater than or equal to two call n-1 and n-2 case
	ori $t5, $0, 2
	bge $a0, $t5, callNMinusOneAndTwo
	
	#if 0, return zero
	beq $a0, $0, returnZero
	
	#else, we know input is one so we return 1
	add $v0, $0, $a0
	ori $v0, $0, 1 #put 1 in there
	addi $sp, $sp, 4
	beq $0, $0, return
	
	
	callNMinusOneAndTwo:
		#call n-1
		add $a0, $a0, -1
		jal fibonacci
		ori $t1, $v0, 0 
		
		
		#a0 got changed by the above code, so we have to restore it
		lw $a0, ($sp)
		addi $sp, $sp, 4
		
		#our t1's are getting overwritten!!!
		#So we overwrite old a0 in stack with t1
		addi $sp, $sp, -4
		sw $t1, ($sp)
		
		#call n-2
		add $a0, $a0, -2
		jal fibonacci
		ori $t2, $v0, 0 
		
		lw $t1, ($sp)
		addi $sp, $sp, 4
		
		add $v0, $t1, $t2 
		beq $0, $0, return
	
	return:
		lw $ra, ($sp)
		addi $sp, $sp, 4
		jr $ra
	
	returnZero:
		ori $v0, $0, 0 #put 0 in there
		addi $sp, $sp, 4
		beq $0, $0, return
	
exiting:					
	
	ori $a0, $0, 0
	ori $v0, $0, 1
	syscall
	
	
	ori $v0, $0, 10				#System call code 10 for exit
	syscall					#exit the program
