Use PROGRAM_NAME in place of string in parse_long_options call.
[platform/upstream/coreutils.git] / src / csplit.c
1 /* csplit - split a file into sections determined by context lines
2    Copyright (C) 91, 1995-1999 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
17
18 /* Written by Stuart Kemp, cpsrk@groper.jcu.edu.au.
19    Modified by David MacKenzie, djm@gnu.ai.mit.edu. */
20
21 #include <config.h>
22
23 #include <stdio.h>
24 #include <assert.h>
25 #include <getopt.h>
26 #include <sys/types.h>
27 #include <signal.h>
28
29 #include "system.h"
30
31 #include <regex.h>
32
33 #include "error.h"
34 #include "long-options.h"
35 #include "safe-read.h"
36 #include "xstrtoul.h"
37 #include "xalloc.h"
38
39 /* The official name of this program (e.g., no `g' prefix).  */
40 #define PROGRAM_NAME "csplit"
41
42 #ifdef STDC_HEADERS
43 # include <stdlib.h>
44 #endif
45
46 #ifndef MAX
47 # define MAX(a,b) (((a) > (b)) ? (a) : (b))
48 #endif
49
50 #ifndef TRUE
51 # define FALSE 0
52 # define TRUE 1
53 #endif
54
55 /* Increment size of area for control records. */
56 #define ALLOC_SIZE 20
57
58 /* The default prefix for output file names. */
59 #define DEFAULT_PREFIX  "xx"
60
61 typedef int boolean;
62
63 /* A compiled pattern arg. */
64 struct control
65 {
66   char *regexpr;                /* Non-compiled regular expression. */
67   struct re_pattern_buffer re_compiled; /* Compiled regular expression. */
68   int offset;                   /* Offset from regexp to split at. */
69   int lines_required;           /* Number of lines required. */
70   unsigned int repeat;          /* Repeat count. */
71   int repeat_forever;           /* Non-zero if `*' used as a repeat count. */
72   int argnum;                   /* ARGV index. */
73   boolean ignore;               /* If true, produce no output (for regexp). */
74 };
75
76 /* Initial size of data area in buffers. */
77 #define START_SIZE      8191
78
79 /* Increment size for data area. */
80 #define INCR_SIZE       2048
81
82 /* Number of lines kept in each node in line list. */
83 #define CTRL_SIZE       80
84
85 #ifdef DEBUG
86 /* Some small values to test the algorithms. */
87 # define START_SIZE     200
88 # define INCR_SIZE      10
89 # define CTRL_SIZE      1
90 #endif
91
92 /* A string with a length count. */
93 struct cstring
94 {
95   int len;
96   char *str;
97 };
98
99 /* Pointers to the beginnings of lines in the buffer area.
100    These structures are linked together if needed. */
101 struct line
102 {
103   unsigned used;                /* Number of offsets used in this struct. */
104   unsigned insert_index;        /* Next offset to use when inserting line. */
105   unsigned retrieve_index;      /* Next index to use when retrieving line. */
106   struct cstring starts[CTRL_SIZE]; /* Lines in the data area. */
107   struct line *next;            /* Next in linked list. */
108 };
109
110 /* The structure to hold the input lines.
111    Contains a pointer to the data area and a list containing
112    pointers to the individual lines. */
113 struct buffer_record
114 {
115   unsigned bytes_alloc;         /* Size of the buffer area. */
116   unsigned bytes_used;          /* Bytes used in the buffer area. */
117   unsigned start_line;          /* First line number in this buffer. */
118   unsigned first_available;     /* First line that can be retrieved. */
119   unsigned num_lines;           /* Number of complete lines in this buffer. */
120   char *buffer;                 /* Data area. */
121   struct line *line_start;      /* Head of list of pointers to lines. */
122   struct line *curr_line;       /* The line start record currently in use. */
123   struct buffer_record *next;
124 };
125
126 static void close_output_file PARAMS ((void));
127 static void create_output_file PARAMS ((void));
128 static void delete_all_files PARAMS ((void));
129 static void save_line_to_file PARAMS ((const struct cstring *line));
130 void usage PARAMS ((int status));
131
132 /* The name this program was run with. */
133 char *program_name;
134
135 /* Convert the number of 8-bit bytes of a binary representation to
136    the number of characters required to represent the same quantity
137    as an unsigned octal.  For example, a 32-bit (4-byte) quantity may
138    require a field width as wide as 11 characters.  */
139 static const unsigned int bytes_to_octal_digits[] =
140 {0, 3, 6, 8, 11, 14, 16, 19, 22, 25, 27, 30, 32, 35, 38, 41, 43};
141
142 /* Input file descriptor. */
143 static int input_desc = 0;
144
145 /* List of available buffers. */
146 static struct buffer_record *free_list = NULL;
147
148 /* Start of buffer list. */
149 static struct buffer_record *head = NULL;
150
151 /* Partially read line. */
152 static char *hold_area = NULL;
153
154 /* Number of chars in `hold_area'. */
155 static unsigned hold_count = 0;
156
157 /* Number of the last line in the buffers. */
158 static unsigned last_line_number = 0;
159
160 /* Number of the line currently being examined. */
161 static unsigned current_line = 0;
162
163 /* If TRUE, we have read EOF. */
164 static boolean have_read_eof = FALSE;
165
166 /* Name of output files. */
167 static char *filename_space = NULL;
168
169 /* Prefix part of output file names. */
170 static char *prefix = NULL;
171
172 /* Suffix part of output file names. */
173 static char *suffix = NULL;
174
175 /* Number of digits to use in output file names. */
176 static int digits = 2;
177
178 /* Number of files created so far. */
179 static unsigned int files_created = 0;
180
181 /* Number of bytes written to current file. */
182 static unsigned int bytes_written;
183
184 /* Output file pointer. */
185 static FILE *output_stream = NULL;
186
187 /* Output file name. */
188 static char *output_filename = NULL;
189
190 /* Perhaps it would be cleaner to pass arg values instead of indexes. */
191 static char **global_argv;
192
193 /* If TRUE, do not print the count of bytes in each output file. */
194 static boolean suppress_count;
195
196 /* If TRUE, remove output files on error. */
197 static boolean remove_files;
198
199 /* If TRUE, remove all output files which have a zero length. */
200 static boolean elide_empty_files;
201
202 /* The compiled pattern arguments, which determine how to split
203    the input file. */
204 static struct control *controls;
205
206 /* Number of elements in `controls'. */
207 static unsigned int control_used;
208
209 static struct option const longopts[] =
210 {
211   {"digits", required_argument, NULL, 'n'},
212   {"quiet", no_argument, NULL, 'q'},
213   {"silent", no_argument, NULL, 's'},
214   {"keep-files", no_argument, NULL, 'k'},
215   {"elide-empty-files", no_argument, NULL, 'z'},
216   {"prefix", required_argument, NULL, 'f'},
217   {"suffix-format", required_argument, NULL, 'b'},
218   {NULL, 0, NULL, 0}
219 };
220
221 /* Optionally remove files created so far; then exit.
222    Called when an error detected. */
223
224 static void
225 cleanup (void)
226 {
227   if (output_stream)
228     close_output_file ();
229
230   if (remove_files)
231     delete_all_files ();
232 }
233
234 static void
235 cleanup_fatal (void)
236 {
237   cleanup ();
238   exit (EXIT_FAILURE);
239 }
240
241 static RETSIGTYPE
242 interrupt_handler (int sig)
243 {
244 #ifdef SA_INTERRUPT
245   struct sigaction sigact;
246
247   sigact.sa_handler = SIG_DFL;
248   sigemptyset (&sigact.sa_mask);
249   sigact.sa_flags = 0;
250   sigaction (sig, &sigact, NULL);
251 #else                           /* !SA_INTERRUPT */
252   signal (sig, SIG_DFL);
253 #endif                          /* SA_INTERRUPT */
254   cleanup ();
255   kill (getpid (), sig);
256 }
257
258 /* Keep track of NUM chars of a partial line in buffer START.
259    These chars will be retrieved later when another large buffer is read.
260    It is not necessary to create a new buffer for these chars; instead,
261    we keep a pointer to the existing buffer.  This buffer *is* on the
262    free list, and when the next buffer is obtained from this list
263    (even if it is this one), these chars will be placed at the
264    start of the new buffer. */
265
266 static void
267 save_to_hold_area (char *start, unsigned int num)
268 {
269   hold_area = start;
270   hold_count = num;
271 }
272
273 /* Read up to MAX_N_BYTES chars from the input stream into DEST.
274    Return the number of chars read. */
275
276 static int
277 read_input (char *dest, unsigned int max_n_bytes)
278 {
279   int bytes_read;
280
281   if (max_n_bytes == 0)
282     return 0;
283
284   bytes_read = safe_read (input_desc, dest, max_n_bytes);
285
286   if (bytes_read == 0)
287     have_read_eof = TRUE;
288
289   if (bytes_read < 0)
290     {
291       error (0, errno, _("read error"));
292       cleanup_fatal ();
293     }
294
295   return bytes_read;
296 }
297
298 /* Initialize existing line record P. */
299
300 static void
301 clear_line_control (struct line *p)
302 {
303   p->used = 0;
304   p->insert_index = 0;
305   p->retrieve_index = 0;
306 }
307
308 /* Initialize all line records in B. */
309
310 static void
311 clear_all_line_control (struct buffer_record *b)
312 {
313   struct line *l;
314
315   for (l = b->line_start; l; l = l->next)
316     clear_line_control (l);
317 }
318
319 /* Return a new, initialized line record. */
320
321 static struct line *
322 new_line_control (void)
323 {
324   struct line *p;
325
326   p = (struct line *) xmalloc (sizeof (struct line));
327
328   p->next = NULL;
329   clear_line_control (p);
330
331   return p;
332 }
333
334 /* Record LINE_START, which is the address of the start of a line
335    of length LINE_LEN in the large buffer, in the lines buffer of B. */
336
337 static void
338 keep_new_line (struct buffer_record *b, char *line_start, int line_len)
339 {
340   struct line *l;
341
342   /* If there is no existing area to keep line info, get some. */
343   if (b->line_start == NULL)
344     b->line_start = b->curr_line = new_line_control ();
345
346   /* If existing area for lines is full, get more. */
347   if (b->curr_line->used == CTRL_SIZE)
348     {
349       b->curr_line->next = new_line_control ();
350       b->curr_line = b->curr_line->next;
351     }
352
353   l = b->curr_line;
354
355   /* Record the start of the line, and update counters. */
356   l->starts[l->insert_index].str = line_start;
357   l->starts[l->insert_index].len = line_len;
358   l->used++;
359   l->insert_index++;
360 }
361
362 /* Scan the buffer in B for newline characters
363    and record the line start locations and lengths in B.
364    Return the number of lines found in this buffer.
365
366    There may be an incomplete line at the end of the buffer;
367    a pointer is kept to this area, which will be used when
368    the next buffer is filled. */
369
370 static unsigned int
371 record_line_starts (struct buffer_record *b)
372 {
373   char *line_start;             /* Start of current line. */
374   char *line_end;               /* End of each line found. */
375   unsigned int bytes_left;      /* Length of incomplete last line. */
376   unsigned int lines;           /* Number of lines found. */
377   unsigned int line_length;     /* Length of each line found. */
378
379   if (b->bytes_used == 0)
380     return 0;
381
382   lines = 0;
383   line_start = b->buffer;
384   bytes_left = b->bytes_used;
385
386   for (;;)
387     {
388       line_end = memchr (line_start, '\n', bytes_left);
389       if (line_end == NULL)
390         break;
391       line_length = line_end - line_start + 1;
392       keep_new_line (b, line_start, line_length);
393       bytes_left -= line_length;
394       line_start = line_end + 1;
395       lines++;
396     }
397
398   /* Check for an incomplete last line. */
399   if (bytes_left)
400     {
401       if (have_read_eof)
402         {
403           keep_new_line (b, line_start, bytes_left);
404           lines++;
405         }
406       else
407         save_to_hold_area (line_start, bytes_left);
408     }
409
410   b->num_lines = lines;
411   b->first_available = b->start_line = last_line_number + 1;
412   last_line_number += lines;
413
414   return lines;
415 }
416
417 /* Return a new buffer with room to store SIZE bytes, plus
418    an extra byte for safety. */
419
420 static struct buffer_record *
421 create_new_buffer (unsigned int size)
422 {
423   struct buffer_record *new_buffer;
424
425   new_buffer = (struct buffer_record *)
426     xmalloc (sizeof (struct buffer_record));
427
428   new_buffer->buffer = (char *) xmalloc (size + 1);
429
430   new_buffer->bytes_alloc = size;
431   new_buffer->line_start = new_buffer->curr_line = NULL;
432
433   return new_buffer;
434 }
435
436 /* Return a new buffer of at least MINSIZE bytes.  If a buffer of at
437    least that size is currently free, use it, otherwise create a new one. */
438
439 static struct buffer_record *
440 get_new_buffer (unsigned int min_size)
441 {
442   struct buffer_record *p, *q;
443   struct buffer_record *new_buffer; /* Buffer to return. */
444   unsigned int alloc_size;      /* Actual size that will be requested. */
445
446   alloc_size = START_SIZE;
447   while (min_size > alloc_size)
448     alloc_size += INCR_SIZE;
449
450   if (free_list == NULL)
451     new_buffer = create_new_buffer (alloc_size);
452   else
453     {
454       /* Use first-fit to find a buffer. */
455       p = new_buffer = NULL;
456       q = free_list;
457
458       do
459         {
460           if (q->bytes_alloc >= min_size)
461             {
462               if (p == NULL)
463                 free_list = q->next;
464               else
465                 p->next = q->next;
466               break;
467             }
468           p = q;
469           q = q->next;
470         }
471       while (q);
472
473       new_buffer = (q ? q : create_new_buffer (alloc_size));
474
475       new_buffer->curr_line = new_buffer->line_start;
476       clear_all_line_control (new_buffer);
477     }
478
479   new_buffer->num_lines = 0;
480   new_buffer->bytes_used = 0;
481   new_buffer->start_line = new_buffer->first_available = last_line_number + 1;
482   new_buffer->next = NULL;
483
484   return new_buffer;
485 }
486
487 /* Add buffer BUF to the list of free buffers. */
488
489 static void
490 free_buffer (struct buffer_record *buf)
491 {
492   buf->next = free_list;
493   free_list = buf;
494 }
495
496 /* Append buffer BUF to the linked list of buffers that contain
497    some data yet to be processed. */
498
499 static void
500 save_buffer (struct buffer_record *buf)
501 {
502   struct buffer_record *p;
503
504   buf->next = NULL;
505   buf->curr_line = buf->line_start;
506
507   if (head == NULL)
508     head = buf;
509   else
510     {
511       for (p = head; p->next; p = p->next)
512         /* Do nothing. */ ;
513       p->next = buf;
514     }
515 }
516
517 /* Fill a buffer of input.
518
519    Set the initial size of the buffer to a default.
520    Fill the buffer (from the hold area and input stream)
521    and find the individual lines.
522    If no lines are found (the buffer is too small to hold the next line),
523    release the current buffer (whose contents would have been put in the
524    hold area) and repeat the process with another large buffer until at least
525    one entire line has been read.
526
527    Return TRUE if a new buffer was obtained, otherwise false
528    (in which case end-of-file must have been encountered). */
529
530 static boolean
531 load_buffer (void)
532 {
533   struct buffer_record *b;
534   unsigned int bytes_wanted = START_SIZE; /* Minimum buffer size. */
535   unsigned int bytes_avail;             /* Size of new buffer created. */
536   unsigned int lines_found;             /* Number of lines in this new buffer. */
537   char *p;                      /* Place to load into buffer. */
538
539   if (have_read_eof)
540     return FALSE;
541
542   /* We must make the buffer at least as large as the amount of data
543      in the partial line left over from the last call. */
544   if (bytes_wanted < hold_count)
545     bytes_wanted = hold_count;
546
547   do
548     {
549       b = get_new_buffer (bytes_wanted);
550       bytes_avail = b->bytes_alloc; /* Size of buffer returned. */
551       p = b->buffer;
552
553       /* First check the `holding' area for a partial line. */
554       if (hold_count)
555         {
556           if (p != hold_area)
557             memcpy (p, hold_area, hold_count);
558           p += hold_count;
559           b->bytes_used += hold_count;
560           bytes_avail -= hold_count;
561           hold_count = 0;
562         }
563
564       b->bytes_used += (unsigned int) read_input (p, bytes_avail);
565
566       lines_found = record_line_starts (b);
567       bytes_wanted = b->bytes_alloc * 2;
568       if (!lines_found)
569         free_buffer (b);
570     }
571   while (!lines_found && !have_read_eof);
572
573   if (lines_found)
574     save_buffer (b);
575
576   return lines_found != 0;
577 }
578
579 /* Return the line number of the first line that has not yet been retrieved. */
580
581 static unsigned int
582 get_first_line_in_buffer (void)
583 {
584   if (head == NULL && !load_buffer ())
585     error (EXIT_FAILURE, errno, _("input disappeared"));
586
587   return head->first_available;
588 }
589
590 /* Return a pointer to the logical first line in the buffer and make the
591    next line the logical first line.
592    Return NULL if there is no more input. */
593
594 static struct cstring *
595 remove_line (void)
596 {
597   struct cstring *line;         /* Return value. */
598   struct line *l;               /* For convenience. */
599
600   if (head == NULL && !load_buffer ())
601     return NULL;
602
603   if (current_line < head->first_available)
604     current_line = head->first_available;
605
606   ++(head->first_available);
607
608   l = head->curr_line;
609
610   line = &l->starts[l->retrieve_index];
611
612   /* Advance index to next line. */
613   if (++l->retrieve_index == l->used)
614     {
615       /* Go on to the next line record. */
616       head->curr_line = l->next;
617       if (head->curr_line == NULL || head->curr_line->used == 0)
618         {
619           /* Go on to the next data block. */
620           struct buffer_record *b = head;
621           head = head->next;
622           free_buffer (b);
623         }
624     }
625
626   return line;
627 }
628
629 /* Search the buffers for line LINENUM, reading more input if necessary.
630    Return a pointer to the line, or NULL if it is not found in the file. */
631
632 static struct cstring *
633 find_line (unsigned int linenum)
634 {
635   struct buffer_record *b;
636
637   if (head == NULL && !load_buffer ())
638     return NULL;
639
640   if (linenum < head->start_line)
641     return NULL;
642
643   for (b = head;;)
644     {
645       if (linenum < b->start_line + b->num_lines)
646         {
647           /* The line is in this buffer. */
648           struct line *l;
649           unsigned int offset;  /* How far into the buffer the line is. */
650
651           l = b->line_start;
652           offset = linenum - b->start_line;
653           /* Find the control record. */
654           while (offset >= CTRL_SIZE)
655             {
656               l = l->next;
657               offset -= CTRL_SIZE;
658             }
659           return &l->starts[offset];
660         }
661       if (b->next == NULL && !load_buffer ())
662         return NULL;
663       b = b->next;              /* Try the next data block. */
664     }
665 }
666
667 /* Return TRUE if at least one more line is available for input. */
668
669 static boolean
670 no_more_lines (void)
671 {
672   return (find_line (current_line + 1) == NULL) ? TRUE : FALSE;
673 }
674
675 /* Set the name of the input file to NAME and open it. */
676
677 static void
678 set_input_file (const char *name)
679 {
680   if (STREQ (name, "-"))
681     input_desc = 0;
682   else
683     {
684       input_desc = open (name, O_RDONLY);
685       if (input_desc < 0)
686         error (EXIT_FAILURE, errno, "%s", name);
687     }
688 }
689
690 /* Write all lines from the beginning of the buffer up to, but
691    not including, line LAST_LINE, to the current output file.
692    If IGNORE is TRUE, do not output lines selected here.
693    ARGNUM is the index in ARGV of the current pattern. */
694
695 static void
696 write_to_file (unsigned int last_line, boolean ignore, int argnum)
697 {
698   struct cstring *line;
699   unsigned int first_line;              /* First available input line. */
700   unsigned int lines;           /* Number of lines to output. */
701   unsigned int i;
702
703   first_line = get_first_line_in_buffer ();
704
705   if (first_line > last_line)
706     {
707       error (0, 0, _("%s: line number out of range"), global_argv[argnum]);
708       cleanup_fatal ();
709     }
710
711   lines = last_line - first_line;
712
713   for (i = 0; i < lines; i++)
714     {
715       line = remove_line ();
716       if (line == NULL)
717         {
718           error (0, 0, _("%s: line number out of range"), global_argv[argnum]);
719           cleanup_fatal ();
720         }
721       if (!ignore)
722         save_line_to_file (line);
723     }
724 }
725
726 /* Output any lines left after all regexps have been processed. */
727
728 static void
729 dump_rest_of_file (void)
730 {
731   struct cstring *line;
732
733   while ((line = remove_line ()) != NULL)
734     save_line_to_file (line);
735 }
736
737 /* Handle an attempt to read beyond EOF under the control of record P,
738    on iteration REPETITION if nonzero. */
739
740 static void
741 handle_line_error (const struct control *p, int repetition)
742 {
743   fprintf (stderr, _("%s: `%d': line number out of range"),
744            program_name, p->lines_required);
745   if (repetition)
746     fprintf (stderr, _(" on repetition %d\n"), repetition);
747   else
748     fprintf (stderr, "\n");
749
750   cleanup_fatal ();
751 }
752
753 /* Determine the line number that marks the end of this file,
754    then get those lines and save them to the output file.
755    P is the control record.
756    REPETITION is the repetition number. */
757
758 static void
759 process_line_count (const struct control *p, int repetition)
760 {
761   unsigned int linenum;
762   unsigned int last_line_to_save = p->lines_required * (repetition + 1);
763   struct cstring *line;
764
765   create_output_file ();
766
767   linenum = get_first_line_in_buffer ();
768
769   /* Initially, I wanted to assert linenum < last_line_to_save, but that
770      condition is false for the valid command: echo | csplit - 1 '{*}'.
771      So, relax it just a little.  */
772   assert ((linenum == 1 && last_line_to_save == 1)
773           || linenum < last_line_to_save);
774
775   while (linenum++ < last_line_to_save)
776     {
777       line = remove_line ();
778       if (line == NULL)
779         handle_line_error (p, repetition);
780       save_line_to_file (line);
781     }
782
783   close_output_file ();
784
785   /* Ensure that the line number specified is not 1 greater than
786      the number of lines in the file. */
787   if (no_more_lines ())
788     handle_line_error (p, repetition);
789 }
790
791 static void
792 regexp_error (struct control *p, int repetition, boolean ignore)
793 {
794   fprintf (stderr, _("%s: `%s': match not found"),
795            program_name, global_argv[p->argnum]);
796
797   if (repetition)
798     fprintf (stderr, _(" on repetition %d\n"), repetition);
799   else
800     fprintf (stderr, "\n");
801
802   if (!ignore)
803     {
804       dump_rest_of_file ();
805       close_output_file ();
806     }
807   cleanup_fatal ();
808 }
809
810 /* Read the input until a line matches the regexp in P, outputting
811    it unless P->IGNORE is TRUE.
812    REPETITION is this repeat-count; 0 means the first time. */
813
814 static void
815 process_regexp (struct control *p, int repetition)
816 {
817   struct cstring *line;         /* From input file. */
818   unsigned int line_len;        /* To make "$" in regexps work. */
819   unsigned int break_line;      /* First line number of next file. */
820   boolean ignore = p->ignore;   /* If TRUE, skip this section. */
821   int ret;
822
823   if (!ignore)
824     create_output_file ();
825
826   /* If there is no offset for the regular expression, or
827      it is positive, then it is not necessary to buffer the lines. */
828
829   if (p->offset >= 0)
830     {
831       for (;;)
832         {
833           line = find_line (++current_line);
834           if (line == NULL)
835             {
836               if (p->repeat_forever)
837                 {
838                   if (!ignore)
839                     {
840                       dump_rest_of_file ();
841                       close_output_file ();
842                     }
843                   exit (EXIT_SUCCESS);
844                 }
845               else
846                 regexp_error (p, repetition, ignore);
847             }
848           line_len = line->len;
849           if (line->str[line_len - 1] == '\n')
850             line_len--;
851           ret = re_search (&p->re_compiled, line->str, line_len,
852                            0, line_len, (struct re_registers *) 0);
853           if (ret == -2)
854             {
855               error (0, 0, _("error in regular expression search"));
856               cleanup_fatal ();
857             }
858           if (ret == -1)
859             {
860               line = remove_line ();
861               if (!ignore)
862                 save_line_to_file (line);
863             }
864           else
865             break;
866         }
867     }
868   else
869     {
870       /* Buffer the lines. */
871       for (;;)
872         {
873           line = find_line (++current_line);
874           if (line == NULL)
875             {
876               if (p->repeat_forever)
877                 {
878                   if (!ignore)
879                     {
880                       dump_rest_of_file ();
881                       close_output_file ();
882                     }
883                   exit (EXIT_SUCCESS);
884                 }
885               else
886                 regexp_error (p, repetition, ignore);
887             }
888           line_len = line->len;
889           if (line->str[line_len - 1] == '\n')
890             line_len--;
891           ret = re_search (&p->re_compiled, line->str, line_len,
892                            0, line_len, (struct re_registers *) 0);
893           if (ret == -2)
894             {
895               error (0, 0, _("error in regular expression search"));
896               cleanup_fatal ();
897             }
898           if (ret >= 0)
899             break;
900         }
901     }
902
903   /* Account for any offset from this regexp. */
904   break_line = current_line + p->offset;
905
906   write_to_file (break_line, ignore, p->argnum);
907
908   if (!ignore)
909     close_output_file ();
910
911   if (p->offset > 0)
912     current_line = break_line;
913 }
914
915 /* Split the input file according to the control records we have built. */
916
917 static void
918 split_file (void)
919 {
920   unsigned int i, j;
921
922   for (i = 0; i < control_used; i++)
923     {
924       if (controls[i].regexpr)
925         {
926           for (j = 0; (controls[i].repeat_forever
927                        || j <= controls[i].repeat); j++)
928             process_regexp (&controls[i], j);
929         }
930       else
931         {
932           for (j = 0; (controls[i].repeat_forever
933                        || j <= controls[i].repeat); j++)
934             process_line_count (&controls[i], j);
935         }
936     }
937
938   create_output_file ();
939   dump_rest_of_file ();
940   close_output_file ();
941 }
942
943 /* Return the name of output file number NUM. */
944
945 static char *
946 make_filename (unsigned int num)
947 {
948   strcpy (filename_space, prefix);
949   if (suffix)
950     sprintf (filename_space+strlen(prefix), suffix, num);
951   else
952     sprintf (filename_space+strlen(prefix), "%0*d", digits, num);
953   return filename_space;
954 }
955
956 /* Create the next output file. */
957
958 static void
959 create_output_file (void)
960 {
961   output_filename = make_filename (files_created);
962   output_stream = fopen (output_filename, "w");
963   if (output_stream == NULL)
964     {
965       error (0, errno, "%s", output_filename);
966       cleanup_fatal ();
967     }
968   files_created++;
969   bytes_written = 0;
970 }
971
972 /* Delete all the files we have created. */
973
974 static void
975 delete_all_files (void)
976 {
977   unsigned int i;
978   char *name;
979
980   for (i = 0; i < files_created; i++)
981     {
982       name = make_filename (i);
983       if (unlink (name))
984         error (0, errno, "%s", name);
985     }
986 }
987
988 /* Close the current output file and print the count
989    of characters in this file. */
990
991 static void
992 close_output_file (void)
993 {
994   if (output_stream)
995     {
996       if (ferror (output_stream) || fclose (output_stream) == EOF)
997         {
998           error (0, errno, _("write error for `%s'"), output_filename);
999           output_stream = NULL;
1000           cleanup_fatal ();
1001         }
1002       if (bytes_written == 0 && elide_empty_files)
1003         {
1004           if (unlink (output_filename))
1005             error (0, errno, "%s", output_filename);
1006           files_created--;
1007         }
1008       else
1009         {
1010           /* FIXME: if we write to stdout here, we have to close stdout
1011              and check for errors.  */
1012           if (!suppress_count)
1013             fprintf (stdout, "%d\n", bytes_written);
1014         }
1015       output_stream = NULL;
1016     }
1017 }
1018
1019 /* Save line LINE to the output file and
1020    increment the character count for the current file. */
1021
1022 static void
1023 save_line_to_file (const struct cstring *line)
1024 {
1025   fwrite (line->str, sizeof (char), line->len, output_stream);
1026   bytes_written += line->len;
1027 }
1028
1029 /* Return a new, initialized control record. */
1030
1031 static struct control *
1032 new_control_record (void)
1033 {
1034   static unsigned control_allocated = 0; /* Total space allocated. */
1035   struct control *p;
1036
1037   if (control_allocated == 0)
1038     {
1039       control_allocated = ALLOC_SIZE;
1040       controls = (struct control *)
1041         xmalloc (sizeof (struct control) * control_allocated);
1042     }
1043   else if (control_used == control_allocated)
1044     {
1045       control_allocated += ALLOC_SIZE;
1046       controls = (struct control *)
1047         xrealloc ((char *) controls,
1048                   sizeof (struct control) * control_allocated);
1049     }
1050   p = &controls[control_used++];
1051   p->regexpr = NULL;
1052   p->repeat = 0;
1053   p->repeat_forever = 0;
1054   p->lines_required = 0;
1055   p->offset = 0;
1056   return p;
1057 }
1058
1059 /* Check if there is a numeric offset after a regular expression.
1060    STR is the entire command line argument.
1061    P is the control record for this regular expression.
1062    NUM is the numeric part of STR. */
1063
1064 static void
1065 check_for_offset (struct control *p, const char *str, const char *num)
1066 {
1067   unsigned long val;
1068
1069   if (*num != '-' && *num != '+')
1070     error (EXIT_FAILURE, 0, _("%s: `+' or `-' expected after delimeter"), str);
1071
1072   if (xstrtoul (num + 1, NULL, 10, &val, "") != LONGINT_OK
1073       || val > UINT_MAX)
1074     error (EXIT_FAILURE, 0, _("%s: integer expected after `%c'"), str, *num);
1075   p->offset = (unsigned int) val;
1076
1077   if (*num == '-')
1078     p->offset = -p->offset;
1079 }
1080
1081 /* Given that the first character of command line arg STR is '{',
1082    make sure that the rest of the string is a valid repeat count
1083    and store its value in P.
1084    ARGNUM is the ARGV index of STR. */
1085
1086 static void
1087 parse_repeat_count (int argnum, struct control *p, char *str)
1088 {
1089   unsigned long val;
1090   char *end;
1091
1092   end = str + strlen (str) - 1;
1093   if (*end != '}')
1094     error (EXIT_FAILURE, 0, _("%s: `}' is required in repeat count"), str);
1095   *end = '\0';
1096
1097   if (str+1 == end-1 && *(str+1) == '*')
1098     p->repeat_forever = 1;
1099   else
1100     {
1101       if (xstrtoul (str + 1, NULL, 10, &val, "") != LONGINT_OK
1102           || val > UINT_MAX)
1103         {
1104           error (EXIT_FAILURE, 0,
1105                  _("%s}: integer required between `{' and `}'"),
1106                  global_argv[argnum]);
1107         }
1108       p->repeat = (unsigned int) val;
1109     }
1110
1111   *end = '}';
1112 }
1113
1114 /* Extract the regular expression from STR and check for a numeric offset.
1115    STR should start with the regexp delimiter character.
1116    Return a new control record for the regular expression.
1117    ARGNUM is the ARGV index of STR.
1118    Unless IGNORE is TRUE, mark these lines for output. */
1119
1120 static struct control *
1121 extract_regexp (int argnum, boolean ignore, char *str)
1122 {
1123   int len;                      /* Number of chars in this regexp. */
1124   char delim = *str;
1125   char *closing_delim;
1126   struct control *p;
1127   const char *err;
1128
1129   closing_delim = strrchr (str + 1, delim);
1130   if (closing_delim == NULL)
1131     error (EXIT_FAILURE, 0,
1132            _("%s: closing delimeter `%c' missing"), str, delim);
1133
1134   len = closing_delim - str - 1;
1135   p = new_control_record ();
1136   p->argnum = argnum;
1137   p->ignore = ignore;
1138
1139   p->regexpr = (char *) xmalloc ((unsigned) (len + 1));
1140   strncpy (p->regexpr, str + 1, len);
1141   p->re_compiled.allocated = len * 2;
1142   p->re_compiled.buffer = (unsigned char *) xmalloc (p->re_compiled.allocated);
1143   p->re_compiled.fastmap = xmalloc (256);
1144   p->re_compiled.translate = 0;
1145   err = re_compile_pattern (p->regexpr, len, &p->re_compiled);
1146   if (err)
1147     {
1148       error (0, 0, _("%s: invalid regular expression: %s"), str, err);
1149       cleanup_fatal ();
1150     }
1151
1152   if (closing_delim[1])
1153     check_for_offset (p, str, closing_delim + 1);
1154
1155   return p;
1156 }
1157
1158 /* Extract the break patterns from args START through ARGC - 1 of ARGV.
1159    After each pattern, check if the next argument is a repeat count. */
1160
1161 static void
1162 parse_patterns (int argc, int start, char **argv)
1163 {
1164   int i;                        /* Index into ARGV. */
1165   struct control *p;            /* New control record created. */
1166   unsigned long val;
1167   static unsigned long last_val = 0;
1168
1169   for (i = start; i < argc; i++)
1170     {
1171       if (*argv[i] == '/' || *argv[i] == '%')
1172         {
1173           p = extract_regexp (i, *argv[i] == '%', argv[i]);
1174         }
1175       else
1176         {
1177           p = new_control_record ();
1178           p->argnum = i;
1179
1180           if (xstrtoul (argv[i], NULL, 10, &val, "") != LONGINT_OK
1181               || val > INT_MAX)
1182             error (EXIT_FAILURE, 0, _("%s: invalid pattern"), argv[i]);
1183           if (val == 0)
1184             error (EXIT_FAILURE, 0,
1185                    _("%s: line number must be greater than zero"),
1186                    argv[i]);
1187           if (val < last_val)
1188             error (EXIT_FAILURE, 0,
1189              _("line number `%s' is smaller than preceding line number, %lu"),
1190                    argv[i], last_val);
1191
1192           if (val == last_val)
1193             error (0, 0,
1194            _("warning: line number `%s' is the same as preceding line number"),
1195                    argv[i]);
1196           last_val = val;
1197
1198           p->lines_required = (int) val;
1199         }
1200
1201       if (i + 1 < argc && *argv[i + 1] == '{')
1202         {
1203           /* We have a repeat count. */
1204           i++;
1205           parse_repeat_count (i, p, argv[i]);
1206         }
1207     }
1208 }
1209
1210 static unsigned
1211 get_format_flags (char **format_ptr)
1212 {
1213   unsigned count = 0;
1214
1215   for (; **format_ptr; (*format_ptr)++)
1216     {
1217       switch (**format_ptr)
1218         {
1219         case '-':
1220           break;
1221
1222         case '+':
1223         case ' ':
1224           count++;
1225           break;
1226
1227         case '#':
1228           count += 2;   /* Allow for 0x prefix preceeding an `x' conversion.  */
1229           break;
1230
1231         default:
1232           return count;
1233         }
1234     }
1235   return count;
1236 }
1237
1238 static unsigned
1239 get_format_width (char **format_ptr)
1240 {
1241   unsigned count = 0;
1242   char *start;
1243   int ch_save;
1244
1245   start = *format_ptr;
1246   for (; ISDIGIT (**format_ptr); (*format_ptr)++)
1247     continue;
1248
1249   ch_save = **format_ptr;
1250   **format_ptr = '\0';
1251   /* In the case where no minimum field width is explicitly specified,
1252      allow for enough octal digits to represent the value of LONG_MAX.  */
1253   count = ((*format_ptr == start)
1254            ? bytes_to_octal_digits[sizeof (long)]
1255            : atoi (start));
1256   **format_ptr = ch_save;
1257   return count;
1258 }
1259
1260 static unsigned
1261 get_format_prec (char **format_ptr)
1262 {
1263   unsigned count = 0;
1264   char *start;
1265   int ch_save;
1266   int is_negative;
1267
1268   if (**format_ptr != '.')
1269     return 0;
1270   (*format_ptr)++;
1271
1272   if (**format_ptr == '-' || **format_ptr == '+')
1273     {
1274       is_negative = (**format_ptr == '-');
1275       (*format_ptr)++;
1276     }
1277   else
1278     {
1279       is_negative = 0;
1280     }
1281
1282   start = *format_ptr;
1283   for (; ISDIGIT (**format_ptr); (*format_ptr)++)
1284     continue;
1285
1286   /* ANSI 4.9.6.1 says that if the precision is negative, it's as good as
1287      not there. */
1288   if (is_negative)
1289     start = *format_ptr;
1290
1291   ch_save = **format_ptr;
1292   **format_ptr = '\0';
1293   count = (*format_ptr == start) ? 11 : atoi (start);
1294   **format_ptr = ch_save;
1295
1296   return count;
1297 }
1298
1299 static void
1300 get_format_conv_type (char **format_ptr)
1301 {
1302   int ch = *((*format_ptr)++);
1303
1304   switch (ch)
1305     {
1306     case 'd':
1307     case 'i':
1308     case 'o':
1309     case 'u':
1310     case 'x':
1311     case 'X':
1312       break;
1313
1314     case 0:
1315       error (EXIT_FAILURE, 0, _("missing conversion specifier in suffix"));
1316       break;
1317
1318     default:
1319       if (ISPRINT (ch))
1320         error (EXIT_FAILURE, 0,
1321                _("invalid conversion specifier in suffix: %c"), ch);
1322       else
1323         error (EXIT_FAILURE, 0,
1324                _("invalid conversion specifier in suffix: \\%.3o"), ch);
1325     }
1326 }
1327
1328 static unsigned
1329 max_out (char *format)
1330 {
1331   unsigned out_count = 0;
1332   unsigned percents = 0;
1333
1334   for (; *format; )
1335     {
1336       int ch = *format++;
1337
1338       if (ch != '%')
1339         out_count++;
1340       else
1341         {
1342           percents++;
1343           out_count += get_format_flags (&format);
1344           {
1345             int width = get_format_width (&format);
1346             int prec = get_format_prec (&format);
1347
1348             out_count += MAX (width, prec);
1349           }
1350           get_format_conv_type (&format);
1351         }
1352     }
1353
1354   if (percents == 0)
1355     error (EXIT_FAILURE, 0,
1356            _("missing %% conversion specification in suffix"));
1357   else if (percents > 1)
1358     error (EXIT_FAILURE, 0,
1359            _("too many %% conversion specifications in suffix"));
1360
1361   return out_count;
1362 }
1363
1364 int
1365 main (int argc, char **argv)
1366 {
1367   int optc;
1368   unsigned long val;
1369 #ifdef SA_INTERRUPT
1370   struct sigaction oldact, newact;
1371 #endif
1372
1373   program_name = argv[0];
1374   setlocale (LC_ALL, "");
1375   bindtextdomain (PACKAGE, LOCALEDIR);
1376   textdomain (PACKAGE);
1377
1378   parse_long_options (argc, argv, PROGRAM_NAME, GNU_PACKAGE, VERSION,
1379                       "Stuart Kemp and David MacKenzie", usage);
1380
1381   global_argv = argv;
1382   controls = NULL;
1383   control_used = 0;
1384   suppress_count = FALSE;
1385   remove_files = TRUE;
1386   prefix = DEFAULT_PREFIX;
1387
1388   /* Change the way xmalloc and xrealloc fail.  */
1389   xalloc_fail_func = cleanup;
1390
1391 #ifdef SA_INTERRUPT
1392   newact.sa_handler = interrupt_handler;
1393   sigemptyset (&newact.sa_mask);
1394   newact.sa_flags = 0;
1395
1396   sigaction (SIGHUP, NULL, &oldact);
1397   if (oldact.sa_handler != SIG_IGN)
1398     sigaction (SIGHUP, &newact, NULL);
1399
1400   sigaction (SIGINT, NULL, &oldact);
1401   if (oldact.sa_handler != SIG_IGN)
1402     sigaction (SIGINT, &newact, NULL);
1403
1404   sigaction (SIGQUIT, NULL, &oldact);
1405   if (oldact.sa_handler != SIG_IGN)
1406     sigaction (SIGQUIT, &newact, NULL);
1407
1408   sigaction (SIGTERM, NULL, &oldact);
1409   if (oldact.sa_handler != SIG_IGN)
1410     sigaction (SIGTERM, &newact, NULL);
1411 #else /* not SA_INTERRUPT */
1412   if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
1413     signal (SIGHUP, interrupt_handler);
1414   if (signal (SIGINT, SIG_IGN) != SIG_IGN)
1415     signal (SIGINT, interrupt_handler);
1416   if (signal (SIGQUIT, SIG_IGN) != SIG_IGN)
1417     signal (SIGQUIT, interrupt_handler);
1418   if (signal (SIGTERM, SIG_IGN) != SIG_IGN)
1419     signal (SIGTERM, interrupt_handler);
1420 #endif /* not SA_INTERRUPT */
1421
1422   while ((optc = getopt_long (argc, argv, "f:b:kn:sqz", longopts, NULL)) != -1)
1423     switch (optc)
1424       {
1425       case 0:
1426         break;
1427
1428       case 'f':
1429         prefix = optarg;
1430         break;
1431
1432       case 'b':
1433         suffix = optarg;
1434         break;
1435
1436       case 'k':
1437         remove_files = FALSE;
1438         break;
1439
1440       case 'n':
1441         if (xstrtoul (optarg, NULL, 10, &val, "") != LONGINT_OK
1442             || val > INT_MAX)
1443           error (EXIT_FAILURE, 0, _("%s: invalid number"), optarg);
1444         digits = (int) val;
1445         break;
1446
1447       case 's':
1448       case 'q':
1449         suppress_count = TRUE;
1450         break;
1451
1452       case 'z':
1453         elide_empty_files = TRUE;
1454         break;
1455
1456       default:
1457         usage (1);
1458       }
1459
1460   if (argc - optind < 2)
1461     {
1462       error (0, 0, _("too few arguments"));
1463       usage (1);
1464     }
1465
1466   if (suffix)
1467     filename_space = (char *) xmalloc (strlen (prefix) + max_out (suffix) + 2);
1468   else
1469     filename_space = (char *) xmalloc (strlen (prefix) + digits + 2);
1470
1471   set_input_file (argv[optind++]);
1472
1473   parse_patterns (argc, optind, argv);
1474
1475   split_file ();
1476
1477   if (close (input_desc) < 0)
1478     {
1479       error (0, errno, _("read error"));
1480       cleanup_fatal ();
1481     }
1482
1483   if (!suppress_count && (ferror (stdout) || fclose (stdout) == EOF))
1484     error (EXIT_FAILURE, errno, _("write error"));
1485
1486   exit (EXIT_SUCCESS);
1487 }
1488
1489 void
1490 usage (int status)
1491 {
1492   if (status != 0)
1493     fprintf (stderr, _("Try `%s --help' for more information.\n"),
1494              program_name);
1495   else
1496     {
1497       printf (_("\
1498 Usage: %s [OPTION]... FILE PATTERN...\n\
1499 "),
1500               program_name);
1501       printf (_("\
1502 Output pieces of FILE separated by PATTERN(s) to files `xx01', `xx02', ...,\n\
1503 and output byte counts of each piece to standard output.\n\
1504 \n\
1505   -b, --suffix-format=FORMAT use sprintf FORMAT instead of %%d\n\
1506   -f, --prefix=PREFIX        use PREFIX instead of `xx'\n\
1507   -k, --keep-files           do not remove output files on errors\n\
1508   -n, --digits=DIGITS        use specified number of digits instead of 2\n\
1509   -s, --quiet, --silent      do not print counts of output file sizes\n\
1510   -z, --elide-empty-files    remove empty output files\n\
1511       --help                 display this help and exit\n\
1512       --version              output version information and exit\n\
1513 \n\
1514 Read standard input if FILE is -.  Each PATTERN may be:\n\
1515 \n\
1516   INTEGER            copy up to but not including specified line number\n\
1517   /REGEXP/[OFFSET]   copy up to but not including a matching line\n\
1518   %%REGEXP%%[OFFSET]   skip to, but not including a matching line\n\
1519   {INTEGER}          repeat the previous pattern specified number of times\n\
1520   {*}                repeat the previous pattern as many times as possible\n\
1521 \n\
1522 A line OFFSET is a required `+' or `-' followed by a positive integer.\n\
1523 "));
1524       puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
1525     }
1526   exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
1527 }