# Author: Steven Carr
# Program Created: March 2023
# Assembly file that counts the amount of times a character occurs in a string
# Start the count file
count.s:
    .text               # Start the code section of the file
    .globl _count       # Define the following function as global
_count:
    push %ebx           # We are going to use ebx to store the count value, so we will reserve its use
    
    # Ensuring that the registers are not in use, we will set them to null
    movl $0, %eax
    movl $0, %ebx
    movl $0, %ecx
    movl $0, %edx

    # We now want to set a stack pointer to the arguments of our function, the first being the string and the
    # second being the character we are searching for and counting
    movl 8(%esp), %eax
    movb (%eax), %ecx       # This specifically will put the first byte of the string into ecx, which will allow comparison
    movb 12(%esp), %edx     # This is for the one character as the second argument

    # Now to start the main loop, which will simulate a while loop
loop_while:
    # Comparing bytes, compare the current letter with a null value, simulating checking if we're at the end of the string
    cmpb $0x0, %cl          # %cl being within the register %ecx
    
    # If null is equal to the value in %cl, then we've reached the end of the string, so jump to the end
    je end_count

    # Comparing bytes, compare the current letter in the string with the given letter in the argument
    cmpb %dl, %cl

    # If the letters are equal, then jump to the part of the program that increments the count
    je loop_increment

    # If they are NOT equal, we are going to jump to the end of this "while" loop before looping back around
    jmp loop_secondpart

loop_increment:
    # Increment the count, being stored in %ebx, by adding one to its value
    addl $1, %ebx

loop_secondpart:
    # If we reach here, the characters were not equal
    # Therefore, we want to check the next letter in the string
    
    # Increment the place in the string to the next spot
    addl $1, %eax       # %eax is holding our pointer to the string argument

    # Now lets reset the value at %ecx
    movl $0, %ecx

    # With %eax incremented to the next place, set that character to %ecx
    movb (%eax), %ecx

    # All steps should now be complete, so we jump back to the beginning of the "while" loop
    jmp loop_while

end_count:
    # Put the return count into %eax
    movl %ebx, %eax

    # Restore ebx so it can no longer be used
    pop %ebx

    # Return the total count of the character to the C function
    ret

    # End the function
    .end
