#include	<stdio.h>
#include	<ctype.h>

/*
 *  hello6.c
 *
 *	purpose: shows how to examine a string char by char
 */

#define	STRSIZE		100

main()
{
	int	maxnum;					/* limit */
	char	message[STRSIZE];			/* an array of chars */

	printf("Print what string? ");
	fgets(message, STRSIZE, stdin);			/* read in a string  */

	maxnum = get_a_positive_number("Print how many times? ", 3);

	repeat_a_message( message, maxnum );
}

repeat_a_message( char message[STRSIZE], int times )
/*
 * purpose: prints out the string in `message' for `times' iterations
 */
{
	int	i;					/* local variable */

	for ( i = 0 ; i<times ; i++ )	
		printf( "%d. %s", i, message ); 	/* print it */
}

int
get_a_positive_number( char promptStr[STRSIZE], int maxBad) 
/*
 * purpose: demand a positive integer from the user
 * returns: a positive integer
 */
{
	int	inputval  = -1;
	int 	badInputs = 0;				/* tracks illegal inputs     */
	char	inputstr[STRSIZE];

	while( inputval <= 0 )
	{
		printf("%s", promptStr);                /* prompt                    */
		fgets(inputstr, STRSIZE, stdin );	/* input                     */
		if ( is_a_number( inputstr ) == 0 ) {   /* digits?                   */
			printf("This is not a number: %s", inputstr );
			badInputs++;			/* increment badInputs       */	
			if ( badInputs > maxBad ) {	/* if too many bad inputsq2  */
				printf("I'm sorry, I don't understand what you said.\n" );
				exit(1);
			}
		}
		else {
			inputval = atoi( inputstr );
			if ( inputval <= 0 )
				printf("%d is not positive number\n", inputval);
		}
	}
	return inputval;				/* send value back to caller */
}

int
is_a_number( char str[STRSIZE] )
/*
 * purpose: examine a string and see if all the chars are digits
 * returns: 1 if all chars before the newline are digits, 0 otherwise
 * bug?:    what if a string with no chars appears?
 */
{
	int	pos;					/* index into string         */
	int  	exitFlag = 0;				/* flag for exit loop        */

	pos = 0;
	while( str[pos] != '\n' ){			/* until done                */
		
		if ( ! isdigit(str[pos]) )		/* if not a dig              */
			exitFlag = 1;			/* tag exit flag             */			
		if ( pos == 0 ) {			/* check if first char       */
			if ( (str[pos] == '+' || str[pos] == '-') /* is + or -       */
                              && str[pos + 1] != '\n' ) /* and subsequent char is not null */
				exitFlag = 0;		/* clear exitFlag, it's OK   */
		}
		
		if ( exitFlag == 1 )			/* exit flag tagged          */
			return 0;			/* exit now with 0           */

		pos++;					/* advance one               */
	}
	return 1;					/* no problems               */
}

