Fix calls to {m,c,re}alloc so that they use x{m,c,re}alloc instead of
[oweals/busybox.git] / editors / sed.c
1 /*
2  * sed.c - very minimalist version of sed
3  *
4  * Copyright (C) 1999,2000 by Lineo, inc.
5  * Written by Mark Whitley <markw@lineo.com>, <markw@enol.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  *
21  */
22
23 /*
24         Supported features and commands in this version of sed:
25
26          - comments ('#')
27          - address matching: num|/matchstr/[,num|/matchstr/|$]command
28          - commands: (p)rint, (d)elete, (s)ubstitue (with g & I flags)
29          - edit commands: (a)ppend, (i)nsert, (c)hange
30          - backreferences in substitution expressions (\1, \2...\9)
31          
32          (Note: Specifying an address (range) to match is *optional*; commands
33          default to the whole pattern space if no specific address match was
34          requested.)
35
36         Unsupported features:
37
38          - transliteration (y/source-chars/dest-chars/) (use 'tr')
39          - no support for characters other than the '/' character for regex matches
40          - no pattern space hold space storing / swapping (x, etc.)
41          - no labels / branching (: label, b, t, and friends)
42          - and lots, lots more.
43
44 */
45
46 #include <stdio.h>
47 #include <unistd.h> /* for getopt() */
48 #include <regex.h>
49 #include <string.h> /* for strdup() */
50 #include <errno.h>
51 #include <ctype.h> /* for isspace() */
52 #include "internal.h"
53
54 #define bb_need_full_version
55 #define BB_DECLARE_EXTERN
56 #include "messages.c"
57
58 /* externs */
59 extern int optind; /* in unistd.h */
60 extern char *optarg; /* ditto */
61
62 /* options */
63 static int be_quiet = 0;
64
65 static const int SUB_G = 1 << 0;
66 #ifdef BB_FEATURE_SED_PATTERN_SPACE
67 static const int SUB_P = 1 << 1;
68 #endif
69
70 struct sed_cmd {
71
72         /* address storage */
73         int beg_line; /* 'sed 1p'   0 == no begining line, apply commands to all lines */
74         int end_line; /* 'sed 1,3p' 0 == no end line, use only beginning. -1 == $ */
75         regex_t *beg_match; /* sed -e '/match/cmd' */
76         regex_t *end_match; /* sed -e '/match/,/end_match/cmd' */
77
78         /* the command */
79         char cmd; /* p,d,s (add more at your leisure :-) */
80
81         /* substitution command specific fields */
82         regex_t *sub_match; /* sed -e 's/sub_match/replace/' */
83         char *replace; /* sed -e 's/sub_match/replace/' XXX: who will hold the \1 \2 \3s? */
84         unsigned int num_backrefs:4; /* how many back references (\1..\9) */
85                         /* Note:  GNU/POSIX sed does not save more than nine backrefs, so
86                          * we only use 4 bits to hold the number */
87 #ifndef BB_FEATURE_SED_PATTERN_SPACE
88         unsigned int sub_flags:1; /* sed -e 's/foo/bar/g' (global) */
89 #else
90         unsigned int sub_flags:2; /* sed -e 's/foo/bar/gp' (global/pattern) */
91 #endif
92
93         /* edit command (a,i,c) speicific field */
94         char *editline;
95 };
96
97 /* globals */
98 static struct sed_cmd *sed_cmds = NULL; /* growable arrary holding a sequence of sed cmds */
99 static int ncmds = 0; /* number of sed commands */
100
101 /*static char *cur_file = NULL;*/ /* file currently being processed XXX: do I need this? */
102
103 #ifdef BB_FEATURE_CLEAN_UP
104 static void destroy_cmd_strs()
105 {
106         if (sed_cmds == NULL)
107                 return;
108
109         /* destroy all the elements in the array */
110         while (--ncmds >= 0) {
111
112                 if (sed_cmds[ncmds].beg_match) {
113                         regfree(sed_cmds[ncmds].beg_match);
114                         free(sed_cmds[ncmds].beg_match);
115                 }
116                 if (sed_cmds[ncmds].end_match) {
117                         regfree(sed_cmds[ncmds].end_match);
118                         free(sed_cmds[ncmds].end_match);
119                 }
120                 if (sed_cmds[ncmds].sub_match) {
121                         regfree(sed_cmds[ncmds].sub_match);
122                         free(sed_cmds[ncmds].sub_match);
123                 }
124                 if (sed_cmds[ncmds].replace)
125                         free(sed_cmds[ncmds].replace);
126         }
127
128         /* destroy the array */
129         free(sed_cmds);
130         sed_cmds = NULL;
131 }
132 #endif
133
134 #if 0
135 /*
136  * trim_str - trims leading and trailing space from a string
137  * 
138  * Note: This returns a malloc'ed string so you must store and free it
139  * XXX: This should be in the utility.c file.
140  * XXX: This is now obsolete. Maybe it belongs nowhere.
141  */
142 static char *trim_str(const char *str)
143 {
144         int i;
145         char *retstr = strdup(str);
146
147         /* trim leading whitespace */
148         memmove(retstr, &retstr[strspn(retstr, " \n\t\v")], strlen(retstr));
149
150         /* trim trailing whitespace */
151         i = strlen(retstr) - 1;
152         while (isspace(retstr[i]))
153                 i--;
154         retstr[++i] = 0;
155
156         /* Aside: 
157          *
158          * you know, a strrspn() would really be nice cuz then we could say:
159          * 
160          * retstr[strrspn(retstr, " \n\t\v") + 1] = 0;
161          */
162         
163         return retstr;
164 }
165 #endif
166
167 #if 0
168 /*
169  * strrspn - works just like strspn() but goes from right to left instead of
170  * left to right
171  */
172 static size_t strrspn(const char *s, const char *accept)
173 {
174         size_t i = strlen(s);
175
176         while (strchr(accept, s[--i]))
177                 ;
178
179         return i;
180 }
181 #endif
182
183 /*
184  * index_of_next_unescaped_slash - walks left to right through a string
185  * beginning at a specified index and returns the index of the next forward
186  * slash ('/') not preceeded by a backslash ('\').
187  */
188 static int index_of_next_unescaped_slash(const char *str, int idx)
189 {
190         for ( ; str[idx]; idx++) {
191                 if (str[idx] == '/' && str[idx-1] != '\\')
192                         return idx;
193         }
194
195         /* if we make it to here, we've hit the end of the string */
196         return -1;
197 }
198
199 /*
200  * returns the index in the string just past where the address ends.
201  */
202 static int get_address(const char *str, int *line, regex_t **regex)
203 {
204         char *my_str = strdup(str);
205         int idx = 0;
206
207         if (isdigit(my_str[idx])) {
208                 do {
209                         idx++;
210                 } while (isdigit(my_str[idx]));
211                 my_str[idx] = 0;
212                 *line = atoi(my_str);
213         }
214         else if (my_str[idx] == '$') {
215                 *line = -1;
216                 idx++;
217         }
218         else if (my_str[idx] == '/') {
219                 idx = index_of_next_unescaped_slash(my_str, ++idx);
220                 if (idx == -1)
221                         fatalError("unterminated match expression\n");
222                 my_str[idx] = '\0';
223                 *regex = (regex_t *)xmalloc(sizeof(regex_t));
224                 xregcomp(*regex, my_str+1, REG_NEWLINE);
225                 idx++; /* so it points to the next character after the last '/' */
226         }
227         else {
228                 errorMsg("get_address: no address found in string\n"
229                                 "\t(you probably didn't check the string you passed me)\n");
230                 idx = -1;
231         }
232
233         free(my_str);
234         return idx;
235 }
236
237 static char *strdup_substr(const char *str, int start, int end)
238 {
239         int size = end - start + 1;
240         char *newstr = xmalloc(size);
241         memcpy(newstr, str+start, size-1);
242         newstr[size-1] = '\0';
243         return newstr;
244 }
245
246 static int parse_subst_cmd(struct sed_cmd *sed_cmd, const char *substr)
247 {
248         int oldidx, cflags = REG_NEWLINE;
249         char *match;
250         int idx = 0;
251         int j;
252
253         /*
254          * the string that gets passed to this function should look like this:
255          *    s/match/replace/gIp
256          *    ||     |        |||
257          *    mandatory       optional
258          *
259          *    (all three of the '/' slashes are mandatory)
260          */
261
262         /* verify that the 's' is followed by a 'slash' */
263         if (substr[++idx] != '/')
264                 fatalError("bad format in substitution expression\n");
265
266         /* save the match string */
267         oldidx = idx+1;
268         idx = index_of_next_unescaped_slash(substr, ++idx);
269         if (idx == -1)
270                 fatalError("bad format in substitution expression\n");
271         match = strdup_substr(substr, oldidx, idx);
272
273         /* determine the number of back references in the match string */
274         /* Note: we compute this here rather than in the do_subst_command()
275          * function to save processor time, at the expense of a little more memory
276          * (4 bits) per sed_cmd */
277         
278         /* sed_cmd->num_backrefs = 0; */ /* XXX: not needed? --apparently not */ 
279         for (j = 0; match[j]; j++) {
280                 /* GNU/POSIX sed does not save more than nine backrefs */
281                 if (match[j] == '\\' && match[j+1] == '(' && sed_cmd->num_backrefs < 9)
282                         sed_cmd->num_backrefs++;
283         }
284
285         /* save the replacement string */
286         oldidx = idx+1;
287         idx = index_of_next_unescaped_slash(substr, ++idx);
288         if (idx == -1)
289                 fatalError("bad format in substitution expression\n");
290         sed_cmd->replace = strdup_substr(substr, oldidx, idx);
291
292         /* process the flags */
293         while (substr[++idx]) {
294                 switch (substr[idx]) {
295                         case 'g':
296                                 sed_cmd->sub_flags = SUB_G;
297                                 break;
298                         case 'I':
299                                 cflags |= REG_ICASE;
300                                 break;
301 #ifdef BB_FEATURE_SED_PATTERN_SPACE
302                         case 'p':
303                                 sed_cmd->sub_flags = SUB_P;
304                                 break;
305 #endif
306                         default:
307                                 /* any whitespace or semicolon trailing after a s/// is ok */
308                                 if (strchr("; \t\v\n\r", substr[idx]))
309                                         goto out;
310                                 /* else */
311                                 fatalError("bad option in substitution expression\n");
312                 }
313         }
314
315 out:    
316         /* compile the match string into a regex */
317         sed_cmd->sub_match = (regex_t *)xmalloc(sizeof(regex_t));
318         xregcomp(sed_cmd->sub_match, match, cflags);
319         free(match);
320
321         return idx;
322 }
323
324 static int parse_edit_cmd(struct sed_cmd *sed_cmd, const char *editstr)
325 {
326         int idx = 0;
327         int slashes_eaten = 0;
328         char *ptr; /* shorthand */
329
330         /*
331          * the string that gets passed to this function should look like this:
332          *
333          *    need one of these 
334          *    |
335          *    |    this backslash (immediately following the edit command) is mandatory
336          *    |    |
337          *    [aic]\
338          *    TEXT1\
339          *    TEXT2\
340          *    TEXTN
341          *
342          * as soon as we hit a TEXT line that has no trailing '\', we're done.
343          * this means a command like:
344          *
345          * i\
346          * INSERTME
347          *
348          * is a-ok.
349          *
350          */
351
352         if (editstr[1] != '\\' && (editstr[2] != '\n' || editstr[2] != '\r'))
353                 fatalError("bad format in edit expression\n");
354
355         /* store the edit line text */
356         /* make editline big enough to accomodate the extra '\n' we will tack on
357          * to the end */
358         sed_cmd->editline = xmalloc(strlen(&editstr[3]) + 2);
359         strcpy(sed_cmd->editline, &editstr[3]);
360         ptr = sed_cmd->editline;
361
362         /* now we need to go through * and: s/\\[\r\n]$/\n/g on the edit line */
363         while (ptr[idx]) {
364                 while (ptr[idx] != '\\' && (ptr[idx+1] != '\n' || ptr[idx+1] != '\r')) {
365                         idx++;
366                         if (!ptr[idx]) {
367                                 goto out;
368                         }
369                 }
370                 /* move the newline over the '\' before it (effectively eats the '\') */
371                 memmove(&ptr[idx], &ptr[idx+1], strlen(&ptr[idx+1]));
372                 ptr[strlen(ptr)-1] = 0;
373                 slashes_eaten++;
374                 /* substitue \r for \n if needed */
375                 if (ptr[idx] == '\r')
376                         ptr[idx] = '\n';
377         }
378
379 out:
380         ptr[idx] = '\n';
381         ptr[idx+1] = 0;
382
383         /* this accounts for discrepancies between the modified string and the
384          * original string passed in to this function */
385         idx += slashes_eaten;
386
387         /* this accounts for the fact that A) we started at index 3, not at index
388          * 0  and B) that we added an extra '\n' at the end (if you think the next
389          * line should read 'idx += 4' remember, arrays are zero-based) */
390
391         idx += 3;
392
393         return idx;
394 }
395
396 static char *parse_cmd_str(struct sed_cmd *sed_cmd, const char *cmdstr)
397 {
398         int idx = 0;
399
400         /* parse the command
401          * format is: [addr][,addr]cmd
402          *            |----||-----||-|
403          *            part1 part2  part3
404          */
405
406
407         /* first part (if present) is an address: either a number or a /regex/ */
408         if (isdigit(cmdstr[idx]) || cmdstr[idx] == '/')
409                 idx = get_address(cmdstr, &sed_cmd->beg_line, &sed_cmd->beg_match);
410
411         /* second part (if present) will begin with a comma */
412         if (cmdstr[idx] == ',')
413                 idx += get_address(&cmdstr[++idx], &sed_cmd->end_line, &sed_cmd->end_match);
414
415         /* last part (mandatory) will be a command */
416         if (cmdstr[idx] == '\0')
417                 fatalError("missing command\n");
418         if (!strchr("pdsaic", cmdstr[idx])) /* <-- XXX add new commands here */
419                 fatalError("invalid command\n");
420         sed_cmd->cmd = cmdstr[idx];
421
422         /* special-case handling for (s)ubstitution */
423         if (sed_cmd->cmd == 's') {
424                 idx += parse_subst_cmd(sed_cmd, &cmdstr[idx]);
425         }
426         /* special-case handling for (a)ppend, (i)nsert, and (c)hange */
427         else if (strchr("aic", cmdstr[idx])) {
428                 if (sed_cmd->end_line || sed_cmd->end_match)
429                         fatalError("only a beginning address can be specified for edit commands\n");
430                 idx += parse_edit_cmd(sed_cmd, &cmdstr[idx]);
431         }
432         /* if it was a single-letter command (such as 'p' or 'd') we need to
433          * increment the index past that command */
434         else
435                 idx++;
436
437         /* give back whatever's left over */
438         return (char *)&cmdstr[idx];
439 }
440
441 static void add_cmd_str(const char *cmdstr)
442 {
443         char *mystr = (char *)cmdstr;
444
445         do {
446
447                 /* trim leading whitespace and semicolons */
448                 memmove(mystr, &mystr[strspn(mystr, "; \n\r\t\v")], strlen(mystr));
449                 /* if we ate the whole thing, that means there was just trailing
450                  * whitespace or a final / no-op semicolon. either way, get out */
451                 if (strlen(mystr) == 0)
452                         return;
453                 /* if this is a comment, jump past it and keep going */
454                 if (mystr[0] == '#') {
455                         mystr = strpbrk(mystr, ";\n\r");
456                         continue;
457                 }
458                 /* grow the array */
459                 sed_cmds = xrealloc(sed_cmds, sizeof(struct sed_cmd) * (++ncmds));
460                 /* zero new element */
461                 memset(&sed_cmds[ncmds-1], 0, sizeof(struct sed_cmd));
462                 /* load command string into new array element, get remainder */
463                 mystr = parse_cmd_str(&sed_cmds[ncmds-1], mystr);
464
465         } while (mystr && strlen(mystr));
466 }
467
468
469 static void load_cmd_file(char *filename)
470 {
471         FILE *cmdfile;
472         char *line;
473         char *nextline;
474
475         cmdfile = fopen(filename, "r");
476         if (cmdfile == NULL)
477                 fatalError(strerror(errno));
478
479         while ((line = get_line_from_file(cmdfile)) != NULL) {
480                 /* if a line ends with '\' it needs the next line appended to it */
481                 while (line[strlen(line)-2] == '\\' &&
482                                 (nextline = get_line_from_file(cmdfile)) != NULL) {
483                         line = xrealloc(line, strlen(line) + strlen(nextline) + 1);
484                         strcat(line, nextline);
485                         free(nextline);
486                 }
487                 /* eat trailing newline (if any) --if I don't do this, edit commands
488                  * (aic) will print an extra newline */
489                 if (line[strlen(line)-1] == '\n')
490                         line[strlen(line)-1] = 0;
491                 add_cmd_str(line);
492                 free(line);
493         }
494 }
495
496 static void print_subst_w_backrefs(const char *line, const char *replace, regmatch_t *regmatch)
497 {
498         int i;
499
500         /* go through the replacement string */
501         for (i = 0; replace[i]; i++) {
502                 /* if we find a backreference (\1, \2, etc.) print the backref'ed * text */
503                 if (replace[i] == '\\' && isdigit(replace[i+1])) {
504                         int j;
505                         char tmpstr[2];
506                         int backref;
507                         ++i; /* i now indexes the backref number, instead of the leading slash */
508                         tmpstr[0] = replace[i];
509                         tmpstr[1] = 0;
510                         backref = atoi(tmpstr);
511                         /* print out the text held in regmatch[backref] */
512                         for (j = regmatch[backref].rm_so; j < regmatch[backref].rm_eo; j++)
513                                 fputc(line[j], stdout);
514                 }
515
516                 /* if we find a backslash escaped character, print the character */
517                 else if (replace[i] == '\\') {
518                         ++i;
519                         fputc(replace[i], stdout);
520                 }
521
522                 /* if we find an unescaped '&' print out the whole matched text.
523                  * fortunately, regmatch[0] contains the indicies to the whole matched
524                  * expression (kinda seems like it was designed for just such a
525                  * purpose...) */
526                 else if (replace[i] == '&' && replace[i-1] != '\\') {
527                         int j;
528                         for (j = regmatch[0].rm_so; j < regmatch[0].rm_eo; j++)
529                                 fputc(line[j], stdout);
530                 }
531                 /* nothing special, just print this char of the replacement string to stdout */
532                 else
533                         fputc(replace[i], stdout);
534         }
535 }
536
537 static int do_subst_command(const struct sed_cmd *sed_cmd, const char *line)
538 {
539         int altered = 0;
540
541         /* we only substitute if the substitution 'search' expression matches */
542         if (regexec(sed_cmd->sub_match, line, 0, NULL, 0) == 0) {
543                 regmatch_t *regmatch = xmalloc(sizeof(regmatch_t) * (sed_cmd->num_backrefs+1));
544                 int i;
545                 char *ptr = (char *)line;
546
547                 while (*ptr) {
548                         /* if we can match the search string... */
549                         if (regexec(sed_cmd->sub_match, ptr, sed_cmd->num_backrefs+1, regmatch, 0) == 0) {
550                                 /* print everything before the match, */
551                                 for (i = 0; i < regmatch[0].rm_so; i++) {
552 #ifdef BB_FEATURE_SED_PATTERN_SPACE
553                                         if(!be_quiet || (sed_cmd->sub_flags & SUB_P))
554 #endif
555                                         fputc(ptr[i], stdout);
556                                 }
557
558                                 /* then print the substitution in its place */
559 #ifdef BB_FEATURE_SED_PATTERN_SPACE
560                                 if(!be_quiet || (sed_cmd->sub_flags & SUB_P))
561 #endif
562                                 print_subst_w_backrefs(ptr, sed_cmd->replace, regmatch);
563
564                                 /* then advance past the match */
565                                 ptr += regmatch[0].rm_eo;
566
567                                 /* and flag that something has changed */
568                                 altered++;
569
570                                 /* if we're not doing this globally... */
571                                 if (!sed_cmd->sub_flags & SUB_G)
572                                         break;
573                         }
574                         /* if we COULD NOT match the search string (meaning we've gone past
575                          * all previous instances), get out */
576                         else
577                                 break;
578                 }
579
580                 /* is there anything left to print? */
581 #ifdef BB_FEATURE_SED_PATTERN_SPACE
582                 if (*ptr && (!be_quiet || sed_cmds->sub_flags & SUB_P))
583 #else
584                 if (*ptr) 
585 #endif
586                         fputs(ptr, stdout);
587
588                 /* cleanup */
589                 free(regmatch);
590         }
591
592         return altered;
593 }
594
595 static int do_sed_command(const struct sed_cmd *sed_cmd, const char *line) 
596 {
597         int altered = 0;
598
599         switch (sed_cmd->cmd) {
600
601                 case 'p':
602                         fputs(line, stdout);
603                         break;
604
605                 case 'd':
606                         altered++;
607                         break;
608
609                 case 's':
610                         altered = do_subst_command(sed_cmd, line);
611                         break;
612
613                 case 'a':
614                         fputs(line, stdout);
615                         fputs(sed_cmd->editline, stdout);
616                         altered++;
617                         break;
618
619                 case 'i':
620                         fputs(sed_cmd->editline, stdout);
621                         break;
622
623                 case 'c':
624                         fputs(sed_cmd->editline, stdout);
625                         altered++;
626                         break;
627         }
628
629         return altered;
630 }
631
632 static void process_file(FILE *file)
633 {
634         char *line = NULL;
635         static int linenum = 0; /* GNU sed does not restart counting lines at EOF */
636         unsigned int still_in_range = 0;
637         int line_altered;
638         int i;
639
640         /* go through every line in the file */
641         while ((line = get_line_from_file(file)) != NULL) {
642
643                 linenum++;
644                 line_altered = 0;
645
646                 /* for every line, go through all the commands */
647                 for (i = 0; i < ncmds; i++) {
648
649                         /* are we acting on a range of matched lines? */
650                         if (sed_cmds[i].beg_match && sed_cmds[i].end_match) {
651                                 if (still_in_range || regexec(sed_cmds[i].beg_match, line, 0, NULL, 0) == 0) {
652                                         line_altered += do_sed_command(&sed_cmds[i], line);
653                                         still_in_range = 1; 
654                                         if (regexec(sed_cmds[i].end_match, line, 0, NULL, 0) == 0)
655                                                 still_in_range = 0;
656                                 }
657                         }
658
659                         /* are we trying to match a single line? */
660                         else if (sed_cmds[i].beg_match) {
661                                 if (regexec(sed_cmds[i].beg_match, line, 0, NULL, 0) == 0)
662                                         line_altered += do_sed_command(&sed_cmds[i], line);
663                         }
664
665                         /* are we acting on a range of line numbers? */
666                         else if (sed_cmds[i].beg_line > 0 && sed_cmds[i].end_line != 0) {
667                                 if (linenum >= sed_cmds[i].beg_line && (sed_cmds[i].end_line == -1 || linenum <= sed_cmds[i].end_line))
668                                         line_altered += do_sed_command(&sed_cmds[i], line);
669                         }
670
671                         /* are we acting on a specified line number */
672                         else if (sed_cmds[i].beg_line > 0) {
673                                 if (linenum == sed_cmds[i].beg_line)
674                                         line_altered += do_sed_command(&sed_cmds[i], line);
675                         }
676
677                         /* not acting on matches or line numbers. act on every line */
678                         else 
679                                 line_altered += do_sed_command(&sed_cmds[i], line);
680
681                 }
682
683                 /* we will print the line unless we were told to be quiet or if
684                  * the line was altered (via a 'd'elete or 's'ubstitution) */
685 #ifndef BB_FEATURE_SED_PATTERN_SPACE
686                 if (!be_quiet &&!line_altered)
687 #else
688                 /*  we where specificly requested to print the output */
689                 if ((!be_quiet || (sed_cmds[i].sub_flags & SUB_P)) && !line_altered)
690 #endif
691                         fputs(line, stdout);
692
693                 free(line);
694         }
695 }
696
697 extern int sed_main(int argc, char **argv)
698 {
699         int opt;
700
701 #ifdef BB_FEATURE_CLEAN_UP
702         /* destroy command strings on exit */
703         if (atexit(destroy_cmd_strs) == -1) {
704                 perror("sed");
705                 exit(1);
706         }
707 #endif
708
709         /* do normal option parsing */
710         while ((opt = getopt(argc, argv, "hne:f:")) > 0) {
711                 switch (opt) {
712                         case 'h':
713                                 usage(sed_usage);
714                                 break;
715                         case 'n':
716                                 be_quiet++;
717                                 break;
718                         case 'e':
719                                 add_cmd_str(optarg);
720                                 break;
721                         case 'f': 
722                                 load_cmd_file(optarg);
723                                 break;
724                 }
725         }
726
727         /* if we didn't get a pattern from a -e and no command file was specified,
728          * argv[optind] should be the pattern. no pattern, no worky */
729         if (ncmds == 0) {
730                 if (argv[optind] == NULL)
731                         usage(sed_usage);
732                 else {
733                         add_cmd_str(argv[optind]);
734                         optind++;
735                 }
736         }
737
738
739         /* argv[(optind)..(argc-1)] should be names of file to process. If no
740          * files were specified or '-' was specified, take input from stdin.
741          * Otherwise, we process all the files specified. */
742         if (argv[optind] == NULL || (strcmp(argv[optind], "-") == 0)) {
743                 process_file(stdin);
744         }
745         else {
746                 int i;
747                 FILE *file;
748                 for (i = optind; i < argc; i++) {
749                         file = fopen(argv[i], "r");
750                         if (file == NULL) {
751                                 errorMsg("%s: %s\n", argv[i], strerror(errno));
752                         } else {
753                                 process_file(file);
754                                 fclose(file);
755                         }
756                 }
757         }
758         
759         return 0;
760 }