# Factorial Demo
# This class will demonstrate what happens when a method is called.
# It will also demonstrate the concept of recursion as it applies to assembly language development.
.data
prompt1: .ascii "\nPlease enter a number: \n\000 "
outputMessage: .ascii "\nThe factorial of the number is: "

.text
main:
	# Get a number from the user for the factorial.
	li $v0, 4	# Prompt the user to enter an int.
	la $a0, prompt1
	syscall
	
	# Read in the number.
	li $v0, 5
	syscall
	
	# calculate the factorial
	move $a0, $v0
	jal factorial

	# Print the result.
	move $t0, $v0
	
	li $v0, 4	# Prompt the user to enter an int.
	la $a0, outputMessage
	syscall
	
	move $a0, $t0
	li $v0, 1
	syscall
	j main

#############################################################################
# The method will calculate the factorial of a given number.
# The return value will be the factorial of the given number.
# The algorithm will use recursion.
# Parameters:
#   $a0 - The value for which we desire to return the factorial.
# Return Value:
#   $v0 - The return value from the method.
#
#############################################################################
factorial:
	#push $ra

	addi $sp, $sp, -8	# Adjust the stack pointer.
	sw $a0, 4($sp)		# Store $a0 as the argument.
	sw $ra, 0($sp)		# STore the item on the stack.
	
	# if (value < 1)
	blt $a0, 1, returnOneValue
			#else
	# {return factorial(value - 1) * value;}

	addi $a0, $a0, -1
	jal factorial
	addi $a0, $a0, 1

	mul $v0, $v0, $a0
	# pop $ra
	lw $ra, 0($sp)		# Load the data into the register.
	lw $a0, 4($sp)		# Load the argument in.
	addi $sp, $sp, 8	# Move the stack pointer a value of 4.

	jr $ra
	# {return 1}
returnOneValue:
	li $v0, 1
	# pop $ra
	lw $ra, 0($sp)		# Load the data into the register.
	lw $a0, 4($sp)		# Load the argument in.
	addi $sp, $sp, 8	# Move the stack pointer a value of 4.
	
	jr $ra
	

	#



#############################################################################
# End factorial procedure
#############################################################################
