/* this program reads from std in and truncates lines to the first space
   after the line limit -10. If the line goes beyond the line limit it is
   immediatly truncated to the limit and output continues on the next line
   NOTE files are assumed to have the last line ending in a newline */

#include <stdio.h>
int linelen = 100 ;
int lookspace ;
main(argc, argv)
int argc ;
char * argv[] ;
{
	int ch ;
	int i ;
	if (argc == 2)
		linelen = atoi(argv[1]) ;
	/* minor sanity check incase the argument was bad */
	if (linelen == 0)
	{
		linelen = 100 ;
	}
	/* where should we start looking for spaces */
	if (linelen > 50)
		lookspace = linelen - 10 ;
	else 
		lookspace = linelen -5 ;
	if(lookspace <5)
		lookspace == linelen ;

	i = 0 ;
	while ((ch = getchar()) != EOF)
	{
		/* we have a newline */
		if (ch == '\n')
		{
			putchar(ch) ;	
			i = 0 ;
		}
		/* we have reached the limit, force a newline */
		else if (i == linelen)
		{
			putchar('\n') ;
			i = 0 ;
			putchar(ch) ;
		}
		else if ((i > lookspace) && (ch == ' '))
		{
			putchar('\n') ;
			i = 0 ;
			/* we dont put the space here */
		}
		else
		{
			/* the line is OK and we dont have a newline */
			i ++ ;
			putchar(ch) ;
		}
	}
}
