chiark / gitweb /
Change `-ise' to `-ize' throughout.
[cfd] / mdwopt.c
1 /* -*-c-*-
2  *
3  * $Id: mdwopt.c,v 1.2 1999/05/13 22:57:23 mdw Exp $
4  *
5  * Options parsing, similar to GNU @getopt_long@
6  *
7  * (c) 1996 Mark Wooding
8  */
9
10 /*----- Licensing notice --------------------------------------------------*
11  *
12  * This file is part of many programs.
13  *
14  * `mdwopt' is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU Library General Public License as
16  * published by the Free Software Foundation; either version 2 of the
17  * License, or (at your option) any later version.
18  *
19  * `mdwopt' is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU Library General Public License for more details.
23  *
24  * You should have received a copy of the GNU Library General Public
25  * License along with `mdwopt'; if not, write to the Free Software
26  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27  */
28
29 /*----- Revision history --------------------------------------------------*
30  *
31  * $Log: mdwopt.c,v $
32  * Revision 1.2  1999/05/13 22:57:23  mdw
33  * Change `-ise' to `-ize' throughout.
34  *
35  * Revision 1.1.1.1  1999/05/05 19:23:47  mdw
36  * New import.  The old CVS repository was lost in a disk disaster.
37  *
38  * --- Previous lives ---
39  *
40  * %Log: mdwopt.c,v %
41  * Revision 1.7  1997/09/11 09:19:11  mdw
42  * (mo__nextWord): Arrrgh.  Don't free the environment variable buffer!
43  * People are still using it!
44  *
45  * Revision 1.6  1997/09/11 09:05:54  mdw
46  * (mo__nextWord): Fix bug which returns too many words from environment
47  * variables.
48  *
49  * Revision 1.5  1997/08/09 20:27:59  mdw
50  * Fix spelling of `Licensing'.
51  *
52  * Revision 1.4  1997/07/29 21:11:35  mdw
53  * Reformatted.  Fixed buffer overflow when dealing with environment
54  * variables.  Included NT in list of daft operating systems with `\' as a
55  * path separator.  Fixed address of the FSF.
56  *
57  * Revision 1.3  1997/02/26 00:41:10  mdw
58  * Added GPL notice to the top.  Slight formatting changes.
59  *
60  * Revision 1.2  1996/10/28 13:12:13  mdw
61  * Fixed calls to ctype.h routines.  Arguments are cast to unsigned char
62  * to avoid invoking undefined behaviour caused by signedness of chars.
63  *
64  * Revision 1.1  1996/09/24 18:01:28  mdw
65  * Initial revision
66  *
67  */
68
69 /*----- External dependencies ---------------------------------------------*/
70
71 #include <ctype.h>
72 #include <stdio.h>
73 #include <stdlib.h>
74 #include <string.h>
75
76 #include "mdwopt.h"
77
78 /*----- Configuration things ----------------------------------------------*/
79
80 #if defined(__riscos)
81 #  define PATHSEP '.'
82 #elif defined(__OS2__) || defined(__MSDOS__) || defined(__WINNT__)
83 #  define PATHSEP '\\'
84 #else /* Assume a sane filing system */
85 #  define PATHSEP '/'
86 #endif
87
88 /*----- Global variables --------------------------------------------------*/
89
90 mdwopt_data mdwopt_global = {0, 0, 0, 1, 0, 0, 0, 0, 0};
91
92 enum {
93   ord__permute = 0,                     /* Permute the options (default) */
94   ord__return = 1,                      /* Return non-option things */
95   ord__posix = 2,                       /* Do POSIX-type hacking */
96   ord__negate = 4                       /* Magic negate-next-thing flag */
97 };
98
99 /*----- Main code ---------------------------------------------------------*/
100
101 /* --- @mo__nextWord@ --- *
102  *
103  * Arguments:   @int argc@ = number of command line options
104  *              @char *argv[]@ = pointer to command line options
105  *              @mdwopt_data *data@ = pointer to persistent state
106  *
107  * Returns:     Pointer to the next word to handle, or 0
108  *
109  * Use:         Extracts the next word from the command line or environment
110  *              variable.
111  */
112
113 static char *mo__nextWord(int argc, char *const *argv, mdwopt_data *data)
114 {
115   if (data->ind == -1) {
116     char *p = data->env;
117     char *q;
118     while (isspace((unsigned char)*p))
119       p++;
120     q = p;
121     while (*p && !isspace((unsigned char)*p))
122       p++;
123     data->env = p;
124     if (*p)
125       *p++ = 0;
126     if (p != q)
127       return (q);
128     data->env = 0;
129     data->ind = 1;
130   }
131
132   if (data->next == argc)
133     return (0);
134   return (argv[data->next++]);
135 }
136
137 /* --- @mo__permute@ --- *
138  *
139  * Arguments:   @char *argv[]@ = pointer to command line arguments
140  *              @mdwopt_data *data@ = pointer to persistent data
141  *
142  * Returns:     --
143  *
144  * Use:         Moves a command line option into the right place.
145  */
146
147 static void mo__permute(char *const *argv, mdwopt_data *data)
148 {
149   char **v = (char **)argv;
150   if (data->ind != -1) {
151     int i = data->next - 1;
152     char *p = v[i];
153     while (i > data->ind) {
154       v[i] = v[i - 1];
155       i--;
156     }
157     v[i] = p;
158     data->ind++;
159   }
160 }
161
162 /* --- @mo__findOpt@ --- *
163  *
164  * Arguments:   @int o@ = which option to search for
165  *              @const char *shortopt@ = short options string to search
166  *              @mdwopt_data *data@ = pointer to persistant state
167  *
168  * Returns:     Pointer to rest of short options string (including magic
169  *              characters)
170  *
171  * Use:         Looks up a short option in the given string.
172  */
173
174 static const char *mo__findOpt(int o, const char *shortopt,
175                                mdwopt_data *data)
176 {
177   const char *p = shortopt;             /* Point to short opts table */
178   for (;;) {
179     if (!*p)                            /* No more options left */
180       return (0);
181
182     if (o != *p || (p[1] != '+' && data->order & ord__negate)) {
183       p++;                              /* Skip this option entry */
184       while (*p == '+')                 /* Jump a `%|+|%' sign */
185         p++;
186       while (*p == ':')                 /* And jump any `%|:|%' characters */
187         p++;                            /* Just in case there are any */
188     }
189     else
190       return (p + 1);
191   }
192 }
193
194 /* --- @mdwopt@ --- *
195  *
196  * Arguments:   @int argc@ = number of command line arguments
197  *              @char * const *argv@ = pointer to command line arguments
198  *              @const char *shortopt@ = pointer to short options information
199  *              @const struct option *longopts@ = pointer to long opts info
200  *              @int *longind@ = where to store matched longopt
201  *              @mdwopt_data *data@ = persistent state for the parser
202  *              @int flags@ = various useful flags
203  *
204  * Returns:     Value of option found next, or an error character, or
205  *              @EOF@ for the last thing.
206  *
207  * Use:         Reads options.  The routine should be more-or-less compatible
208  *              with standard getopts, although it provides many more
209  *              features even than the standard GNU implementation.
210  *
211  *              The precise manner of options parsing is determined by
212  *              various flag settings, which are described below.  By setting
213  *              flag values appropriately, you can achieve behaviour very
214  *              similar to most other getopt routines.
215  *
216  *
217  *          How options parsing appears to users
218  *
219  *              A command line consists of a number of `words' (which may
220  *              contain spaces, according to various shell quoting
221  *              conventions).  A word may be an option, an argument to an
222  *              option, or a non-option.  An option begins with a special
223  *              character, usually `%|-|%', although `%|+|%' is also used
224  *              sometimes.  As special exceptions, the word containing only a
225  *              `%|-|%' is considered to be a non-option, since it usually
226  *              represents standard input or output as a filename, and the
227  *              word containing a double-dash `%|--|%' is used to mark all
228  *              following words as being non-options regardless of their
229  *              initial character.
230  *
231  *              Traditionally, all words after the first non-option have been
232  *              considered to be non-options automatically, so that options
233  *              must be specified before filenames.  However, this
234  *              implementation can extract all the options from the command
235  *              line regardless of their position.  This can usually be
236  *              disabled by setting one of the environment variables
237  *              `%|POSIXLY_CORRECT|%' or `%|_POSIX_OPTION_ORDER|%'.
238  *
239  *              There are two different styles of options: `short' and
240  *              `long'.
241  *
242  *              Short options are the sort which Unix has known for ages: an
243  *              option is a single letter, preceded by a `%|-|%'.  Short
244  *              options can be joined together to save space (and possibly to
245  *              make silly words): e.g., instead of giving options
246  *              `%|-x -y|%', a user could write `%|-xy|%'.  Some short
247  *              options can have arguments, which appear after the option
248  *              letter, either immediately following, or in the next `word'
249  *              (so an option with an argument could be written as
250  *              `%|-o foo|%' or as `%|-ofoo|%').  Note that options with
251  *              optional arguments must be written in the second style.
252  *
253  *              When a short option controls a flag setting, it is sometimes
254  *              possible to explicitly turn the flag off, as well as turning
255  *              it on, (usually to override default options).  This is
256  *              usually done by using a `%|+|%' instead of a `%|-|%' to
257  *              introduce the option.
258  *
259  *              Long options, as popularized by the GNU utilities, are given
260  *              long-ish memorable names, preceded by a double-dash `%|--|%'.
261  *              Since their names are more than a single character, long
262  *              options can't be combined in the same way as short options.
263  *              Arguments to long options may be given either in the same
264  *              `word', separated from the option name by an equals sign, or
265  *              in the following `word'.
266  *
267  *              Long option names can be abbreviated if necessary, as long
268  *              as the abbreviation is unique.  This means that options can
269  *              have sensible and memorable names but still not require much
270  *              typing from an experienced user.
271  *
272  *              Like short options, long options can control flag settings.
273  *              The options to manipulate these settings come in pairs: an
274  *              option of the form `%|--set-flag|%' might set the flag, while
275  *              an option of the form `%|--no-set-flag|%' might clear it.
276  *
277  *              It is usual for applications to provide both short and long
278  *              options with identical behaviour.  Some applications with
279  *              lots of options may only provide long options (although they
280  *              will often be only two or three characters long).  In this
281  *              case, long options can be preceded with a single `%|-|%'
282  *              character, and negated by a `%|+|%' character.
283  *
284  *              Finally, some (older) programs accept arguments of the form
285  *              `%%@.{"-"<number>}%%', to set some numerical parameter,
286  *              typically a line count of some kind.
287  *
288  *
289  *          How programs parse options
290  *
291  *              An application parses its options by calling mdwopt
292  *              repeatedly.  Each time it is called, mdwopt returns a value
293  *              describing the option just read, and stores information about
294  *              the option in a data block.  The value %$-1$% is returned
295  *              when there are no more options to be read.  The `%|?|%'
296  *              character is returned when an error is encountered.
297  *
298  *              Before starting to parse options, the value @data->ind@ must
299  *              be set to 0 or 1. The value of @data->err@ can also be set,
300  *              to choose whether errors are reported by mdwopt.
301  *
302  *              The program's `@argc@' and `@argv@' arguments are passed to
303  *              the options parser, so that it can read the command line.  A
304  *              flags word is also passed, allowing the program fine control
305  *              over parsing.  The flags are described above.
306  *
307  *              Short options are described by a string, which once upon a
308  *              time just contained the permitted option characters.  Now the
309  *              options string begins with a collection of flag characters,
310  *              and various flag characters can be put after options
311  *              characters to change their properties.
312  *
313  *              If the first character of the short options string is
314  *              `%|+|%', `%|-|%' or `%|!|%', the order in which options are
315  *              read is modified, as follows:
316  *
317  *              `%|+|%' forces the POSIX order to be used. As soon as a non-
318  *                      option is found, mdwopt returns %$-1$%.
319  *
320  *              `%|-|%' makes mdwopt treat non-options as being `special'
321  *                      sorts of option. When a non-option word is found, the
322  *                      value 0 is returned, and the actual text of the word
323  *                      is stored as being the option's argument.
324  *
325  *              `%|!|%' forces the default order to be used.  The entire
326  *                      command line is scanned for options, which are
327  *                      returned in order.  However, during this process,
328  *                      the options are moved in the @argv@ array, so that
329  *                      they appear before the non- options.
330  *
331  *              A `%|:|%' character may be placed after the ordering flag (or
332  *              at the very beginning if no ordering flag is given) which
333  *              indicates that the character `%|:|%', rather than `%|?|%',
334  *              should be returned if a missing argument error is detected.
335  *
336  *              Each option in the string can be followed by a `%|+|%' sign,
337  *              indicating that it can be negated, a `%|:|%' sign indicating
338  *              that it requires an argument, or a `%|::|%' string,
339  *              indicating an optional argument.  Both `%|+|%' and `%|:|%' or
340  *              `%|::|%' may be given, although the `%|+|%' must come first.
341  *
342  *              If an option is found, the option character is returned to
343  *              the caller.  A pointer to an argument is stored in
344  *              @data->arg@, or @NULL@ is stored if there was no argument.
345  *              If a negated option was found, the option character is
346  *              returned ORred with @gFlag_negated@ (bit 8 set).
347  *
348  *              Long options are described in a table.  Each entry in the
349  *              table is of type @struct option@, and the table is terminated
350  *              by an entry whose @name@ field is null.  Each option has
351  *              a flags word which, due to historical reasons, is called
352  *              @has_arg@.  This describes various properties of the option,
353  *              such as what sort of argument it takes, and whether it can
354  *              be negated.
355  *
356  *              When mdwopt finds a long option, it looks the name up in the
357  *              table. The index of the matching entry is stored in the
358  *              @longind@ variable, passed to mdwopt (unless @longind@ is 0):
359  *              a value of %$-1$% indicates that no long option was
360  *              found. The behaviour is then dependent on the values in the
361  *              table entry.  If @flag@ is nonzero, it points to an integer
362  *              to be modified by mdwopt.  Usually the value in the @val@
363  *              field is simply stored in the @flag@ variable. If the flag
364  *              @gFlag_switch@ is set, however, the value is combined with
365  *              the existing value of the flags using a bitwise OR.  If
366  *              @gFlag_negate@ is set, then the flag bit will be cleared if a
367  *              matching negated long option is found.  The value 0 is
368  *              returned.
369  *
370  *              If @flag@ is zero, the value in @val@ is returned by mdwopt,
371  *              possibly with bit 8 set if the option was negated.
372  *
373  *              Arguments for long options are stored in @data->arg@, as
374  *              before.
375  *
376  *              Numeric options, if enabled, cause the value `%|#|%' to be
377  *              returned, and the numeric value to be stored in @data->opt@.
378  *
379  *              If the flag @gFlag_envVar@ is set on entry, options will be
380  *              extracted from an environment variable whose name is built by
381  *              capitalising all the letters of the program's name.  (This
382  *              allows a user to have different default settings for a
383  *              program, by calling it through different symbolic links.)  */
384
385 int mdwopt(int argc, char *const *argv,
386            const char *shortopt,
387            const struct option *longopts, int *longind,
388            mdwopt_data *data, int flags)
389 {
390   /* --- Local variables --- */
391
392   char *p, *q, *r;                      /* Some useful things to have */
393   char *prefix;                         /* Prefix from this option */
394   int i;                                /* Always useful */
395   char noarg = '?';                     /* Standard missing-arg char */
396
397   /* --- Sort out our data --- */
398
399   if (!data)                            /* If default data requested */
400     data = &mdwopt_global;              /* Then use the global stuff */
401
402   /* --- See if this is the first time --- */
403
404   if (data->ind == 0 || (data->ind == 1 && ~flags & gFlag_noProgName)) {
405
406     /* --- Sort out default returning order --- */
407
408     if (getenv("_POSIX_OPTION_ORDER") || /* Examine environment for opts */
409         getenv("POSIXLY_CORRECT"))      /* To see if we disable features */
410       data->order = ord__posix;         /* If set, use POSIX ordering */
411     else
412       data->order = ord__permute;       /* Otherwise mangle the options */
413
414     /* --- Now see what the caller actually wants --- */
415
416     switch (shortopt[0]) {              /* Look at the first character */
417       case '-':                         /* `%|-|%' turns on in-orderness */
418         data->order = ord__return;
419         break;
420       case '+':                         /* `%|+|%' turns on POSIXness */
421         data->order = ord__posix;
422         break;
423       case '!':                         /* `%|!|%' ignores POSIXness */
424         data->order = ord__permute;
425         break;
426     }
427
428     /* --- Now decide on the program's name --- */
429
430     if (~flags & gFlag_noProgName) {
431       p = q = (char *)argv[0];
432       while (*p) {
433         if (*p++ == PATHSEP)
434           q = p;
435       }
436       data->prog = q;
437
438       data->ind = data->next = 1;
439       data->list = 0;
440
441       /* --- See about environment variables --- *
442        *
443        * Be careful.  The program may be setuid, and an attacker might have
444        * given us a long name in @argv[0]@.  If the name is very long, don't
445        * support this option.
446        */
447
448       if (flags & gFlag_envVar && strlen(data->prog) < 48) {
449
450         char buf[64];
451
452         /* --- For RISC OS, support a different format --- *
453          *
454          * Acorn's RISC OS tends to put settings in variables named
455          * `App$Options' rather than `APP'.  Under RISC OS, I'll support
456          * both methods, just to avoid confuddlement.
457          */
458
459 #ifdef __riscos
460         sprintf(buf, "%s$Options", data->prog);
461         p = getenv(buf);
462         if (!p) {
463 #endif
464
465           p = buf;                      /* Point to a buffer */
466           q = data->prog;               /* Point to program name */
467           while (*q)                    /* While characters left here */
468             *p++ = toupper(*q++);       /* Copy and uppercase */
469           *p++ = 0;                     /* Terminate my copy of this */
470           p = getenv(buf);              /* Get the value of the variable */
471
472 #ifdef __riscos
473         }
474 #endif
475
476         /* --- Copy the options string into a buffer --- */
477
478         if (p) {                        /* If it is defined */
479           q = malloc(strlen(p) + 1);    /* Allocate space for a copy */
480           if (!q) {                     /* If that failed */
481             fprintf(stderr,             /* Report a nice error */
482                     "%s: Not enough memory to read settings in "
483                     "environment variable\n",
484                     data->prog);
485           } else {                      /* Otherwise */
486             strcpy(q, p);               /* Copy the text over */
487             data->ind = -1;             /* Mark that we're parsing envvar */
488             data->env = data->estart = q; /* And store the pointer away */
489           }
490         }
491
492       }
493     }
494     else
495       data->ind = data->next = 0;
496   }
497
498   /* --- Do some initial bodgery --- *
499    *
500    * The @shortopt@ string can have some interesting characters at the
501    * beginning.  We'll skip past them.
502    */
503
504   switch (shortopt[0]) {
505     case '+':
506     case '-':
507     case '!':
508       shortopt++;
509       break;
510   }
511
512   if (shortopt[0] == ':') {
513     noarg = shortopt[0];
514     shortopt++;
515   }
516
517   if (longind)                          /* Allow longind to be null */
518     *longind = -1;                      /* Clear this to avoid confusion */
519   data->opt = -1;                       /* And this too */
520   data->arg = 0;                        /* No option set up here */
521
522   /* --- Now go off and search for an option --- */
523
524   if (!data->list || !*data->list) {
525     data->order &= 3;                   /* Clear negation flag */
526
527     /* --- Now we need to find the next option --- *
528      *
529      * Exactly how we do this depends on the settings of the order variable.
530      * We identify options as being things starting with `%|-|%', and which
531      * aren't equal to `%|-|%' or `%|--|%'.  We'll look for options until:
532      *
533      *   * We find something which isn't an option AND @order == ord__posix@
534      *   * We find a `%|--|%'
535      *   * We reach the end of the list
536      *
537      * There are some added little wrinkles, which we'll meet as we go.
538      */
539
540     for (;;) {                          /* Keep looping for a while */
541       p = mo__nextWord(argc, argv, data); /* Get the next word out */
542       if (!p)                           /* If there's no next word */
543         return (EOF);                   /* There's no more now */
544
545       /* --- See if we've found an option --- */
546
547       if ((p[0] == '-' || (p[0] == '+' && flags & gFlag_negation)) &&
548           p[1] != 0) {
549         if (strcmp(p, "--") == 0) {     /* If this is the magic marker */
550           mo__permute(argv, data);      /* Stow the magic marker item */
551           return (EOF);                 /* There's nothing else to do */
552         }
553         break;                          /* We've found something! */
554       }
555
556       /* --- Figure out how to proceed --- */
557
558       switch (data->order & 3) {
559         case ord__posix:                /* POSIX option order */
560           return (EOF);                 /* This is easy */
561           break;
562         case ord__permute:              /* Permute the option order */
563           break;
564         case ord__return:               /* Return each argument */
565           mo__permute(argv, data);      /* Insert word in same place */
566           data->arg = p;                /* Point to the argument */
567           return (0);                   /* Return the value */
568       }
569     }
570
571     /* --- We found an option --- */
572
573     mo__permute(argv, data);            /* Do any permuting necessary */
574
575     /* --- Check for a numeric option --- *
576      *
577      * We only check the first character (or the second if the first is a
578      * sign).  This ought to be enough.
579      */
580
581     if (flags & gFlag_numbers && (p[0] == '-' || flags & gFlag_negNumber)) {
582       if (((p[1] == '+' || p[1] == '-') && isdigit((unsigned char)p[2])) ||
583           isdigit((unsigned char)p[1])) {
584         data->opt = strtol(p + 1, &data->arg, 10);
585         while (isspace((unsigned char)data->arg[0]))
586           data->arg++;
587         if (!data->arg[0])
588           data->arg = 0;
589         return (p[0] == '-' ? '#' : '#' | gFlag_negated);
590       }
591     }
592
593     /* --- Check for a long option --- */
594
595     if (p[0] == '+')
596       data->order |= ord__negate;
597
598     if (((p[0] == '-' && p[1] == '-') ||
599          (flags & gFlag_noShorts && !mo__findOpt(p[1], shortopt, data))) &&
600         (~flags & gFlag_noLongs))       /* Is this a long option? */
601     {
602       int match = -1;                   /* Count matches as we go */
603
604       if (p[0] == '+') {                /* If it's negated */
605         data->order |= ord__negate;     /* Set the negate flag */
606         p++;                            /* Point to the main text */
607         prefix = "+";                   /* Set the prefix string up */
608       } else if (p[1] == '-') {         /* If this is a `%|--|%' option */
609         if ((flags & gFlag_negation) && strncmp(p + 2, "no-", 3) == 0) {
610           p += 5;                       /* Point to main text */
611           prefix = "--no-";             /* And set the prefix */
612           data->order |= ord__negate;   /* Set the negatedness flag */
613         } else {
614           p += 2;                       /* Point to the main text */
615           prefix = "--";                /* Remember the prefix string */
616         }
617       } else {
618         if ((flags & gFlag_negation) && strncmp(p + 1, "no-", 3) == 0) {
619           p += 4;                       /* Find the text */
620           prefix = "-no-";              /* Set the prefix */
621           data->order |= ord__negate;   /* Set negatedness flag */
622         } else {
623           p++;                          /* Otherwise find the text */
624           prefix = "-";                 /* And remember the prefix */
625         }
626       }
627
628       for (i = 0; longopts[i].name; i++) { /* Loop through the options */
629         if ((data->order & ord__negate) &&
630             (~longopts[i].has_arg & gFlag_negate))
631           continue;                     /* If neg and opt doesn't allow */
632
633         r = (char *) longopts[i].name;  /* Point to the name string */
634         q = p;                          /* Point to the string start */
635         for (;;) {                      /* Do a loop here */
636           if (*q == 0 || *q == '=') {   /* End of the option string? */
637             if (*r == 0) {              /* If end of other string */
638               match = i;                /* This is the match */
639               goto botched;             /* And exit the loop now */
640             }
641             if (match == -1) {          /* If no match currently */
642               match = i;                /* Then this is it, here */
643               break;                    /* Stop looking now */
644             } else {
645               match = -1;               /* Else it's ambiguous */
646               goto botched;             /* So give up right now */
647             }
648           }
649           else if (*q != *r)            /* Otherwise if mismatch */
650             break;                      /* Abort this loop */
651           q++, r++;                     /* Increment the counters */
652         }
653       }
654
655     botched:
656       if (match == -1) {                /* If we couldn't find a match */
657         if (data->err) {
658           fprintf(stderr, "%s: unrecognized option `%s%s'\n",
659                   data->prog,
660                   prefix, p);
661         }
662         return ('?');
663       }
664
665       if (longind)                      /* Allow longind to be null */
666         *longind = match;               /* Store the match away */
667
668       /* --- Handle argument behaviour --- */
669
670       while (*p != 0 && *p != '=')      /* Find the argument string */
671         p++;
672       p = (*p ? p + 1 : 0);             /* Sort out argument presence */
673       q = (char *) longopts[match].name; /* Remember the name here */
674
675       switch (longopts[match].has_arg & 3) {
676         case no_argument:
677           if (p) {
678             if (data->err) {
679               fprintf(stderr,
680                       "%s: option `%s%s' does not accept arguments\n",
681                       data->prog,
682                       prefix, q);
683             }
684             return ('?');
685           }
686           break;
687
688         case required_argument:
689           if (!p) {                     /* If no argument given */
690             p = mo__nextWord(argc, argv, data);
691
692             if (!p) {                   /* If no more arguments */
693               if (data->err) {
694                 fprintf(stderr, "%s: option `%s%s' requires an argument\n",
695                         data->prog,
696                         prefix, q);
697               }
698               return (noarg);
699             }
700
701             mo__permute(argv, data);
702           }
703           break;
704
705         case optional_argument:
706           /* Who cares? */
707           break;
708       }
709       data->arg = p;
710
711       /* --- Do correct things now we have a match --- */
712
713       if (longopts[match].flag) {       /* If he has a @flag@ argument */
714         if (longopts[match].has_arg & gFlag_switch) {
715           if (data->order & ord__negate)
716             *longopts[match].flag &= ~longopts[match].val;
717           else
718             *longopts[match].flag |= longopts[match].val;
719         } else {
720           if (data->order & ord__negate)
721             *longopts[match].flag = 0;
722           else
723             *longopts[match].flag = longopts[match].val;
724         }
725         return (0);                     /* And return something */
726       } else {
727         if (data->order & ord__negate)
728           return (longopts[match].val | gFlag_negated);
729         else
730           return (longopts[match].val);
731       }
732     }
733
734     /* --- Do short options things --- */
735
736     else {
737       if (p[0] == '+')                  /* If starts with a `%|+|%' */
738         data->order |= ord__negate;
739       data->list = p + 1;               /* Omit leading `%|-|%'/`%|+|%' */
740     }
741   }
742
743   /* --- Now process the short options --- */
744
745   i = *data->list++;                    /* Get the next option letter */
746   data->opt = i;                        /* Store this away nicely */
747
748   p = (char *) mo__findOpt(i, shortopt, data);
749   if (!p) {                             /* No more options left */
750     if (data->err) {
751       fprintf(stderr, "%s: unknown option `%c%c'\n",
752               data->prog,
753               data->order & ord__negate ? '+' : '-',
754               i);
755     }
756     return ('?');
757   }
758
759   data->opt = i;                        /* Store this for the caller */
760
761   /* --- Sort out an argument, if we expect one --- */
762
763   if (p[0] == ':') {                    /* If we expect an option */
764     q = (data->list[0] ? data->list : 0); /* If argument expected, use it */
765     data->list = 0;                     /* Kill the remaining options */
766     if (p[1] != ':' && !q) {            /* If no arg, and not optional */
767
768       /* --- Same code as before --- */
769
770       q = mo__nextWord(argc, argv, data); /* Read the next word */
771       if (!q) {                         /* If no more arguments */
772         if (data->err) {
773           fprintf(stderr, "%s: option `%c%c' requires an argument\n",
774                   data->prog,
775                   data->order & ord__negate ? '+' : '-',
776                   i);
777         }
778         return (noarg);
779       }
780       mo__permute(argv, data);
781     }
782
783     data->arg = q;
784   }
785   return ((data->order & ord__negate) ? i | gFlag_negated : i);
786 }
787
788 /*----- That's all, folks -------------------------------------------------*/