/*
 * K&R C Programming Language
 * -------------------------------------------------------------
 * Excersise 1-19
 *
 * Write a function reverse(s) that reverses the character string s.
 * Use it to write a program that reverses its input a line at a time.
 *
 */

#include <stdio.h>

#define BUFSIZE 1024        /* maximum length of buffer */

void reverse(char s[]);
int getline1(char buf[], int n);

/* use getline and reverse functions */
int
main()
{
    int len;
    char buf[BUFSIZE];

    while ((len = getline1(buf, BUFSIZE)) > 0) {
        if (buf[len-1] == '\n')     /* remove \n from input line if exist */
            buf[len-1] = '\0';
        reverse(buf);
        printf("%s\n", buf);
    }
    return 0;
}

void
reverse(char s[])
{
    int i, j, tmp;

    for (j = 0; s[j] != '\0'; j++)
        ;

    for (i=0, j=j-1; i < j; ++i, --j) {
        tmp = s[i];
        s[i] =s[j];
        s[j] = tmp;
    }
}

int
getline1(char buf[], int n)
{
    int i, c;

    for (i = 0; i<n-1 && (c=getchar())!=EOF && c!='\n'; ++i)
        buf[i] = c;

    if (c == '\n') {
        buf[i] = c;
        ++i;
    }
    buf[i] = '\0';
    return i;
}
