/*
 * K&R C Programming language
 * -----------------------------------------------------------
 * Exercise 1-16.
 *
 * Revise the main routine of the longest-line program so it
 * will correctly print the length of arbitrarily long input
 * lines, and as much as possible of the text.
 *
 */

#include <stdio.h>

int getline1(char buf[], int n);

#define BUFLEN  5

int
main()
{
    char buf[BUFLEN];       /* current input line */
    int len;        /* current input line length */
    int lensofar;   /* length of current long input line */
    int max;        /* max length seen so far */

    max = 0;
    lensofar = 0;
    while ((len = getline1(buf, BUFLEN)) > 0) {
        if (len == BUFLEN-1 && buf[len-1] != '\n') {
            lensofar = lensofar + len;
            continue;
        }

        if (len+lensofar > max)
            max = len + lensofar;

        lensofar = 0;
    }

    if (max > 0)
        printf("%d\n", max);

    return 0;
}

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

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