#include <stdio.h>
#include "genlib.h"

#define MAXWORDLEN 20

void GetWord (char word[]);
void Reverse (char word[], char rev[]);
bool LexOrder (char wordA[], char wordB[]);
bool IsPalindrome (char word[]);

void main()
{
  char word[MAXWORDLEN];
  GetWord(word);
  if (IsPalindrome(word))
    printf("%s is a palindrome\n", word);
  else
    printf("%s is not a palindrome\n", word);
}

void GetWord (char word[])
{
  int i;
  printf("enter a word: ");
  for (i = 0; (word[i] = getchar()) != '\n'; i++); /* getchar until newline */
  word[i] = '\0';   /* put null character at end or word */
}

void Reverse (char word[], char rev[])
{
  int i, j;
  for (i = 0; word[i] != '\0'; i++);  /* advance i to point to end of word[] */
  for (j = i - 1; j >= 0; j--)
    rev[i-j-1] = word[j];      /* copy from back of word[] to front of rev[] */
  rev[i] = '\0';               /* null terminate the new reversed word */
}

bool LexOrder (char wordA[], char wordB[])
{
  int i;
  char a,b;
  for (i = 0; (a = wordA[i]) != '\0'; i++) { /* compare each char of wordA to wordB */
    if ((b = wordB[i]) == '\0')/* end of wordB reached meaning wordB */
      return FALSE;	       /* is a substring or wordA */
    if (a < b)
      return TRUE;             /* wordA comes before word B */
    if (b < a)
      return FALSE;            /* wordB comes before word A */
  }                            /* otherwise move on to compare the next char */
  return TRUE; /* end of wordA reached meaning wordA is a substring of wordB */
}

bool IsPalindrome (char word[])
{
  char rev[MAXWORDLEN];
  Reverse(word, rev); /* get the reverse of the word */
  /* a word is equal to its reverse if and only if LexOrder(word, rev)
     and LexOrder(rev, word) are both true */
  return (LexOrder(word, rev) && LexOrder(rev,word));
}
