/* Dennis W. Brylow   */
/* COSC 065 Fall 2007 */
/* getInt demo part 2 */
#include <mips.h>

.data

FMT:    .string "%d\r\n"
FMT2:   .string "Number read is = %d\r\n"

.text
.globl main

main:
        /* Function prolog.             */
        /* Sets up environment for user program to execute.             */
        addiu   sp, sp, -32  /* Make room on Stack for O/S values.  */
        sw      ra, 28(sp)   /* Store O/S return address on Stack.  */
        /* Start of your program.       */

loop:   
        jal     getInt
        bnez    v1, done
        la      a0, FMT2
        move    a1, v0
        jal     kprintf         /* Printf final answer. */
        b       loop
                
done:   
        /* End of your program.         */
        /* Function epilogue.           */
        /* Restores the environment from the O/S. */
        lw      ra, 28(sp)  /* Restore O/S return address.              */
        addiu   sp, sp, 32  /* Restore O/S stack pointer.               */
        li      v0, 0       /* Return value of 0 (normal exit).         */
        jr      ra          /* Return to Operating System.              */



#define EOF   4
#define TOTAL s7
#define MINUS s6
#define CHAR  t9
#define RETRN s4
                
getInt:
        move    RETRN, ra
        move    TOTAL, zero     /* s1 is total.  Initialize to 0.      */
        li      MINUS, 1        /* s2 is minus flag.  Init to 1.       */

        jal     getchar         /* Get first character.                */
        li      t0, '-'         /* Check for literal ASCII minus sign. */
        bne     t0, v0, gt2     /* IF there is NOT a minus, jump into  */
        li      MINUS, -1       /*  main loop, otherwise set flag.     */
gtlp:
        jal     getchar         
gt2:    move    CHAR, v0        /* Save last character read.           */

        li      t3, EOF
        li      t2, '\n'
        li      t0, '0'
        li      t1, '9'

        beq     CHAR, t3, gtdn2 /* IF EOF, jump to gtdone2.             */
        beq     CHAR, t2, gtdn  /* IF newline, jump to gtdone.          */
        blt     CHAR, t0, gtlp  /* IF less than '0', try again.       */
        bgt     CHAR, t1, gtlp  /* IF greater than '9', try again.    */
        
        li      t0, '0'         /* Subtract value of ASCII '0' to     */
        sub     CHAR, CHAR, t0  /*  get actual numeral value.         */

        li      t0, 10          /* Horner's Algorithm.  Multiply      */
                                /*  total by base, add in next digit. */
        mul     TOTAL, TOTAL, t0        
        add     TOTAL, TOTAL, CHAR

        b       gtlp

gtdn2:  addi    v1, zero, 1
        jr      RETRN
                
gtdn:                               /* Multiply by minus flag. */
        mul     v0, TOTAL, MINUS
        move    v1, zero
        jr      RETRN

                
