/**********************************************************************
 * wrap.c -- utility to wrap infinitely long lines
 *
 * $Author$
 * $Source$
 * $Header$
 *
 * Copyright 1991 by the Massachusetts Institute of Technology.
 *
 * For copying and distribution information, please see the file
 * <mit-copyright.h>.
 **********************************************************************/
#include <mit-copyright.h>

#ifndef lint
static char rcsid_wrap_c[] = "$Header$";
#endif /* lint */

#include <stdio.h>
#define RMARGIN 72
char *malloc();			/* really should be in header file */

main(argc, argv)
     int argc;
     char *argv[];
{
  register char *s, *white = NULL; /* index, last beginning whitespace */
  char *buf1, *buf2, *un, *last;	/* buffers, unwritten chars */
  int n, column, multispace=1;

  /* allocate consecutive pair of buffers */
  if ((buf1 = malloc(2*RMARGIN)) == NULL) {
    perror(argv[0]);
    exit(1);
  }
  buf2 = buf1 + RMARGIN;

  /* read a buffer */
  un = buf2;
  while(n = fread(buf2, sizeof(char), RMARGIN, stdin) {
    column = 0;
    for(s=buf2; s < buf2 + n; s++) {
      switch(*s) {
      case ' ':
	column++;
	if (column < RMARGIN && !multispace) white = s;
	multispace = 1;
	break;
      case '\t':
	column += 8;
	if (column < RMARGIN && !multispace) white = s;
	multispace = 1;
	break;
      case '\n':
	if (fwrite(un, sizeof(char), s-un+1, stdout) < s-un+1) {
	  perror(argv[0]);
	  exit(1);
	}
	un = s+1;
	column=0;
	multispace = 1;		/* ignore indents at beginning of line */
	break;
      default:
	column++;
      }
    }
    /* if it's a long line, just write it */
    
