/*
 * Copyright 2026 Naomi Alterman
 * Ask user for a word and print it forwards and backwards.
 * CSE 333 demo (for debugging).
 */

#define MAX_STR 100   /* length of longest input string */

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

/* Return a new string with the contents of s backwards */
char* Reverse(char* s) {
  char* result = NULL;            /* the reversed string */
  int left_index, right_index;
  char ch;

  /* copy original string then reverse and return the copy */
  int strsize = strlen(s)+1;
  /* EX2 Fix: Allocate space for reversed string*/
  result = (char*) malloc(strsize);
  /* EX3 Fix: Check for malloc failure */
  if (result == NULL) {
    exit(EXIT_FAILURE);
  }
  strncpy(result, s, strsize);

  left_index = 0;
  right_index = strlen(result) - 1;
  while (left_index < right_index) {
    ch = result[left_index];
    result[left_index] = result[right_index];
    result[right_index] = ch;
    ++left_index; --right_index;
  }

  return result;
}

/* Ask the user for a string, then print it forwards and backwards.     */
int main() {
  char line[MAX_STR];    /* original input line */
  char* rev_line;       /* backwards copy from reverse function */

  printf("Please enter a string: ");
  fgets(line, MAX_STR, stdin);
  line[strlen(line)-1] = '\0';
  rev_line = Reverse(line);
  printf("The original string was:   >%s<\n", line);
  printf("Backwards, that string is: >%s<\n", rev_line);
  printf("Thank you for trying our program.\n");
  /* EX2 Fix: Free the reversed string preventing memory leak */
  free(rev_line);
  return EXIT_SUCCESS;
}