################################################################################
##
## Solution to LSU EE 3755 Fall 2001 Practice Final Problem 2
##

# Exam: http://www.ece.lsu.edu/ee3755/2001f/fep.pdf

# The solution starts at the "atoi" label below.

# Program Output:
#
#    The string at address 0x10010000 which is "713" has a value of 713.
#    Confused?  If so then think about it.
#    Still confused?  Ask for help before it's too late!

        .data
SEVEN_HUNDRED_THIRTEEN:
        .asciiz "713"
MSG:
        .ascii  "The string at address 0x%/a1/x which is \"%/a1/s\" "
        .ascii  "has a value of %/v1/d.\n"
        .ascii  "Confused?  If so then think about it.\n"
        .asciiz "Still confused?  Ask for help before it's too late!"

        .text
        .globl __start
__start:
        la $a0, SEVEN_HUNDRED_THIRTEEN
        add $a1, $a0, $0  # Make a copy of the address
        jal atoi
        nop
        # $v0 should contain 713.
        add $v1, $v0, $0  # Make a copy of the return value.
        la $a0, MSG
        addi $v0, $0, 11  # Print out results.
        syscall
        addi $v0, $0, 10  # Exit.
        syscall

atoi:
        # Called with $a0 the address of an ASCII null-terminated string.
        # Return value of string as an integer in $v0.
        # String contains only digits, no whitespace, no - or +.
        # Number in string is in decimal.
        # This routine is allowed to modify $a0.
        j START
        add $v0, $0, $0
LOOP:
        addi $t1, $t1, -48  # '0' = 48
        sll $t2, $v0, 3
        sll $t3, $v0, 1
        add $v0, $t2, $t3
        add $v0, $v0, $t1
START:
        lb $t1, 0($a0)
        bne $t1, $0, LOOP
        addi $a0, $a0, 1
        jr $ra
        nop