/*
 * rf.c - a "WordStar"-like paragraph reformatter for vi.  From the
 * "Wizard's Grabbag" article (Dr. Rebecca Thomas) in the Nov. '85
 * issue of Unix/World.
 *
 */

#include <stdio.h>
#define YES 1
#define NO 0
#define LINELENGTH 70

main()
{

int endchar;			/* does this word end a sentence? */
int getword();			/* get next word on stdin */
int length;			/* length of word read by getword */
int count = 0;			/* number of characters on line so far */
char word[81];			/* word read from stdin */

while ((endchar = getword(word)) != EOF) {
	count += length = strlen(word);
	if (count > LINELENGTH) {	/* split the line here */
		putchar('\n');
		count = length;	/* beginning count for next line */
		printf("%s ", word);
		if (endchar == YES)
			putchar(' ');	/* end of sentence space */
	}
	else	if (endchar == YES) {
			printf("%s  ", word);	/* extra space */
			count++;	/* and account for it */
		}
		else
			printf("%s ", word);
	count++;		/* to account for the extra space */
}

if (strlen(word) > 0)
	printf("%s", word);	/* print any left over word */
putchar('\n');
exit(0);

}

int getword(word)
char *word;			/* storage for word read */
{
char c;
int endflag = NO;		/* does this word end a sentence? */
int beginflag = YES;		/* is this the beginning of new word? */

while((c = getchar()) != EOF) {
	switch(c) {
	case '.':
	case '!':		/* end of sentence characters */
	case '?':
		endflag = YES;
		*word++ = c;
		break;
	case ' ':
	case '\t':		/* word delimiters - white space */
	case '\n':
		if (beginflag == YES)
			continue;	/* skip leading white space */
		*word = '\0';		/* terminate word */
		return(endflag);	/* non-EOF return */
	default:		/* just another character */
		endflag = NO;
		*word++ = c;
	}
	beginflag = NO;		/* no longer at beginning of word */
}

*word = '\0';			/* terminate the word */
return(EOF);

}
