/*
 *	This program reverses characters in input
 *	strings a line at a time, and prints them
 */

#include <stdio.h>
#define NUL '\0'	/* Define the end-of-string NUL char */
#define MAXLEN 1000	/* Define arbitrary limit on length of input line */

main ()
{
	char line[MAXLEN];	/* Character array to hold input line first,
					then its reversed version */

					/*
					 * While getline() returns input lines 
					 */

	while (getline(line, MAXLEN) > 0)
	  {
		reverse(line);	/* Reverse each input line */
		printf("%s\n", line);	/* Print each reversed line */
	      }
}  

/*
 *	This function copies an input line into
 *	the character array s[]
 */

getline(s, lim)
char s[];
int lim;

{
	int c, n;

			/*
			 * Get input a character at a time
			 * and copy into character array s.
			 * Stop if getchar() returns EOF,
			 * end-of-line, or the limit -1
			 */

	for(n = 0; (c = getchar()) != EOF && c != '\n' && n < lim - 1; ++n)
	  {
		s[n] = c;	/* Put character into the array */
	      }

	s[n] = NUL;	/* Append NUL to end of array */
	return(n);	/* Return the length of the string in the array */
      }

/*
 * This function reverses order of characters in character array
 */

reverse(s)
char s[];	/* Declare the character array */
{
	int length, n;
	char r[MAXLEN];		/* The reverse string */

	length = len(s);	/* Get the length of s */

			/*
			 * The following loop reverses characters in s
			 * by copying to r:
			 *
			 * Until we reach the last s character before NUL--
			 */

	for(n = 0; n <= (length - 1); ++n)
	  {
		r[n] = s[length - 1 - n];	/* Copy a character to
						 * appropriate place in r,
						 * offsetting for the NUL */
	      }

			/*
			 * This loop copies reverse string back to s
			 */

	for(n = 0; n <= (length - 1); ++n)
	  {
		s[n] = r[n];
	      }
	return;
      }

/*
 *	This function determines length of string,
 *	including string's NUL charcater
 */

len(s)
char s[];
{
	int n;

				/* The following loop increments n */

	for(n = 0; s[n] != NUL; ++n)
	  {
		;
	      }
	return(n);	/* Return string's length */
      }
