/* strutils.C
 * John Viega
 *
 * Jan 28-29 2000
 */

#include "config.H"
#include "fatal.H"

/* 
 * Remove leading and trailing white space.  Deposit in buf.
 */

int Strip(char *s, char *buf)
{
  char *end = s + strlen(s);
  char *start = s;
  while(1)
    {
      switch(*start)
	{
	case ' ':
	case '\t':
	case '\v':
	case '\f':
	case '\n':
	case '\r':
	  start++;
	  continue;
	}
      break;
    }
  while(end > start)
    {
      switch(*end)
	{
	case ' ':
	case '\t':
	case '\v':
	case '\f':
	case '\n':
	case '\r':
	  end--;
	  continue;
	}
	  break;
    }
  for(char *p=start;p<end;p++)
    {
      *buf++ = *p;
    }
  *buf=0;
  return end-start;
}


char *Wrap(char *str)
{
  if(GetMSVSFormat()) {
    char *res = new char[strlen(str)+1];
    strcpy(res, str); // ITS4: ignore strcpy
    return res;
  }
  int  width = GetOutputWidth();
  size_t len = strlen(str) + 1; // length of string including null byte
  // I think this is the right upper bound on the length of the result.
  char *result = new char[len + 2*(len/width+strlen(NEWLINE)-1)+1];
  if(!result)
    OutOfMemory();
  result[0] = '\0';
  char *bgn = str;
  char *ptr = bgn;
  while(ptr < str + len)
  { 
  int counter = 0;
  char *last_space = 0;
  while((counter < width) && (ptr < str + len))
    {
      if(*ptr=='\n') counter = 0;
      if(*ptr==' ') last_space = ptr;
      ptr++;
      counter++;
    }
  if(*ptr == ' ') last_space = ptr;
  if(last_space && (counter == width))
    {
      strncat(result, bgn, last_space-bgn);
      strcat(result, NEWLINE);  /* ITS4: ignore */
      bgn = last_space+1;
      ptr = bgn;
      continue;
    }
  if(ptr == str + len)
    {
      strncat(result, bgn, ptr-bgn);
      break;
    }
  strncat(result, bgn, width-1);
  strcat(result, "-"); 
  strcat(result, NEWLINE); /* ITS4: ignore strcat */
  bgn = --ptr;
  continue;
  }

  return result;
}
