/*
In this task, you should get familiar with file manipulation in C
by performing operations like reading the file content,
moving the file cursor, and writing the predefined string
"Halftime is for the real fans" to a specific position in a file.

Your tasks are:
- Open file quote.txt in read/write mode
  if fopen == NULL
  - Print "Could not open file\n"
  - return 1
- Print original content of file to console
- Ask user to enter a position to insert a predefined string
- move cursor to the specified position
  if cannot be moved
  - Print "Could not move the file cursor\n"
  - return 1
- overwrite existing content (i.e. use fseek to move the cursor)
- Write the predefined string into the file using fputs
- Rewind the file to the beginning and print the updated content of the file to the console
- Close the file properly after processing.

Examples:

Original file content: The first 90 minutes are the most important
Position to insert the string: 4
Updated file content: The Halftime is for the real fans important

Original file content: The first 90 minutes are the most important
Position to insert the string: -5
Could not move the file cursor
*/

#include <stdio.h>

int main(void)
{
  FILE *file = fopen("quote.txt", "r+");
  if (NULL == file) {
    printf("Could not open file\n");
    return 1;
  }

  printf("Original file content: ");
  int character = 0;
  while ((character = fgetc(file)) != EOF)
  {
    printf("%c", character);
  }
  printf("\n");
  rewind(file);

  long insert_position = 0;
  printf("Position to insert the string: ");
  scanf("%ld", &insert_position);

  if (fseek(file, insert_position, SEEK_CUR))
  {
    printf("Could not move the file cursor\n");
    fclose(file);
    return 1;
  }
  
  char* text_to_insert = "Halftime is for the real fans";
  fputs(text_to_insert, file);
  rewind(file);

  printf("Updated file content: ");
  while ((character = fgetc(file)) != EOF)
  {
    printf("%c", character);
  }
  printf("\n");

  fclose(file);
  return 0;
}
