#---------------------------------
# Lab 8
#
# 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 20
	sum:				.word 0x00000000
	powerOfTen:			.word 0x00000000
	j:				.word 0x00000000
	stringLength:			.word 0x00000000
	newLine:			.asciiz "\n"
	
.text 0x3000

main:
	
	
	#init j as zero 
	ori $t3, $0, 0
	
	sw $t3, spaceForStringThatIsRead
	
	
	#read in string
	
	ori $v0, $0, 8 				#tell it to do readstring
	la $a0, spaceForStringThatIsRead	#space for it to be put. This will be in the first spot. 
	ori $a1, $0, 20				#max char to read	
	syscall
	
	
	#branch out if the value is 0
	lw $a0, spaceForStringThatIsRead
	ori $t1, $0, 2608
	
	#print word for debugging
	#la $a0, spaceForStringThatIsRead
	#ori $v0, $0, 4
	#syscall
	
	beq $a0, $t1, exiting
	

	#The address of the string read by main must be passed to a_to_i in register $a0
	la $a0, spaceForStringThatIsRead
	#then we call the subroutine 
	jal a_to_i
	
	
	#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
	
	
a_to_i:
	
	#sum is t0
	ori $t0, $0, 0
	#power of ten is t1
	ori $t1, $0, 1
	#j is t2
	ori $t2, $0, 0
	#stringlen is t3
	ori $t3, $0, 0
	
	
	#memory address of string is $a0
	counterLoop:
		
		#current index in string is stored in t4
		add $t4, $t2, $a0
		
		lb $t6, ($t4)
		beq $t6, 0, initSumming #we've hit the end of the string. problem here
	
	
		addi $t3, $t3, 1
		addi $t2, $t2, 1 	#because we're loading bytes, it's adding 1 to memory address
		
		beq $0, $0, counterLoop
	
	initSumming:
	
		#we counted the new line so subtract that here
		#addi $t3, $t3, -1
	
		
				

		#make t4 the end of the string now
		add $t4, $0, $a0
		
		#we have a newline so start 1 less
		addi $t4, $t4, -2
		
		add $t4, $t4, $t3
		
		
	summing:
		
		lb $t6, ($t4)
		sub $t8, $t6, 48 
		mul $t9, $t1, $t8
		add $t0, $t0, $t9
		
		mul $t1, $t1, 10		
	
		beq $t4, $a0, returnBack
		
		addi $t4, $t4, -1
		
		beq $0, $0, summing
	
	#return value in v0
	
	returnBack:
		
		ori $v0, $0, 0
		or $v0, $0, $t0																										
		jr $ra	
	
	


	
exiting:					
	
	or $a0, $0, $0
	ori $v0, $0, 1
	syscall
	
	
	ori $v0, $0, 10				#System call code 10 for exit
	syscall					#exit the program
