#include <stdio.h>
#ifndef hpux
#include <strings.h>
#else
#include <string.h>
#endif
#include <ctype.h>
#include "config.h"
#include "lint.h"
/* Textformat(string[,width]) primitive -- Render 3/30/91, modified from telmud
*/

#ifndef TEXT_WIDTH
#define TEXT_WIDTH 70
#endif

#define TEXTSIZE 256   /* Must be 2 larger than max column width */
#define BIGBUFSIZ 4096

static int scrwidth = TEXT_WIDTH;
static char buffer[BIGBUFSIZ];
static char textbuf[TEXTSIZE], *buf;
static char *s = textbuf;
static char *b = buffer;
static char *endbuf = buffer + BIGBUFSIZ - 1;
static int pos = 0;

static int addchar(c)
char c;
{
  *b++ = c;
  return (b >= endbuf);
}

static int addstr(str)
char *str;
{
   while (*str && b<endbuf)
      *b++ = *str++;
   if (b < endbuf)
      *b++ = '\n';
   return (b >= endbuf);
}

static int addnstr(str, len)
char *str;
int len;
{
   if (b + len >= endbuf)
      return 1;
   bcopy(str, b, len);
   b += len;
   return 0;
}

static int text(string)
char *string;
{
   register char *p;
   int l = strlen(string), max;

   while(l > 0)
   {
      max = TEXTSIZE-1-(s-textbuf);
      strncpy(s, string, l > max ? max : l);
      s[l > max ? max : l] = '\0';
      l -= max;  string += max;
      buf = textbuf;
      for(p = s; *p; p++, pos++)
      {
	 if (*p == '\n' || pos >= scrwidth)
	 {
	    if (*p == '\n')
	    {
	       *p = 0;
	       if (addstr(buf)) return -1;
	       buf = p + 1;
	    }
	    else
	    {
	       while (p > buf && !isspace(*p))
		  p--;
	       if (p==buf)
	       {
		  if (addnstr(buf, scrwidth) || addchar('\n'))
		     return -1;
		  buf += scrwidth; p = buf-1;
	       }
	       else
	       {
		  *p = 0;
	          if (addstr(buf)) return -1;
		  buf = p + 1;
	       }
               while (isspace(*buf)) buf++;
	    }
	    pos = -1;
	 }
      }
      if (pos > 0)
      {
	 bcopy(buf, textbuf, pos);
	 textbuf[pos] = 0;
	 s = textbuf + pos;
      }
      else
	 s = textbuf;
      
   }

   fflush(stdout);
   return pos;
}

static int textnl()
{
   textbuf[pos]=0;
   if (addstr(textbuf)) return -1;
   pos = 0;
   s = textbuf;
   return 0;
}

static void textflush()
{
   pos = 0;
   *textbuf = 0;
   s = textbuf;
   b = buffer;
}

char *textformat(string, width)
char *string;
int width;
{
   int stupid;

   textflush();
   if (width)
      scrwidth = width;
   else
      scrwidth = TEXT_WIDTH;
   if (scrwidth > TEXTSIZE-2)
      return NULL;

   stupid = text(string);
   if (stupid > 0 && textnl() < 0)
      return NULL;
   else if (stupid < 0)
      return NULL;
   *b = '\0';
   return buffer;
}