#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>

static void mySignalHandler(int iSignal) {
   printf("\nSorry. You took too long.\n");
   exit(1);
}

void disable_buffering() {
    setvbuf(stdin, NULL, _IONBF, 0);
    setvbuf(stdout, NULL, _IONBF, 0);
    setvbuf(stderr, NULL, _IONBF, 0);
}


int main() {
  void (*pfRet)(int); 
  pfRet = signal(SIGALRM, mySignalHandler);
  
  disable_buffering();

  char input[16];  // Buffer to read each guess (we only need one char)
  int correct_count = 0; // Amount of "right" chars

  char* flag = getenv("FLAG"); // The flag

  int i = 0; // The current char
  while (correct_count <= (int)strlen(flag)-1) {
    char guess; // The users guess
    int valid = 0; // Is the users't input valid?

    // Read a guess from the user until a valid non-newline character is provided
    while (!valid) {
      printf("Guess for character %d: ", i + 1);
      fflush(stdout);
      alarm(3);
      if (fgets(input, sizeof(input), stdin) == NULL) {
        printf("Error reading input.\n");
        exit(1);
      }
      if (input[0] == '\n') {
        continue;
      }
      guess = input[0];
      valid = 1;
    }

    // Compare the guessed character with the flag character
    if (guess == flag[i]) {
      printf("Correct!\n");
      correct_count++;
      i += 1;
    } else if (guess < flag[i]) {
      printf("Hint: The correct character is higher than '%c'.\n", guess);
    } else {
      printf("Hint: The correct character is lower than '%c'.\n", guess);
    }
  }

  if (correct_count == ((int)strlen(flag))) {
    printf("\nCongratulations! You've guessed the entire flag correctly!\n");
  } else {
    printf("\nYou guessed %d out of %d characters correctly. Better luck next time!\n", correct_count, (int)strlen(flag));
  }

  return 0;
}
