#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX_NUMBER 100

/* External variable */
int secret_number;

// Prototypes
void initialize_number_generator(void);
void choose_new_secret_number(void);
void read_guess(void);

int main() {
  char command = 'y';
  printf("Guess the secret number between 1 and %d. \n\n", MAX_NUMBER);
  initialize_number_generator();
  do {
    choose_new_secret_number();
    printf("New number has been chosen.\n");
    read_guess();
    printf("Play again? (Y/N)\n");
    while (getchar() != '\n')
      ; // Discard any leftover input
    scanf("%c", &command);
    printf("\n");
  } while (command == 'y' || command == 'Y');
  exit(0);
}

/**
 * @brief Initializing random number generator based on current time
 * time(NULL) returns current time in `time_t` format
 */
void initialize_number_generator(void) { srand((unsigned)time(NULL)); }

/**
 * @brief Here we are using rand() function and getting the remaining value of
 * deletion by MAX_NUMBER + 1 to get random value between 0 and 100
 */
void choose_new_secret_number(void) {
  secret_number = rand() % MAX_NUMBER + 1;
};

void read_guess(void) {
  int guess, num_guesses = 0;
  for (;;) {
    num_guesses++;
    printf("Enter guess: ");
    scanf("%d", &guess);
    if (guess == secret_number) {
      printf("You guessed the number after %d attempts!\n\n", num_guesses);
      return;
    } else if (guess < secret_number) {
      printf("Missed! Secret value is lower than your value\n");
    } else {
      printf("Missed! Secret value is higher than your value\n");
    }
  }
};
