/*************************
 * COSC 065 Fall 2006    *
 * getInt Demo           *
 * D.W. Brylow           *
 *************************/
	
#include <cosc065.h>

.rodata

FMT:	.string "%d\n"

.text
.globl main

main:
        /* Function prolog. */
        /* Sets up environment for user program to execute. */
        stwu    r1,-32(r1)  /* Make room on Stack for O/S values.  */
        mflr    r0          /* Store O/S return address on Stack.  */
        stw     r0,36(r1)
        stw     r31,28(r1)  /* Store O/S frame pointer on Stack.   */
        mr      r31,r1      /* new stack top is now frame pointer. */

        /* Start of your program. */
loop:
	bl	getInt
	cmpwi	r3, 0	    /* Watch for EOF.                      */
	blt	done

	mr	r4, r3      /* Print out integer result.           */
	lis	r3, FMT@ha
	addi	r3, r3, FMT@l
	bl	printf

	b	loop	
done:

        /* End of your program. */

        /* Function epilogue. */
        /* Restores the environment from the O/S. */
	mr	r1, r31     /* Discard stack below frame pointer.  */
	lwz	r31,28(r1)  /* Restore O/S frame pointer.          */
	lwz	r0, 36(r1)
	mtlr	r0          /* Restore O/S return address.         */
	lwz	r1, 0(r1)   /* Restore O/S Stack pointer.          */
	li r3, 0            /* Return value of 0 (normal exit).    */
        blr                 /* Return to Operating System.         */


/*******************
 * getInt
 * Calls getchar repeatedly to read in characters from
 *  the O/S which are interpreted as a multi-digit,
 *  positive integer.  Filters out unwanted non-digits.
 * Returns EOF if end of file reached.
 *******************/
getInt:
	mflr	r14	    /* Save my return address in r14.      */
	li	r13, 0      /* Initialize grand total.             */
	
giloop:
        bl      getchar     /* Get a character from O/S.           */
                            /* Note: Calling another function like */
			    /*  getchar may nuke the values in reg */
	                    /* r0, and r3 - r12.                   */
	
        cmpwi   r3, 0       /* Check for EOF.                      */
        blt     gieof
        cmpwi   r3, '0'     /* Check for non-digits.               */
        blt     gidone
        cmpwi   r3, '9'
        bgt     gidone

        subi    r3, r3, '0' /* Subtract ASCII offset of '0'.       */
		            /* Horner's Algorithm.                 */
        mulli   r13, r13, 10
        add     r13, r13, r3
        b       giloop
gidone:
	mr	r3, r13	    /* Return value in r3, like all good   */
gieof:			    /*  functions.                         */
	mtlr	r14         /* Restore return address to LR.       */
	blr


















