/* Fold each input line to fit in specified width.
   Copyright (C) 1986 Richard M. Stallman

		       NO WARRANTY

  BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW.  EXCEPT
WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC,
RICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS"
WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY
AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.

 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY
WHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE
LIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR
OTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR
A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS
PROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY.

		GENERAL PUBLIC LICENSE TO COPY

  1. You may copy and distribute verbatim copies of this source file
as you receive it, in any medium, provided that you conspicuously
and appropriately publish on each copy a valid copyright notice
"Copyright (C) 1986 Richard M. Stallman"; and include following the
copyright notice a verbatim copy of the above disclaimer of warranty
and of this License.

  2. You may modify your copy or copies of this source file or
any portion of it, and copy and distribute such modifications under
the terms of Paragraph 1 above, provided that you also do the following:

    a) cause the modified files to carry prominent notices stating
    that you changed the files and the date of any change; and

    b) cause the whole of any work that you distribute or publish,
    that in whole or in part contains or is a derivative of this
    program or any part thereof, to be freely distributed
    and licensed to all third parties on terms identical to those
    contained in this License Agreement (except that you may choose
    to grant more extensive warranty protection to third parties,
    at your option).

  3. You may copy and distribute this program or any portion of it in
compiled, executable or object code form under the terms of Paragraphs
1 and 2 above provided that you do the following:

    a) cause each such copy to be accompanied by the
    corresponding machine-readable source code, which must
    be distributed under the terms of Paragraphs 1 and 2 above; or,

    b) cause each such copy to be accompanied by a
    written offer, with no time limit, to give any third party
    free (except for a nominal shipping charge) a machine readable
    copy of the corresponding source code, to be distributed
    under the terms of Paragraphs 1 and 2 above; or,

    c) in the case of a recipient of this program in compiled, executable
    or object code form (without the corresponding source code) you
    shall cause copies you distribute to be accompanied by a copy
    of the written offer of source code which you received along
    with the copy you received.

  4. You may not copy, sublicense, distribute or transfer this program
except as expressly provided under this License Agreement.  Any attempt
otherwise to copy, sublicense, distribute or transfer this program is void and
your rights to use the program under this License agreement shall be
automatically terminated.  However, parties who have received computer
software programs from you with this License Agreement will not have
their licenses terminated so long as such parties remain in full compliance.

 In other words, you are welcome to use, share and improve this program.
 You are forbidden to forbid anyone else to use, share and improve
 what you give them.   Help stamp out software-hoarding!  */

#include <stdio.h>

/* A `struct linebuffer' is a structure which holds a line of text.
 `readline' reads a line from a stream into a linebuffer
 and works regardless of the length of the line.  */

struct linebuffer
  {
    long size;
    char *buffer;
  };

void initbuffer ();
void copy_file ();
long readline ();
void writeline ();
char *concat ();
long integer_arg ();
char *writesegment ();
void to_hpos ();

main (argc, argv)
     int argc;
     char **argv;
{
  int width = 80;
  int i;
  int nfiles;

  for (i = 1; i < argc; i++)
    if (!strcmp (argv[i], "-w"))
      {
	if (++i == argc)
	  fatal ("no argument following -w");
	width = integer_arg (argv[i]);
      }
    else if (argv[i][0] == '-' && argv[i][1])
      width = integer_arg (argv[i] + 1);
    else nfiles++;

  if (!nfiles)
    copy_file ("-", width);
  else
    for (i = 1; i < argc; i++)
      if (!strcmp (argv[i], "-w"))
	i++;
      else if (!(argv[i][0] == '-' && argv[i][1]))
	copy_file (argv[i], width);
}

void
copy_file (filename, width)
     char *filename;
{
  FILE *istream;
  struct linebuffer lb;

  if (!strcmp (filename, "-"))
    istream = stdin;
  else
    istream = fopen (filename, "r");

  if (!istream)
    {
      perror_with_name (filename);
      return;
    }

  initbuffer (&lb);

  while (!feof (istream))
    {
      readline (&lb, istream);
      writeline (lb.buffer, width);
    }

  if (istream != stdin)
    fclose (istream);
}

void
writeline (string, width)
     char *string;
     int width;
{
  int seghpos = 0;
  char *segptr = string;
  int segstarthpos = 0;

  while (segptr)
    {
      segptr = writesegment (segptr, segstarthpos, seghpos, seghpos + width, &segstarthpos);
      seghpos += width;
      putchar ('\n');
    }
}

/* Output one "segment" (line, after folding) of the input line `string'.
This segment contants everything at horizontal positions `bhpos' to `ehpos'.
The first character of `string' is assumed to come at position `starthpos'
in the input line.

The returned value is a pointer to the first character in `string' that
belongs in a later segment.  Also, the horizontal position in the input line
of that character is stored into where `nextseghposptr' points.
If this segment should be the last one, zero is returned.
*/

char *
writesegment (string, starthpos, bhpos, ehpos, nextseghposptr)
     char *string;
     int bhpos;
     int ehpos;
     int *nextseghposptr;
{
  int hpos = starthpos;
  char *p = string;
  char *nextseg = 0;
  int nextseghpos;
  int lhpos = bhpos;

  while (1)
    {
      char c = *p++;
      switch (c)
	{
	case 0:
	  *nextseghposptr = nextseghpos;
	  return nextseg;

	case '\b':
	  if (hpos > 0) hpos--;
	  break;

	case '\t':
	  hpos = ((hpos + 8) / 8) * 8;
	  break;

	case '\r':
	  hpos = 0;
	  break;

	default:
	  if (hpos >= bhpos && hpos < ehpos)
	    {
	      if (hpos != lhpos)
	        to_hpos (hpos, lhpos, bhpos);
	      putchar (c);
	      if (c == 0177 || (c < 040 && c != 033))
		hpos ++;
	      hpos++;
	      lhpos = hpos;
	    }
	  else
	    {
	      if (hpos >= ehpos && !nextseg)
		{
		  nextseg = p - 1;
		  nextseghpos = hpos;
		}
	      if (c == 0177 || (c < 040 && c != 033))
		hpos ++;
	      hpos++;
	    }
	}
    }
}

void
to_hpos (to, from, base)
     int to, from, base;
{
  int real_to = to - base;
  int real_from = from - base;
  int i;

  if (real_to > real_from)
    for (i = real_from; i < real_to; i++)
      putchar (' ');
  else if (real_to < real_from)
    {
    for (i = real_from; i > real_to; i--)
	putchar ('\b');
    }
}
   
/* Initialize a linebuffer for use */

void
initbuffer (linebuffer)
     struct linebuffer *linebuffer;
{
  linebuffer->size = 200;
  linebuffer->buffer = (char *) xmalloc (200);
}

/* Read a line of text from `stream' into `linebuffer'.
 Return the length of the line.  */

long
readline (linebuffer, stream)
     struct linebuffer *linebuffer;
     FILE *stream;
{
  char *buffer = linebuffer->buffer;
  char *p = linebuffer->buffer;
  char *end = p + linebuffer->size;

  while (1)
    {
      int c = getc (stream);
      if (p == end)
	{
	  buffer = (char *) xrealloc (buffer, linebuffer->size *= 2);
	  p += buffer - linebuffer->buffer;
	  end += buffer - linebuffer->buffer;
	  linebuffer->buffer = buffer;
	}
      if (c < 0 || c == '\n')
	{
	  *p = 0;
	  break;
	}
      *p++ = c;
    }

  return p - buffer;
}

/* Print error message and exit.  */

fatal (s1, s2)
     char *s1, *s2;
{
  error (s1, s2);
  exit (1);
}

/* Print error message.  `s1' is printf control string, `s2' is arg for it. */

error (s1, s2)
     char *s1, *s2;
{
  printf ("fold: ");
  printf (s1, s2);
  printf ("\n");
}

perror_with_name (name)
     char *name;
{
  extern int errno, sys_nerr;
  extern char *sys_errlist[];
  char *s;

  if (errno < sys_nerr)
    s = concat ("", sys_errlist[errno], " for %s");
  else
    s = "cannot open %s";
  error (s, name);
}

/* Return a newly-allocated string whose contents concatenate those of s1, s2, s3.  */

char *
concat (s1, s2, s3)
     char *s1, *s2, *s3;
{
  int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
  char *result = (char *) xmalloc (len1 + len2 + len3 + 1);

  strcpy (result, s1);
  strcpy (result + len1, s2);
  strcpy (result + len1 + len2, s3);
  *(result + len1 + len2 + len3) = 0;

  return result;
}

/* Like malloc but get fatal error if memory is exhausted.  */

int
xmalloc (size)
     int size;
{
  int result = malloc (size);
  if (!result)
    fatal ("virtual memory exhausted", 0);
  return result;
}


int
xrealloc (ptr, size)
     char *ptr;
     int size;
{
  int result = realloc (ptr, size);
  if (!result)
    fatal ("virtual memory exhausted");
  return result;
}

/* Parse string `s' as an integer, using decimal radix by default,
 but allowing octal and hex numbers as in C.  */

long
integer_arg (s)
     char *s;
{
  long value;
  int radix = 10;
  char *p = s;
  int c;

  if (*p != '0')
    radix = 10;
  else if (*++p == 'x')
    {
      radix = 16;
      p++;
    }
  else
    radix = 8;

  value = 0;
  while (((c = *p++) >= '0' && c <= '9')
	 || (radix == 16 && (c & ~40) >= 'A' && (c & ~40) <= 'Z'))
    {
      value *= radix;
      if (c >= '0' && c <= '9')
	value += c - '0';
      else
	value += (c & ~40) - 'A';
    }

  if (c)
    fatal ("invalid integer argument %s", s);
  return value;
}
