/* Split input on line boundaries into files of specified size.

   Has the following extensions to un*x split:
   "-l <number>" or "-lines <number>" means the same as "-<number>":
     split into subfiles which contain <= <number> lines.
   "-c <number>" or "-characters <number> means
     split into subfiles which contain <= <number> characters.

   Copyright 1986 (C) Richard 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>

char *concat ();
char *make_suffix ();
long integer_arg ();

main (argc, argv)
     int argc;
     char **argv;

{
  long nlines = 1000;
  long nchars = 0;
  FILE *stream;
  char *outname = "x";	/* Prefix for names of output files.  */
  char *file = 0;	/* Name of input file; 0 or "-" means stdin.  */
  int eof;
  int filecount = 0;	/* Counts output files */
  int i;

  i = 1;
  while (i < argc && argv[i][0] == '-')
    {
      if (argv[i][1] >= '0' && argv[i][1] <= '9')
	{
	  nlines = integer_arg (argv[i] + 1);
	  nchars = 0;
	}
      else if (!strcmp (argv[i], "-l") || !strcmp (argv[i], "-lines"))
	{
	  if (++i > argc) goto require_arg;
	  nlines = integer_arg (argv[i]);
	  nchars = 0;
	}
      else if (!strcmp (argv[i], "-c") || !strcmp (argv[i], "-characters"))
	{
	  if (++i > argc)
	    {
	    require_arg:
	      fatal ("the \"%s\" switch must be followed by a number.", argv[i - 1]);
	    }
	  nchars = integer_arg (argv[i]);
	  nlines = 0;
	}
      else
	fatal ("unknown switch \"%s\"\n\tExpected -<number-or-lines>, -l <number-of-lines> or -c <number-of-chars>",
	       argv[i]);
      i++;
    }
  if (i < argc)
    file = argv[i++];
  if (i < argc)
    outname = argv[i++];
  if (i < argc)
    fatal ("too many arguments", 0);

  if (!file || !strcmp (file, "-"))
    stream = stdin;
  else
    stream = fopen (file, "r");
  if (!stream)
    perror_with_name (file);

  while (!eof)
    {
      char *suffix = make_suffix (filecount++);
      char *ofile = concat (outname, "", suffix);	/* Name of next output file */
      FILE *ostream = fopen (ofile, "w");
      int linesp = nlines > 0;
      register long count = 0;
      if (!ostream)
	perror_with_name (ofile);
      /* Copy out lines until end of input or desired number of lines */
      while (1)
	{
	  int c = getc (stream);
	  if (c < 0)
	    {
	      eof = 1;
	      break;
	    }
	  putc (c, ostream);
	  if (linesp)
	    {
	      if (c == '\n' && ++count >= nlines)
		break;
	    }
	  else
	    {
	      if (++count >= nchars)
		break;
	    }
	}
      fclose (ostream);
    }

  fclose (stream);
}

/* Create the file-suffix to use for the `count''th output file */

char *
make_suffix (count)
     int count;
{
  int len;
  /* `len' gets number of digits in radix 26 needed for this number */
  len = 0;
  {
    int tem = count;
    while (tem > 0)
      {
	len++;
	tem /= 26;
      }
  }

  /* Increase number of digits up to a power of 2.  */
  len += len - 1;
  {  /* Clear all but the highest bit of `len'. */
    int i;
    for (i = 0; 1 << i < len; i++)
      len &= ~(1 << i);
  }
  if (len < 2) len = 2;

  {
    /* `len - 2' "z"'s, `len' significant letters, and a null.  */
    char *str = (char *) xmalloc (len + len - 1);
    char *p = str + len + len - 2;
    char *beg = str + len - 2;
    int tem = count;
    *p = 0;
    while (p > beg)
      {
	*--p = tem % 26 + 'a';
	tem /= 26;
      }
    while (p > str)
      *--p = 'z';
    return str;
  }
}

/* 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 ("split: ");
  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";
  fatal (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.  */

xmalloc (size)
     int size;
{
  int result = malloc (size);
  if (!result)
    fatal ("virtual memory exhausted", 0);
  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;
{
  int 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 (*--p)
    fatal ("invalid integer argument %s", s);
  return value;
}
