// ex_ch8_5.c
#include <stdio.h>
#include <stdbool.h>
char get_first(void);

int main(void)
{
	int guess = 50;
	char response;
	int min = 0, max = 100;

	printf("Pick an integer from 1 to 100. I will try to guess it.\n");
	printf("Respond with y if my guess is right and with n if it is "
	       "wrong\n");
	printf("Uh... is your number %d?\n", guess);
	printf("y)es\t\tl)ower\t\th) higher\n");
	
	// get response, compare to 'y'
	while ((response = get_first()) != 'y')
	{
		if (response == 'l')
		{
			max = guess;
			guess -= ((max - min) / 2);
			printf("Well, then, it is %d? ", guess);
		}
		else if (response == 'h')
		{
			min = guess;
			guess += ((max - min) / 2);
			// when min and max are 99 and 100 for example
			if (min + 1 == max)
				guess++;
			printf("Well, then, it is %d? ", guess);
		}
		else
			printf("Sorry, I understand only y, h and l.\n");
	}
	printf("I knew I could do it!\n");
	
	return 0;
}

char get_first(void)
{
	int ch;
	// get the first non-newline character, save it in ch
	while ((ch = getchar()) && isspace(ch))
 		continue;
 	
	// skip all the other characters until the newline
	while (getchar() != '\n')
		continue;
	
	// return the first non newline character
 	return ch;
}
