/*---------------------------------------------------------------*/
/*   Copyright (c) 1994 Regents of the University of California  */
/*                 All Rights Reserved                           */
/*---------------------------------------------------------------*/
/*-- WordWrap -----------------------------------------
   Task a string a returns a copy of the string with 
   newline characters inserted so that when printed
   no line exceeds the maximum width given. 

   Entry Requirements:
      string: The string to reformat.
      width: The maximum width for a string.

   Return Value:
      NULL : If unable to allocate a string to hold the
	     reformtted string.
      otherwise : A pointer to the reformatted string.

   Development History:
      Begun: 04/18/94 - Todd King

   Version:
      @(#)WordWrap.c	1.1   (UCLA/IGPP)   18 Apr 1994
------------------------------------------------------*/
#ifdef _MSDOS
#include <stdio.h>	/* For NULL */
#else
#include <unistd.h>	/* For NULL */
#endif
#include <ctype.h>	/* for isspace() */ 
#include <string.h>
#include <malloc.h>

char *
WordWrap(string, width)
char	*string;
int	width;
{
   int	i = 0;
   int	n = 0;
   int	count = 0;
   int	lastSpace = 0;
   char *tmp;
   int slen = strlen(string);
   int newLineLength = strlen("\n");
   char	*ptr = (char *) calloc(1, slen + 1 + ((slen / width) * newLineLength));

   if(ptr != NULL) {
      tmp = &string[i];
      for(i = 0; i < slen; i++) {
	 count++;
	 if(count > width) { /* Then break at last space or here if none. */
	    if(lastSpace != 0) {
	       i -= strlen(&ptr[lastSpace + 1]);
	       n -= strlen(&ptr[lastSpace + 1]);
	    }
	    ptr[lastSpace] = '\n';
	    n++;
	    count = 0;
	    lastSpace = 0;
	 } else if(string[i] == '\n') {	/* Break string now */
	    lastSpace = 0;
	    count = 0;
	    ptr[n++] = string[i];
	 } else {
	    if(isspace(string[i])) lastSpace = n;
	    ptr[n++] = string[i];
	 }
      }
   }

   return(ptr);
}
